Эх сурвалжийг харах

Merge branch 'develop' of http://code.dashoo.cn/chengjian/opms_backend into develop

liuyaqi 3 жил өмнө
parent
commit
058a08e583
30 өөрчлөгдсөн 702 нэмэгдсэн , 531 устгасан
  1. 8 0
      .idea/.gitignore
  2. 22 4
      doc/订单全流程管理平台.pdma.json
  3. 35 5
      opms_admin/app/service/context.go
  4. 38 15
      opms_admin/app/service/sys_user.go
  5. 8 6
      opms_libary/request/request.go
  6. 3 0
      opms_parent/app/dao/cust/internal/cust_customer.go
  7. 3 3
      opms_parent/app/dao/cust/internal/cust_customer_belong.go
  8. 23 0
      opms_parent/app/handler/base/distributor.go
  9. 3 1
      opms_parent/app/handler/base/product.go
  10. 1 1
      opms_parent/app/handler/cust/belong.go
  11. 3 3
      opms_parent/app/handler/cust/contant.go
  12. 86 82
      opms_parent/app/handler/cust/customer.go
  13. 14 14
      opms_parent/app/model/base/base_distributor.go
  14. 0 1
      opms_parent/app/model/base/base_product.go
  15. 15 6
      opms_parent/app/model/cust/cust_customer.go
  16. 2 2
      opms_parent/app/model/cust/cust_customer_belong.go
  17. 1 2
      opms_parent/app/model/cust/cust_customer_dynamics.go
  18. 1 2
      opms_parent/app/model/cust/internal/cust_customer.go
  19. 1 1
      opms_parent/app/service/base.go
  20. 11 5
      opms_parent/app/service/base/base_distributor.go
  21. 0 5
      opms_parent/app/service/base/base_district.go
  22. 26 22
      opms_parent/app/service/base/base_product.go
  23. 0 1
      opms_parent/app/service/base/base_sales_region.go
  24. 0 1
      opms_parent/app/service/base/base_sales_region_detail.go
  25. 32 2
      opms_parent/app/service/context.go
  26. 1 0
      opms_parent/app/service/contract/ctr_contract.go
  27. 331 329
      opms_parent/app/service/cust/cust_customer.go
  28. 24 5
      opms_parent/app/service/cust/cust_customer_belong.go
  29. 9 12
      opms_parent/app/service/cust/cust_customer_contact.go
  30. 1 1
      opms_parent/main.go

+ 8 - 0
.idea/.gitignore

@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
+# Editor-based HTTP Client requests
+/httpRequests/

+ 22 - 4
doc/订单全流程管理平台.pdma.json

@@ -11634,6 +11634,24 @@
           "notes": {},
           "id": "BD26C064-7BB5-4B2F-B462-0204CF0A0347"
         },
+        {
+          "defKey": "prod_id",
+          "defName": "关联产品",
+          "comment": "",
+          "type": "",
+          "len": "",
+          "scale": "",
+          "primaryKey": false,
+          "notNull": true,
+          "autoIncrement": false,
+          "defaultValue": "",
+          "hideInGraph": false,
+          "domain": "16120F75-6AA7-4483-868D-F07F511BB081",
+          "refDict": "",
+          "extProps": {},
+          "notes": {},
+          "id": "812C6609-3FE8-454F-BE38-1829D55490C9"
+        },
         {
           "defKey": "name",
           "defName": "产品名称",
@@ -11699,7 +11717,7 @@
           "hideInGraph": false,
           "refDict": "",
           "extProps": {},
-          "domain": "6BC8F04B-6CFA-4995-98D3-318F5CDD774E",
+          "domain": "C3B1681B-99F9-4818-9E80-DE1652A51D85",
           "id": "3A8526D9-EBBA-4DA0-A6CD-71B224D17702"
         },
         {
@@ -11716,7 +11734,7 @@
           "hideInGraph": false,
           "refDict": "",
           "extProps": {},
-          "domain": "6BC8F04B-6CFA-4995-98D3-318F5CDD774E",
+          "domain": "C3B1681B-99F9-4818-9E80-DE1652A51D85",
           "id": "EA13B6AB-39D6-440F-B7DD-2BFF30F68038"
         },
         {
@@ -11750,7 +11768,7 @@
           "hideInGraph": false,
           "refDict": "",
           "extProps": {},
-          "domain": "6BC8F04B-6CFA-4995-98D3-318F5CDD774E",
+          "domain": "C3B1681B-99F9-4818-9E80-DE1652A51D85",
           "id": "DEC06D76-4CEB-49DD-B4A9-29690B3141EE"
         },
         {
@@ -11767,7 +11785,7 @@
           "hideInGraph": false,
           "refDict": "",
           "extProps": {},
-          "domain": "6BC8F04B-6CFA-4995-98D3-318F5CDD774E",
+          "domain": "C3B1681B-99F9-4818-9E80-DE1652A51D85",
           "id": "94C71517-F3A6-4A1A-B308-7F9E10C23922"
         },
         {

+ 35 - 5
opms_admin/app/service/context.go

@@ -2,29 +2,36 @@ package service
 
 import (
 	"context"
-	"dashoo.cn/micro/app/dao"
-	"dashoo.cn/micro/app/model"
-	"dashoo.cn/opms_libary/micro_srv"
-	"dashoo.cn/opms_libary/request"
 	"fmt"
+	"reflect"
+
 	"github.com/gogf/gf/container/gset"
 	"github.com/gogf/gf/database/gdb"
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
 	"github.com/gogf/gf/os/glog"
 	"github.com/gogf/gf/util/gconv"
-	"reflect"
+
+	"dashoo.cn/micro/app/dao"
+	"dashoo.cn/micro/app/model"
+	"dashoo.cn/opms_libary/micro_srv"
+	"dashoo.cn/opms_libary/request"
 )
 
 // Context 上下文管理服务
 type contextService struct {
 	Tenant  string            `json:"tenant"`
 	Table   string            `json:"table"`
+	Ctx     context.Context   `json:"ctx"`
 	CxtUser *request.UserInfo `json:"cxtUser"`
 }
 
 // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
 func (c *contextService) Init(ctx context.Context) (*contextService, error) {
+	cs := ctx.Value("contextService")
+	if cs != nil {
+		return cs.(*contextService), nil
+	}
 	c = new(contextService)
 	// 获取租户码
 	tenant, err := micro_srv.GetTenant(ctx)
@@ -42,6 +49,8 @@ func (c *contextService) Init(ctx context.Context) (*contextService, error) {
 		}
 		c.CxtUser = &userInfo
 	}
+
+	c.Ctx = context.WithValue(ctx, "contextService", c)
 	return c, nil
 }
 
@@ -156,3 +165,24 @@ func (c *contextService) GetCxtUserDeptId() int {
 	}
 	return c.CxtUser.DeptId
 }
+
+func (c *contextService) GetCxtUserRoles() []string {
+	if c.CxtUser == nil {
+		return []string{}
+	}
+	return c.CxtUser.Roles
+}
+
+func (c *contextService) GetCxtUserPosts() []string {
+	if c.CxtUser == nil {
+		return []string{}
+	}
+	return c.CxtUser.Posts
+}
+
+func (c *contextService) GetCxtUserGroups() []string {
+	if c.CxtUser == nil {
+		return []string{}
+	}
+	return c.CxtUser.Groups
+}

+ 38 - 15
opms_admin/app/service/sys_user.go

@@ -40,10 +40,10 @@ func NewUserService(ctx context.Context) (svc *userService, err error) {
 func (s *userService) Login(username, password string) (*request.UserInfo, error) {
 	record, err := s.Dao.Where("user_name", username).Where("status='10'").FindOne()
 	if err != nil {
-		return nil, errors.New("系统异常")
+		return nil, gerror.New("系统异常")
 	}
 	if record == nil {
-		return nil, errors.New("账号或密码错误,或限制登录")
+		return nil, gerror.New("账号或密码错误,或限制登录")
 	}
 	// 验证密码
 	if utils.EncryptPassword(password, record.UserSalt) != record.Password {
@@ -58,15 +58,10 @@ func (s *userService) Login(username, password string) (*request.UserInfo, error
 		return nil, err
 	}
 	// 权限
-	//permissionService, err := permission.NewService(s.Tenant)
-	//if err != nil {
-	//	return nil, errors.New("系统异常,请重新尝试")
-	//}
-	//userRoles, err := permissionService.GetRoleIdsByUser(userInfo.Id)
-	//if err != nil {
-	//	return nil, err
-	//}
-	//userInfo.Roles = userRoles
+	userInfo.Roles, userInfo.Posts, userInfo.Groups, err = s.GetUserPermission(userInfo.Id)
+	if err != nil {
+		return nil, gerror.New("获取用户权限失败")
+	}
 	return userInfo, nil
 }
 
@@ -120,8 +115,8 @@ func (s *userService) GetUserList(req *model.SysUserSearchReq) (total int, userL
 	return
 }
 
-// 获取部门下用户
-func (s userService) GetUserByDept(deptId int) (userList []*model.SysUser, err error) {
+// GetUserByDept 获取部门下用户
+func (s *userService) GetUserByDept(deptId int) (userList []*model.SysUser, err error) {
 	count, err := dao.NewSysDeptDao(s.Tenant).Where(dao.SysDept.Columns.Id, deptId).Where(dao.SysDept.Columns.Status, "10").Count()
 	if err != nil {
 		return nil, err
@@ -133,8 +128,8 @@ func (s userService) GetUserByDept(deptId int) (userList []*model.SysUser, err e
 	return userList, err
 }
 
-// 获取角色关联的用户
-func (s userService) GetUserByRole(roleId int) (userList []*model.SysUser, err error) {
+// GetUserByRole 获取角色关联的用户
+func (s *userService) GetUserByRole(roleId int) (userList []*model.SysUser, err error) {
 	count, err := dao.NewSysRoleDao(s.Tenant).Where(dao.SysRole.Columns.Id, roleId).Where(dao.SysRole.Columns.Status, "10").Count()
 	if err != nil {
 		return nil, err
@@ -204,6 +199,33 @@ func (s *userService) GetUserInfoById(id int, withPwd ...bool) (user *model.SysU
 	return
 }
 
+// GetUserPermission 获取用户权限字符(角色、岗位、用户组)
+func (s *userService) GetUserPermission(userId int) ([]string, []string, []string, error) {
+	s.userRoleDao = dao.NewSysUserRoleDao(s.Tenant)
+	s.userPostDao = dao.NewSysUserPostDao(s.Tenant)
+	s.userGroupDao = dao.NewSysUserGroupDao(s.Tenant)
+	roleList, err := s.userRoleDao.As("user_role").LeftJoin(dao.SysRole.Table, "role", "user_role.role_id=role.id").
+		Fields(dao.SysRole.Columns.RoleKey).Where(s.userRoleDao.Columns.UserId, userId).Array()
+	if err != nil {
+		g.Log().Error(err)
+		return nil, nil, nil, err
+	}
+	postList, err := s.userPostDao.As("user_post").LeftJoin(dao.SysPost.Table, "post", "user_post.post_id=post.id").
+		Fields(dao.SysPost.Columns.PostCode).Where(s.userPostDao.Columns.UserId, userId).Array()
+	if err != nil {
+		g.Log().Error(err)
+		return nil, nil, nil, err
+	}
+	groupList, err := s.userGroupDao.As("user_group").LeftJoin(dao.SysGroup.Table, "group", "user_group.group_id=group.id").
+		Fields(dao.SysGroup.Columns.GroupCode).Where(s.userGroupDao.Columns.UserId, userId).Array()
+	if err != nil {
+		g.Log().Error(err)
+		return nil, nil, nil, err
+	}
+
+	return gconv.Strings(roleList), gconv.Strings(postList), gconv.Strings(groupList), err
+}
+
 // GetUserRoleIds 获取用户角色
 func (s *userService) GetUserRoleIds(userId int) (roleIds []int, err error) {
 	s.userRoleDao = dao.NewSysUserRoleDao(s.Tenant)
@@ -294,6 +316,7 @@ func (s *userService) CreateUser(req *model.AddUserReq) (err error) {
 	}
 	userData.UserSalt = grand.S(10)
 	userData.Password = utils.EncryptPassword(userData.Password, userData.UserSalt)
+	g.Log("xxxxpassword",userData.Password)
 	SetCreatedInfo(userData, s.GetCxtUserId(), s.GetCxtUserName())
 	res, err := Model.Insert(userData)
 	if err != nil {

+ 8 - 6
opms_libary/request/request.go

@@ -29,12 +29,14 @@ func (p *PageReq) GetPage() (int, int) {
 
 // UserInfo 登录用户信息
 type UserInfo struct {
-	Id       int    `json:"id"`
-	Uuid     string `json:"uuid"`
-	UserName string `json:"userName"`
-	NickName string `json:"nickName"`
-	DeptId   int    `json:"deptId"` // 所属部门
-	Roles    string `json:"roles"`  // 所属角色
+	Id       int      `json:"id"`
+	Uuid     string   `json:"uuid"`
+	UserName string   `json:"userName"`
+	NickName string   `json:"nickName"`
+	DeptId   int      `json:"deptId"` // 所属部门
+	Roles    []string `json:"roles"`  // 所属角色
+	Posts    []string `json:"posts"`  // 所属岗位
+	Groups   []string `json:"groups"` // 所属用户组
 }
 
 // 设置当前登录用户信息

+ 3 - 0
opms_parent/app/dao/cust/internal/cust_customer.go

@@ -37,6 +37,7 @@ type custCustomerColumns struct {
 	CustLocation string // 所在地区
 	CustAddress  string // 详细地址
 	CustStatus   string // 客户状态(10正常20)
+	CustSource   string // 客户来源
 	IsPublic     string // 公海客户(10是20否)
 	DeptId       string // 所属部门ID
 	DeptName     string // 所属部门
@@ -68,6 +69,7 @@ var (
 			AbbrName:     "abbr_name",
 			CustLocation: "cust_location",
 			CustAddress:  "cust_address",
+			CustSource:   "cust_source",
 			CustStatus:   "cust_status",
 			IsPublic:     "is_public",
 			DeptId:       "dept_id",
@@ -103,6 +105,7 @@ func NewCustCustomerDao(tenant string) CustCustomerDao {
 			CustLevel:    "cust_level",
 			CustAddress:  "cust_address",
 			CustStatus:   "cust_status",
+			CustSource:   "cust_source",
 			IsPublic:     "is_public",
 			DeptId:       "dept_id",
 			DeptName:     "dept_name",

+ 3 - 3
opms_parent/app/dao/cust/internal/cust_customer_belong.go

@@ -29,7 +29,7 @@ type CustCustomerBelongDao struct {
 type custCustomerBelongColumns struct {
 	Id           string // 主键
 	CustId       string // 关联客户
-	SaleName     string // 归属销售
+	SalesName    string // 归属销售
 	OrigSaleName string // 原来归属
 	OpnType      string // 操作方式(10分配20转移)
 	OpnPeople    string // 操作人
@@ -53,7 +53,7 @@ var (
 		Columns: custCustomerBelongColumns{
 			Id:           "id",
 			CustId:       "cust_id",
-			SaleName:     "sale_name",
+			SalesName:    "sales_name",
 			OrigSaleName: "orig_sale_name",
 			OpnType:      "opn_type",
 			OpnPeople:    "opn_people",
@@ -79,7 +79,7 @@ func NewCustCustomerBelongDao(tenant string) CustCustomerBelongDao {
 		Columns: custCustomerBelongColumns{
 			Id:           "id",
 			CustId:       "cust_id",
-			SaleName:     "sale_name",
+			SalesName:    "sales_name",
 			OrigSaleName: "orig_sale_name",
 			OpnType:      "opn_type",
 			OpnPeople:    "opn_people",

+ 23 - 0
opms_parent/app/handler/base/distributor.go

@@ -51,6 +51,29 @@ func (p *DistributorHandler) Create(ctx context.Context, req *model.AddDistribut
 	return nil
 }
 
+//详情
+func (p *DistributorHandler) GetEntityById(ctx context.Context, req *comm_def.IdReq, rsp *comm_def.CommonMsg) error {
+
+	if err := gvalid.CheckStruct(ctx, req, nil); err != nil {
+		return err
+	}
+	distributorServer, err := server.NewDistributorService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return err
+	}
+	list, err := distributorServer.GetEntityById(req.Id)
+	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
+	if err != nil {
+		g.Log().Error(err)
+		return err
+	}
+	rsp.Data = g.Map{"list": list}
+	return nil
+}
+
+//删掉
+
 // 编辑
 func (p *DistributorHandler) UpdateById(ctx context.Context, req *model.UpdateDistributorReq, rsp *comm_def.CommonMsg) error {
 

+ 3 - 1
opms_parent/app/handler/base/product.go

@@ -85,12 +85,14 @@ func (p *ProductHandler) GetEntityById(ctx context.Context, req *comm_def.IdReq,
 		g.Log().Error(err)
 		return gerror.New("系统异常,请重新尝试")
 	}
-	_, err = productServer.GetEntityById(req.Id)
+	list, err := productServer.GetEntityById(req.Id)
+
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
+	rsp.Data = g.Map{"list": list}
 	return nil
 }
 

+ 1 - 1
opms_parent/app/handler/cust/belong.go

@@ -25,7 +25,7 @@ func (c *CustBelongHeader) GetEntityById(ctx context.Context, req *model.Contact
 		g.Log().Error(err)
 		return gerror.New("系统异常,请重新尝试")
 	}
-	list, err := belongServer.GetEntityById(req.CustId)
+	list, err := belongServer.GetList(req.CustId)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)

+ 3 - 3
opms_parent/app/handler/cust/contant.go

@@ -68,8 +68,8 @@ func (c *CustomerContantHeader) UpdateById(ctx context.Context, req *model.Updat
 	return nil
 }
 
-//客户联系人详情
-func (c *CustomerContantHeader) GetEntityById(ctx context.Context, req *model.ContactSeq, rsp *comm_def.CommonMsg) error {
+//客户联系人详情 //GetEntityById
+func (c *CustomerContantHeader) GetList(ctx context.Context, req *model.ContactSeq, rsp *comm_def.CommonMsg) error {
 	if err := gvalid.CheckStruct(ctx, req, nil); err != nil {
 		return err
 	}
@@ -78,7 +78,7 @@ func (c *CustomerContantHeader) GetEntityById(ctx context.Context, req *model.Co
 		g.Log().Error(err)
 		return gerror.New("系统异常,请重新尝试")
 	}
-	list, err := customerServer.GetEntityById(req.CustId)
+	list, err := customerServer.GetList(req.CustId)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)

+ 86 - 82
opms_parent/app/handler/cust/customer.go

@@ -30,103 +30,131 @@ const (
 	Receive          = "领取"
 )
 
-//公海列表
-func (c *CustomerHeader) PublicGetList(ctx context.Context, req *model.CustCustomerSearchReq, rsp *comm_def.CommonMsg) error {
+//创建客户
+func (c *CustomerHeader) Create(ctx context.Context, req *model.CustomerAddSeq, rsp *comm_def.CommonMsg) error {
+	g.Log().Info("客户名称", req.CustName)
+	if err := gvalid.CheckStruct(ctx, req, nil); err != nil {
+		return err
+	}
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
+	id, err := customerServer.Create(req)
 
-	req.IsPublic = noCustomer
-	g.Log().Info("publicGetlist", req)
-
-	total, list, err := customerServer.GetList(req)
+	var Ids []int64
+	Ids = append(Ids, gconv.Int64(id))
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
-	rsp.Data = g.Map{"list": list, "total": total}
+	//创建客户
+	c.WriteCustLog(ctx, Creates, Ids, req)
+	rsp.Data = g.Map{"lastId": id}
 	return nil
-
 }
 
-//客户列表
-func (c *CustomerHeader) GetList(ctx context.Context, req *model.CustCustomerSearchReq, rsp *comm_def.CommonMsg) error {
+//客户详情
+func (c *CustomerHeader) GetEntityById(ctx context.Context, req *comm_def.IdsReq, rsp *comm_def.CommonMsg) error {
+	if len(req.Ids) == 0 {
+
+		return gerror.New("参数有误!")
+	}
 	customerServer, err := server.NewCustomerService(ctx)
+	if err != nil {
+
+		return myerrors.New("系统异常,请重新尝试", err)
+	}
+	list, err := customerServer.GetEntityById(req.Ids)
+	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
-	total, list, err := customerServer.GetList(req)
+	rsp.Data = g.Map{"list": list}
+	return nil
+}
+
+//删除客户
+func (c *CustomerHeader) DeleteById(ctx context.Context, req *model.DelCustomer, rsp *comm_def.CommonMsg) error {
+	if req.Id == 0 {
+		return gerror.New("参数有误!")
+	}
+	customerServer, err := server.NewCustomerService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return myerrors.New("系统异常,请重新尝试", err)
+	}
+	err = customerServer.DeleteById(req.Id)
+	var Ids []int64
+	Ids = append(Ids, gconv.Int64(req.Id))
+	//删除客户
+	c.WriteCustLog(ctx, DeleteById, Ids, req)
 
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
-	rsp.Data = g.Map{"list": list, "total": total}
 	return nil
-
 }
 
-//创建客户
-func (c *CustomerHeader) Create(ctx context.Context, req *model.Customer, rsp *comm_def.CommonMsg) error {
-	g.Log().Info("客户名称", req.CustName)
-	if err := gvalid.CheckStruct(ctx, req, nil); err != nil {
-		return err
-	}
+//公海列表
+func (c *CustomerHeader) PublicGetList(ctx context.Context, req *model.CustCustomerSearchReq, rsp *comm_def.CommonMsg) error {
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
-	id, err := customerServer.Create(req)
-	var Ids []int64
-	Ids = append(Ids, gconv.Int64(id))
+
+	req.IsPublic = noCustomer
+	g.Log().Info("publicGetlist", req)
+
+	total, list, err := customerServer.GetList(req)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
-	//创建客户
-	c.WriteCustLog(ctx, Creates, Ids, req)
-	rsp.Data = g.Map{"lastId": id}
+	rsp.Data = g.Map{"list": list, "total": total}
 	return nil
+
 }
 
-//客户详情
-func (c *CustomerHeader) GetEntityById(ctx context.Context, req *comm_def.IdsReq, rsp *comm_def.CommonMsg) error {
-	if len(req.Ids) == 0 {
-		return gerror.New("参数有误!")
-	}
+//客户列表
+func (c *CustomerHeader) GetList(ctx context.Context, req *model.CustCustomerSearchReq, rsp *comm_def.CommonMsg) error {
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
 		g.Log().Error(err)
-		return gerror.New("系统异常,请重新尝试")
+		return err
 	}
-	list, err := customerServer.GetEntityById(req.Ids)
+	total, list, err := customerServer.GetList(req)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
 		return err
 	}
-	rsp.Data = g.Map{"list": list}
+	rsp.Data = g.Map{"list": list, "total": total}
 	return nil
+
 }
 
 //转移客户
-func (c *CustomerHeader) UpdateBytransfer(ctx context.Context, req *model.CustSalesReq, rsp *comm_def.CommonMsg) error {
-	if len(req.Ids) == 0 || req.SalesIds == 0 {
+func (c *CustomerHeader) UpdateBytransfer(ctx context.Context, req *model.DistriCustomer, rsp *comm_def.CommonMsg) error {
+	if len(req.Ids) == 0 || req.SalesId == 0 {
 		return gerror.New("参数有误!")
 	}
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
-		g.Log().Error(err)
-		return gerror.New("系统异常,请重新尝试")
+		return myerrors.New("系统异常,请重新尝试", err)
+	}
+	err = customerServer.UpdateBytransfer(req)
+	if err != nil {
+		return gerror.New("转移失败")
+
 	}
-	_, err = customerServer.UpdateBytransfer(req)
 	var Ids []int64
 	Ids = append(Ids, gconv.Int64(req.Ids))
 	//转移客户
@@ -144,19 +172,22 @@ func (c *CustomerHeader) DistriCustomer(ctx context.Context, req *model.DistriCu
 	if len(req.Ids) == 0 || req.SalesId == 0 {
 		return gerror.New("参数有误!")
 	}
-	g.Log().Info("DistriCustomer", req.Ids)
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
-		g.Log().Error(err)
-		return gerror.New("系统异常,请重新尝试")
+
+		return myerrors.New("系统异常,请重新尝试", err)
 	}
 	err = customerServer.DistriCustomer(req)
-
+	if err != nil {
+		return err
+	}
+	var behavior string
 	if req.Receive == "" {
-		c.WriteCustLog(ctx, DistriCustomer, req.Ids, req)
+		behavior = DistriCustomer
 	} else {
-		c.WriteCustLog(ctx, Receive, req.Ids, req)
+		behavior = Receive
 	}
+	c.WriteCustLog(ctx, behavior, req.Ids, req)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
 		g.Log().Error(err)
@@ -167,30 +198,6 @@ func (c *CustomerHeader) DistriCustomer(ctx context.Context, req *model.DistriCu
 
 }
 
-//删除客户
-func (c *CustomerHeader) DeleteById(ctx context.Context, req *model.DelCustomer, rsp *comm_def.CommonMsg) error {
-	if req.Id == 0 {
-		return gerror.New("参数有误!")
-	}
-	customerServer, err := server.NewCustomerService(ctx)
-	if err != nil {
-		g.Log().Error(err)
-		return gerror.New("系统异常,请重新尝试")
-	}
-	err = customerServer.DeleteById(req.Id)
-	var Ids []int64
-	Ids = append(Ids, gconv.Int64(req.Id))
-	//删除客户
-	c.WriteCustLog(ctx, DeleteById, Ids, req)
-
-	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
-	if err != nil {
-		g.Log().Error(err)
-		return err
-	}
-	return nil
-}
-
 //移入公海
 func (c *CustomerHeader) MoveToPubic(ctx context.Context, req *model.MoveToPubicRep, rsp *comm_def.CommonMsg) error {
 	if len(req.Ids) == 0 {
@@ -198,8 +205,8 @@ func (c *CustomerHeader) MoveToPubic(ctx context.Context, req *model.MoveToPubic
 	}
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
-		g.Log().Error(err)
-		return gerror.New("系统异常,请重新尝试")
+
+		return myerrors.New("系统异常,请重新尝试", err)
 	}
 
 	err = customerServer.MoveToPubic(req.Ids)
@@ -219,14 +226,11 @@ func (c *CustomerHeader) MoveToPubic(ctx context.Context, req *model.MoveToPubic
 func (c *CustomerHeader) DynamicsList(ctx context.Context, req *model.CustomerDynameicsReq, rsp *comm_def.CommonMsg) error {
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
-
-		g.Log().Error(err)
-		return err
+		return myerrors.New("系统异常,请重新尝试", err)
 	}
 	total, list, err := customerServer.DynamicsList(req)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
-		g.Log().Error(err)
 		return err
 	}
 	rsp.Data = g.Map{"list": list, "total": total}
@@ -237,8 +241,8 @@ func (c *CustomerHeader) DynamicsList(ctx context.Context, req *model.CustomerDy
 func (c *CustomerHeader) Mergecustomer(ctx context.Context, req *model.MergecustomerRep, rsp *comm_def.CommonMsg) error {
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
-		g.Log().Error(err)
-		return err
+		return myerrors.New("系统异常,请重新尝试", err)
+
 	}
 	if err := gvalid.CheckStruct(ctx, req, nil); err != nil {
 		return err
@@ -248,7 +252,7 @@ func (c *CustomerHeader) Mergecustomer(ctx context.Context, req *model.Mergecust
 	Ids = append(Ids, gconv.Int64(req.Id))
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
-		g.Log().Error(err)
+
 		return err
 	}
 	c.WriteCustLog(ctx, Mergecustomer, Ids, req)
@@ -259,8 +263,8 @@ func (c *CustomerHeader) Mergecustomer(ctx context.Context, req *model.Mergecust
 func (c *CustomerHeader) UpdateById(ctx context.Context, req *model.UpdateCustomer, rsp *comm_def.CommonMsg) error {
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
-		g.Log().Error(err)
-		return gerror.New("系统异常,请重新尝试")
+
+		return myerrors.New("系统异常,请重新尝试", err)
 	}
 	err = customerServer.UpdateById(req)
 	var Ids []int64
@@ -268,7 +272,6 @@ func (c *CustomerHeader) UpdateById(ctx context.Context, req *model.UpdateCustom
 	c.WriteCustLog(ctx, UpdateById, Ids, req)
 	_, err, rsp.Code, rsp.Msg = myerrors.CheckError(err)
 	if err != nil {
-		g.Log().Error(err)
 		return err
 	}
 	return nil
@@ -300,14 +303,15 @@ func (c *CustomerHeader) WriteCustLog(ctx context.Context, custType string, cust
 	CustomerService.OperationLog(ctx, custId, custDynameics)
 }
 
+//导出
 func (c *CustomerHeader) DeriveList(ctx context.Context, req *model.CustCustomerExport, rsp *comm_def.CommonMsg) error {
 
 	customerServer, err := server.NewCustomerService(ctx)
 	if err != nil {
 		g.Log().Error(err)
 		return gerror.New("系统异常,请重新尝试")
-	}
-	buffer, _ := customerServer.Derive(req)
+	} //Export
+	buffer, _ := customerServer.Export(req)
 	rsp.Data = g.Map{"list": buffer}
 	return nil
 }

+ 14 - 14
opms_parent/app/model/base/base_distributor.go

@@ -39,20 +39,20 @@ type AddDistributor struct {
 
 //列表返回字段
 type DistributorRonp struct {
-	Id            int         `orm:"id,primary"      json:"id"`            // 主健
-	DistCode      string      `orm:"dist_code"       json:"distCode"`      // 经销商编码
-	DistName      string      `orm:"dist_name"       json:"distName"`      // 经销商名字
-	AbbrName      string      `orm:"abbr_name"       json:"abbrName"`      // 助记名
-	DistBoss      string      `orm:"dist_boss"       json:"distBoss"`      // 负责人
-	DistBossPhone int         `orm:"dist_boss_phone" json:"distBossPhone"` // 负责人电话
-	BelongSale    string      `orm:"belong_sale"     json:"belongSale"`    // 销售
-	ProvinceDesc  string      `orm:"province_desc"   json:"provinceDesc"`  // 省份描述
-	ProvinceId    string      `orm:"province_id"   json:"provinceId"`      // 省份Id
-	BusinessScope string      `orm:"business_scope"  json:"businessScope"` // 业务范围
-	CreatedName   string      `orm:"created_name"    json:"createdName"`   // 创建人名字
-	CreatedTime   *gtime.Time `orm:"created_time"    json:"createdTime"`   // 创建时间
-	DistDesc      string      `orm:"dist_desc"    json:"distDesc"`         // 说明
-	//District      *BaseDistrict `orm:"with:id=province_id"`
+	Id            int           `orm:"id,primary"      json:"id"`            // 主健
+	DistCode      string        `orm:"dist_code"       json:"distCode"`      // 经销商编码
+	DistName      string        `orm:"dist_name"       json:"distName"`      // 经销商名字
+	AbbrName      string        `orm:"abbr_name"       json:"abbrName"`      // 助记名
+	DistBoss      string        `orm:"dist_boss"       json:"distBoss"`      // 负责人
+	DistBossPhone int           `orm:"dist_boss_phone" json:"distBossPhone"` // 负责人电话
+	BelongSale    string        `orm:"belong_sale"     json:"belongSale"`    // 销售
+	ProvinceDesc  string        `orm:"province_desc"   json:"provinceDesc"`  // 省份描述
+	ProvinceId    string        `orm:"province_id"   json:"provinceId"`      // 省份Id
+	BusinessScope string        `orm:"business_scope"  json:"businessScope"` // 业务范围
+	CreatedName   string        `orm:"created_name"    json:"createdName"`   // 创建人名字
+	CreatedTime   *gtime.Time   `orm:"created_time"    json:"createdTime"`   // 创建时间
+	DistDesc      string        `orm:"dist_desc"    json:"distDesc"`         // 说明
+	District      *BaseDistrict `orm:"with:id=province_id"`
 	//*Contanct
 }
 

+ 0 - 1
opms_parent/app/model/base/base_product.go

@@ -22,7 +22,6 @@ type BaseProductSearchReq struct {
 
 //添加数据
 type AddBaseProductReq struct {
-	ProdCode    string `p:"prodCode"    json:"prodCode"   v:"required#产品编号不能为空"`
 	ProdName    string `p:"prodName"    json:"prodName"   v:"required#产品名称不能为空"`
 	ProdClass   string `p:"prodClass"   json:"prodClass"  v:"required#产品分类不能为空"`
 	GuidPrice   string `p:"guidPrice"   json:"guidPrice"      v:"required#建议成交价"`

+ 15 - 6
opms_parent/app/model/cust/cust_customer.go

@@ -24,6 +24,7 @@ type CustCustomerSearchReq struct {
 	CustLevel    string `json:"custLevel"`
 	TargetType   string `json:"targetType,omitempty"`
 	FollowUpDate string `json:"followUpDate,omitempty"`
+	Remark       string `json:"remark"`
 	request.PageReq
 }
 
@@ -43,12 +44,12 @@ type CustExport struct {
 
 // 添加客户信息表
 type AddCustCustomerReq struct {
-	Cust *Customer
+	Cust *CustomerAddSeq
 	Info *Information
 }
 
 // 单表添加客户信息表
-type Customer struct {
+type CustomerAddSeq struct {
 	CustName     string      `p:"custName"        json:"custName"   v:"required#客户名称不能为空"`
 	AbbrName     string      `p:"abbrName"        json:"abbrName"   `                         // 助计名
 	CustLocation string      `p:"custLocation"    json:"custLocation"    `                    // 所在地区
@@ -56,10 +57,11 @@ type Customer struct {
 	FollowUpDate *gtime.Time `p:"followUpDate"     json:"followUpDate"   `                    //跟进时间
 	CustIndustry string      `p:"custIndustry"     json:"custIndustry" v:"required#客户行业不能为空"` //客户行业
 	CustLevel    string      `p:"custLevel"     json:"custLevel"       v:"required#客户级别不能为空"` //客户级别
+	CustSource   string      `p:"custSource"     json:"source"       v:"required#客户来源不能为空"`   //客户级别
 	CustDistCode int         `p:"custDistCode" json:"custDistCode"  v:"required#省份不能为空" `     // 省份Id
 	Remark       string      `p:"remark" json:"remark""`                                      //备注
 	SalesName    string      `p:"salesName"       json:"salesName"   `                        //
-	SalesId      string      `p:"salesId"         json:"salesId"   `                          //
+	SalesId      int         `p:"salesId"         json:"salesId"   `                          //
 }
 
 //客户联系人信息
@@ -84,8 +86,12 @@ type CustList struct {
 	FollowUpDate string `orm:"follow_up_date" json:"followUpDate"` // 最后跟进时间
 	CustIndustry string `orm:"cust_industry"  json:"custIndustry"` // 客户行业
 	CustLevel    string `orm:"cust_level"     json:"custLevel"`    // 客户级别(10 重点客户 20 普通客户 30非优客户)
+	CustSource   string `orm:"cust_soucrce"    json:"source"`      // 客户来源
 	CreatedName  string `orm:"created_name"   json:"createdName"`  // 创建人
 	CreatedTime  string `orm:"created_time"   json:"createdTime"`  // 创建时间
+	SalesId      int    `orm:"sales_id"   json:"salesId"`          //
+	SalesName    string `orm:"sales_name"   json:"salesName"`      //
+	Remark       string `orm:"remark"   json:"remark"`
 	//Follow       *Follow     `json:"follow"`
 }
 
@@ -108,9 +114,10 @@ type CustSalesReq struct {
 	SalesIds  int64   `json:"salesIds,omitempty"`
 	SalesName string  `json:"salesName,omitempty"`
 	Remark    string  `json:"remark,omitempty"`
+	Receive   string  `json:"receive,omitempty"` //有值领取 无值分配
 }
 
-//分配客户参数
+//分配 领取 转移 客户参数
 type DistriCustomer struct {
 	Ids       []int64 `json:"ids,omitempty"`       //客户id
 	SalesId   int64   `json:"salesId,omitempty"`   //分配到销售人员的id
@@ -132,14 +139,16 @@ type DelCustomerContact struct {
 //合并客户参数
 type MergecustomerRep struct {
 	Id int `json:"id"` //目标Id
-	*Customer
+	*CustomerAddSeq
+	//*CustCustomerContactSeq
+	*AddCustomerBelong
 	ChooseId []int64 `json:"chooseId,omitempty"` //被合并的客户id
 }
 
 //修改客户
 type UpdateCustomer struct {
 	Id int `json:"id,omitempty"` //客户id
-	*Customer
+	*CustomerAddSeq
 }
 
 //移入公海

+ 2 - 2
opms_parent/app/model/cust/cust_customer_belong.go

@@ -20,8 +20,8 @@ type AddCustomerBelong struct {
 	SaleName     string      `      json:"saleName" v:"required#归属销售不能为空"`  // 归属销售
 	OrigSaleName string      `      json:"origSaleName"   `                 // 原来归属
 	OpnType      string      `      json:"opnType"`                         // 操作方式(10分配20转移)
-	OpnPeople    string      `      json:"opnPeople" v:"required#操作人必填"`    // 操作人
-	OpnDatetime  *gtime.Time `   json:"opnDatetime" v:"required#操作时间必填"`    // 操作时间
+	OpnPeople    string      `      json:"opnPeople" `                      // 操作人
+	OpnDatetime  *gtime.Time `   json:"opnDatetime" `                       // 操作时间
 }
 
 type CustomerBelongInfo struct {

+ 1 - 2
opms_parent/app/model/cust/cust_customer_dynamics.go

@@ -5,7 +5,6 @@
 package cust
 
 import (
-	"dashoo.cn/opms_libary/request"
 	"github.com/gogf/gf/os/gtime"
 
 	"dashoo.cn/micro/app/model/cust/internal"
@@ -28,7 +27,7 @@ type AddCustomerDynameicsReq struct {
 }
 type CustomerDynameicsReq struct {
 	CustId int `    json:"custId"` // 客户Id
-	request.PageReq
+	//request.PageReq
 }
 
 //客户表动态记录

+ 1 - 2
opms_parent/app/model/cust/internal/cust_customer.go

@@ -19,6 +19,7 @@ type CustCustomer struct {
 	CustAddress  string      `orm:"cust_address"   json:"custAddress"`     // 详细地址
 	CustIndustry string      `orm:"cust_industry"   json:"custIndustry"`   //客户行业
 	CustLevel    string      `orm:"cust_level"   json:"custLevel"`         //客户级别(10 重点客户 20 普通客户 30非优客户)
+	CustSource   string      `orm:"cust_source"   json:"source"`           //客户来源
 	CustStatus   string      `orm:"cust_status"    json:"custStatus"`      // 客户状态(10正常20)
 	IsPublic     string      `orm:"is_public"      json:"isPublic"`        // 公海客户(10是20否)
 	DeptId       int         `orm:"dept_id"        json:"deptId"`          // 所属部门ID
@@ -34,6 +35,4 @@ type CustCustomer struct {
 	UpdatedName  string      `orm:"updated_name"   json:"updatedName"`     // 更新人
 	UpdatedTime  *gtime.Time `orm:"updated_time"   json:"updatedTime"`     // 更新时间
 	DeletedTime  *gtime.Time `orm:"deleted_time"   json:"deletedTime"`     // 删除时间
-	//Distributor  *base.BaseDistributor `orm:"with:belong_sale_id =sales_id"`      //
-	Contact *CustCustomerContact `orm:"with:cust_id=id"`
 }

+ 1 - 1
opms_parent/app/service/base.go

@@ -7,7 +7,7 @@ import (
 )
 
 var (
-	// CommonUpdateFieldEx, UpdateFieldEx 更新过滤字段
+	// CommonUpdateFieldEx  UpdateFieldEx 更新过滤字段
 	CommonUpdateFieldEx = []interface{}{"created_by", "created_name", "created_time"}
 	UpdateFieldEx       = []interface{}{"id", "created_by", "created_name", "created_time"}
 )

+ 11 - 5
opms_parent/app/service/base/base_distributor.go

@@ -55,10 +55,7 @@ func (d *distributorService) GetList(req *model.BaseDistributorSearchReq) (total
 		err = gerror.New("获取总行数失败")
 		return
 	}
-	if req.PageNum == 0 {
-		req.PageNum = 1
-	}
-	err = distributorModel.Page(req.PageNum, req.PageSize).Order("id desc").Scan(&distributorList)
+	err = distributorModel.Page(req.GetPage()).Order("id desc").Scan(&distributorList)
 	g.Log().Info("返回列表", distributorList)
 	return
 }
@@ -81,7 +78,16 @@ func (d *distributorService) Create(req *model.AddDistributor) (err error) {
 	return
 }
 
-//修改
+//详情
+func (p *distributorService) GetEntityById(id int64) (distributorInfo *model.DistributorRonp, err error) {
+	err = p.Dao.Where(base.BaseProduct.Columns.Id, id).Scan(&distributorInfo)
+	if err != nil {
+		g.Log().Error(err)
+		return nil, gerror.New("获取经销商数据失败")
+	}
+	return
+}
+
 //修改数据
 func (p *distributorService) UpdateById(req *model.UpdateDistributorReq) (err error) {
 	//uptime := gtime.New(time.Now())

+ 0 - 5
opms_parent/app/service/base/base_district.go

@@ -86,11 +86,6 @@ func (d *districtService) ListToRegions() (region []*model.Region) {
 		})
 	}
 	for _, v := range region {
-		g.Log().Info("msssss", ms[v.Id])
-		//if _, ok := ms[v.Id]; ok {
-		//	v.Children = ms[v.Id]
-		//	continue
-		//}
 		v.Children = ms[v.Id]
 	}
 	g.Log().Info("return", region)

+ 26 - 22
opms_parent/app/service/base/base_product.go

@@ -3,9 +3,12 @@ package base
 import (
 	"context"
 	"fmt"
+	"strconv"
 
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/os/gtime"
+	"github.com/gogf/gf/text/gstr"
 	"github.com/gogf/gf/util/gconv"
 
 	"dashoo.cn/micro/app/dao/base"
@@ -50,6 +53,16 @@ func (p *productService) GetList(req *model.BaseProductSearchReq) (total int, pr
 	return
 }
 
+//编辑查询单条查询
+func (p *productService) GetEntityById(id int64) (product *model.BaseProduct, err error) {
+	err = p.Dao.Where(base.BaseProduct.Columns.Id, id).Scan(&product)
+	if err != nil {
+		g.Log().Error(err)
+		return nil, gerror.New("获取用户数据失败")
+	}
+	return
+}
+
 //添加信息
 func (p *productService) Create(req *model.AddBaseProductReq) (err error) {
 	productData := new(model.BaseProduct)
@@ -58,6 +71,7 @@ func (p *productService) Create(req *model.AddBaseProductReq) (err error) {
 	}
 	service.SetCreatedInfo(productData, p.GetCxtUserId(), p.GetCxtUserName())
 	Model := p.Dao.M
+	productData.ProdCode = gstr.SubStr(strconv.Itoa(int(gtime.Now().UnixNano()/1e6)), 0, -5)
 	res, err := Model.Insert(productData)
 	if err != nil {
 		return
@@ -67,24 +81,6 @@ func (p *productService) Create(req *model.AddBaseProductReq) (err error) {
 	return
 }
 
-//删掉数据
-func (p *productService) DeleteByIds(dicIds []int64) (err error) {
-	_, err = base.BaseProduct.Fields(base.BaseProduct.Columns.CreatedTime).
-		Where(base.BaseProduct.Columns.Id+" in (?) ", dicIds).All()
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("没有要删除的数据")
-		return
-	}
-	_, err = p.Dao.Delete(base.BaseProduct.Columns.Id+" in (?) ", dicIds)
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("删除数据失败")
-		return err
-	}
-	return
-}
-
 //修改数据
 func (p *productService) UpdateById(req *model.UpdateBaseProductReq) (err error) {
 	//uptime := gtime.New(time.Now())
@@ -112,12 +108,20 @@ func (p *productService) UpdateById(req *model.UpdateBaseProductReq) (err error)
 	return
 }
 
-//编辑查询单条查询
-func (p *productService) GetEntityById(id int64) (product *model.BaseProduct, err error) {
-	err = p.Dao.Where(base.BaseProduct.Columns.Id, id).Scan(&product)
+//删掉数据
+func (p *productService) DeleteByIds(dicIds []int64) (err error) {
+	_, err = base.BaseProduct.Fields(base.BaseProduct.Columns.CreatedTime).
+		Where(base.BaseProduct.Columns.Id+" in (?) ", dicIds).All()
 	if err != nil {
 		g.Log().Error(err)
-		return nil, gerror.New("获取用户数据失败")
+		err = gerror.New("没有要删除的数据")
+		return
+	}
+	_, err = p.Dao.Delete(base.BaseProduct.Columns.Id+" in (?) ", dicIds)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("删除数据失败")
+		return err
 	}
 	return
 }

+ 0 - 1
opms_parent/app/service/base/base_sales_region.go

@@ -53,7 +53,6 @@ func (p *salesRegionService) Create(req *model.AddRegionReq) (err error) {
 	}
 	service.SetCreatedInfo(regionData, p.GetCxtUserId(), p.GetCxtUserName())
 	regionData.RegionCode = strconv.Itoa(int(gtime.Timestamp()))
-	service.SetCreatedInfo(regionData, p.GetCxtUserId(), p.GetCxtUserName())
 	_, err = Model.Insert(regionData)
 	if err != nil {
 		return err

+ 0 - 1
opms_parent/app/service/base/base_sales_region_detail.go

@@ -108,7 +108,6 @@ func (p *salesRegionDetailService) Create(req *model.AddBaseRegionDetailReq) (er
 	if err = gconv.Struct(req, detailData); err != nil {
 		return
 	}
-	service.SetCreatedInfo(detailData, p.GetCxtUserId(), p.GetCxtUserName())
 	detailData.RegionId = req.RegionId
 	detailData.ProvinceCode = req.ProvinceCode
 	service.SetCreatedInfo(detailData, p.GetCxtUserId(), p.GetCxtUserName())

+ 32 - 2
opms_parent/app/service/context.go

@@ -3,20 +3,28 @@ package service
 import (
 	"context"
 
+	"github.com/gogf/gf/os/glog"
+
 	"dashoo.cn/opms_libary/micro_srv"
 	"dashoo.cn/opms_libary/request"
-	"github.com/gogf/gf/os/glog"
 )
 
-// Context 上下文管理服务
+// ContextService 上下文管理服务
 type ContextService struct {
 	Tenant  string            `json:"tenant"`
+	Table   string            `json:"table"`
+	Ctx     context.Context   `json:"ctx"`
 	CxtUser *request.UserInfo `json:"cxtUser"`
 }
 
 // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
 func (c *ContextService) Init(ctx context.Context) (*ContextService, error) {
+	cs := ctx.Value("contextService")
+	if cs != nil {
+		return cs.(*ContextService), nil
+	}
 	c = new(ContextService)
+	c.Ctx = ctx
 	// 获取租户码
 	tenant, err := micro_srv.GetTenant(ctx)
 	if err != nil {
@@ -33,6 +41,7 @@ func (c *ContextService) Init(ctx context.Context) (*ContextService, error) {
 		}
 		c.CxtUser = &userInfo
 	}
+	c.Ctx = context.WithValue(ctx, "contextService", c)
 	return c, nil
 }
 
@@ -63,3 +72,24 @@ func (c *ContextService) GetCxtUserDeptId() int {
 	}
 	return c.CxtUser.DeptId
 }
+
+func (c *ContextService) GetCxtUserRoles() []string {
+	if c.CxtUser == nil {
+		return []string{}
+	}
+	return c.CxtUser.Roles
+}
+
+func (c *ContextService) GetCxtUserPosts() []string {
+	if c.CxtUser == nil {
+		return []string{}
+	}
+	return c.CxtUser.Posts
+}
+
+func (c *ContextService) GetCxtUserGroups() []string {
+	if c.CxtUser == nil {
+		return []string{}
+	}
+	return c.CxtUser.Groups
+}

+ 1 - 0
opms_parent/app/service/contract/ctr_contract.go

@@ -266,6 +266,7 @@ func (s CtrContractService) BindProduct(tx *gdb.TX, id int, product []model.CtrA
 			DeletedTime:   gtime.Now(),
 		})
 	}
+
 	if len(tocreate) != 0 {
 		_, err = tx.Insert("ctr_contract_product", tocreate)
 		if err != nil {

+ 331 - 329
opms_parent/app/service/cust/cust_customer.go

@@ -5,8 +5,8 @@ import (
 	"context"
 	"math"
 	"strconv"
-	"time"
 
+	"dashoo.cn/opms_libary/myerrors"
 	"github.com/360EntSecGroup-Skylar/excelize"
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
@@ -24,17 +24,19 @@ const TIME_LAYOUT = "2006-01-02 15:04:05"
 
 type CustomerService struct {
 	*service.ContextService
-	Dao         *cust.CustCustomerDao
-	BelongDao   *cust.CustCustomerBelongDao
-	DynamicsDao *cust.CustCustomerDynamicsDao
-	ContactDao  *cust.CustCustomerContactDao
-	FollowDao   *platdao.PlatFollowupDao
+	Dao            *cust.CustCustomerDao
+	BelongDao      *cust.CustCustomerBelongDao
+	DynamicsDao    *cust.CustCustomerDynamicsDao
+	ContactDao     *cust.CustCustomerContactDao
+	FollowDao      *platdao.PlatFollowupDao
+	BelongServer   *CustomerbelongService
+	ContanctServer *CustomercontactService
 }
 
-var isPublic, noPublic = "10", "20" // 公海,非公海
-var isTransfer int8 = 1             //转移
-var isAllocation int8 = 2           //分配 Allocation
-var OperaTion, AllocaTion, Receive = "20", "10", "30"
+var isPublic, noPublic = "10", "20"                                // 公海,非公海
+var isTransfer int8 = 1                                            //转移
+var isAllocation int8 = 2                                          //分配 Allocation
+var OperaTion, AllocaTion, Receive, Merge = "20", "10", "30", "40" // 10分配20转移30领取40合并
 
 type OpnType struct {
 	OperaTion string
@@ -50,140 +52,156 @@ func NewCustomerService(ctx context.Context) (svc *CustomerService, err error) {
 	svc.DynamicsDao = cust.NewCustCustomerDynamicsDao(svc.Tenant)
 	svc.ContactDao = cust.NewCustCustomerContactDao(svc.Tenant)
 	svc.FollowDao = platdao.NewPlatFollowupDao(svc.Tenant)
+	svc.BelongServer, _ = NewCustomerBelongService(ctx)
+	svc.ContanctServer, _ = NewCustomerContactService(ctx)
 	return svc, nil
 }
 
-//导出数据
-func (c *CustomerService) Derive(req *model.CustCustomerExport) (content *model.CustExport, err error) {
-	var con model.CustExport
-	req.CustCustomerSearchReq.TargetType = "11"
-	total, data, err := c.GetList(&req.CustCustomerSearchReq)
+//创建客户
+func (c *CustomerService) Create(req *model.CustomerAddSeq) (insertId int64, err error) {
+	cusTomer := new(model.CustCustomer)
+	count, err := c.Dao.Where(g.Map{"cust_name": req.CustName}).Count()
 	if err != nil {
+		err = myerrors.New("Sql执行异常", err)
 		return
 	}
-	f := excelize.NewFile()
-	index := f.NewSheet("Sheet1")
-	for index, item := range req.Columns {
-		sheetPosition := service.Div(index+1) + "1"
-		f.SetCellValue("Sheet1", sheetPosition, item)
+	if count > 0 {
+		err = myerrors.NewMsgError(nil, "该客户信息已存在,不可重复添加")
+		return
 	}
-	if total > 0 {
 
-		for ck, item := range data {
-			for index, v := range req.Columns {
-				if v == "经销商编码" {
-					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustCode)
-				}
-				if v == "经销商名称" {
-					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustName)
-				}
-				if v == "助记名" {
-					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.AbbrName)
-				}
-				//if v == "所在地区" {
-				//	f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.)
-				//}
-			}
+	if err = gconv.Struct(req, cusTomer); err != nil {
+		return
+	}
+	service.SetCreatedInfo(cusTomer, c.GetCxtUserId(), c.GetCxtUserName())
+	cusTomer.CustCode = "CT" + strconv.Itoa(int(gtime.Timestamp()))
+	cusTomer.CustStatus = "10"
 
+	Roles := c.GetCxtUserRoles()
+	roles := false
+	for _, v := range Roles {
+		if v == "Sales" { // 销售角色
+			roles = true
 		}
-
 	}
-	f.SetActiveSheet(index)
-
-	var buffer *bytes.Buffer
-	buffer, _ = f.WriteToBuffer()
-	con.Content = buffer.Bytes()
+	// 销售角色
+	if roles {
+		cusTomer.IsPublic = noPublic
+		cusTomer.SalesId = c.GetCxtUserId()
+		cusTomer.SalesName = c.GetCxtUserName()
+		insertId, err = c.Dao.InsertAndGetId(cusTomer)
+		if err != nil {
+			return
+		}
+		c.CreateContact(int(insertId))
 
-	return &con, err
+	} else {
+		cusTomer.IsPublic = isPublic
+		insertId, err = c.Dao.InsertAndGetId(cusTomer)
+		if err != nil {
+			err = gerror.New("创建失败")
+			return
+		}
+	}
+	return
 }
+func (c *CustomerService) CreateContact(cust_id int) (err error) {
+
+	belongData := new(model.CustCustomerBelong)
+	service.SetCreatedInfo(belongData, c.GetCxtUserId(), c.GetCxtUserName())
+	belongData.CustId = cust_id
+	belongData.SaleName = c.GetCxtUserName()
+	belongData.OpnType = AllocaTion
+	belongData.OpnPeople = c.GetCxtUserName()
+	belongData.OpnDatetime = gtime.Now()
+	_, err = c.BelongDao.InsertAndGetId(belongData)
+	if err != nil {
 
-//创建客户
-func (c *CustomerService) Create(req *model.Customer) (insertId int64, err error) {
-	cusTomer := new(model.CustCustomer)
-	g.Log().Info(err)
-	Model := c.Dao.M
-	record, err := Model.Where(g.Map{"cust_name": req.CustName}).One()
-	g.Log().Info("recordE", record.IsEmpty())
-	if err != nil || !record.IsEmpty() {
-		err = gerror.New("该客户信息已存在,不可重复添加")
 		return
 	}
-	//OpnPeopleId int         ` json:"opnPeopleId"` // 操作人ID
-	//OpnPeople   string      ` json:"opnPeople"`   // 操作人
-	//OpnDate     *gtime.Time ` json:"opnDate"`     // 操作日期
-	//OpnType     string      ` json:"opnType"`     // 操作类型
-	//OpnContent  string      ` json:"opnContent"`  // 操作内容
+	return
+}
 
-	//c.OperationLog()
-	if err = gconv.Struct(req, cusTomer); err != nil {
-		return
-	}
-	g.Log().Info("部门ID", c.CxtUser.DeptId)
-	service.SetCreatedInfo(cusTomer, c.GetCxtUserId(), c.GetCxtUserName())
-	cusTomer.CustCode = strconv.Itoa(int(gtime.Timestamp()))
-	cusTomer.IsPublic = isPublic
-	cusTomer.CustStatus = "10"
-	//if c.CxtUser.DeptId == 2 {
-	//	cusTomer.IsPublic = noPublic            //   非公海用户
-	//	cusTomer.DeptId = c.GetCxtUserDeptId()  //   部门id
-	//	cusTomer.DeptId = c.GetCxtUserDeptId()  //   部门名称
-	//	cusTomer.SalesId = c.GetCxtUserId()     //   销售id
-	//	cusTomer.SalesName = c.GetCxtUserName() //   销售名称
-	//}
-	res, err := Model.Insert(cusTomer)
+//删除客户
+func (c *CustomerService) DeleteById(id int) error {
+	Model := c.Dao
+	ContactModel := c.ContactDao //联系人
+	BelongModel := c.BelongDao
+	regionDetail := new(model.CustCustomer)
+	err := Model.Where(c.Dao.Columns.Id, id).Scan(&regionDetail)
 	if err != nil {
 		g.Log().Error(err)
-		err = gerror.New("创建失败")
-		return
+		err = gerror.New("没有要删除的数据")
+		return err
 	}
-	//
-
-	insertId, _ = res.LastInsertId()
 
-	//销售人员创建条件成立 同步belong 表
-	//custBelong := new(model.AddCustomerBelong)
-	//custBelong.CustId = int(insertId)
-	//custBelong.SaleName = "xxx"
-	//custBelong.OpnPeople = "xxxx"
-	//custBelong.OpnDatetime = gtime.Now()
-	//err = c.CreateBelong()
-	return
+	//删除客户表
+	_, err = Model.Where(c.Dao.Columns.Id, id).Delete()
+	if err == nil {
+		_, err = ContactModel.Where(c.ContactDao.Columns.CustId, id).Delete()
+		if err == nil {
+			_, err = BelongModel.Where(c.BelongDao.Columns.CustId, id).Delete()
+			if err != nil {
+				err = gerror.New("删除数据失败")
+				return err
+			}
+		} else {
+			err = gerror.New("删除数据失败")
+			return err
+		}
+	} else {
+		g.Log().Error(err)
+		err = gerror.New("删除数据失败")
+		return err
+	}
+	return nil
 }
 
-//销售人员创建 直接认领客户
-func (c *CustomerService) CreateBelong(req *model.AddCustomerBelong) (err error) {
-	cusTomerBelong := new(model.CustCustomerBelong)
-	if err = gconv.Struct(req, cusTomerBelong); err != nil {
-		g.Log().Info("error", err)
+//修改客户
+func (c *CustomerService) UpdateById(req *model.UpdateCustomer) (err error) {
+	db := c.Dao.M
+	count, err := db.Where(c.Dao.Columns.Id, req.Id).Count()
+	if err != nil {
+		err = gerror.New("修改用户信息失败")
 		return
 	}
-	service.SetCreatedInfo(cusTomerBelong, c.GetCxtUserId(), c.GetCxtUserName())
-
-	cusTomerBelong.OpnType = isPublic
-	cusTomerBelong.OpnDatetime = gtime.Now()
-	service.SetCreatedInfo(cusTomerBelong, c.GetCxtUserId(), c.GetCxtUserName())
-	_, err = c.BelongDao.Insert(cusTomerBelong)
+	if count == 0 {
+		err = gerror.New("用户信息不存在")
+		return
+	}
+	countNums, err := db.Where(c.Dao.Columns.CustName+" = ", req.CustName).Where(c.Dao.Columns.Id+" not in (?)", req.Id).Count()
 	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("创建失败")
+		err = gerror.New("修改用户信息失败")
+		return
+	}
+	if countNums > 0 {
+		err = gerror.New("客户名称已存在")
 		return
 	}
-	return nil
 
+	CustomertData := new(model.CustomerAddSeq)
+	if err = gconv.Struct(req, CustomertData); err != nil {
+		return
+	}
+	service.SetUpdatedInfo(CustomertData, c.GetCxtUserId(), c.GetCxtUserName())
+	_, err = db.FieldsEx(c.Dao.Columns.CreatedTime, c.Dao.Columns.CreatedBy, c.Dao.Columns.CreatedName, c.Dao.Columns.Id, c.Dao.Columns.CustCode, c.Dao.Columns.SalesName, c.Dao.Columns.SalesId).
+		WherePri(c.Dao.Columns.Id, req.Id).Update(CustomertData)
+	if err != nil {
+		err = gerror.New("修改用户信息失败")
+		return
+	}
+	return
 }
 
 //客户列表列表
 func (c *CustomerService) GetList(req *model.CustCustomerSearchReq) (total int, customerList []*model.CustList, err error) {
-
-	g.Log().Info("serverS", req)
 	Model := c.Dao.M
-	Model = Model.Where(c.Dao.Columns.DeletedTime + " is null")
 	if req.TargetType == "" {
 		if !req.IsPublic {
-			g.Log().Info("ISPUblic", "xxxxxx")
+
 			Model = Model.Where(c.Dao.Columns.SalesId, c.CxtUser.Id).Where(c.Dao.Columns.IsPublic, noPublic)
 		} else {
-			g.Log().Info("serverS", req)
+
 			Model = Model.Where(c.Dao.Columns.IsPublic, isPublic)
 		}
 	}
@@ -217,7 +235,8 @@ func (c *CustomerService) GetList(req *model.CustCustomerSearchReq) (total int,
 	if req.PageNum == 0 {
 		req.PageNum = 1
 	}
-	err = Model.Page(req.PageNum, req.PageSize).Order("id desc").Scan(&customerList)
+
+	err = Model.Page(req.GetPage()).Order("id desc").Scan(&customerList)
 	for _, v := range customerList {
 		times := gconv.String(v.CreatedTime)
 		v.FollowUpDate = gstr.SubStr(v.FollowUpDate, 0, 16)
@@ -226,65 +245,9 @@ func (c *CustomerService) GetList(req *model.CustCustomerSearchReq) (total int,
 	return
 }
 
-//删除客户
-func (c *CustomerService) DeleteById(id int) error {
-
-	Model := c.Dao.M
-	ContactModel := c.ContactDao //联系人
-	regionDetail := new(model.CustCustomer)
-	err := Model.Where(c.Dao.Columns.Id, id).Scan(&regionDetail)
-	//g.Log().Info("DeleteByIds", one)
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("没有要删除的数据")
-		return err
-	}
-	deleteTime := gtime.Now()
-	//删除客户表
-	_, err = Model.Data(g.Map{
-		"deleted_time": deleteTime,
-	}).Where(c.Dao.Columns.Id, id).Update()
-	// 删除客户联系人表
-	_, err = ContactModel.Data(g.Map{
-		"deleted_time": deleteTime,
-	}).Where(c.ContactDao.Columns.CustId, id).Update()
-
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("删除数据失败")
-		return err
-	}
-	return nil
-}
-
-//修改客户
-func (c *CustomerService) UpdateById(req *model.UpdateCustomer) (err error) {
-	db := c.Dao.M
-	record, err := db.FindOne(c.Dao.Columns.Id, req.Id)
-	if err != nil || record.IsEmpty() {
-		err = gerror.New("该数据不存在")
-		return err
-	}
-	CustomertData := new(model.Customer)
-	if err = gconv.Struct(req, CustomertData); err != nil {
-		return
-	}
-	service.SetUpdatedInfo(CustomertData, c.GetCxtUserId(), c.GetCxtUserName())
-	_, err = db.FieldsEx(c.Dao.Columns.CreatedTime, c.Dao.Columns.CreatedBy, c.Dao.Columns.CreatedName, c.Dao.Columns.Id, c.Dao.Columns.CustCode, c.Dao.Columns.SalesName, c.Dao.Columns.SalesId).
-		WherePri(c.Dao.Columns.Id, req.Id).Update(CustomertData)
-
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("修改用户信息失败")
-		return
-	}
-	return
-}
-
 //移入公海
 func (c *CustomerService) MoveToPubic(ids []int64) error {
 	Model := c.Dao.M
-	//Cust := new(model.CustCustomer)
 	list, err := Model.Fields(c.Dao.Columns.CreatedTime).Where(c.Dao.Columns.Id+" in (?) ", ids).All()
 	if err != nil || list.Len() <= 0 {
 		g.Log().Error(err)
@@ -313,29 +276,39 @@ func (c *CustomerService) MoveToPubic(ids []int64) error {
 
 //分配客户
 func (c *CustomerService) DistriCustomer(req *model.DistriCustomer) error {
-	custModel := c.Dao.M
+	custModel := c.Dao
 	rep, err := custModel.Where(cust.CustCustomer.Columns.Id+" in (?)  ", req.Ids).Where(cust.CustCustomer.Columns.IsPublic, isPublic).All()
 	if err != nil {
-		err = gerror.New("该数据不存在")
+		err = myerrors.New("DistriCustomer Sql执行异常", err)
 		return err
 	}
+	var custMap = make(map[int]string)
+	for _, v := range rep {
+		custMap[v.Id] = v.SalesName
+	}
+	g.Log().Info("fadfadsfaf", custMap)
+	for _, v := range req.Ids {
+		g.Log().Info("req.Ids", v)
+		if custMap[gconv.Int(v)] != "" {
+			err = gerror.New("ID" + gconv.String(v) + "已被认领")
+			return err
+		}
+	}
 	err = c.updateCustomer(req.Ids, req.SalesId, req.SalesName)
 	if err != nil {
 		err = gerror.New("可配客户失败")
 		return err
 
 	}
-	var maps = make(map[string]string)
-	maps["remark"] = req.Remark
 	if req.Receive != "" {
-		maps["opn_type"] = AllocaTion
+		req.Receive = Receive
 	} else {
-		maps["opn_type"] = Receive
+		req.Receive = AllocaTion
 	}
-	maps["sale_name"] = req.SalesName
-	maps["opn_people"] = c.GetCxtUserName()
-	//maps["created_by"] = c.GetCxtUserId()
-	err = c.belongInsters(rep.List(), maps)
+
+	err = c.Createbelong(rep, req)
+	g.Log().Info("errr", req)
+
 	if err != nil {
 		err = gerror.New("分配客户失败")
 		return err
@@ -345,59 +318,59 @@ func (c *CustomerService) DistriCustomer(req *model.DistriCustomer) error {
 
 //客户详情
 func (c *CustomerService) GetEntityById(ids []int64) (entityInfo []*model.CustList, err error) {
-	Model := c.Dao.M //
-	//FollowModel := c.FollowDao.M
-
+	Model := c.Dao //
 	err = Model.Where(cust.CustCustomer.Columns.Id+" in (?)", ids).Scan(&entityInfo)
+	if err != nil {
+		return nil, myerrors.New("获取用户数据失败", err)
+
+	}
 	for _, v := range entityInfo {
 		v.FollowUpDate = gstr.SubStr(v.FollowUpDate, 0, 16)
 		v.CreatedTime = gstr.SubStr(v.CreatedTime, 0, 16)
 	}
-	if err != nil {
-		g.Log().Error(err)
-		return nil, gerror.New("获取用户数据失败")
-	}
+
 	return
 }
 
 //客户摘要
 func (c *CustomerService) CustAbstract(id int64) (followInfo *model.Follow, err error) {
-	custModel := c.Dao.M //
-	Model := c.FollowDao.M
-
+	custModel := c.Dao //
+	Model := c.FollowDao
 	count, err := Model.Where(c.FollowDao.Columns.CustId, id).Count()
-	g.Log().Info("count", count)
 	if err != nil {
-		g.Log().Error(err)
-		return nil, gerror.New("获取用户数据失败")
-	}
 
+		err = myerrors.New("获取用户数据失败", err)
+		return
+	}
 	followInfo = new(model.Follow)
 	followInfo.FollowCount = count
 	//
-	find, err := custModel.Fields(c.Dao.Columns.FollowUpDate).Where(c.Dao.Columns.Id, id).FindOne()
-	g.Log().Info("find", find)
 
+	followUpdate, err := custModel.Fields(c.Dao.Columns.FollowUpDate).FindOne(id)
 	if err != nil {
-		g.Log().Error(err)
-		return nil, gerror.New("获取用户数据失败")
-	}
-
-	findOne := find.Map()
-	if findOne["follow_up_date"] == "" {
-		followInfo.NotFollowDay = 0
+		err = myerrors.New("CustAbstract Sql执行错误", err)
 		return
 	}
-	upDate := gconv.String(findOne["follow_up_date"])
-	follow_up, err1 := time.Parse(TIME_LAYOUT, upDate)
-	now := gtime.Now()
-	follow_next, err2 := time.Parse(TIME_LAYOUT, gconv.String(now))
-	if err1 != nil || err2 != nil {
+	if followUpdate.FollowUpDate == nil {
 		followInfo.NotFollowDay = 0
 		return
 	}
-	poor := follow_next.Sub(follow_up)
-	g.Log().Info("xxxxfdsaf", follow_up)
+
+	g.Log().Info("fasa1211", followUpdate)
+	//g.Log().Info("find", followUpdate)
+	//if err != nil {
+	//	g.Log().Error(err)
+	//	myerrors.New("获取用户数据失败", err)
+	//	return
+	//}
+	//if followUpdate.FollowUpDate != nil {
+	//	followInfo.NotFollowDay = 0
+	//	return
+	//}
+	upDate := gtime.New(followUpdate.FollowUpDate)
+	now := gtime.Now()
+	//
+	poor := now.Sub(upDate)
 	hours := float64(poor.Hours() / 24)
 	if hours < 0 {
 		followInfo.NotFollowDay = 0
@@ -408,27 +381,26 @@ func (c *CustomerService) CustAbstract(id int64) (followInfo *model.Follow, err
 }
 
 //转移客户
-func (c *CustomerService) UpdateBytransfer(req *model.CustSalesReq) (entityInfo []*model.CustCustomer, err error) {
-	custModel := c.Dao.M
-	rep, err := custModel.Fields("sales_id,sales_name,id").Where(cust.CustCustomer.Columns.Id+" in (?)", req.Ids).All()
-	if err != nil || rep.IsEmpty() {
-		err = gerror.New("该数据不存在")
+func (c *CustomerService) UpdateBytransfer(req *model.DistriCustomer) (err error) {
+	custModel := c.Dao
+	data, err := custModel.Fields("sales_id,sales_name,id").Where(cust.CustCustomer.Columns.Id+" in (?)", req.Ids).All()
+	if err != nil {
+		err = myerrors.New("Sql执行异常", err)
+		return err
+	}
+
+	if len(data) == 0 {
+		err = myerrors.New("该数据不存在", err)
 		return
 	}
-	err = c.updateCustomer(req.Ids, req.SalesIds, req.SalesName)
+	err = c.updateCustomer(req.Ids, req.SalesId, req.SalesName)
 	if err != nil {
-		err = gerror.New("转移客户失败")
 		return
 	}
 
-	var maps = make(map[string]string)
-	maps["remark"] = req.Remark
-	maps["opn_type"] = OperaTion
-	maps["sale_name"] = req.SalesName
-
-	err = c.belongInsters(rep.List(), maps)
+	err = c.Createbelong(data, req)
+	g.Log().Info("err", err)
 	if err != nil {
-		err = gerror.New("转移客户失败")
 		return
 	}
 	return
@@ -448,8 +420,7 @@ func (c *CustomerService) updateCustomer(ids []int64, salesId int64, salesName s
 	}).Where(cust.CustCustomer.Columns.Id+" in (?)", ids).Update()
 
 	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("变更失败")
+		err = myerrors.New("updateCustomer 变更执行失败", err)
 		return err
 	}
 	return nil
@@ -482,10 +453,13 @@ func (c *CustomerService) OperationLog(ctx context.Context, ids []int64, req *mo
 		contact["opn_content"] = req.OpnContent
 		maps = append(maps, contact)
 	}
-	_, err = Model.Insert(maps)
+	lastId, err := Model.InsertAndGetId(maps)
 	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("创建失败")
+		err = myerrors.New("OperationLog Sql执行失败", err)
+		return
+	}
+	if lastId == 0 {
+		err = myerrors.New("客户操作日志失败", err)
 		return
 	}
 	return
@@ -500,11 +474,11 @@ func (c *CustomerService) DynamicsList(req *model.CustomerDynameicsReq) (total i
 		err = gerror.New("获取总行数失败")
 		return
 	}
-	if req.PageNum == 0 {
-		req.PageNum = 1
-	}
+	//if req.PageNum == 0 {
+	//	req.PageNum = 1
+	//}
 	dynamics := []*model.CustomerDynameicsRep{}
-	err = Model.Page(req.PageNum, req.PageSize).Where("cust_id = ", req.CustId).Order("created_time desc").Scan(&dynamics)
+	err = Model.Where("cust_id = ", req.CustId).Order("created_time desc").Scan(&dynamics)
 	dynamicsList := make(map[string][]*model.CustomerDynameicsRep)
 
 	for _, v := range dynamics {
@@ -518,150 +492,178 @@ func (c *CustomerService) DynamicsList(req *model.CustomerDynameicsReq) (total i
 		})
 
 	}
-	g.Log().Info("DynamicsList----", dynamics)
-	//var ks []string
-	//for k, _ := range dynamicsList {
-	//	ks = append(ks, k)
-	//}
-	//sort.Sort(sort.Reverse(ks))
-	result = append(result, dynamicsList)
-	//var sslice []string
-	//for key, _ := range result {
-	//	sslice = append(sslice, key)
-	//}
-	//sort.Strings(sslice)
-
-	g.Log().Info("Dy---", result)
+	//g.Log().Info("DynamicsList----", dynamicsList)
+	//result = append(result, dynamicsList)
+	//g.Log().Info("Dy---", result)
 	return
 }
 
 //合并客户
 func (c *CustomerService) Mergecustomer(req *model.MergecustomerRep) (err error) {
 	Model := c.Dao.M
-	ContactModel := c.ContactDao.M
-	BelongDao := c.BelongDao.M
+	//ContactModel := c.ContactDao.M
+	BelongDao := c.BelongDao
 	//当前目标客户是否存在
 	FindOne, err := Model.Where(c.Dao.Columns.DeletedTime+" is  null").Where(c.Dao.Columns.Id, req.Id).FindOne()
 	if err != nil || FindOne.IsEmpty() {
 		err = gerror.New("该数据不存在")
 		return
 	}
-	//所选客户联系人信息
-	List, err := ContactModel.Where(c.ContactDao.Columns.CustId+" in (?)", req.ChooseId).All()
-	g.Log().Info("list", List.List())
-	CustomertData := new(model.Customer)
+	ContactModel := c.ContactDao
+	_, err = ContactModel.Where(c.ContactDao.Columns.CustId+" in (?)", req.ChooseId).WhereOr(c.ContactDao.Columns.CustId, req.Id).Delete()
+	if err != nil {
+		err = gerror.New("合并联系人失败")
+		return
+	}
+	CustomertData := new(model.CustomerAddSeq)
 	if err = gconv.Struct(req, CustomertData); err != nil {
 		return
 	}
 	service.SetUpdatedInfo(CustomertData, c.GetCxtUserId(), c.GetCxtUserName())
 	_, err = Model.FieldsEx(c.Dao.Columns.CreatedTime, c.Dao.Columns.CreatedBy,
 		c.Dao.Columns.CreatedName, c.Dao.Columns.Id,
-		c.Dao.Columns.CustCode,
-		c.Dao.Columns.SalesName,
-		c.Dao.Columns.SalesId).WherePri(c.Dao.Columns.Id, req.Id).Update(CustomertData)
+		c.Dao.Columns.CustCode).WherePri(c.Dao.Columns.Id, req.Id).Update(CustomertData)
 	if err != nil {
 		err = gerror.New("合并失败")
 		return
 	}
-	Model.Data(g.Map{"deleted_time": gtime.Now()}).Where(c.ContactDao.Columns.Id+" in (?)", req.ChooseId).Update()
-	if err != nil || List.Len() > 0 {
-		err = c.contactInster(req.Id, req.ChooseId, List.List())
-		if err != nil {
-			err = gerror.New("合并失败")
-			return
-		}
+	//删除被合并的客户信息
+	Model.Where(c.Dao.Columns.Id+" in (?)", req.ChooseId).Delete()
+	//删除 所选客户销售联系人
+	_, err = BelongDao.Where(c.BelongDao.Columns.CustId+" in (?)", req.ChooseId).WhereOr(c.BelongDao.Columns.CustId, req.Id).Delete()
+	if err != nil {
+		err = gerror.New("合并失败")
+		return
 	}
-	////所选客户销售联系人信息
-	BelongList, err := BelongDao.Where(c.BelongDao.Columns.CustId+" in (?)", req.ChooseId).All()
-	if err != nil || BelongList.Len() > 0 {
-		err = c.belongInster(req.Id, req.ChooseId, req.Customer.SalesName)
-		if err != nil {
-			err = gerror.New("合并失败")
-			return
-		}
+
+	//插入一条合并成功的归属记录
+	belongService := c.BelongServer //
+	req.AddCustomerBelong.CustId = req.Id
+	req.AddCustomerBelong.OpnType = Merge
+	req.AddCustomerBelong.OpnPeople = c.GetCxtUserName()
+	req.AddCustomerBelong.OpnDatetime = gtime.Now()
+	req.AddCustomerBelong.SaleName = req.SalesName
+	err = belongService.Create(req.AddCustomerBelong)
+	if err != nil {
+		err = gerror.New("合并失败")
+		return
 	}
 	return
 }
 
-//联系人
-func (c *CustomerService) contactInster(id int, Ids []int64, list []map[string]interface{}) (err error) {
+//联系人(合并)
+func (c *CustomerService) Createcontact(id int, Ids []int64, req *model.CustCustomerContactSeq) (err error) {
 	ContactModel := c.ContactDao.M
-	ContactModel.Data(g.Map{"deleted_time": gtime.Now()}).Where(c.ContactDao.Columns.CustId+" in (?)", Ids).Update()
-	maps := []map[string]interface{}{}
-	for _, v := range list {
-		contact := map[string]interface{}{}
-		contact["cust_id"] = id
-		contact["cuct_name"] = v["cuct_name"]
-		contact["cuct_gender"] = v["cuct_gender"]
-		contact["postion"] = v["postion"]
-		contact["telephone"] = v["telephone"]
-		contact["wechat"] = v["wechat"]
-		contact["email"] = v["email"]
-		contact["policy"] = v["policy"]
-		contact["remark"] = v["remark"]
-		contact["created_by"] = v["created_by"]
-		contact["created_name"] = v["created_name"]
-		contact["created_time"] = v["created_time"]
-		maps = append(maps, contact)
-	}
-	_, err = ContactModel.Insert(maps)
+	_, err = ContactModel.Where(c.ContactDao.Columns.CustId+" in (?)", Ids).WhereOr(c.ContactDao.Columns.CustId, id).Delete()
 	if err != nil {
-		err = gerror.New("操作失败")
-		g.Log().Info("contactInster", err)
+		err = gerror.New("合并联系人失败")
 		return
-
 	}
-
-	return
-}
-
-//销售
-func (c *CustomerService) belongInster(Id int, BelongIds []int64, SaleName string) (err error) {
-	BelongDao := c.BelongDao.M
-	BelongDao.Data(g.Map{"deleted_time": gtime.Now()}).Where(c.BelongDao.Columns.CustId+" in (?)", BelongIds).Update()
-	BelongData := new(model.CustCustomerBelong)
-	BelongData.CustId = Id
-	service.SetCreatedInfo(BelongData, c.GetCxtUserId(), c.GetCxtUserName())
-	BelongData.SaleName = SaleName
-	BelongData.OpnType = AllocaTion
-	BelongData.OrigSaleName = ""
-	BelongData.OpnPeople = "admin"
-	BelongData.OpnDatetime = gtime.Now()
-	_, err = BelongDao.Insert(BelongData)
+	contactService := c.ContanctServer //new(CustomercontactService)
+	err = contactService.Create(req)
 	if err != nil {
-		g.Log().Info("BeloongInster", err)
-		err = gerror.New("操作失败")
+		err = gerror.New("合并联系人失败")
 		return
 	}
 	return
 }
 
-//批量插入客户归属记录表
-func (c *CustomerService) belongInsters(rep []map[string]interface{}, parameter map[string]string) (err error) {
-	belongModel := c.BelongDao.M
-	maps := []map[string]interface{}{}
+//批量插入客户归属记录表//parameter map[string]string
+func (c *CustomerService) Createbelong(rep []*model.CustCustomer, req *model.DistriCustomer) (err error) {
+	belongModel := c.BelongDao
+	var belongData []*model.CustCustomerBelong
 	date_time := gtime.Now()
+	userName := c.GetCxtUserName()
 	for _, v := range rep {
-		orig_sale_name := v["sales_name"]
-		belong := map[string]interface{}{}
-		belong["cust_id"] = v["id"].(int)
-		belong["sale_name"] = parameter["sale_name"]
-		belong["orig_sale_name"] = orig_sale_name
-		belong["opn_type"] = parameter["opn_type"]
-		belong["opn_people"] = parameter["opn_people"]
-		belong["opn_datetime"] = date_time
-		belong["created_by"] = c.GetCxtUserId()
-		belong["remark"] = parameter["remark"]
-		belong["created_name"] = c.GetCxtUserName()
-		belong["created_time"] = date_time
-		belong["opn_datetime"] = date_time
-		maps = append(maps, belong)
-	}
-	_, err = belongModel.Insert(maps)
+		orig_sale_name := v.SalesName
+		belong := new(model.CustCustomerBelong) //map[string]interface{}{}
+		belong.CustId = v.Id
+		belong.SaleName = req.SalesName
+		belong.OrigSaleName = orig_sale_name
+		belong.OpnType = req.Receive
+		belong.OpnPeople = userName
+		belong.CreatedName = userName
+		belong.OpnDatetime = date_time
+		belong.Remark = req.Remark
+		belong.CreatedBy = c.GetCxtUserId()
+		belongData = append(belongData, belong)
+	}
+	lastId, err := belongModel.InsertAndGetId(belongData)
+	g.Log().Info("belong", belongData)
 	if err != nil {
-		err = gerror.New("插入失败")
+		err = myerrors.New("Createbelong Sql执行异常", err)
+		return err
+	}
+	if lastId == 0 {
+		err = myerrors.New("Createbelong 插入", err)
 		return err
 	}
-
 	return
 }
+
+//导出数据
+func (c *CustomerService) Export(req *model.CustCustomerExport) (content *model.CustExport, err error) {
+	var con model.CustExport
+	total, data, err := c.GetList(&req.CustCustomerSearchReq)
+	if err != nil {
+		return
+	}
+	f := excelize.NewFile()
+	index := f.NewSheet("Sheet1")
+	for index, item := range req.Columns {
+		sheetPosition := service.Div(index+1) + "1"
+		f.SetCellValue("Sheet1", sheetPosition, item)
+	}
+	if total > 0 {
+
+		for ck, item := range data {
+			for index, v := range req.Columns {
+				// "CustCode":客户编码
+				if v == "客户编码" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustCode)
+				}
+				if v == "客户名称" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustName)
+				}
+				if v == "助记名" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.AbbrName)
+				}
+				if v == "助记名" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.AbbrName)
+				}
+				if v == "所在地区" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustLocation)
+				}
+				if v == "客户行业" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustIndustry)
+				}
+				if v == "客户级别" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CustLevel)
+				}
+				if v == "客户状态" {
+					var CustStatus string
+					CustStatus = "正常"
+					if item.CustStatus != "10" {
+						CustStatus = "异常"
+					}
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), CustStatus)
+				}
+				if v == "最后跟进时间" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.FollowUpDate)
+				}
+				if v == "创建时间" {
+					f.SetCellValue("Sheet1", service.Div(index+1)+strconv.Itoa(ck+2), item.CreatedTime)
+				}
+			}
+
+		}
+
+	}
+	f.SetActiveSheet(index)
+
+	var buffer *bytes.Buffer
+	buffer, _ = f.WriteToBuffer()
+	con.Content = buffer.Bytes()
+
+	return &con, err
+}

+ 24 - 5
opms_parent/app/service/cust/cust_customer_belong.go

@@ -5,19 +5,20 @@ import (
 
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/util/gconv"
 
 	"dashoo.cn/micro/app/dao/cust"
 	model "dashoo.cn/micro/app/model/cust"
 	"dashoo.cn/micro/app/service"
 )
 
-type customerbelongService struct {
+type CustomerbelongService struct {
 	*service.ContextService
 	Dao *cust.CustCustomerBelongDao
 }
 
-func NewCustomerBelongService(ctx context.Context) (svc *customerbelongService, err error) {
-	svc = new(customerbelongService)
+func NewCustomerBelongService(ctx context.Context) (svc *CustomerbelongService, err error) {
+	svc = new(CustomerbelongService)
 	if svc.ContextService, err = svc.Init(ctx); err != nil {
 		return nil, err
 	}
@@ -26,8 +27,8 @@ func NewCustomerBelongService(ctx context.Context) (svc *customerbelongService,
 }
 
 //获取客户归属信息
-func (c *customerbelongService) GetEntityById(CustId int) (Info []*model.CustomerBelongInfo, err error) {
-	Model := c.Dao.M
+func (c *CustomerbelongService) GetList(CustId int) (Info []*model.CustomerBelongInfo, err error) {
+	Model := c.Dao
 	err = Model.Where(c.Dao.Columns.CustId, CustId).Where(c.Dao.Columns.DeletedTime + " is null ").Scan(&Info)
 	if err != nil {
 		g.Log().Error(err)
@@ -36,3 +37,21 @@ func (c *customerbelongService) GetEntityById(CustId int) (Info []*model.Custome
 	}
 	return
 }
+
+//插入归属销售
+func (c *CustomerbelongService) Create(req *model.AddCustomerBelong) (err error) {
+	Model := c.Dao
+	cusTomerBelong := new(model.CustCustomerBelong)
+	if err = gconv.Struct(req, cusTomerBelong); err != nil {
+		g.Log().Info("error", err)
+		return
+	}
+	service.SetCreatedInfo(cusTomerBelong, c.GetCxtUserId(), c.GetCxtUserName())
+	_, err = Model.Insert(cusTomerBelong)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("创建失败")
+		return
+	}
+	return nil
+}

+ 9 - 12
opms_parent/app/service/cust/cust_customer_contact.go

@@ -6,7 +6,6 @@ import (
 
 	"github.com/gogf/gf/errors/gerror"
 	"github.com/gogf/gf/frame/g"
-	"github.com/gogf/gf/os/gtime"
 	"github.com/gogf/gf/util/gconv"
 
 	"dashoo.cn/micro/app/dao/cust"
@@ -15,13 +14,13 @@ import (
 	//serviceLog "dashoo.cn/micro/app/service/cust"
 )
 
-type customercontactService struct {
+type CustomercontactService struct {
 	*service.ContextService
 	Dao *cust.CustCustomerContactDao
 }
 
-func NewCustomerContactService(ctx context.Context) (svc *customercontactService, err error) {
-	svc = new(customercontactService)
+func NewCustomerContactService(ctx context.Context) (svc *CustomercontactService, err error) {
+	svc = new(CustomercontactService)
 
 	if svc.ContextService, err = svc.Init(ctx); err != nil {
 		return nil, err
@@ -33,7 +32,7 @@ func NewCustomerContactService(ctx context.Context) (svc *customercontactService
 }
 
 //添加联系人
-func (c *customercontactService) Create(req *model.CustCustomerContactSeq) (err error) {
+func (c *CustomercontactService) Create(req *model.CustCustomerContactSeq) (err error) {
 	contact := new(model.CustCustomerContact)
 	if err = gconv.Struct(req, contact); err != nil {
 		g.Log().Info("error", err)
@@ -52,7 +51,7 @@ func (c *customercontactService) Create(req *model.CustCustomerContactSeq) (err
 }
 
 //修改联系人
-func (c *customercontactService) UpdateById(req *model.UpdateCustCustomerContactSeq) (err error) {
+func (c *CustomercontactService) UpdateById(req *model.UpdateCustCustomerContactSeq) (err error) {
 	Model := c.Dao.M
 	record, err := Model.FindOne("Id", req.Id)
 	if err != nil || record.IsEmpty() {
@@ -76,7 +75,7 @@ func (c *customercontactService) UpdateById(req *model.UpdateCustCustomerContact
 }
 
 //获取联系人信息
-func (c *customercontactService) GetEntityById(CustId int) (Info []*model.CustCustomerContactInfo, err error) {
+func (c *CustomercontactService) GetList(CustId int) (Info []*model.CustCustomerContactInfo, err error) {
 	Model := c.Dao.M
 	err = Model.Where(c.Dao.Columns.CustId, CustId).Where(c.Dao.Columns.DeletedTime + " is null").Scan(&Info)
 	if err != nil {
@@ -88,14 +87,12 @@ func (c *customercontactService) GetEntityById(CustId int) (Info []*model.CustCu
 }
 
 //删除联系人
-func (c *customercontactService) DeleteById(id int) error {
+func (c *CustomercontactService) DeleteById(id int) error {
 	Model := c.Dao.M
 
-	deleteTime := gtime.Now()
+	//deleteTime := gtime.Now()
 	// 删除客户联系人表
-	_, err := Model.Data(g.Map{
-		"deleted_time": deleteTime,
-	}).Where(c.Dao.Columns.Id, id).Update()
+	_, err := Model.Where(c.Dao.Columns.Id, id).Delete()
 	if err != nil {
 		g.Log().Error(err)
 		err = gerror.New("删除数据失败")

+ 1 - 1
opms_parent/main.go

@@ -28,7 +28,7 @@ func main() {
 	s.RegisterName("District", new(base.DistrictHandler), "")
 	s.RegisterName("Region", new(base.RegionHandler), "")
 	s.RegisterName("Customer", new(cust.CustomerHeader), "")
-	s.RegisterName("Contant", new(cust.CustomerContantHeader), "")
+	s.RegisterName("Contact", new(cust.CustomerContantHeader), "")
 	s.RegisterName("Belong", new(cust.CustBelongHeader), "")
 	s.RegisterName("FollowUp", new(plat.FollowUpHandler), "")
 	s.RegisterName("FollowUpComment", new(plat.FollowUpCommentHandler), "")