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) } }