chore: 初始开源发布

iotlcm-worker-svr:异步执行中枢(RabbitMQ 消费者 + 全量同步编排)。

- Go module:iotlcm-worker-svr → git.5iot.com/iotlcm-public/iotlcm-worker-svr(214 文件)
- 凭据与内部标识脱敏:MySQL/Redis 凭据、私网与生产 IP、内网域名、
  库名 xiujie_admin → iotlcm、哨兵名占位
- 159 处真实手机号 → 合法 11 位编造号(保留号段与后 4 位,维持互异,
  不破坏「校验 MSISDN 格式」等测试断言)
- 移除内部资产:CI 触发器、Jenkins 触发测试文档、预演门禁与镜像
  digest 记录
- Dockerfile 改用公共基础镜像(golang:1.25-alpine → alpine:3.23),
  移除写死的 git 凭据
- README 重写(架构/全量同步模型/配置/已知失败),补 Apache-2.0
  LICENSE,LF 行尾 + .gitattributes

已知:3 个测试包在源仓同一提交上同样失败(client/upstream、
service/allocate、service/inbound),属既有缺陷,本仓未引入亦未修复。
This commit is contained in:
MiFaZhan
2026-10-22 16:37:56 +08:00
commit 2bec257289
361 changed files with 71524 additions and 0 deletions
@@ -0,0 +1,142 @@
package trafficcutoffconfig
import (
"context"
"strings"
"time"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/gtime"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/consts"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/model/entity"
)
const (
noDetailsReason = "达量断网配置批次没有可处理明细"
validationFailureReason = "部分达量断网配置校验失败"
emptyICCIDReason = "ICCID不能为空"
duplicateICCIDReason = "ICCID在批次内重复"
unauthorizedReason = "ICCID不在当前操作员授权范围内"
cardMissingReason = "ICCID不存在或不属于当前租户"
msisdnMismatchReason = "MSISDN与卡档案不一致"
imsiMismatchReason = "IMSI与卡档案不一致"
flowPoolCardReason = "流量池卡不支持达量断网配置"
packageTotalExceededReason = "达量断网阈值不能大于套餐总流量"
)
type executor struct {
repository *Repository
}
const trafficCutoffConfigProcessingRetryAfter = 2 * time.Minute
func NewExecutor() *executor {
return &executor{repository: NewRepository()}
}
func (e *executor) CanExecuteProcessing(_ context.Context, main *entity.BatchMain) (bool, error) {
if main == nil || main.BatchType != consts.BatchTypeTrafficCutoffConfig || main.BatchAsyncStatus != consts.BatchAsyncStatusProcessing {
return false, nil
}
if main.StartTime == nil || main.StartTime.IsZero() {
return true, nil
}
return gtime.Now().Sub(main.StartTime) >= trafficCutoffConfigProcessingRetryAfter, nil
}
func (e *executor) Execute(ctx context.Context, batchNo string) error {
task, err := e.repository.Load(ctx, strings.TrimSpace(batchNo))
if err != nil {
return gerror.Wrap(err, "load traffic cutoff config batch failed")
}
validateTask(task)
return gerror.Wrap(e.repository.Commit(ctx, task), "commit traffic cutoff config batch failed")
}
func validateTask(task *Task) {
if task == nil || len(task.Details) == 0 {
if task != nil {
task.FailureReason = noDetailsReason
}
return
}
iccidCounts := make(map[string]int, len(task.Details))
for _, detail := range task.Details {
if detail == nil {
continue
}
detail.ICCID = strings.TrimSpace(detail.ICCID)
detail.MSISDN = strings.TrimSpace(detail.MSISDN)
detail.IMSI = strings.TrimSpace(detail.IMSI)
if detail.ICCID != "" {
iccidCounts[detail.ICCID]++
}
}
for _, detail := range task.Details {
validateDetail(task, detail)
if detail != nil && detail.Reason == "" && iccidCounts[detail.ICCID] > 1 {
detail.Reason = duplicateICCIDReason
}
}
_, failCount := countResult(task)
if failCount > 0 {
task.FailureReason = validationFailureReason
} else {
task.FailureReason = ""
}
}
func validateDetail(task *Task, detail *Detail) {
if detail == nil || detail.Reason != "" {
return
}
if detail.ICCID == "" {
detail.Reason = emptyICCIDReason
return
}
if !detail.Authorized {
detail.Reason = unauthorizedReason
return
}
if detail.Card == nil {
detail.Reason = cardMissingReason
return
}
detail.Card.ICCID = strings.TrimSpace(detail.Card.ICCID)
detail.Card.MSISDN = strings.TrimSpace(detail.Card.MSISDN)
detail.Card.IMSI = strings.TrimSpace(detail.Card.IMSI)
if detail.MSISDN != "" && detail.MSISDN != detail.Card.MSISDN {
detail.Reason = msisdnMismatchReason
return
}
if detail.IMSI != "" && detail.IMSI != detail.Card.IMSI {
detail.Reason = imsiMismatchReason
return
}
if detail.Card.IsFlowPool != 0 {
detail.Reason = flowPoolCardReason
return
}
if task.Config.TrafficCutoffStatus == 1 &&
detail.Card.PackageTotalFlowMb > 0 &&
task.Config.TrafficCutoffThreshold > detail.Card.PackageTotalFlowMb {
detail.Reason = packageTotalExceededReason
}
}
func countResult(task *Task) (successCount, failCount int) {
if task == nil {
return 0, 0
}
for _, detail := range task.Details {
if detail != nil && detail.Success() {
successCount++
} else {
failCount++
}
}
return successCount, failCount
}
@@ -0,0 +1,190 @@
package trafficcutoffconfig
import "testing"
func TestValidateTaskAllowsDifferentCardStatusesAndMissingEffectivePackage(t *testing.T) {
task := validConfigTask(512)
task.Details = []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000002"),
validConfigDetail(3, "898600000000003"),
}
task.Details[0].Card.BossCardStatus = 1
task.Details[0].Card.PackageStatus = 0
task.Details[0].Card.PackageTotalFlowMb = 0
task.Details[1].Card.BossCardStatus = 4
task.Details[1].Card.PackageStatus = 1
task.Details[1].Card.PackageTotalFlowMb = 0
task.Details[2].Card.BossCardStatus = 9
task.Details[2].Card.PackageStatus = 3
task.Details[2].Card.PackageTotalFlowMb = 0
validateTask(task)
if success, fail := countResult(task); success != 3 || fail != 0 {
t.Fatalf("countResult() = (%d, %d), want (3, 0); task = %+v", success, fail, task)
}
}
func TestValidateTaskAllowsPartialSuccessForThresholdGreaterThanPositivePackageTotal(t *testing.T) {
task := validConfigTask(512)
task.Details = []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000002"),
}
task.Details[0].Card.PackageTotalFlowMb = 128
task.Details[1].Card.PackageTotalFlowMb = 0
validateTask(task)
assertDetailReason(t, task.Details[0], packageTotalExceededReason)
assertDetailReason(t, task.Details[1], "")
if success, fail := countResult(task); success != 1 || fail != 1 {
t.Fatalf("countResult() = (%d, %d), want (1, 1)", success, fail)
}
}
func TestValidateTaskAllowsPartialSuccessForInvalidRows(t *testing.T) {
tests := []struct {
name string
details []*Detail
wantReason map[int]string
}{
{
name: "empty ICCID",
details: []*Detail{
{RowNo: 1, ICCID: " ", Authorized: true, Card: validConfigCard(1, "")},
validConfigDetail(2, "898600000000002"),
},
wantReason: map[int]string{1: emptyICCIDReason, 2: ""},
},
{
name: "duplicate ICCID",
details: []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000001"),
validConfigDetail(3, "898600000000003"),
},
wantReason: map[int]string{1: duplicateICCIDReason, 2: duplicateICCIDReason, 3: ""},
},
{
name: "unauthorized",
details: []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000002"),
},
wantReason: map[int]string{1: unauthorizedReason, 2: ""},
},
{
name: "missing card",
details: []*Detail{
{RowNo: 1, ICCID: "898600000000001", Authorized: true},
validConfigDetail(2, "898600000000002"),
},
wantReason: map[int]string{1: cardMissingReason, 2: ""},
},
{
name: "MSISDN mismatch",
details: []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000002"),
},
wantReason: map[int]string{1: msisdnMismatchReason, 2: ""},
},
{
name: "IMSI mismatch",
details: []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000002"),
},
wantReason: map[int]string{1: imsiMismatchReason, 2: ""},
},
{
name: "flow pool card",
details: []*Detail{
validConfigDetail(1, "898600000000001"),
validConfigDetail(2, "898600000000002"),
},
wantReason: map[int]string{1: flowPoolCardReason, 2: ""},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
task := validConfigTask(512)
task.Details = tt.details
switch tt.name {
case "unauthorized":
task.Details[0].Authorized = false
case "MSISDN mismatch":
task.Details[0].MSISDN = "13900009999"
case "IMSI mismatch":
task.Details[0].IMSI = "460009999999999"
case "flow pool card":
task.Details[0].Card.IsFlowPool = 1
}
validateTask(task)
for _, detail := range task.Details {
assertDetailReason(t, detail, tt.wantReason[detail.RowNo])
}
if success, fail := countResult(task); success != 1 || fail != len(task.Details)-1 {
t.Fatalf("countResult() = (%d, %d), want (1, %d)", success, fail, len(task.Details)-1)
}
})
}
}
func validConfigTask(threshold float64) *Task {
return &Task{
Batch: Batch{
BatchNo: "TCC-41",
BatchType: 41,
TenantID: "000000",
CreatedBy: 7,
},
Config: Config{
TrafficCutoffStatus: 1,
TrafficCutoffThreshold: threshold,
},
Details: []*Detail{validConfigDetail(1, "898600000000001")},
}
}
func validConfigDetail(rowNo int, iccid string) *Detail {
card := validConfigCard(rowNo, iccid)
return &Detail{
ID: int64(rowNo),
RowNo: rowNo,
ICCID: iccid,
MSISDN: card.MSISDN,
IMSI: card.IMSI,
Authorized: true,
Card: card,
}
}
func validConfigCard(rowNo int, iccid string) *Card {
return &Card{
ID: int64(rowNo),
ICCID: iccid,
MSISDN: "1380000000" + string(rune('0'+rowNo)),
IMSI: "46000100000000" + string(rune('0'+rowNo)),
PackageStatus: 0,
BossCardStatus: rowNo,
PackageTotalFlowMb: 1024,
TrafficCutoffStatus: 0,
TrafficCutoffThreshold: 0,
}
}
func assertDetailReason(t *testing.T, detail *Detail, want string) {
t.Helper()
if detail == nil {
t.Fatal("detail is nil")
}
if detail.Reason != want {
t.Fatalf("row %d reason = %q, want %q", detail.RowNo, detail.Reason, want)
}
}
@@ -0,0 +1,499 @@
package trafficcutoffconfig
import (
"context"
"math"
"sort"
"strings"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/consts"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/dao"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/model/do"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/model/entity"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/service/batchresult"
)
type Repository struct {
db gdb.DB
results batchresult.Generator
lockEnabled bool
}
func NewRepository() *Repository {
return &Repository{results: batchresult.New(), lockEnabled: true}
}
func (r *Repository) database() gdb.DB {
if r.db != nil {
return r.db
}
return g.DB()
}
func (r *Repository) applyLock(model *gdb.Model) *gdb.Model {
if r.lockEnabled {
return model.LockUpdate()
}
return model
}
func (r *Repository) Load(ctx context.Context, batchNo string) (*Task, error) {
batchNo = strings.TrimSpace(batchNo)
if batchNo == "" {
return nil, gerror.New("达量断网配置批次号不能为空")
}
var main *entity.BatchMain
if err := r.database().Model(dao.BatchMain.Table()).Safe().Ctx(ctx).
Where(dao.BatchMain.Columns().BatchNo, batchNo).
Where(dao.BatchMain.Columns().BatchType, consts.BatchTypeTrafficCutoffConfig).
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
Scan(&main); err != nil {
return nil, gerror.Wrap(err, "查询达量断网配置批次主表失败")
}
if main == nil || main.Id == 0 {
return nil, gerror.New("处理中达量断网配置批次不存在")
}
config, err := configFromBatchInfo(main.BatchInfo)
if err != nil {
return nil, err
}
var batchDetails []*entity.BatchDetail
if err = r.database().Model(dao.BatchDetail.Table()).Safe().Ctx(ctx).
Where(dao.BatchDetail.Columns().BatchNo, batchNo).
Where(dao.BatchDetail.Columns().BatchType, consts.BatchTypeTrafficCutoffConfig).
Where(dao.BatchDetail.Columns().DetailStatus, consts.BatchDetailStatusRunning).
OrderAsc(dao.BatchDetail.Columns().RowNo).
Scan(&batchDetails); err != nil {
return nil, gerror.Wrap(err, "查询达量断网配置批次明细失败")
}
if len(batchDetails) == 0 {
return nil, gerror.New("达量断网配置批次没有运行中明细")
}
task := &Task{
Batch: Batch{
ID: main.Id,
BatchNo: main.BatchNo,
BatchType: main.BatchType,
TenantID: main.TenantId,
CreatedDept: main.CreatedDept,
CreatedBy: main.CreatedBy,
StartTime: main.StartTime,
BatchInfo: main.BatchInfo,
},
Config: config,
Details: make([]*Detail, 0, len(batchDetails)),
}
for _, batchDetail := range batchDetails {
if batchDetail == nil {
continue
}
detail := &Detail{
ID: batchDetail.Id,
RowNo: batchDetail.RowNo,
ICCID: strings.TrimSpace(batchDetail.ItemId),
Reason: strings.TrimSpace(batchDetail.ErrorReason),
}
if batchDetail.Snapshot != nil {
if value := firstSnapshot(batchDetail.Snapshot, "ICCID", "iccid"); value != "" {
detail.ICCID = value
}
detail.MSISDN = firstSnapshot(batchDetail.Snapshot, "MSISDN", "msisdn", "inputMsisdn", "input_msisdn")
detail.IMSI = firstSnapshot(batchDetail.Snapshot, "IMSI", "imsi", "inputImsi", "input_imsi")
detail.Authorized = batchDetail.Snapshot.Get("authorized").Bool()
}
task.Details = append(task.Details, detail)
}
if len(task.Details) == 0 {
return nil, gerror.New("达量断网配置批次没有可读取明细")
}
if err = r.loadCards(ctx, task); err != nil {
return nil, err
}
return task, nil
}
func firstSnapshot(snapshot *gjson.Json, keys ...string) string {
if snapshot == nil {
return ""
}
for _, key := range keys {
if value := strings.TrimSpace(snapshot.Get(key).String()); value != "" {
return value
}
}
return ""
}
func (r *Repository) loadCards(ctx context.Context, task *Task) error {
iccids := make([]string, 0, len(task.Details))
for _, detail := range task.Details {
if detail != nil && strings.TrimSpace(detail.ICCID) != "" {
iccids = append(iccids, strings.TrimSpace(detail.ICCID))
}
}
iccids = uniqueSortedStrings(iccids)
if len(iccids) == 0 {
return nil
}
var cards []*entity.TSimCardInfo
columns := dao.TSimCardInfo.Columns()
if err := r.database().Model(dao.TSimCardInfo.Table()).Safe().Ctx(ctx).
Where(columns.TenantId, task.Batch.TenantID).
WhereIn(columns.Iccid, iccids).
Scan(&cards); err != nil {
return gerror.Wrap(err, "查询SIM卡档案失败")
}
byICCID := make(map[string]*entity.TSimCardInfo, len(cards))
for _, card := range cards {
if card != nil {
byICCID[strings.TrimSpace(card.Iccid)] = card
}
}
for _, detail := range task.Details {
if detail == nil {
continue
}
card := byICCID[strings.TrimSpace(detail.ICCID)]
if card == nil {
continue
}
detail.Card = &Card{
ID: card.Id,
ICCID: strings.TrimSpace(card.Iccid),
MSISDN: strings.TrimSpace(card.Msisdn),
IMSI: strings.TrimSpace(card.Imsi),
CurrentPackageCode: strings.TrimSpace(card.CurrentPackageCode),
PackageStatus: card.PackageStatus,
BossCardStatus: card.BossCardStatus,
IsFlowPool: card.IsFlowPool,
PackageTotalFlowMb: card.PackageTotalFlowMb,
TrafficCutoffStatus: card.TrafficCutoffStatus,
TrafficCutoffThreshold: card.TrafficCutoffThreshold,
}
}
return nil
}
func (r *Repository) Commit(ctx context.Context, task *Task) error {
if task == nil {
return gerror.New("达量断网配置任务不能为空")
}
successCount, failCount := countResult(task)
artifact, artifactErr := r.createResultFile(ctx, task)
if artifactErr != nil {
g.Log().Warningf(ctx, "traffic cutoff config result file generation failed, batchNo:%s, err:%+v", task.Batch.BatchNo, artifactErr)
}
now := gtime.Now()
err := r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
if successCount > 0 {
if err := r.updateAllCardConfigs(ctx, tx, task); err != nil {
return err
}
}
if err := r.updateDetails(ctx, tx, task); err != nil {
return err
}
var ossID, downloadID int64
if artifactErr == nil {
var err error
ossID, downloadID, err = r.persistArtifact(ctx, tx, task, artifact, successCount, failCount, now)
if err != nil {
return err
}
}
return r.finalizeBatch(ctx, tx, task, successCount, failCount, ossID, downloadID, now, artifactErr != nil)
})
if err != nil && artifactErr == nil && artifact.Path != "" {
batchresult.RemoveLocalFile(artifact)
}
return gerror.Wrap(err, "保存达量断网配置批次结果失败")
}
func (r *Repository) updateAllCardConfigs(ctx context.Context, tx gdb.TX, task *Task) error {
cardIDs := successDetailCardIDs(task.Details)
if len(cardIDs) == 0 {
return nil
}
columns := dao.TSimCardInfo.Columns()
var lockedCards []*entity.TSimCardInfo
model := tx.Ctx(ctx).Model(dao.TSimCardInfo.Table()).Safe().
Fields(columns.Id).
Where(columns.TenantId, task.Batch.TenantID).
WhereIn(columns.Id, cardIDs)
if err := r.applyLock(model).Scan(&lockedCards); err != nil {
return gerror.Wrap(err, "锁定达量断网配置卡档案失败")
}
if len(lockedCards) != len(cardIDs) {
return gerror.New("部分达量断网配置卡档案已发生变化")
}
_, err := tx.Ctx(ctx).Model(dao.TSimCardInfo.Table()).Safe().
Where(columns.TenantId, task.Batch.TenantID).
WhereIn(columns.Id, cardIDs).
Data(trafficCutoffConfigData(task)).Update()
if err != nil {
return gerror.Wrap(err, "保存达量断网配置失败")
}
return nil
}
func (r *Repository) updateDetails(ctx context.Context, tx gdb.TX, task *Task) error {
for _, detail := range task.Details {
if detail == nil {
continue
}
if err := r.updateDetail(ctx, tx, task, detail); err != nil {
return err
}
}
return nil
}
func (r *Repository) updateDetail(ctx context.Context, tx gdb.TX, task *Task, detail *Detail) error {
status := consts.BatchDetailStatusFailed
if detail.Success() {
status = consts.BatchDetailStatusSuccess
}
result, err := tx.Ctx(ctx).Model(dao.BatchDetail.Table()).
Where(dao.BatchDetail.Columns().Id, detail.ID).
Where(dao.BatchDetail.Columns().BatchNo, task.Batch.BatchNo).
Where(dao.BatchDetail.Columns().BatchType, consts.BatchTypeTrafficCutoffConfig).
Where(dao.BatchDetail.Columns().DetailStatus, consts.BatchDetailStatusRunning).
Data(do.BatchDetail{
DetailStatus: status,
ErrorReason: detail.Reason,
Snapshot: detail.Snapshot(task.Config),
UpdatedBy: task.Batch.CreatedBy,
}).Update()
if err != nil {
return gerror.Wrap(err, "更新达量断网配置批次明细失败")
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected != 1 {
return gerror.Newf("达量断网配置批次明细%d已不是运行中状态", detail.ID)
}
return nil
}
func (r *Repository) finalizeBatch(ctx context.Context, tx gdb.TX, task *Task, successCount, failCount int, ossID, downloadID int64, now *gtime.Time, resultFileFailed bool) error {
batchAsyncStatus, runResult := batchResult(successCount, failCount)
result, err := tx.Ctx(ctx).Model(dao.BatchMain.Table()).
Where(dao.BatchMain.Columns().BatchNo, task.Batch.BatchNo).
Where(dao.BatchMain.Columns().BatchType, consts.BatchTypeTrafficCutoffConfig).
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
Data(do.BatchMain{
BatchAsyncStatus: batchAsyncStatus,
RunResult: runResult,
TotalCount: len(task.Details),
ValidCount: successCount,
SuccessCount: successCount,
FailCount: failCount,
FailReason: task.FailureReason,
BatchInfo: mergeBatchInfo(task.Batch.BatchInfo, ossID, downloadID, resultFileFailed),
EndTime: now,
UpdatedBy: task.Batch.CreatedBy,
}).Update()
if err != nil {
return gerror.Wrap(err, "更新达量断网配置批次主表失败")
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected != 1 {
return gerror.New("达量断网配置批次已不是处理中状态")
}
return nil
}
func (r *Repository) createResultFile(ctx context.Context, task *Task) (batchresult.Artifact, error) {
if r.results == nil {
return batchresult.Artifact{}, gerror.New("result generator is not configured")
}
return r.results.Create(ctx, batchresult.Request{
BatchNo: task.Batch.BatchNo,
BatchType: task.Batch.BatchType,
TenantID: task.Batch.TenantID,
Rows: task.ResultRows(),
})
}
func (r *Repository) persistArtifact(ctx context.Context, tx gdb.TX, task *Task, artifact batchresult.Artifact, successCount, failCount int, now *gtime.Time) (int64, int64, error) {
ossID, err := tx.Ctx(ctx).Model(dao.SysOss.Table()).Data(do.SysOss{
TenantId: task.Batch.TenantID,
FileName: artifact.FileName,
OriginalName: artifact.OriginalName,
FileSuffix: artifact.FileSuffix,
Path: artifact.Path,
Url: artifact.URL,
CreatedDept: task.Batch.CreatedDept,
CreatedBy: task.Batch.CreatedBy,
UpdatedBy: task.Batch.CreatedBy,
Service: "local",
Md5: artifact.MD5,
FileSize: artifact.Size,
}).InsertAndGetId()
if err != nil {
return 0, 0, gerror.Wrap(err, "写入达量断网配置结果文件OSS失败")
}
downloadID, err := tx.Ctx(ctx).Model(dao.TResourceBatchDownload.Table()).Data(do.TResourceBatchDownload{
BatchNo: task.Batch.BatchNo,
TaskName: batchresult.TaskName(task.Batch.BatchType),
ResourceType: consts.ResourceTypeExcel,
ExportScene: consts.BatchTypeTrafficCutoffConfig,
TotalCount: len(task.Details),
SuccessCount: successCount,
FailCount: failCount,
DownloadStatus: consts.DownloadStatusGenerated,
OssId: ossID,
FileName: artifact.FileName,
FileExt: artifact.FileSuffix,
FileUrl: artifact.URL,
FilePath: artifact.Path,
FileSize: artifact.Size,
FileMd5: artifact.MD5,
DownloadCount: 0,
MaxDownloadCount: 0,
DeptId: task.Batch.CreatedDept,
StartTime: task.Batch.StartTime,
FinishTime: now,
TenantId: task.Batch.TenantID,
CreatedDept: task.Batch.CreatedDept,
CreatedBy: task.Batch.CreatedBy,
UpdatedBy: task.Batch.CreatedBy,
}).InsertAndGetId()
if err != nil {
return 0, 0, gerror.Wrap(err, "写入达量断网配置结果下载记录失败")
}
return ossID, downloadID, nil
}
func configFromBatchInfo(info *gjson.Json) (Config, error) {
if info == nil || info.IsNil() {
return Config{}, gerror.New("达量断网配置批次缺少批次参数")
}
status := info.Get("trafficCutoffStatus")
if status.IsNil() {
return Config{}, gerror.New("达量断网配置批次缺少trafficCutoffStatus")
}
config := Config{
TrafficCutoffCrossMonthHold: info.Get("trafficCutoffCrossMonthHold").Int(),
TrafficCutoffStatus: status.Int(),
TrafficCutoffThreshold: info.Get("trafficCutoffThreshold").Float64(),
}
if config.TrafficCutoffStatus != 0 && config.TrafficCutoffStatus != 1 && config.TrafficCutoffStatus != 2 {
return Config{}, gerror.New("达量断网启停状态无效")
}
if config.TrafficCutoffThreshold < 0 {
return Config{}, gerror.New("达量断网阈值不能小于0")
}
if config.TrafficCutoffStatus == 0 && config.TrafficCutoffThreshold != 0 {
return Config{}, gerror.New("未配置达量断网时阈值必须为0")
}
if config.TrafficCutoffStatus == 1 && config.TrafficCutoffThreshold <= 0 {
return Config{}, gerror.New("开启达量断网时阈值必须大于0")
}
if config.TrafficCutoffCrossMonthHold != 0 && config.TrafficCutoffCrossMonthHold != 1 {
return Config{}, gerror.New("invalid cross-month traffic cutoff hold value")
}
if config.TrafficCutoffStatus != 1 && config.TrafficCutoffCrossMonthHold != 0 {
return Config{}, gerror.New("cross-month hold requires traffic cutoff to be enabled")
}
rounded := math.Round(config.TrafficCutoffThreshold*1000) / 1000
if math.Abs(config.TrafficCutoffThreshold-rounded) > 0.0000001 {
return Config{}, gerror.New("达量断网阈值最多保留3位小数")
}
return config, nil
}
func trafficCutoffConfigData(task *Task) do.TSimCardTrafficCutoffConfig {
data := do.TSimCardTrafficCutoffConfig{
TrafficCutoffStatus: task.Config.TrafficCutoffStatus,
TrafficCutoffThreshold: task.Config.TrafficCutoffThreshold,
TrafficCutoffCrossMonthHold: task.Config.TrafficCutoffCrossMonthHold,
UpdatedBy: task.Batch.CreatedBy,
}
if task.Config.TrafficCutoffStatus != 1 || task.Config.TrafficCutoffCrossMonthHold == 0 {
data.TrafficCutoffTriggeredAt = gdb.Raw("NULL")
}
return data
}
func mergeBatchInfo(info *gjson.Json, ossID, downloadID int64, resultFileFailed bool) *gjson.Json {
data := make(map[string]any)
if info != nil {
for key, value := range info.Map() {
data[key] = value
}
}
if ossID > 0 {
data["resultFileOssId"] = ossID
}
if resultFileFailed {
data["resultFile"] = map[string]any{"status": "failed"}
} else if downloadID > 0 {
data["resultDownloadId"] = downloadID
data["resultFile"] = map[string]any{"status": "generated"}
} else {
data["resultFile"] = map[string]any{"status": "skipped"}
}
return gjson.New(data)
}
func batchResult(successCount, failCount int) (int, int) {
if failCount == 0 {
return consts.BatchAsyncStatusSuccess, consts.BatchRunResultSuccess
}
if successCount > 0 {
return consts.BatchAsyncStatusPartialSuccess, consts.BatchRunResultPartialSuccess
}
return consts.BatchAsyncStatusFailed, consts.BatchRunResultFailed
}
func successDetailCardIDs(details []*Detail) []int64 {
ids := make([]int64, 0, len(details))
seen := make(map[int64]struct{}, len(details))
for _, detail := range details {
if detail != nil && detail.Success() && detail.Card != nil && detail.Card.ID > 0 {
if _, exists := seen[detail.Card.ID]; exists {
continue
}
seen[detail.Card.ID] = struct{}{}
ids = append(ids, detail.Card.ID)
}
}
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
return ids
}
func uniqueSortedStrings(values []string) []string {
seen := make(map[string]struct{}, len(values))
out := make([]string, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
out = append(out, value)
}
sort.Strings(out)
return out
}
@@ -0,0 +1,462 @@
package trafficcutoffconfig
import (
"context"
"testing"
_ "github.com/gogf/gf/contrib/drivers/sqlite/v2"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/encoding/gjson"
batchdomain "git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/batch"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/consts"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/dao"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/model/do"
)
const (
testTenantID = "000000"
testDeptID = int64(100)
)
func TestExecuteAllSuccessUpdatesAllCardsAndFinalizesSuccess(t *testing.T) {
ctx := context.Background()
repo := newConfigTestRepository(t)
batchNo := "TCC-41-SUCCESS"
seedConfigProcessingBatch(t, ctx, repo.db, batchNo, 512)
seedConfigRunningDetail(t, ctx, repo.db, batchNo, 1, "898600000000001", "13800000001", "460001000000001", true)
seedConfigRunningDetail(t, ctx, repo.db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, repo.db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 1, PackageStatus: 0, PackageTotal: 0})
seedConfigCard(t, ctx, repo.db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 9, PackageStatus: 3, PackageTotal: 0})
if err := (&executor{repository: repo}).Execute(ctx, batchNo); err != nil {
t.Fatalf("Execute() error = %v", err)
}
assertConfigBatchMain(t, ctx, repo.db, batchNo, consts.BatchAsyncStatusSuccess, consts.BatchRunResultSuccess, 2, 0)
assertConfigDetailStatusCount(t, ctx, repo.db, batchNo, consts.BatchDetailStatusSuccess, 2)
assertConfigDetailStatusCount(t, ctx, repo.db, batchNo, consts.BatchDetailStatusFailed, 0)
assertConfigTrafficCutoff(t, ctx, repo.db, "898600000000001", 1, 512, 7)
assertConfigTrafficCutoff(t, ctx, repo.db, "898600000000002", 1, 512, 7)
assertNoPartialSuccess(t, ctx, repo.db, batchNo)
}
func TestExecuteDuplicateRowsMarksWholeBatchFailedWithoutCardUpdate(t *testing.T) {
ctx := context.Background()
repo := newConfigTestRepository(t)
batchNo := "TCC-41-DUPLICATE"
seedConfigProcessingBatch(t, ctx, repo.db, batchNo, 512)
seedConfigRunningDetail(t, ctx, repo.db, batchNo, 1, "898600000000001", "13800000001", "460001000000001", true)
seedConfigRunningDetail(t, ctx, repo.db, batchNo, 2, "898600000000001", "13800000001", "460001000000001", true)
seedConfigCard(t, ctx, repo.db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
if err := (&executor{repository: repo}).Execute(ctx, batchNo); err != nil {
t.Fatalf("Execute() error = %v", err)
}
assertConfigBatchMain(t, ctx, repo.db, batchNo, consts.BatchAsyncStatusFailed, consts.BatchRunResultFailed, 0, 2)
assertConfigDetailStatusCount(t, ctx, repo.db, batchNo, consts.BatchDetailStatusSuccess, 0)
assertConfigDetailStatusCount(t, ctx, repo.db, batchNo, consts.BatchDetailStatusFailed, 2)
assertAnyDetailReason(t, ctx, repo.db, batchNo, duplicateICCIDReason)
assertAllConfigTrafficCutoffUnchanged(t, ctx, repo.db)
assertNoPartialSuccess(t, ctx, repo.db, batchNo)
}
func TestExecuteInvalidRowsAllowPartialSuccess(t *testing.T) {
tests := []struct {
name string
threshold float64
validICCID string
invalidICCID string
mutate func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string)
wantReason string
}{
{
name: "unauthorized",
threshold: 512,
validICCID: "898600000000002",
invalidICCID: "898600000000001",
wantReason: unauthorizedReason,
mutate: func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string) {
seedConfigRunningDetail(t, ctx, db, batchNo, 1, "898600000000001", "13800000001", "460001000000001", false)
seedConfigRunningDetail(t, ctx, db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
},
},
{
name: "missing",
threshold: 512,
validICCID: "898600000000002",
wantReason: cardMissingReason,
mutate: func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string) {
seedConfigRunningDetail(t, ctx, db, batchNo, 1, "898600000000404", "13800000404", "460001000000404", true)
seedConfigRunningDetail(t, ctx, db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
},
},
{
name: "MSISDN mismatch",
threshold: 512,
validICCID: "898600000000002",
invalidICCID: "898600000000001",
wantReason: msisdnMismatchReason,
mutate: func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string) {
seedConfigRunningDetail(t, ctx, db, batchNo, 1, "898600000000001", "13900009999", "460001000000001", true)
seedConfigRunningDetail(t, ctx, db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
},
},
{
name: "IMSI mismatch",
threshold: 512,
validICCID: "898600000000002",
invalidICCID: "898600000000001",
wantReason: imsiMismatchReason,
mutate: func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string) {
seedConfigRunningDetail(t, ctx, db, batchNo, 1, "898600000000001", "13800000001", "460009999999999", true)
seedConfigRunningDetail(t, ctx, db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
},
},
{
name: "flow pool",
threshold: 512,
validICCID: "898600000000002",
invalidICCID: "898600000000001",
wantReason: flowPoolCardReason,
mutate: func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string) {
seedConfigRunningDetail(t, ctx, db, batchNo, 1, "898600000000001", "13800000001", "460001000000001", true)
seedConfigRunningDetail(t, ctx, db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024, IsFlowPool: 1})
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
},
},
{
name: "package total exceeded",
threshold: 2048,
validICCID: "898600000000002",
invalidICCID: "898600000000001",
wantReason: packageTotalExceededReason,
mutate: func(ctx context.Context, t *testing.T, db gdb.DB, batchNo string) {
seedConfigRunningDetail(t, ctx, db, batchNo, 1, "898600000000001", "13800000001", "460001000000001", true)
seedConfigRunningDetail(t, ctx, db, batchNo, 2, "898600000000002", "13800000002", "460001000000002", true)
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 2, PackageTotal: 1024})
seedConfigCard(t, ctx, db, cardSeed{ICCID: "898600000000002", MSISDN: "13800000002", IMSI: "460001000000002", BossStatus: 2, PackageStatus: 2, PackageTotal: 0})
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
repo := newConfigTestRepository(t)
batchNo := "TCC-41-" + tt.name
seedConfigProcessingBatch(t, ctx, repo.db, batchNo, tt.threshold)
tt.mutate(ctx, t, repo.db, batchNo)
if err := (&executor{repository: repo}).Execute(ctx, batchNo); err != nil {
t.Fatalf("Execute() error = %v", err)
}
assertConfigBatchMain(t, ctx, repo.db, batchNo, consts.BatchAsyncStatusPartialSuccess, consts.BatchRunResultPartialSuccess, 1, 1)
assertConfigDetailStatusCount(t, ctx, repo.db, batchNo, consts.BatchDetailStatusSuccess, 1)
assertConfigDetailStatusCount(t, ctx, repo.db, batchNo, consts.BatchDetailStatusFailed, 1)
assertAnyDetailReason(t, ctx, repo.db, batchNo, tt.wantReason)
assertConfigTrafficCutoff(t, ctx, repo.db, tt.validICCID, 1, tt.threshold, 7)
if tt.invalidICCID != "" {
assertConfigTrafficCutoff(t, ctx, repo.db, tt.invalidICCID, 0, 0, 0)
}
})
}
}
func TestExecuteDuplicateMessageDoesNotReapplyBusinessUpdate(t *testing.T) {
ctx := context.Background()
repo := newConfigTestRepository(t)
batchNo := "TCC-41-REPLAY"
seedConfigProcessingBatch(t, ctx, repo.db, batchNo, 512)
seedConfigRunningDetail(t, ctx, repo.db, batchNo, 1, "898600000000001", "13800000001", "460001000000001", true)
seedConfigCard(t, ctx, repo.db, cardSeed{ICCID: "898600000000001", MSISDN: "13800000001", IMSI: "460001000000001", BossStatus: 2, PackageStatus: 0, PackageTotal: 0})
exec := &executor{repository: repo}
if err := exec.Execute(ctx, batchNo); err != nil {
t.Fatalf("first Execute() error = %v", err)
}
assertConfigTrafficCutoff(t, ctx, repo.db, "898600000000001", 1, 512, 7)
if _, err := repo.db.Model(dao.TSimCardInfo.Table()).Ctx(ctx).
Where(dao.TSimCardInfo.Columns().Iccid, "898600000000001").
Data(do.TSimCardInfo{TrafficCutoffStatus: 0, TrafficCutoffThreshold: 0, UpdatedBy: 99}).
Update(); err != nil {
t.Fatalf("reset card after first execute: %v", err)
}
if err := exec.Execute(ctx, batchNo); err == nil {
t.Fatal("second Execute() error = nil, want non-nil for finalized duplicate message")
}
assertConfigBatchMain(t, ctx, repo.db, batchNo, consts.BatchAsyncStatusSuccess, consts.BatchRunResultSuccess, 1, 0)
assertConfigTrafficCutoff(t, ctx, repo.db, "898600000000001", 0, 0, 99)
}
type cardSeed struct {
ICCID string
MSISDN string
IMSI string
BossStatus int
PackageStatus int
PackageTotal float64
IsFlowPool int
}
func newConfigTestRepository(t *testing.T) *Repository {
t.Helper()
ctx := context.Background()
db, err := gdb.New(gdb.ConfigNode{
Type: "sqlite",
Link: "sqlite::@file(:memory:)",
})
if err != nil {
t.Fatalf("create sqlite database: %v", err)
}
statements := []string{
`CREATE TABLE batch_main (
source_channel TEXT NOT NULL DEFAULT 'legacy',
execution_mode INTEGER NOT NULL DEFAULT 0,
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_no TEXT NOT NULL,
batch_type INTEGER NOT NULL,
batch_async_status INTEGER NOT NULL,
run_result INTEGER NOT NULL DEFAULT 0,
total_count INTEGER NOT NULL DEFAULT 0,
valid_count INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
fail_count INTEGER NOT NULL DEFAULT 0,
fail_reason TEXT,
start_time DATETIME,
end_time DATETIME,
created_by INTEGER NOT NULL DEFAULT 0,
created_dept INTEGER NOT NULL DEFAULT 0,
tenant_id TEXT NOT NULL DEFAULT '',
batch_info TEXT,
updated_by INTEGER NOT NULL DEFAULT 0
)`,
`CREATE TABLE batch_detail (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_no TEXT NOT NULL,
batch_type INTEGER NOT NULL,
detail_status INTEGER NOT NULL,
error_reason TEXT,
snapshot TEXT,
item_id TEXT,
row_no INTEGER NOT NULL DEFAULT 0,
updated_by INTEGER NOT NULL DEFAULT 0
)`,
`CREATE TABLE t_sim_card_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
iccid TEXT NOT NULL,
msisdn TEXT,
imsi TEXT,
current_package_code TEXT,
package_status INTEGER NOT NULL DEFAULT 0,
boss_card_status INTEGER NOT NULL DEFAULT 0,
is_flow_pool INTEGER NOT NULL DEFAULT 0,
package_total_flow_mb REAL NOT NULL DEFAULT 0,
traffic_cutoff_status INTEGER NOT NULL DEFAULT 0,
traffic_cutoff_threshold REAL NOT NULL DEFAULT 0,
tenant_id TEXT NOT NULL DEFAULT '',
updated_by INTEGER NOT NULL DEFAULT 0
)`,
}
for _, statement := range statements {
if _, err = db.Exec(ctx, statement); err != nil {
t.Fatalf("create test schema: %v", err)
}
}
t.Cleanup(func() { _ = db.Close(ctx) })
return &Repository{db: db}
}
func seedConfigProcessingBatch(t *testing.T, ctx context.Context, db gdb.DB, batchNo string, threshold float64) {
t.Helper()
info := gjson.New(map[string]any{
"operation": "traffic_cutoff_config",
"trafficCutoffStatus": 1,
"trafficCutoffThreshold": threshold,
"thresholdUnit": "MB",
})
if _, err := db.Model(dao.BatchMain.Table()).Ctx(ctx).Data(do.BatchMain{
BatchNo: batchNo,
BatchType: consts.BatchTypeTrafficCutoffConfig,
BatchAsyncStatus: consts.BatchAsyncStatusProcessing,
RunResult: batchdomain.RunResultRunning,
CreatedBy: 7,
CreatedDept: testDeptID,
TenantId: testTenantID,
BatchInfo: info,
}).Insert(); err != nil {
t.Fatalf("insert batch main: %v", err)
}
}
func TestConfigFromBatchInfoValidatesThreeStateContract(t *testing.T) {
tests := []struct {
name string
info map[string]any
wantStatus int
wantErr bool
}{
{name: "unconfigured", info: map[string]any{"trafficCutoffStatus": 0, "trafficCutoffThreshold": 0}},
{name: "enabled", info: map[string]any{"trafficCutoffStatus": 1, "trafficCutoffThreshold": 1.125}, wantStatus: 1},
{name: "disabled with retained threshold", info: map[string]any{"trafficCutoffStatus": 2, "trafficCutoffThreshold": 1.125}, wantStatus: 2},
{name: "old field only", info: map[string]any{"trafficCutoffEnabled": 1, "trafficCutoffThreshold": 1}, wantErr: true},
{name: "unconfigured nonzero threshold", info: map[string]any{"trafficCutoffStatus": 0, "trafficCutoffThreshold": 1}, wantErr: true},
{name: "enabled zero threshold", info: map[string]any{"trafficCutoffStatus": 1, "trafficCutoffThreshold": 0}, wantErr: true},
{name: "negative threshold", info: map[string]any{"trafficCutoffStatus": 2, "trafficCutoffThreshold": -1}, wantErr: true},
{name: "too many decimals", info: map[string]any{"trafficCutoffStatus": 2, "trafficCutoffThreshold": 1.0001}, wantErr: true},
{name: "invalid status", info: map[string]any{"trafficCutoffStatus": 3, "trafficCutoffThreshold": 0}, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := configFromBatchInfo(gjson.New(tt.info))
if (err != nil) != tt.wantErr {
t.Fatalf("configFromBatchInfo() error = %v, wantErr %v", err, tt.wantErr)
}
if got.TrafficCutoffStatus != tt.wantStatus {
t.Fatalf("configFromBatchInfo() status = %d, want %d", got.TrafficCutoffStatus, tt.wantStatus)
}
})
}
}
func seedConfigRunningDetail(t *testing.T, ctx context.Context, db gdb.DB, batchNo string, rowNo int, iccid, msisdn, imsi string, authorized bool) {
t.Helper()
snapshot := gjson.New(map[string]any{
"ICCID": iccid,
"MSISDN": msisdn,
"IMSI": imsi,
"authorized": authorized,
})
if _, err := db.Model(dao.BatchDetail.Table()).Ctx(ctx).Data(do.BatchDetail{
BatchNo: batchNo,
BatchType: consts.BatchTypeTrafficCutoffConfig,
DetailStatus: consts.BatchDetailStatusRunning,
RowNo: rowNo,
ItemId: iccid,
Snapshot: snapshot,
}).Insert(); err != nil {
t.Fatalf("insert batch detail: %v", err)
}
}
func seedConfigCard(t *testing.T, ctx context.Context, db gdb.DB, seed cardSeed) {
t.Helper()
if _, err := db.Model(dao.TSimCardInfo.Table()).Ctx(ctx).Data(do.TSimCardInfo{
Iccid: seed.ICCID,
Msisdn: seed.MSISDN,
Imsi: seed.IMSI,
CurrentPackageCode: "PKG-" + seed.ICCID,
PackageStatus: seed.PackageStatus,
BossCardStatus: seed.BossStatus,
IsFlowPool: seed.IsFlowPool,
PackageTotalFlowMb: seed.PackageTotal,
TrafficCutoffStatus: 0,
TrafficCutoffThreshold: 0,
TenantId: testTenantID,
}).Insert(); err != nil {
t.Fatalf("insert sim card: %v", err)
}
}
func assertConfigBatchMain(t *testing.T, ctx context.Context, db gdb.DB, batchNo string, wantAsync, wantRun, wantSuccess, wantFail int) {
t.Helper()
var row struct {
Async int `orm:"batch_async_status"`
Run int `orm:"run_result"`
Success int `orm:"success_count"`
Fail int `orm:"fail_count"`
}
if err := db.Model(dao.BatchMain.Table()).Ctx(ctx).
Where(dao.BatchMain.Columns().BatchNo, batchNo).
Fields(dao.BatchMain.Columns().BatchAsyncStatus, dao.BatchMain.Columns().RunResult, dao.BatchMain.Columns().SuccessCount, dao.BatchMain.Columns().FailCount).
Scan(&row); err != nil {
t.Fatalf("query batch main: %v", err)
}
if row.Async != wantAsync || row.Run != wantRun || row.Success != wantSuccess || row.Fail != wantFail {
t.Fatalf("batch main = %+v, want async=%d run=%d success=%d fail=%d", row, wantAsync, wantRun, wantSuccess, wantFail)
}
}
func assertConfigDetailStatusCount(t *testing.T, ctx context.Context, db gdb.DB, batchNo string, status, want int) {
t.Helper()
count, err := db.Model(dao.BatchDetail.Table()).Ctx(ctx).
Where(dao.BatchDetail.Columns().BatchNo, batchNo).
Where(dao.BatchDetail.Columns().DetailStatus, status).
Count()
if err != nil {
t.Fatalf("count details: %v", err)
}
if count != want {
t.Fatalf("detail status %d count = %d, want %d", status, count, want)
}
}
func assertConfigTrafficCutoff(t *testing.T, ctx context.Context, db gdb.DB, iccid string, enabled int, threshold float64, updatedBy int64) {
t.Helper()
var row struct {
Enabled int `orm:"traffic_cutoff_status"`
Threshold float64 `orm:"traffic_cutoff_threshold"`
UpdatedBy int64 `orm:"updated_by"`
}
if err := db.Model(dao.TSimCardInfo.Table()).Ctx(ctx).
Where(dao.TSimCardInfo.Columns().Iccid, iccid).
Fields(dao.TSimCardInfo.Columns().TrafficCutoffStatus, dao.TSimCardInfo.Columns().TrafficCutoffThreshold, dao.TSimCardInfo.Columns().UpdatedBy).
Scan(&row); err != nil {
t.Fatalf("query traffic cutoff fields: %v", err)
}
if row.Enabled != enabled || row.Threshold != threshold || row.UpdatedBy != updatedBy {
t.Fatalf("%s cutoff = (%d, %v, updatedBy=%d), want (%d, %v, updatedBy=%d)", iccid, row.Enabled, row.Threshold, row.UpdatedBy, enabled, threshold, updatedBy)
}
}
func assertAllConfigTrafficCutoffUnchanged(t *testing.T, ctx context.Context, db gdb.DB) {
t.Helper()
count, err := db.Model(dao.TSimCardInfo.Table()).Ctx(ctx).
Where(dao.TSimCardInfo.Columns().TrafficCutoffStatus, 1).
Count()
if err != nil {
t.Fatalf("count updated cards: %v", err)
}
if count != 0 {
t.Fatalf("updated card count = %d, want 0", count)
}
}
func assertAnyDetailReason(t *testing.T, ctx context.Context, db gdb.DB, batchNo, want string) {
t.Helper()
count, err := db.Model(dao.BatchDetail.Table()).Ctx(ctx).
Where(dao.BatchDetail.Columns().BatchNo, batchNo).
Where(dao.BatchDetail.Columns().ErrorReason, want).
Count()
if err != nil {
t.Fatalf("count detail reason: %v", err)
}
if count == 0 {
t.Fatalf("detail reason %q count = 0, want at least 1", want)
}
}
func assertNoPartialSuccess(t *testing.T, ctx context.Context, db gdb.DB, batchNo string) {
t.Helper()
count, err := db.Model(dao.BatchMain.Table()).Ctx(ctx).
Where(dao.BatchMain.Columns().BatchNo, batchNo).
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusPartialSuccess).
Count()
if err != nil {
t.Fatalf("count partial success batch main: %v", err)
}
if count != 0 {
t.Fatalf("partial success batch count = %d, want 0", count)
}
}
@@ -0,0 +1,125 @@
package trafficcutoffconfig
import (
"strings"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/os/gtime"
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/service/batchresult"
)
type Batch struct {
ID int64
BatchNo string
BatchType int
TenantID string
CreatedDept int64
CreatedBy int64
StartTime *gtime.Time
BatchInfo *gjson.Json
}
type Config struct {
TrafficCutoffCrossMonthHold int
TrafficCutoffStatus int
TrafficCutoffThreshold float64
}
type Card struct {
ID int64
ICCID string
MSISDN string
IMSI string
CurrentPackageCode string
PackageStatus int
BossCardStatus int
IsFlowPool int
PackageTotalFlowMb float64
TrafficCutoffStatus int
TrafficCutoffThreshold float64
}
type Detail struct {
ID int64
RowNo int
ICCID string
MSISDN string
IMSI string
Authorized bool
Card *Card
Reason string
}
type Task struct {
Batch Batch
Config Config
Details []*Detail
FailureReason string
}
func (d *Detail) Success() bool {
return d != nil && strings.TrimSpace(d.Reason) == ""
}
func (d *Detail) DisplayCode() string {
if d == nil {
return ""
}
if d.Card != nil && strings.TrimSpace(d.Card.ICCID) != "" {
return strings.TrimSpace(d.Card.ICCID)
}
return strings.TrimSpace(d.ICCID)
}
func (d *Detail) Snapshot(config Config) *gjson.Json {
if d == nil {
return gjson.New(nil)
}
data := map[string]any{
"rowNo": d.RowNo,
"ICCID": d.ICCID,
"MSISDN": d.MSISDN,
"IMSI": d.IMSI,
"authorized": d.Authorized,
"trafficCutoffStatusAfter": config.TrafficCutoffStatus,
"trafficCutoffThresholdAfter": config.TrafficCutoffThreshold,
"trafficCutoffCrossMonthHoldAfter": config.TrafficCutoffCrossMonthHold,
"thresholdUnit": "MB",
"errorReason": d.Reason,
}
if d.Card != nil {
data["cardId"] = d.Card.ID
data["cardIccid"] = d.Card.ICCID
data["cardMsisdn"] = d.Card.MSISDN
data["cardImsi"] = d.Card.IMSI
data["currentPackageCode"] = d.Card.CurrentPackageCode
data["packageStatus"] = d.Card.PackageStatus
data["bossCardStatus"] = d.Card.BossCardStatus
data["isFlowPool"] = d.Card.IsFlowPool
data["packageTotalFlowMb"] = d.Card.PackageTotalFlowMb
data["trafficCutoffStatusBefore"] = d.Card.TrafficCutoffStatus
data["trafficCutoffThresholdBefore"] = d.Card.TrafficCutoffThreshold
}
return gjson.New(data)
}
func (t *Task) ResultRows() []batchresult.Row {
rows := make([]batchresult.Row, 0, len(t.Details))
for _, detail := range t.Details {
if detail == nil {
continue
}
rows = append(rows, batchresult.Row{
RowNo: detail.RowNo,
ObjectCode: detail.DisplayCode(),
ICCID: detail.ICCID,
MSISDN: detail.MSISDN,
IMSI: detail.IMSI,
Operation: "达量断网配置",
Success: detail.Success(),
Reason: detail.Reason,
})
}
return rows
}