chore: 并入 iotlcm-worker-svr 历史到 worker-svr/(原提交 96f0f4e)
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/encoding/gjson"
|
||||
)
|
||||
|
||||
func TestPreferredLifecycleChanKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
appBatch bool
|
||||
snapshot string
|
||||
card string
|
||||
want string
|
||||
}{
|
||||
{name: "app resolved snapshot wins", appBatch: true, snapshot: " legacy-129 ", card: "stale-1", want: "legacy-129"},
|
||||
{name: "console keeps card channel", snapshot: "legacy-129", card: " card-112 ", want: "card-112"},
|
||||
{name: "card fallback", card: " card-112 ", want: "card-112"},
|
||||
{name: "empty", want: ""},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := preferredLifecycleChanKey(test.appBatch, test.snapshot, test.card); got != test.want {
|
||||
t.Fatalf("preferredLifecycleChanKey() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppBatchUsesSnapshotChannel(t *testing.T) {
|
||||
if !appBatchUsesSnapshotChannel(gjson.New(map[string]any{"source": "APP"})) {
|
||||
t.Fatal("app batch should use the resolved snapshot channel")
|
||||
}
|
||||
if appBatchUsesSnapshotChannel(gjson.New(map[string]any{"source": "console"})) {
|
||||
t.Fatal("console batch must continue using the current card channel")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/model/entity"
|
||||
lifecycle "git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/service/lifecycle"
|
||||
)
|
||||
|
||||
// batchFailureSummary 生成中文失败汇总,替代原先的英文「N SIM cards failed」。
|
||||
// 形如:共50张,成功28张,失败22张;主要失败原因:当前卡状态不支持该操作
|
||||
func batchFailureSummary(total, success, fail int, reasons []string) string {
|
||||
var builder strings.Builder
|
||||
fmt.Fprintf(&builder, "共%d张,成功%d张,失败%d张", total, success, fail)
|
||||
if reason := dominantReason(reasons); reason != "" {
|
||||
builder.WriteString(";主要失败原因:")
|
||||
builder.WriteString(reason)
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// dominantReason 取出现次数最多的失败原因;次数相同时按字典序,保证结果稳定可测。
|
||||
func dominantReason(reasons []string) string {
|
||||
counts := make(map[string]int, len(reasons))
|
||||
for _, reason := range reasons {
|
||||
trimmed := strings.TrimSpace(reason)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
counts[trimmed]++
|
||||
}
|
||||
if len(counts) == 0 {
|
||||
return ""
|
||||
}
|
||||
keys := make([]string, 0, len(counts))
|
||||
for key := range counts {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if counts[keys[i]] != counts[keys[j]] {
|
||||
return counts[keys[i]] > counts[keys[j]]
|
||||
}
|
||||
return keys[i] < keys[j]
|
||||
})
|
||||
return keys[0]
|
||||
}
|
||||
|
||||
// lifecycleFailureSummary 依据内存中的任务明细生成汇总。
|
||||
func lifecycleFailureSummary(details []*lifecycle.Detail, success, fail int) string {
|
||||
reasons := make([]string, 0, fail)
|
||||
for _, detail := range details {
|
||||
if detail != nil && strings.TrimSpace(detail.Reason) != "" {
|
||||
reasons = append(reasons, detail.Reason)
|
||||
}
|
||||
}
|
||||
return batchFailureSummary(len(details), success, fail, reasons)
|
||||
}
|
||||
|
||||
// storedFailureSummary 依据已落库的批次明细生成汇总(重启批次的复机阶段使用)。
|
||||
func storedFailureSummary(details []*entity.BatchDetail, success, fail int) string {
|
||||
reasons := make([]string, 0, fail)
|
||||
for _, detail := range details {
|
||||
if detail != nil && strings.TrimSpace(detail.ErrorReason) != "" {
|
||||
reasons = append(reasons, detail.ErrorReason)
|
||||
}
|
||||
}
|
||||
return batchFailureSummary(len(details), success, fail, reasons)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/model/entity"
|
||||
lifecycle "git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/service/lifecycle"
|
||||
)
|
||||
|
||||
// TestBatchFailureSummaryUsesChineseAndCounts 固化用户要求的失败文案:
|
||||
// 必须是中文、带成功失败张数,并附带最主要的失败原因。
|
||||
func TestBatchFailureSummaryUsesChineseAndCounts(t *testing.T) {
|
||||
got := batchFailureSummary(50, 28, 22, []string{
|
||||
"当前卡状态不支持该操作",
|
||||
"当前卡状态不支持该操作",
|
||||
"请求上游超时",
|
||||
})
|
||||
want := "共50张,成功28张,失败22张;主要失败原因:当前卡状态不支持该操作"
|
||||
if got != want {
|
||||
t.Fatalf("失败汇总=%q,期望%q", got, want)
|
||||
}
|
||||
if strings.Contains(got, "SIM cards failed") {
|
||||
t.Fatal("仍包含英文文案")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchFailureSummaryWithoutReason 覆盖没有具体原因的情况,不能拼出空的原因段。
|
||||
func TestBatchFailureSummaryWithoutReason(t *testing.T) {
|
||||
if got := batchFailureSummary(3, 1, 2, nil); got != "共3张,成功1张,失败2张" {
|
||||
t.Fatalf("无原因时=%q", got)
|
||||
}
|
||||
if got := batchFailureSummary(3, 1, 2, []string{"", " "}); got != "共3张,成功1张,失败2张" {
|
||||
t.Fatalf("空白原因应被忽略,实际=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDominantReasonStableOnTie 同频时按字节序取最小值,保证同一批次文案稳定。
|
||||
// 注意这里是字节序而非拼音序:「乙」的 UTF-8 编码小于「甲」,所以同频时取「乙原因」。
|
||||
func TestDominantReasonStableOnTie(t *testing.T) {
|
||||
if got := dominantReason([]string{"甲原因", "乙原因"}); got != "乙原因" {
|
||||
t.Fatalf("同频应按字节序取最小,实际=%q", got)
|
||||
}
|
||||
if got := dominantReason([]string{"少数", "多数", "多数"}); got != "多数" {
|
||||
t.Fatalf("应取出现次数最多,实际=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStoredFailureSummarySkipsNilAndEmpty 覆盖重启复机阶段:落库明细里的空原因与空指针不能参与统计。
|
||||
func TestStoredFailureSummarySkipsNilAndEmpty(t *testing.T) {
|
||||
details := []*entity.BatchDetail{
|
||||
{DetailStatus: 2},
|
||||
nil,
|
||||
{DetailStatus: 3, ErrorReason: "当前卡状态不支持该操作"},
|
||||
{DetailStatus: 3, ErrorReason: ""},
|
||||
}
|
||||
got := storedFailureSummary(details, 1, 2)
|
||||
if !strings.HasPrefix(got, "共4张,成功1张,失败2张") || !strings.Contains(got, "当前卡状态不支持该操作") {
|
||||
t.Fatalf("落库汇总=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLifecycleFailureSummaryUsesDetailReason 覆盖停复机首阶段:内存明细的 Reason 作为主要失败原因。
|
||||
func TestLifecycleFailureSummaryUsesDetailReason(t *testing.T) {
|
||||
details := []*lifecycle.Detail{
|
||||
{Reason: ""},
|
||||
{Reason: "停机或预销户卡,不能办理该业务"},
|
||||
}
|
||||
got := lifecycleFailureSummary(details, 1, 1)
|
||||
if got != "共2张,成功1张,失败1张;主要失败原因:停机或预销户卡,不能办理该业务" {
|
||||
t.Fatalf("首阶段汇总=%q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"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"
|
||||
lifecycle "git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/service/lifecycle"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db gdb.DB
|
||||
resultFiles batchresult.Generator
|
||||
}
|
||||
|
||||
func New() *Repository {
|
||||
return &Repository{resultFiles: batchresult.New()}
|
||||
}
|
||||
|
||||
func (r *Repository) database() gdb.DB {
|
||||
if r.db != nil {
|
||||
return r.db
|
||||
}
|
||||
return g.DB()
|
||||
}
|
||||
|
||||
func (r *Repository) Load(ctx context.Context, batchNo string) (*lifecycle.Task, error) {
|
||||
if batchNo == "" {
|
||||
return nil, gerror.New("lifecycle batch number is empty")
|
||||
}
|
||||
batch := entity.BatchMain{}
|
||||
if err := r.database().Model(dao.BatchMain.Table()).Safe().Ctx(ctx).
|
||||
Where(dao.BatchMain.Columns().BatchNo, batchNo).
|
||||
WhereIn(dao.BatchMain.Columns().BatchType, []int{consts.BatchTypeSimCardStart, consts.BatchTypeSimCardStop}).
|
||||
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Scan(&batch); err != nil {
|
||||
return nil, gerror.Wrap(err, "query lifecycle batch")
|
||||
}
|
||||
if batch.Id == 0 {
|
||||
return nil, gerror.New("processing lifecycle batch does not exist")
|
||||
}
|
||||
operation, err := lifecycle.OperationByBatchType(batch.BatchType)
|
||||
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, batch.BatchType).
|
||||
Where(dao.BatchDetail.Columns().DetailStatus, consts.BatchDetailStatusRunning).
|
||||
OrderAsc(dao.BatchDetail.Columns().RowNo).
|
||||
Scan(&batchDetails); err != nil {
|
||||
return nil, gerror.Wrap(err, "query running lifecycle details")
|
||||
}
|
||||
if len(batchDetails) == 0 {
|
||||
return nil, gerror.New("lifecycle batch has no running details")
|
||||
}
|
||||
|
||||
task := &lifecycle.Task{
|
||||
Batch: lifecycle.Batch{
|
||||
ID: batch.Id,
|
||||
BatchNo: batch.BatchNo,
|
||||
BatchType: batch.BatchType,
|
||||
TenantID: batch.TenantId,
|
||||
CreatedBy: batch.CreatedBy,
|
||||
CreatedDept: batch.CreatedDept,
|
||||
StartTime: batch.StartTime,
|
||||
BatchInfo: batch.BatchInfo,
|
||||
},
|
||||
Operation: operation,
|
||||
Details: make([]*lifecycle.Detail, 0, len(batchDetails)),
|
||||
}
|
||||
for _, batchDetail := range batchDetails {
|
||||
if batchDetail == nil {
|
||||
continue
|
||||
}
|
||||
detail := &lifecycle.Detail{
|
||||
ID: batchDetail.Id,
|
||||
RowNo: batchDetail.RowNo,
|
||||
ICCID: strings.TrimSpace(batchDetail.ItemId),
|
||||
Reason: strings.TrimSpace(batchDetail.ErrorReason),
|
||||
OriginalSnapshot: batchDetail.Snapshot,
|
||||
}
|
||||
if batchDetail.Snapshot != nil {
|
||||
if value := strings.TrimSpace(batchDetail.Snapshot.Get("ICCID").String()); value != "" {
|
||||
detail.ICCID = value
|
||||
}
|
||||
detail.InputMSISDN = strings.TrimSpace(batchDetail.Snapshot.Get("MSISDN").String())
|
||||
detail.InputIMSI = strings.TrimSpace(batchDetail.Snapshot.Get("IMSI").String())
|
||||
detail.MSISDN = detail.InputMSISDN
|
||||
detail.IMSI = detail.InputIMSI
|
||||
detail.Authorized = batchDetail.Snapshot.Get("authorized").Bool()
|
||||
detail.ChanKey = strings.TrimSpace(batchDetail.Snapshot.Get("chanKey").String())
|
||||
}
|
||||
task.Details = append(task.Details, detail)
|
||||
}
|
||||
if len(task.Details) == 0 {
|
||||
return nil, gerror.New("lifecycle batch has no readable running details")
|
||||
}
|
||||
if err = r.loadCards(ctx, task); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return task, nil
|
||||
}
|
||||
|
||||
func (r *Repository) loadCards(ctx context.Context, task *lifecycle.Task) error {
|
||||
iccids := make([]string, 0, len(task.Details))
|
||||
for _, detail := range task.Details {
|
||||
if detail != nil && detail.ICCID != "" {
|
||||
iccids = append(iccids, detail.ICCID)
|
||||
}
|
||||
}
|
||||
if len(iccids) == 0 {
|
||||
return nil
|
||||
}
|
||||
var cards []*entity.TSimCardInfo
|
||||
if err := r.database().Model(dao.TSimCardInfo.Table()).Safe().Ctx(ctx).
|
||||
Where(dao.TSimCardInfo.Columns().TenantId, task.Batch.TenantID).
|
||||
WhereIn(dao.TSimCardInfo.Columns().Iccid, iccids).
|
||||
Scan(&cards); err != nil {
|
||||
return gerror.Wrap(err, "query lifecycle SIM cards")
|
||||
}
|
||||
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 {
|
||||
card := byICCID[detail.ICCID]
|
||||
if card == nil {
|
||||
continue
|
||||
}
|
||||
detail.Card = &lifecycle.Card{
|
||||
ID: card.Id,
|
||||
ICCID: strings.TrimSpace(card.Iccid),
|
||||
MSISDN: strings.TrimSpace(card.Msisdn),
|
||||
IMSI: strings.TrimSpace(card.Imsi),
|
||||
ChanKey: preferredLifecycleChanKey(appBatchUsesSnapshotChannel(task.Batch.BatchInfo), detail.ChanKey, card.ChanKey),
|
||||
BossCardStatus: card.BossCardStatus,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func preferredLifecycleChanKey(useSnapshot bool, snapshotChanKey string, cardChanKey string) string {
|
||||
if useSnapshot {
|
||||
if value := strings.TrimSpace(snapshotChanKey); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(cardChanKey)
|
||||
}
|
||||
|
||||
func appBatchUsesSnapshotChannel(info *gjson.Json) bool {
|
||||
if info == nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSpace(info.Get("source").String()), "app")
|
||||
}
|
||||
|
||||
func (r *Repository) SaveValidationFailure(ctx context.Context, task *lifecycle.Task) error {
|
||||
return r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
||||
for _, detail := range task.Details {
|
||||
if detail == nil {
|
||||
continue
|
||||
}
|
||||
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().DetailStatus, consts.BatchDetailStatusRunning).
|
||||
Data(do.BatchDetail{
|
||||
DetailStatus: consts.BatchDetailStatusFailed,
|
||||
ErrorReason: detail.Reason,
|
||||
Snapshot: detail.Snapshot(),
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.Newf("lifecycle detail %d is no longer running", detail.ID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) SaveResult(ctx context.Context, task *lifecycle.Task, detail *lifecycle.Detail, outcome lifecycle.Outcome) (lifecycle.Outcome, error) {
|
||||
if detail == nil {
|
||||
return lifecycle.Outcome{}, gerror.New("lifecycle detail is nil")
|
||||
}
|
||||
resolved := outcome
|
||||
err := r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
||||
if resolved.Success {
|
||||
if detail.Card == nil {
|
||||
resolved.Success = false
|
||||
resolved.Message = "卡记录不存在,未办理"
|
||||
} else {
|
||||
result, err := tx.Ctx(ctx).Model(dao.TSimCardInfo.Table()).
|
||||
Where(dao.TSimCardInfo.Columns().Id, detail.Card.ID).
|
||||
Where(dao.TSimCardInfo.Columns().TenantId, task.Batch.TenantID).
|
||||
Where(dao.TSimCardInfo.Columns().BossCardStatus, detail.StatusBefore).
|
||||
Data(do.TSimCardInfo{
|
||||
BossCardStatus: task.Operation.TargetStatus,
|
||||
StatusSyncTime: gtime.Now(),
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
resolved.Success = false
|
||||
resolved.Message = "卡本地状态已变更"
|
||||
}
|
||||
}
|
||||
}
|
||||
detail.ApplyOutcome(resolved)
|
||||
detailStatus := consts.BatchDetailStatusFailed
|
||||
if resolved.Success {
|
||||
detailStatus = 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().DetailStatus, consts.BatchDetailStatusRunning).
|
||||
Data(do.BatchDetail{
|
||||
DetailStatus: detailStatus,
|
||||
ErrorCode: strconv.Itoa(resolved.Code),
|
||||
ErrorReason: detail.Reason,
|
||||
Snapshot: detail.Snapshot(),
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.Newf("lifecycle detail %d is no longer running", detail.ID)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return resolved, err
|
||||
}
|
||||
|
||||
func (r *Repository) Finalize(ctx context.Context, task *lifecycle.Task) error {
|
||||
successCount := 0
|
||||
for _, detail := range task.Details {
|
||||
if detail != nil && detail.Reason == "" {
|
||||
successCount++
|
||||
}
|
||||
}
|
||||
failCount := len(task.Details) - successCount
|
||||
batchAsyncStatus, runResult := batchResult(successCount, failCount)
|
||||
if task.FailureReason == "" && failCount > 0 {
|
||||
task.FailureReason = lifecycleFailureSummary(task.Details, successCount, failCount)
|
||||
}
|
||||
validCount := 0
|
||||
if task.ValidationOK {
|
||||
validCount = len(task.Details)
|
||||
}
|
||||
artifact, err := r.artifactGenerator().Create(ctx, artifactRequest(task))
|
||||
if err != nil {
|
||||
return gerror.Wrap(err, "generate lifecycle result file")
|
||||
}
|
||||
now := gtime.Now()
|
||||
err = r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) 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 gerror.Wrap(err, "insert lifecycle result 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: task.Batch.BatchType,
|
||||
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 gerror.Wrap(err, "insert lifecycle result download")
|
||||
}
|
||||
result, err := tx.Ctx(ctx).Model(dao.BatchMain.Table()).
|
||||
Where(dao.BatchMain.Columns().BatchNo, task.Batch.BatchNo).
|
||||
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Data(do.BatchMain{
|
||||
BatchAsyncStatus: batchAsyncStatus,
|
||||
ValidCount: validCount,
|
||||
SuccessCount: successCount,
|
||||
FailCount: failCount,
|
||||
RunResult: runResult,
|
||||
FailReason: task.FailureReason,
|
||||
ResultOssId: lifecycleOssIDValue(ossID),
|
||||
BatchInfo: buildBatchInfo(task, ossID, downloadID),
|
||||
EndTime: now,
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.New("lifecycle batch is no longer processing")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
batchresult.RemoveLocalFile(artifact)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) artifactGenerator() batchresult.Generator {
|
||||
if r.resultFiles != nil {
|
||||
return r.resultFiles
|
||||
}
|
||||
return batchresult.New()
|
||||
}
|
||||
|
||||
func artifactRequest(task *lifecycle.Task) batchresult.Request {
|
||||
rows := make([]batchresult.Row, 0, len(task.Details))
|
||||
for _, detail := range task.Details {
|
||||
if detail == nil {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, batchresult.Row{
|
||||
RowNo: detail.RowNo,
|
||||
ICCID: detail.ICCID,
|
||||
MSISDN: detail.MSISDN,
|
||||
IMSI: detail.IMSI,
|
||||
Success: detail.Reason == "",
|
||||
Reason: detail.Reason,
|
||||
UpstreamCode: detail.UpstreamCode,
|
||||
OrderNum: detail.OrderNum,
|
||||
})
|
||||
}
|
||||
return batchresult.Request{BatchNo: task.Batch.BatchNo, BatchType: task.Batch.BatchType, TenantID: task.Batch.TenantID, Rows: rows}
|
||||
}
|
||||
|
||||
func buildBatchInfo(task *lifecycle.Task, ossID, downloadID int64) *gjson.Json {
|
||||
info := make(map[string]any)
|
||||
if task.Batch.BatchInfo != nil {
|
||||
for key, value := range task.Batch.BatchInfo.Map() {
|
||||
info[key] = value
|
||||
}
|
||||
}
|
||||
operation := "start"
|
||||
if task.Batch.BatchType == consts.BatchTypeSimCardStop {
|
||||
operation = "stop"
|
||||
}
|
||||
info["operation"] = operation
|
||||
info["operType"] = task.Operation.OperType
|
||||
info["resultFileOssId"] = ossID
|
||||
info["resultDownloadId"] = downloadID
|
||||
return gjson.New(info)
|
||||
}
|
||||
|
||||
func lifecycleOssIDValue(ossID int64) any {
|
||||
if ossID <= 0 {
|
||||
return nil
|
||||
}
|
||||
return ossID
|
||||
}
|
||||
|
||||
func batchResult(successCount, failCount int) (int, int) {
|
||||
switch {
|
||||
case failCount == 0:
|
||||
return consts.BatchAsyncStatusSuccess, consts.BatchRunResultSuccess
|
||||
case successCount == 0:
|
||||
return consts.BatchAsyncStatusFailed, consts.BatchRunResultFailed
|
||||
default:
|
||||
return consts.BatchAsyncStatusPartialSuccess, consts.BatchRunResultPartialSuccess
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"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/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"
|
||||
lifecycle "git.5iot.com/iotlcm-public/iotlcm-worker-svr/internal/service/lifecycle"
|
||||
)
|
||||
|
||||
func (r *Repository) FindRestartMain(ctx context.Context, batchNo string) (*entity.BatchMain, error) {
|
||||
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.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Scan(&main); err != nil {
|
||||
return nil, gerror.Wrap(err, "query restart batch main")
|
||||
}
|
||||
return main, nil
|
||||
}
|
||||
|
||||
func (r *Repository) LoadRestartStop(ctx context.Context, batchNo string) (*lifecycle.Task, error) {
|
||||
return r.loadRestartTask(ctx, batchNo, consts.BatchDetailStatusRunning, lifecycle.Operation{
|
||||
BatchType: consts.BatchTypeSimCardRestart,
|
||||
OperType: consts.SimCardStatusOperTypeStop,
|
||||
ExpectedStatus: consts.SimBossCardStatusActivated,
|
||||
TargetStatus: consts.SimBossCardStatusStopped,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) LoadRestartResume(ctx context.Context, batchNo string) (*lifecycle.Task, error) {
|
||||
return r.loadRestartTask(ctx, batchNo, consts.BatchDetailStatusRunning, lifecycle.Operation{
|
||||
BatchType: consts.BatchTypeSimCardRestart,
|
||||
OperType: consts.SimCardStatusOperTypeStart,
|
||||
ExpectedStatus: consts.SimBossCardStatusStopped,
|
||||
TargetStatus: consts.SimBossCardStatusActivated,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) loadRestartTask(ctx context.Context, batchNo string, detailStatus int, operation lifecycle.Operation) (*lifecycle.Task, error) {
|
||||
if batchNo == "" {
|
||||
return nil, gerror.New("restart batch number is empty")
|
||||
}
|
||||
batch := 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.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Scan(&batch); err != nil {
|
||||
return nil, gerror.Wrap(err, "query restart batch")
|
||||
}
|
||||
if batch.Id == 0 {
|
||||
return nil, gerror.New("processing restart batch does not exist")
|
||||
}
|
||||
|
||||
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.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchDetail.Columns().DetailStatus, detailStatus).
|
||||
OrderAsc(dao.BatchDetail.Columns().RowNo).
|
||||
Scan(&batchDetails); err != nil {
|
||||
return nil, gerror.Wrap(err, "query restart details")
|
||||
}
|
||||
if len(batchDetails) == 0 {
|
||||
return nil, gerror.New("restart batch has no runnable details")
|
||||
}
|
||||
|
||||
task := &lifecycle.Task{
|
||||
Batch: lifecycle.Batch{
|
||||
ID: batch.Id,
|
||||
BatchNo: batch.BatchNo,
|
||||
BatchType: batch.BatchType,
|
||||
TenantID: batch.TenantId,
|
||||
CreatedBy: batch.CreatedBy,
|
||||
CreatedDept: batch.CreatedDept,
|
||||
StartTime: batch.StartTime,
|
||||
BatchInfo: batch.BatchInfo,
|
||||
},
|
||||
Operation: operation,
|
||||
Details: make([]*lifecycle.Detail, 0, len(batchDetails)),
|
||||
}
|
||||
for _, batchDetail := range batchDetails {
|
||||
if batchDetail == nil {
|
||||
continue
|
||||
}
|
||||
task.Details = append(task.Details, restartDetail(batchDetail))
|
||||
}
|
||||
if len(task.Details) == 0 {
|
||||
return nil, gerror.New("restart batch has no readable details")
|
||||
}
|
||||
if err := r.loadCards(ctx, task); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return task, nil
|
||||
}
|
||||
|
||||
func restartDetail(batchDetail *entity.BatchDetail) *lifecycle.Detail {
|
||||
detail := &lifecycle.Detail{
|
||||
ID: batchDetail.Id,
|
||||
RowNo: batchDetail.RowNo,
|
||||
ICCID: strings.TrimSpace(batchDetail.ItemId),
|
||||
Reason: strings.TrimSpace(batchDetail.ErrorReason),
|
||||
OriginalSnapshot: batchDetail.Snapshot,
|
||||
}
|
||||
if batchDetail.Snapshot != nil {
|
||||
if value := strings.TrimSpace(batchDetail.Snapshot.Get("ICCID").String()); value != "" {
|
||||
detail.ICCID = value
|
||||
}
|
||||
detail.InputMSISDN = strings.TrimSpace(batchDetail.Snapshot.Get("MSISDN").String())
|
||||
detail.InputIMSI = strings.TrimSpace(batchDetail.Snapshot.Get("IMSI").String())
|
||||
detail.MSISDN = detail.InputMSISDN
|
||||
detail.IMSI = detail.InputIMSI
|
||||
detail.Authorized = batchDetail.Snapshot.Get("authorized").Bool()
|
||||
detail.ChanKey = strings.TrimSpace(batchDetail.Snapshot.Get("chanKey").String())
|
||||
}
|
||||
return detail
|
||||
}
|
||||
|
||||
func (r *Repository) SaveRestartValidationFailure(ctx context.Context, task *lifecycle.Task, stage string) error {
|
||||
return r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
||||
for _, detail := range task.Details {
|
||||
if detail == nil {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(detail.Reason) == "" {
|
||||
detail.Reason = "重启校验未通过,未发起上游请求"
|
||||
}
|
||||
outcome := lifecycle.Outcome{Message: detail.Reason}
|
||||
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.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchDetail.Columns().DetailStatus, consts.BatchDetailStatusRunning).
|
||||
Data(do.BatchDetail{
|
||||
DetailStatus: consts.BatchDetailStatusFailed,
|
||||
ErrorCode: strconv.Itoa(outcome.Code),
|
||||
ErrorReason: detail.Reason,
|
||||
Snapshot: restartSnapshot(task, detail, outcome, stage, gtime.Now()),
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.Newf("restart detail %d is no longer running", detail.ID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) SaveRestartResult(ctx context.Context, task *lifecycle.Task, detail *lifecycle.Detail, outcome lifecycle.Outcome, stage string) (lifecycle.Outcome, error) {
|
||||
if detail == nil {
|
||||
return lifecycle.Outcome{}, gerror.New("restart detail is nil")
|
||||
}
|
||||
resolved := outcome
|
||||
now := gtime.Now()
|
||||
err := r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
||||
if resolved.Success {
|
||||
if detail.Card == nil {
|
||||
resolved.Success = false
|
||||
resolved.Message = "卡记录不存在,未办理"
|
||||
} else {
|
||||
result, err := tx.Ctx(ctx).Model(dao.TSimCardInfo.Table()).
|
||||
Where(dao.TSimCardInfo.Columns().Id, detail.Card.ID).
|
||||
Where(dao.TSimCardInfo.Columns().TenantId, task.Batch.TenantID).
|
||||
Where(dao.TSimCardInfo.Columns().BossCardStatus, detail.StatusBefore).
|
||||
Data(do.TSimCardInfo{
|
||||
BossCardStatus: task.Operation.TargetStatus,
|
||||
StatusSyncTime: now,
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
resolved.Success = false
|
||||
resolved.Message = "卡本地状态已变更"
|
||||
}
|
||||
}
|
||||
}
|
||||
detail.ApplyOutcome(resolved)
|
||||
detailStatus := consts.BatchDetailStatusFailed
|
||||
if resolved.Success {
|
||||
detailStatus = 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.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchDetail.Columns().DetailStatus, consts.BatchDetailStatusRunning).
|
||||
Data(do.BatchDetail{
|
||||
DetailStatus: detailStatus,
|
||||
ErrorCode: strconv.Itoa(resolved.Code),
|
||||
ErrorReason: detail.Reason,
|
||||
Snapshot: restartSnapshot(task, detail, resolved, stage, now),
|
||||
UpdatedBy: task.Batch.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.Newf("restart detail %d is no longer running", detail.ID)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return resolved, err
|
||||
}
|
||||
|
||||
func (r *Repository) WaitRestartResume(ctx context.Context, task *lifecycle.Task, resumeAt *gtime.Time) error {
|
||||
info := buildRestartBatchInfo(task.Batch.BatchInfo)
|
||||
restart := restartInfo(info)
|
||||
restart["phase"] = consts.RestartPhaseWaitingResume
|
||||
restart["stopCompletedAt"] = gtime.Now().String()
|
||||
restart["resumeAt"] = resumeAt.String()
|
||||
restart["validationOK"] = true
|
||||
info = setRestartInfo(info, restart)
|
||||
return r.updateRestartInfo(ctx, task.Batch.BatchNo, info, task.Batch.CreatedBy)
|
||||
}
|
||||
|
||||
func (r *Repository) ClaimRestartResume(ctx context.Context, batchNo string, now *gtime.Time) (claimed bool, err error) {
|
||||
main, err := r.FindRestartMain(ctx, batchNo)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if main == nil || restartPhase(main.BatchInfo) != consts.RestartPhaseWaitingResume {
|
||||
return false, nil
|
||||
}
|
||||
resumeAt := restartResumeAt(main.BatchInfo)
|
||||
if resumeAt == nil || resumeAt.After(now) {
|
||||
return false, nil
|
||||
}
|
||||
info := buildRestartBatchInfo(main.BatchInfo)
|
||||
restart := restartInfo(info)
|
||||
restart["phase"] = consts.RestartPhaseResuming
|
||||
restart["resumeStartedAt"] = now.String()
|
||||
info = setRestartInfo(info, restart)
|
||||
|
||||
err = r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
||||
mainColumns := dao.BatchMain.Columns()
|
||||
result, updateErr := tx.Ctx(ctx).Model(dao.BatchMain.Table()).
|
||||
Where(mainColumns.BatchNo, batchNo).
|
||||
Where(mainColumns.BatchType, consts.BatchTypeSimCardRestart).
|
||||
Where(mainColumns.BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Where("JSON_UNQUOTE(JSON_EXTRACT("+mainColumns.BatchInfo+", '$.restart.phase')) = ?", consts.RestartPhaseWaitingResume).
|
||||
Data(do.BatchMain{
|
||||
BatchInfo: info,
|
||||
UpdatedBy: main.CreatedBy,
|
||||
}).Update()
|
||||
if updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
affected, affectedErr := result.RowsAffected()
|
||||
if affectedErr != nil {
|
||||
return affectedErr
|
||||
}
|
||||
if affected == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, updateErr = tx.Ctx(ctx).Model(dao.BatchDetail.Table()).
|
||||
Where(dao.BatchDetail.Columns().BatchNo, batchNo).
|
||||
Where(dao.BatchDetail.Columns().BatchType, consts.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchDetail.Columns().DetailStatus, consts.BatchDetailStatusSuccess).
|
||||
Data(do.BatchDetail{
|
||||
DetailStatus: consts.BatchDetailStatusRunning,
|
||||
UpdatedBy: main.CreatedBy,
|
||||
}).Update(); updateErr != nil {
|
||||
return updateErr
|
||||
}
|
||||
claimed = true
|
||||
return nil
|
||||
})
|
||||
return claimed, err
|
||||
}
|
||||
|
||||
func (r *Repository) FinalizeRestart(ctx context.Context, batchNo string) error {
|
||||
main, err := r.FindRestartMain(ctx, batchNo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if main == nil {
|
||||
return gerror.New("processing restart batch does not exist")
|
||||
}
|
||||
var details []*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.BatchTypeSimCardRestart).
|
||||
OrderAsc(dao.BatchDetail.Columns().RowNo).
|
||||
Scan(&details); err != nil {
|
||||
return gerror.Wrap(err, "query restart final details")
|
||||
}
|
||||
if len(details) == 0 {
|
||||
return gerror.New("restart batch has no final details")
|
||||
}
|
||||
|
||||
successCount := 0
|
||||
for _, detail := range details {
|
||||
if detail != nil && detail.DetailStatus == consts.BatchDetailStatusSuccess {
|
||||
successCount++
|
||||
}
|
||||
}
|
||||
failCount := len(details) - successCount
|
||||
batchAsyncStatus, runResult := batchResult(successCount, failCount)
|
||||
failReason := ""
|
||||
if failCount > 0 {
|
||||
failReason = storedFailureSummary(details, successCount, failCount)
|
||||
}
|
||||
validCount := 0
|
||||
if restartValidationOK(main.BatchInfo) {
|
||||
validCount = len(details)
|
||||
}
|
||||
|
||||
artifact, err := r.artifactGenerator().Create(ctx, restartArtifactRequest(main, details))
|
||||
if err != nil {
|
||||
return gerror.Wrap(err, "generate restart result file")
|
||||
}
|
||||
now := gtime.Now()
|
||||
err = r.database().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
||||
ossID, err := tx.Ctx(ctx).Model(dao.SysOss.Table()).Data(do.SysOss{
|
||||
TenantId: main.TenantId,
|
||||
FileName: artifact.FileName,
|
||||
OriginalName: artifact.OriginalName,
|
||||
FileSuffix: artifact.FileSuffix,
|
||||
Path: artifact.Path,
|
||||
Url: artifact.URL,
|
||||
CreatedDept: main.CreatedDept,
|
||||
CreatedBy: main.CreatedBy,
|
||||
UpdatedBy: main.CreatedBy,
|
||||
Service: "local",
|
||||
Md5: artifact.MD5,
|
||||
FileSize: artifact.Size,
|
||||
}).InsertAndGetId()
|
||||
if err != nil {
|
||||
return gerror.Wrap(err, "insert restart result OSS")
|
||||
}
|
||||
downloadID, err := tx.Ctx(ctx).Model(dao.TResourceBatchDownload.Table()).Data(do.TResourceBatchDownload{
|
||||
BatchNo: main.BatchNo,
|
||||
TaskName: batchresult.TaskName(consts.BatchTypeSimCardRestart),
|
||||
ResourceType: consts.ResourceTypeExcel,
|
||||
ExportScene: consts.BatchTypeSimCardRestart,
|
||||
TotalCount: len(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: main.CreatedDept,
|
||||
StartTime: main.StartTime,
|
||||
FinishTime: now,
|
||||
TenantId: main.TenantId,
|
||||
CreatedDept: main.CreatedDept,
|
||||
CreatedBy: main.CreatedBy,
|
||||
UpdatedBy: main.CreatedBy,
|
||||
}).InsertAndGetId()
|
||||
if err != nil {
|
||||
return gerror.Wrap(err, "insert restart result download")
|
||||
}
|
||||
result, err := tx.Ctx(ctx).Model(dao.BatchMain.Table()).
|
||||
Where(dao.BatchMain.Columns().BatchNo, main.BatchNo).
|
||||
Where(dao.BatchMain.Columns().BatchType, consts.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Data(do.BatchMain{
|
||||
BatchAsyncStatus: batchAsyncStatus,
|
||||
ValidCount: validCount,
|
||||
SuccessCount: successCount,
|
||||
FailCount: failCount,
|
||||
RunResult: runResult,
|
||||
FailReason: failReason,
|
||||
ResultOssId: lifecycleOssIDValue(ossID),
|
||||
BatchInfo: buildRestartFinishedInfo(main.BatchInfo, ossID, downloadID, now),
|
||||
EndTime: now,
|
||||
UpdatedBy: main.CreatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.New("restart batch is no longer processing")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
batchresult.RemoveLocalFile(artifact)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) updateRestartInfo(ctx context.Context, batchNo string, info *gjson.Json, updatedBy int64) error {
|
||||
result, err := r.database().Model(dao.BatchMain.Table()).Ctx(ctx).
|
||||
Where(dao.BatchMain.Columns().BatchNo, batchNo).
|
||||
Where(dao.BatchMain.Columns().BatchType, consts.BatchTypeSimCardRestart).
|
||||
Where(dao.BatchMain.Columns().BatchAsyncStatus, consts.BatchAsyncStatusProcessing).
|
||||
Data(do.BatchMain{
|
||||
BatchInfo: info,
|
||||
UpdatedBy: updatedBy,
|
||||
}).Update()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected != 1 {
|
||||
return gerror.New("restart batch info was not updated")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func restartArtifactRequest(main *entity.BatchMain, details []*entity.BatchDetail) batchresult.Request {
|
||||
rows := make([]batchresult.Row, 0, len(details))
|
||||
for _, detail := range details {
|
||||
if detail == nil {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, restartArtifactRow(detail))
|
||||
}
|
||||
return batchresult.Request{BatchNo: main.BatchNo, BatchType: consts.BatchTypeSimCardRestart, TenantID: main.TenantId, Rows: rows}
|
||||
}
|
||||
|
||||
func restartArtifactRow(detail *entity.BatchDetail) batchresult.Row {
|
||||
row := batchresult.Row{
|
||||
RowNo: detail.RowNo,
|
||||
ICCID: strings.TrimSpace(detail.ItemId),
|
||||
Success: detail.DetailStatus == consts.BatchDetailStatusSuccess,
|
||||
Reason: strings.TrimSpace(detail.ErrorReason),
|
||||
}
|
||||
if detail.Snapshot != nil {
|
||||
if value := strings.TrimSpace(detail.Snapshot.Get("ICCID").String()); value != "" {
|
||||
row.ICCID = value
|
||||
}
|
||||
row.MSISDN = strings.TrimSpace(detail.Snapshot.Get("MSISDN").String())
|
||||
row.IMSI = strings.TrimSpace(detail.Snapshot.Get("IMSI").String())
|
||||
row.OrderNum = strings.TrimSpace(detail.Snapshot.Get("restart.resume.orderNum").String())
|
||||
if row.OrderNum == "" {
|
||||
row.OrderNum = strings.TrimSpace(detail.Snapshot.Get("restart.stop.orderNum").String())
|
||||
}
|
||||
}
|
||||
if code, err := strconv.Atoi(strings.TrimSpace(detail.ErrorCode)); err == nil {
|
||||
row.UpstreamCode = code
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
func restartSnapshot(task *lifecycle.Task, detail *lifecycle.Detail, outcome lifecycle.Outcome, stage string, now *gtime.Time) *gjson.Json {
|
||||
base := snapshotMap(detail)
|
||||
base["ICCID"] = detail.ICCID
|
||||
base["inputMsisdn"] = detail.InputMSISDN
|
||||
base["inputImsi"] = detail.InputIMSI
|
||||
base["MSISDN"] = detail.MSISDN
|
||||
base["IMSI"] = detail.IMSI
|
||||
base["authorized"] = detail.Authorized
|
||||
base["chanKey"] = detail.ChanKey
|
||||
base["statusBefore"] = detail.StatusBefore
|
||||
base["orderNum"] = detail.OrderNum
|
||||
base["upstreamCode"] = detail.UpstreamCode
|
||||
base["upstreamMessage"] = detail.UpstreamReason
|
||||
|
||||
restart := snapshotNestedMap(base["restart"])
|
||||
statusAfter := detail.StatusBefore
|
||||
if outcome.Success {
|
||||
statusAfter = task.Operation.TargetStatus
|
||||
}
|
||||
restart[stage] = map[string]any{
|
||||
"success": outcome.Success,
|
||||
"reason": detail.Reason,
|
||||
"upstreamCode": outcome.Code,
|
||||
"upstreamMessage": strings.TrimSpace(outcome.Message),
|
||||
"orderNum": strings.TrimSpace(outcome.OrderNum),
|
||||
"operType": task.Operation.OperType,
|
||||
"statusBefore": detail.StatusBefore,
|
||||
"statusAfter": statusAfter,
|
||||
"processedAt": now.String(),
|
||||
}
|
||||
base["restart"] = restart
|
||||
return gjson.New(base)
|
||||
}
|
||||
|
||||
func snapshotMap(detail *lifecycle.Detail) map[string]any {
|
||||
if detail != nil && detail.OriginalSnapshot != nil {
|
||||
return copyMap(detail.OriginalSnapshot.Map())
|
||||
}
|
||||
if detail != nil {
|
||||
return copyMap(detail.Snapshot().Map())
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
func snapshotNestedMap(value any) map[string]any {
|
||||
if nested, ok := value.(map[string]any); ok {
|
||||
return copyMap(nested)
|
||||
}
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
func buildRestartBatchInfo(info *gjson.Json) *gjson.Json {
|
||||
data := copyMap(nil)
|
||||
if info != nil {
|
||||
data = copyMap(info.Map())
|
||||
}
|
||||
data["operation"] = "restart"
|
||||
data["stopOperType"] = consts.SimCardStatusOperTypeStop
|
||||
data["resumeOperType"] = consts.SimCardStatusOperTypeStart
|
||||
if _, ok := data["resumeDelaySeconds"]; !ok {
|
||||
data["resumeDelaySeconds"] = 300
|
||||
}
|
||||
data["restart"] = restartInfo(info)
|
||||
return gjson.New(data)
|
||||
}
|
||||
|
||||
func buildRestartFinishedInfo(info *gjson.Json, ossID, downloadID int64, finishedAt *gtime.Time) *gjson.Json {
|
||||
updated := buildRestartBatchInfo(info)
|
||||
restart := restartInfo(updated)
|
||||
restart["phase"] = consts.RestartPhaseFinished
|
||||
restart["finishedAt"] = finishedAt.String()
|
||||
data := updated.Map()
|
||||
data["resultFileOssId"] = ossID
|
||||
data["resultDownloadId"] = downloadID
|
||||
data["restart"] = restart
|
||||
return gjson.New(data)
|
||||
}
|
||||
|
||||
func setRestartInfo(info *gjson.Json, restart map[string]any) *gjson.Json {
|
||||
data := map[string]any{}
|
||||
if info != nil {
|
||||
data = copyMap(info.Map())
|
||||
}
|
||||
data["restart"] = restart
|
||||
return gjson.New(data)
|
||||
}
|
||||
|
||||
func restartInfo(info *gjson.Json) map[string]any {
|
||||
if info == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
return copyMap(info.Get("restart").Map())
|
||||
}
|
||||
|
||||
func restartPhase(info *gjson.Json) string {
|
||||
if info == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(info.Get("restart.phase").String())
|
||||
}
|
||||
|
||||
func restartResumeAt(info *gjson.Json) *gtime.Time {
|
||||
if info == nil {
|
||||
return nil
|
||||
}
|
||||
value := strings.TrimSpace(info.Get("restart.resumeAt").String())
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
parsed := gtime.NewFromStr(value)
|
||||
if parsed == nil || parsed.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func restartValidationOK(info *gjson.Json) bool {
|
||||
if info == nil {
|
||||
return false
|
||||
}
|
||||
return info.Get("restart.validationOK").Bool()
|
||||
}
|
||||
|
||||
func copyMap(source map[string]any) map[string]any {
|
||||
copied := make(map[string]any, len(source))
|
||||
for key, value := range source {
|
||||
copied[key] = value
|
||||
}
|
||||
return copied
|
||||
}
|
||||
Reference in New Issue
Block a user