package export_task import ( "context" "strconv" "gorm.io/gorm" "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit" "github.com/break/junhong_cmp_fiber/internal/model" "github.com/break/junhong_cmp_fiber/pkg/auditfailure" "github.com/break/junhong_cmp_fiber/pkg/constants" "github.com/break/junhong_cmp_fiber/pkg/middleware" ) func (s *Service) writeTaskAudit(ctx context.Context, tx *gorm.DB, actionCode, summary string, task *model.ExportTask, before, after map[string]any, result, phase, errorCode, errorSummary string) error { scopeType, scopeID := constants.AuditScopePlatform, "" if task.CreatorShopID != nil { scopeType, scopeID = constants.AuditScopeShop, strconv.FormatUint(uint64(*task.CreatorShopID), 10) } return s.auditWriter.WriteTask(ctx, tx, audit.TaskInput{ EventID: audit.TaskEventID(constants.AuditResourceExportTask, task.ID, phase), ActionCode: actionCode, Summary: summary, TaskID: task.ID, TaskNo: task.TaskNo, Actor: audit.ActorInput{ Kind: constants.AuditActorAccount, ID: strconv.FormatUint(uint64(middleware.GetUserIDFromContext(ctx)), 10), Name: middleware.GetUsernameFromContext(ctx), ShopID: task.CreatorShopID, EnterpriseID: task.CreatorEnterpriseID, }, Source: constants.AuditSourceAdminAPI, ScopeType: scopeType, ScopeID: scopeID, Result: result, ErrorCode: errorCode, ErrorSummary: errorSummary, IdentitySnapshot: map[string]any{ "id": task.ID, "task_no": task.TaskNo, "scene": task.Scene, "format": task.Format, "creator_user_id": task.CreatorUserID, "creator_user_type": task.CreatorUserType, "creator_shop_id": task.CreatorShopID, "creator_enterprise_id": task.CreatorEnterpriseID, "scope_shop_ids": task.ScopeShopIDs, }, BeforeData: before, AfterData: after, }) } func (s *Service) recordTaskAudit(ctx context.Context, actionCode, summary string, task *model.ExportTask, before, after map[string]any, result, phase string, errorCode int) { if s == nil || s.auditWriter == nil || s.db == nil || task == nil || task.TaskNo == "" { return } code := strconv.Itoa(errorCode) err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { return s.writeTaskAudit(ctx, tx, actionCode, summary, task, before, after, result, phase, code, summary) }) if err != nil { auditfailure.RecordSecondaryWriteFailure(actionCode, task.TaskNo, "", task.TaskNo, code, err) } } func exportTaskState(task *model.ExportTask) map[string]any { if task == nil { return nil } return map[string]any{ "status": task.Status, "cancel_requested": task.CancelRequested, "progress": task.Progress, } }