// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package neighbor import ( "context" "encoding/json" "fmt" "gorm.io/gorm" "property-garden/errors" "property-garden/impl/v1/oss_utils" dbmodel "property-garden/model" pb_v1 "property-garden/pb/v1" "property-garden/utils" "strings" "time" "git.getensh.com/common/gopkgs/database" "git.getensh.com/common/gopkgs/logger" "go.uber.org/zap" "google.golang.org/grpc/status" ) func checkNeighborArticleAddParam(req *pb_v1.NeighborArticleAddRequest) error { switch { case req.GardenId == 0: return status.Error(10003, "小区不能为空") case req.ClassId == 0: return status.Error(10003, "分类id不能为空") case len(req.Title) > 128: return status.Error(10003, "标题过长") case req.Content == "" && len(req.Pics) == 0: return status.Error(10003, "内容不能为空") case req.Uid == 0: return status.Error(10003, "uid 不能为空") } return nil } func NeighborArticleAdd(ctx context.Context, req *pb_v1.NeighborArticleAddRequest) (reply *pb_v1.NeighborArticleAddReply, err error) { reply = &pb_v1.NeighborArticleAddReply{} // 捕获各个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")) } } }() // 参数检查 err = checkNeighborArticleAddParam(req) if err != nil { return nil, err } now := time.Now() dbname := utils.GetGardenDbName(req.GardenId) class := dbmodel.NewNeighborClass(dbname) where := map[string]interface{}{ "id": req.ClassId, } err = class.Find(database.DB(), where) if err != nil && err != gorm.ErrRecordNotFound { return nil, errors.DataBaseError } if class.ID == 0 { return nil, status.Error(10003, "分类不存在") } db := database.DB().Begin() p := dbmodel.TNeighborArticle{ Title: req.Title, ClassId: req.ClassId, Content: req.Content, Pics: utils.StringJoin(req.Pics, ";"), UpdatedAt: now, CreatedAt: now, UserIcon: req.UserIcon, Uid: req.Uid, NickName: req.NickName, } p.SetTable(dbname) err = p.Insert(db) if err != nil { db.Rollback() if strings.Contains(strings.ToLower(err.Error()), "duplicate") { return nil, status.Error(10003, "分类名已存在") } return nil, errors.DataBaseError } values := map[string]interface{}{ "article_count": gorm.Expr("article_count + ?", 1), } if err = class.Update(db, where, values); err != nil { db.Rollback() return nil, errors.DataBaseError } if err := oss_utils.OssObjAdd(req.Pics, nil); err != nil { db.Rollback() return nil, err } db.Commit() return reply, nil }