diff --git a/internal/repository/material_import.go b/internal/repository/material_import.go new file mode 100644 index 00000000..5200c853 --- /dev/null +++ b/internal/repository/material_import.go @@ -0,0 +1,23 @@ +package repository + +import ( + "github.com/wmms/wmms/internal/model" + "github.com/wmms/wmms/pkg/database" +) + +type MaterialImportLogRepo struct{} + +func NewMaterialImportLogRepo() *MaterialImportLogRepo { return &MaterialImportLogRepo{} } + +// Create 写一条导入记录。成功和失败都会调用;失败原因只存汇总,逐行明细 +// 只随接口响应返回,不落库。 +func (r *MaterialImportLogRepo) Create(log *model.MaterialImportLog) error { + result, err := database.DB.Exec( + `INSERT INTO material_import_logs (organization_id, operator, file_name, total_rows, success_rows, failed_rows, status, failure_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + log.OrganizationID, log.Operator, log.FileName, log.TotalRows, log.SuccessRows, log.FailedRows, log.Status, log.FailureReason) + if err != nil { + return err + } + log.ID, err = result.LastInsertId() + return err +} diff --git a/internal/repository/material_import_test.go b/internal/repository/material_import_test.go index f9bb7ae4..a231f437 100644 --- a/internal/repository/material_import_test.go +++ b/internal/repository/material_import_test.go @@ -175,3 +175,27 @@ func TestMaterialLogRepoCreateBatchTx(t *testing.T) { t.Fatal(err) } } + +func TestMaterialImportLogRepoCreate(t *testing.T) { + mock, cleanup := newImportMock(t) + defer cleanup() + + mock.ExpectExec(regexp.QuoteMeta(`INSERT INTO material_import_logs (organization_id, operator, file_name, total_rows, success_rows, failed_rows, status, failure_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)). + WithArgs(int64(1), "tester", "物料.xlsx", 200, 0, 3, "failed", "共 3 行校验未通过"). + WillReturnResult(sqlmock.NewResult(9, 1)) + + log := &model.MaterialImportLog{ + OrganizationID: 1, Operator: "tester", FileName: "物料.xlsx", + TotalRows: 200, SuccessRows: 0, FailedRows: 3, + Status: "failed", FailureReason: "共 3 行校验未通过", + } + if err := NewMaterialImportLogRepo().Create(log); err != nil { + t.Fatalf("create: %v", err) + } + if log.ID != 9 { + t.Fatalf("id = %d, want 9", log.ID) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatal(err) + } +}