// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package contact import ( "context" "encoding/json" "fmt" "git.getensh.com/common/gopkgs/database" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" "time" "xingjia-management-gateway/apis" "xingjia-management-gateway/consts" "xingjia-management-gateway/errors" "xingjia-management-gateway/impl/v1/operation_log" dbmodel "xingjia-management-gateway/model" ) func checkContactAddParam(req *apis.ContactAddRequest) error { switch { case req.SelfId == 0: return status.Error(10003, "未知操作者") } return nil } func getContactContent(p dbmodel.TContact) string { m := map[string]interface{}{ "电话": p.Phone, "地址": p.Addr, "邮箱": p.Email, } bytes, _ := json.Marshal(m) return string(bytes) } // func ContactAdd(ctx context.Context, req *apis.ContactAddRequest) (reply *apis.ContactAddReply, err error) { reply = &apis.ContactAddReply{} // 捕获各个task中的异常并返回给调用者 defer func() { if r := recover(); r != nil { err = fmt.Errorf("%+v", r) e := &status.Status{} if er := json.Unmarshal([]byte(err.Error()), e); er != nil { logger.Error("err", zap.String("system_err", err.Error()), zap.Stack("stacktrace")) } } }() if err = checkContactAddParam(req); err != nil { return nil, err } now := time.Now() p := dbmodel.TContact{} p.Phone = req.Phone p.Addr = req.Addr p.Email = req.Email p.CreatedAt = now p.UpdatedAt = now exist := false operation := consts.OperationActionAdd if req.Id > 0 { exist = true operation = consts.OperationActionUpdate } db := database.DB().Begin() defer func() { if err != nil { db.Rollback() } }() originContent := "" targetContent := "" if !exist { p.ID = 1 err = p.Insert(db) if err != nil { return nil, errors.DataBaseError } targetContent = getContactContent(p) } else { where := map[string]interface{}{ "id": req.Id, } values := map[string]interface{}{ "addr": req.Addr, "phone": req.Phone, "email": req.Email, "updated_at": time.Now(), } old := dbmodel.TContact{} err = old.Find(db, where) if err != nil { return nil, errors.DataBaseError } err = p.Update(db, where, values) if err != nil { return nil, errors.DataBaseError } originContent = getContactContent(old) targetContent = getContactContent(p) } // 操作日志 logReq := &apis.OperationLogAddRequest{ OriginContent: originContent, TargetContent: targetContent, Uid: req.SelfId, User: req.SelfName, Module: consts.OperationModuleContact, OperationTime: now.Unix(), Operation: int32(operation), } err = operation_log.OperationLogAddHandle(logReq, db) if err != nil { return nil, err } db.Commit() return reply, nil }