77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package common
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
|
||
"github.com/gogf/gf/v2/database/gdb"
|
||
"github.com/gogf/gf/v2/frame/g"
|
||
"github.com/gogf/gf/v2/os/gtime"
|
||
"github.com/tiger1103/gfast/v3/internal/app/lock"
|
||
"github.com/tiger1103/gfast/v3/internal/app/system/service"
|
||
)
|
||
|
||
type audit struct{}
|
||
|
||
var Audit = new(audit)
|
||
|
||
type AuditReq struct {
|
||
Id int `p:"id" v:"required#主键ID不能为空"`
|
||
AuditStatus int `p:"auditStatus"`
|
||
AuditView string `p:"auditView"`
|
||
AuditUser uint64 `p:"auditUser"`
|
||
AuditDate *gtime.Time `p:"auditDate"`
|
||
AuditDept string `p:"auditDept"`
|
||
Status int `p:"status"`
|
||
Version int `p:"version"`
|
||
}
|
||
|
||
// Audit 审核逻辑(通用方法)
|
||
// 参数说明:
|
||
// - ctx: 请求上下文
|
||
// - model: 数据表操作对象(如 dao.YourModel.Ctx(ctx))
|
||
// - req: 审核请求结构体(包含 id, version, 审核状态等)
|
||
// - save: 实际保存函数,由业务层传入
|
||
func (c *audit) Audit(
|
||
ctx context.Context,
|
||
model *gdb.Model,
|
||
req *AuditReq,
|
||
save func(ctx context.Context, req *AuditReq) error,
|
||
) error {
|
||
if req.Id == 0 || req.Version == 0 {
|
||
return errors.New("缺少 ID 或版本号")
|
||
}
|
||
if req.AuditStatus == 0 {
|
||
return errors.New("审核状态不能为空")
|
||
}
|
||
|
||
// 执行乐观锁检查与 version 自增
|
||
newVersion, err := lock.TryOptimisticLock(ctx, model, "id", req.Id, req.Version)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
// 填充审核人、时间、新版本号
|
||
req.Version = newVersion
|
||
if req.AuditDate == nil {
|
||
req.AuditDate = gtime.Now()
|
||
}
|
||
if req.AuditUser == 0 {
|
||
req.AuditUser = service.Context().GetUserId(ctx)
|
||
}
|
||
// 执行业务 save
|
||
return save(ctx, req)
|
||
}
|
||
func (c *audit) SaveAudit(model *gdb.Model, req *AuditReq) error {
|
||
_, err := model.Data(g.Map{
|
||
"audit_status": req.AuditStatus,
|
||
"audit_user": req.AuditUser,
|
||
"audit_date": req.AuditDate,
|
||
"version": req.Version,
|
||
"audit_view": req.AuditView,
|
||
"audit_dept": req.AuditDept,
|
||
"status": req.Status,
|
||
}).Where("id", req.Id).Update()
|
||
return err
|
||
}
|