Selaa lähdekoodia

Merge branch 'develop' into feature/项目管理

# Conflicts:
#	opms_parent/app/handler/dingtalk/ding_event.go
#	opms_parent/app/model/workflow/plat_workflow.go
ZZH-wl 3 vuotta sitten
vanhempi
commit
ffbb47cefa
34 muutettua tiedostoa jossa 1811 lisäystä ja 204 poistoa
  1. 36 0
      opms_admin/app/dao/base_region_auth.go
  2. 450 0
      opms_admin/app/dao/internal/base_region_auth.go
  3. 2 2
      opms_admin/app/handler/base_product_auth.go
  4. 64 0
      opms_admin/app/handler/base_region_auth.go
  5. 17 7
      opms_admin/app/model/base_product_auth.go
  6. 63 0
      opms_admin/app/model/base_region_auth.go
  7. 32 0
      opms_admin/app/model/internal/base_region_auth.go
  8. 3 9
      opms_admin/app/service/base_product_auth.go
  9. 187 0
      opms_admin/app/service/base_region_auth.go
  10. 1 0
      opms_admin/main.go
  11. 42 36
      opms_parent/app/dao/base/internal/base_sales_region_detail.go
  12. 1 1
      opms_parent/app/dao/contract/internal/ctr_contract_invoice.go
  13. 14 0
      opms_parent/app/handler/contract/ctr_contract_invoice.go
  14. 2 16
      opms_parent/app/handler/cust/customer.go
  15. 53 0
      opms_parent/app/handler/dingtalk/ding_event.go
  16. 20 17
      opms_parent/app/model/base/base_sales_region_detail.go
  17. 14 12
      opms_parent/app/model/base/internal/base_sales_region_detail.go
  18. 6 0
      opms_parent/app/model/contract/ctr_contract_invoice.go
  19. 1 1
      opms_parent/app/model/contract/internal/ctr_contract_invoice.go
  20. 1 1
      opms_parent/app/model/cust/cust_customer.go
  21. 5 3
      opms_parent/app/model/workflow/plat_workflow.go
  22. 1 1
      opms_parent/app/service/base/base_sales_region.go
  23. 2 2
      opms_parent/app/service/base/base_sales_region_detail.go
  24. 3 5
      opms_parent/app/service/contract/ctr_contract.go
  25. 2 3
      opms_parent/app/service/contract/ctr_contract_append.go
  26. 2 3
      opms_parent/app/service/contract/ctr_contract_collection.go
  27. 2 3
      opms_parent/app/service/contract/ctr_contract_collection_plan.go
  28. 228 5
      opms_parent/app/service/contract/ctr_contract_invoice.go
  29. 39 0
      opms_parent/app/service/contract/ctr_contract_test.go
  30. 429 75
      opms_parent/app/service/cust/cust_customer.go
  31. 86 0
      opms_parent/app/service/cust/cust_customer_test.go
  32. 1 1
      opms_parent/app/service/workflow/work_flow.go
  33. 1 1
      opms_parent/schema/contract.sql
  34. 1 0
      opms_parent/schema/tmp.sql

+ 36 - 0
opms_admin/app/dao/base_region_auth.go

@@ -0,0 +1,36 @@
+// ============================================================================
+// This is auto-generated by gf cli tool only once. Fill this file as you wish.
+// ============================================================================
+
+package dao
+
+import (
+	"dashoo.cn/micro/app/dao/internal"
+)
+
+// baseRegionAuthDao is the manager for logic model data accessing
+// and custom defined data operations functions management. You can define
+// methods on it to extend its functionality as you wish.
+type baseRegionAuthDao struct {
+	internal.BaseRegionAuthDao
+}
+
+var (
+	// BaseRegionAuth is globally public accessible object for table base_region_auth operations.
+	BaseRegionAuth = baseRegionAuthDao{
+		internal.BaseRegionAuth,
+	}
+)
+
+type BaseRegionAuthDao struct {
+	internal.BaseRegionAuthDao
+}
+
+func NewBaseRegionAuthDao(tenant string) *BaseRegionAuthDao {
+	dao := internal.NewBaseRegionAuthDao(tenant)
+	return &BaseRegionAuthDao{
+		dao,
+	}
+}
+
+// Fill with you ideas below.

+ 450 - 0
opms_admin/app/dao/internal/base_region_auth.go

@@ -0,0 +1,450 @@
+// ==========================================================================
+// This is auto-generated by gf cli tool. DO NOT EDIT THIS FILE MANUALLY.
+// ==========================================================================
+
+package internal
+
+import (
+	"context"
+	"database/sql"
+	"github.com/gogf/gf/database/gdb"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/frame/gmvc"
+	"time"
+
+	"dashoo.cn/micro/app/model"
+)
+
+// BaseRegionAuthDao is the manager for logic model data accessing
+// and custom defined data operations functions management.
+type BaseRegionAuthDao struct {
+	gmvc.M
+	DB      gdb.DB
+	Table   string
+	Columns baseRegionAuthColumns
+}
+
+// BaseRegionAuthColumns defines and stores column names for table base_region_auth.
+type baseRegionAuthColumns struct {
+	Id             string // 主键
+	UserId         string // 用户ID
+	UserName       string // 姓名
+	UserPost       string // 岗位
+	UserPhone      string // 电话
+	SaleRegionId   string // 销售区域ID
+	SaleRegionName string // 销售区域名称
+	ProvinceId     string // 省ID
+	ProvinceName   string // 省名称
+	CityId         string // 市ID
+	CityName       string // 市名称
+	Remark         string // 备注
+	CreatedBy      string // 创建者
+	CreatedName    string // 创建人
+	CreatedTime    string // 创建时间
+	UpdatedBy      string // 更新者
+	UpdatedName    string // 更新人
+	UpdatedTime    string // 更新时间
+	DeletedTime    string // 删除时间
+}
+
+var (
+	// BaseRegionAuth is globally public accessible object for table base_region_auth operations.
+	BaseRegionAuth = BaseRegionAuthDao{
+		M:     g.DB("default").Model("base_region_auth").Safe(),
+		DB:    g.DB("default"),
+		Table: "base_region_auth",
+		Columns: baseRegionAuthColumns{
+			Id:             "id",
+			UserId:         "user_id",
+			UserName:       "user_name",
+			UserPost:       "user_post",
+			UserPhone:      "user_phone",
+			SaleRegionId:   "sale_region_id",
+			SaleRegionName: "sale_region_name",
+			ProvinceId:     "province_id",
+			ProvinceName:   "province_name",
+			CityId:         "city_id",
+			CityName:       "city_name",
+			Remark:         "remark",
+			CreatedBy:      "created_by",
+			CreatedName:    "created_name",
+			CreatedTime:    "created_time",
+			UpdatedBy:      "updated_by",
+			UpdatedName:    "updated_name",
+			UpdatedTime:    "updated_time",
+			DeletedTime:    "deleted_time",
+		},
+	}
+)
+
+func NewBaseRegionAuthDao(tenant string) BaseRegionAuthDao {
+	var dao BaseRegionAuthDao
+	dao = BaseRegionAuthDao{
+		M:     g.DB(tenant).Model("base_region_auth").Safe(),
+		DB:    g.DB(tenant),
+		Table: "base_region_auth",
+		Columns: baseRegionAuthColumns{
+			Id:             "id",
+			UserId:         "user_id",
+			UserName:       "user_name",
+			UserPost:       "user_post",
+			UserPhone:      "user_phone",
+			SaleRegionId:   "sale_region_id",
+			SaleRegionName: "sale_region_name",
+			ProvinceId:     "province_id",
+			ProvinceName:   "province_name",
+			CityId:         "city_id",
+			CityName:       "city_name",
+			Remark:         "remark",
+			CreatedBy:      "created_by",
+			CreatedName:    "created_name",
+			CreatedTime:    "created_time",
+			UpdatedBy:      "updated_by",
+			UpdatedName:    "updated_name",
+			UpdatedTime:    "updated_time",
+			DeletedTime:    "deleted_time",
+		},
+	}
+	return dao
+}
+
+// Ctx is a chaining function, which creates and returns a new DB that is a shallow copy
+// of current DB object and with given context in it.
+// Note that this returned DB object can be used only once, so do not assign it to
+// a global or package variable for long using.
+func (d *BaseRegionAuthDao) Ctx(ctx context.Context) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Ctx(ctx)}
+}
+
+// As sets an alias name for current table.
+func (d *BaseRegionAuthDao) As(as string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.As(as)}
+}
+
+// TX sets the transaction for current operation.
+func (d *BaseRegionAuthDao) TX(tx *gdb.TX) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.TX(tx)}
+}
+
+// Master marks the following operation on master node.
+func (d *BaseRegionAuthDao) Master() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Master()}
+}
+
+// Slave marks the following operation on slave node.
+// Note that it makes sense only if there's any slave node configured.
+func (d *BaseRegionAuthDao) Slave() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Slave()}
+}
+
+// Args sets custom arguments for model operation.
+func (d *BaseRegionAuthDao) Args(args ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Args(args...)}
+}
+
+// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
+// The parameter <table> can be joined table and its joined condition,
+// and also with its alias name, like:
+// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
+// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
+func (d *BaseRegionAuthDao) LeftJoin(table ...string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.LeftJoin(table...)}
+}
+
+// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
+// The parameter <table> can be joined table and its joined condition,
+// and also with its alias name, like:
+// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
+// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
+func (d *BaseRegionAuthDao) RightJoin(table ...string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.RightJoin(table...)}
+}
+
+// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
+// The parameter <table> can be joined table and its joined condition,
+// and also with its alias name, like:
+// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
+// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
+func (d *BaseRegionAuthDao) InnerJoin(table ...string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.InnerJoin(table...)}
+}
+
+// Fields sets the operation fields of the model, multiple fields joined using char ','.
+// The parameter <fieldNamesOrMapStruct> can be type of string/map/*map/struct/*struct.
+func (d *BaseRegionAuthDao) Fields(fieldNamesOrMapStruct ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Fields(fieldNamesOrMapStruct...)}
+}
+
+// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
+// The parameter <fieldNamesOrMapStruct> can be type of string/map/*map/struct/*struct.
+func (d *BaseRegionAuthDao) FieldsEx(fieldNamesOrMapStruct ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.FieldsEx(fieldNamesOrMapStruct...)}
+}
+
+// Option sets the extra operation option for the model.
+func (d *BaseRegionAuthDao) Option(option int) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Option(option)}
+}
+
+// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
+// the data and where attributes for empty values.
+func (d *BaseRegionAuthDao) OmitEmpty() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.OmitEmpty()}
+}
+
+// Filter marks filtering the fields which does not exist in the fields of the operated table.
+func (d *BaseRegionAuthDao) Filter() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Filter()}
+}
+
+// Where sets the condition statement for the model. The parameter <where> can be type of
+// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
+// multiple conditions will be joined into where statement using "AND".
+// Eg:
+// Where("uid=10000")
+// Where("uid", 10000)
+// Where("money>? AND name like ?", 99999, "vip_%")
+// Where("uid", 1).Where("name", "john")
+// Where("status IN (?)", g.Slice{1,2,3})
+// Where("age IN(?,?)", 18, 50)
+// Where(User{ Id : 1, UserName : "john"})
+func (d *BaseRegionAuthDao) Where(where interface{}, args ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Where(where, args...)}
+}
+
+// WherePri does the same logic as M.Where except that if the parameter <where>
+// is a single condition like int/string/float/slice, it treats the condition as the primary
+// key value. That is, if primary key is "id" and given <where> parameter as "123", the
+// WherePri function treats the condition as "id=123", but M.Where treats the condition
+// as string "123".
+func (d *BaseRegionAuthDao) WherePri(where interface{}, args ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.WherePri(where, args...)}
+}
+
+// And adds "AND" condition to the where statement.
+func (d *BaseRegionAuthDao) And(where interface{}, args ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.And(where, args...)}
+}
+
+// Or adds "OR" condition to the where statement.
+func (d *BaseRegionAuthDao) Or(where interface{}, args ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Or(where, args...)}
+}
+
+// Group sets the "GROUP BY" statement for the model.
+func (d *BaseRegionAuthDao) Group(groupBy string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Group(groupBy)}
+}
+
+// Order sets the "ORDER BY" statement for the model.
+func (d *BaseRegionAuthDao) Order(orderBy ...string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Order(orderBy...)}
+}
+
+// Limit sets the "LIMIT" statement for the model.
+// The parameter <limit> can be either one or two number, if passed two number is passed,
+// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
+// statement.
+func (d *BaseRegionAuthDao) Limit(limit ...int) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Limit(limit...)}
+}
+
+// Offset sets the "OFFSET" statement for the model.
+// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
+func (d *BaseRegionAuthDao) Offset(offset int) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Offset(offset)}
+}
+
+// Page sets the paging number for the model.
+// The parameter <page> is started from 1 for paging.
+// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
+func (d *BaseRegionAuthDao) Page(page, limit int) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Page(page, limit)}
+}
+
+// Batch sets the batch operation number for the model.
+func (d *BaseRegionAuthDao) Batch(batch int) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Batch(batch)}
+}
+
+// Cache sets the cache feature for the model. It caches the result of the sql, which means
+// if there's another same sql request, it just reads and returns the result from cache, it
+// but not committed and executed into the database.
+//
+// If the parameter <duration> < 0, which means it clear the cache with given <name>.
+// If the parameter <duration> = 0, which means it never expires.
+// If the parameter <duration> > 0, which means it expires after <duration>.
+//
+// The optional parameter <name> is used to bind a name to the cache, which means you can later
+// control the cache like changing the <duration> or clearing the cache with specified <name>.
+//
+// Note that, the cache feature is disabled if the model is operating on a transaction.
+func (d *BaseRegionAuthDao) Cache(duration time.Duration, name ...string) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Cache(duration, name...)}
+}
+
+// Data sets the operation data for the model.
+// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
+// Eg:
+// Data("uid=10000")
+// Data("uid", 10000)
+// Data(g.Map{"uid": 10000, "name":"john"})
+// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
+func (d *BaseRegionAuthDao) Data(data ...interface{}) *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Data(data...)}
+}
+
+// All does "SELECT FROM ..." statement for the model.
+// It retrieves the records from table and returns the result as []*model.BaseRegionAuth.
+// It returns nil if there's no record retrieved with the given conditions from table.
+//
+// The optional parameter <where> is the same as the parameter of M.Where function,
+// see M.Where.
+func (d *BaseRegionAuthDao) All(where ...interface{}) ([]*model.BaseRegionAuth, error) {
+	all, err := d.M.All(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entities []*model.BaseRegionAuth
+	if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entities, nil
+}
+
+// One retrieves one record from table and returns the result as *model.BaseRegionAuth.
+// It returns nil if there's no record retrieved with the given conditions from table.
+//
+// The optional parameter <where> is the same as the parameter of M.Where function,
+// see M.Where.
+func (d *BaseRegionAuthDao) One(where ...interface{}) (*model.BaseRegionAuth, error) {
+	one, err := d.M.One(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entity *model.BaseRegionAuth
+	if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entity, nil
+}
+
+// FindOne retrieves and returns a single Record by M.WherePri and M.One.
+// Also see M.WherePri and M.One.
+func (d *BaseRegionAuthDao) FindOne(where ...interface{}) (*model.BaseRegionAuth, error) {
+	one, err := d.M.FindOne(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entity *model.BaseRegionAuth
+	if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entity, nil
+}
+
+// FindAll retrieves and returns Result by by M.WherePri and M.All.
+// Also see M.WherePri and M.All.
+func (d *BaseRegionAuthDao) FindAll(where ...interface{}) ([]*model.BaseRegionAuth, error) {
+	all, err := d.M.FindAll(where...)
+	if err != nil {
+		return nil, err
+	}
+	var entities []*model.BaseRegionAuth
+	if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
+		return nil, err
+	}
+	return entities, nil
+}
+
+// Struct retrieves one record from table and converts it into given struct.
+// The parameter <pointer> should be type of *struct/**struct. If type **struct is given,
+// it can create the struct internally during converting.
+//
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+//
+// Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions
+// from table and <pointer> is not nil.
+//
+// Eg:
+// user := new(User)
+// err  := dao.User.Where("id", 1).Struct(user)
+//
+// user := (*User)(nil)
+// err  := dao.User.Where("id", 1).Struct(&user)
+func (d *BaseRegionAuthDao) Struct(pointer interface{}, where ...interface{}) error {
+	return d.M.Struct(pointer, where...)
+}
+
+// Structs retrieves records from table and converts them into given struct slice.
+// The parameter <pointer> should be type of *[]struct/*[]*struct. It can create and fill the struct
+// slice internally during converting.
+//
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+//
+// Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions
+// from table and <pointer> is not empty.
+//
+// Eg:
+// users := ([]User)(nil)
+// err   := dao.User.Structs(&users)
+//
+// users := ([]*User)(nil)
+// err   := dao.User.Structs(&users)
+func (d *BaseRegionAuthDao) Structs(pointer interface{}, where ...interface{}) error {
+	return d.M.Structs(pointer, where...)
+}
+
+// Scan automatically calls Struct or Structs function according to the type of parameter <pointer>.
+// It calls function Struct if <pointer> is type of *struct/**struct.
+// It calls function Structs if <pointer> is type of *[]struct/*[]*struct.
+//
+// The optional parameter <where> is the same as the parameter of Model.Where function,
+// see Model.Where.
+//
+// Note that it returns sql.ErrNoRows if there's no record retrieved and given pointer is not empty or nil.
+//
+// Eg:
+// user  := new(User)
+// err   := dao.User.Where("id", 1).Scan(user)
+//
+// user  := (*User)(nil)
+// err   := dao.User.Where("id", 1).Scan(&user)
+//
+// users := ([]User)(nil)
+// err   := dao.User.Scan(&users)
+//
+// users := ([]*User)(nil)
+// err   := dao.User.Scan(&users)
+func (d *BaseRegionAuthDao) Scan(pointer interface{}, where ...interface{}) error {
+	return d.M.Scan(pointer, where...)
+}
+
+// Chunk iterates the table with given size and callback function.
+func (d *BaseRegionAuthDao) Chunk(limit int, callback func(entities []*model.BaseRegionAuth, err error) bool) {
+	d.M.Chunk(limit, func(result gdb.Result, err error) bool {
+		var entities []*model.BaseRegionAuth
+		err = result.Structs(&entities)
+		if err == sql.ErrNoRows {
+			return false
+		}
+		return callback(entities, err)
+	})
+}
+
+// LockUpdate sets the lock for update for current operation.
+func (d *BaseRegionAuthDao) LockUpdate() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.LockUpdate()}
+}
+
+// LockShared sets the lock in share mode for current operation.
+func (d *BaseRegionAuthDao) LockShared() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.LockShared()}
+}
+
+// Unscoped enables/disables the soft deleting feature.
+func (d *BaseRegionAuthDao) Unscoped() *BaseRegionAuthDao {
+	return &BaseRegionAuthDao{M: d.M.Unscoped()}
+}

+ 2 - 2
opms_admin/app/handler/base_product_auth.go

@@ -20,11 +20,11 @@ func (h *BaseProductAuthHandler) GetList(ctx context.Context, req *model.BasePro
 		g.Log().Error(err)
 		return errors.New("系统异常,请重新尝试")
 	}
-	total, list, err := lineService.GetList(req)
+	list, err := lineService.GetList(req)
 	if err != nil {
 		return err
 	}
-	rsp.Data = g.Map{"list": list, "total": total}
+	rsp.Data = g.Map{"list": list}
 	return nil
 }
 

+ 64 - 0
opms_admin/app/handler/base_region_auth.go

@@ -0,0 +1,64 @@
+package handler
+
+import (
+	"context"
+	"errors"
+	"github.com/gogf/gf/util/gvalid"
+
+	"dashoo.cn/common_definition/comm_def"
+	"dashoo.cn/micro/app/model"
+	"dashoo.cn/micro/app/service"
+	"github.com/gogf/gf/frame/g"
+)
+
+type BaseRegionAuthHandler struct{}
+
+// GetList 获取列表
+func (h *BaseRegionAuthHandler) GetList(ctx context.Context, req *model.BaseRegionAuthSearchReq, rsp *comm_def.CommonMsg) error {
+	regionService, err := service.NewRegionService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return errors.New("系统异常,请重新尝试")
+	}
+	list, err := regionService.GetList(req)
+	if err != nil {
+		return err
+	}
+	rsp.Data = g.Map{"list": list}
+	return nil
+}
+
+// Save 保存数据
+func (h *BaseRegionAuthHandler) Save(ctx context.Context, req *model.SaveBaseRegionAuthReq, rsp *comm_def.CommonMsg) (err error) {
+	// 检查请求参数
+	if v := gvalid.CheckStruct(ctx, req, nil); v != nil {
+		return v
+	}
+	// 检查列表数据
+	for _, region := range req.Regions {
+		if v := gvalid.CheckStruct(ctx, region, nil); v != nil {
+			return v
+		}
+	}
+	regionService, err := service.NewRegionService(ctx)
+	if err != nil {
+		return err
+	}
+	err = regionService.Save(req)
+	return err
+}
+
+// GetRegionUsers 获取列表
+func (h *BaseRegionAuthHandler) GetRegionUsers(ctx context.Context, req *model.SysUserSearchReq, rsp *comm_def.CommonMsg) error {
+	regionService, err := service.NewRegionService(ctx)
+	if err != nil {
+		g.Log().Error(err)
+		return errors.New("系统异常,请重新尝试")
+	}
+	total, list, err := regionService.GetRegionUsers(req)
+	if err != nil {
+		return err
+	}
+	rsp.Data = g.Map{"list": list, "total": total}
+	return nil
+}

+ 17 - 7
opms_admin/app/model/base_product_auth.go

@@ -14,7 +14,17 @@ type BaseProductAuth internal.BaseProductAuth
 
 // Fill with you ideas below.
 
-// BaseProductAuthSearchReq 产品线受权查询
+// ReturnBaseProductAuth 返回前端的数据
+type ReturnBaseProductAuth struct {
+	UserId      int    `orm:"user_id"      json:"userId"`      // 用户ID
+	UserName    string `orm:"user_name"    json:"userName"`    // 用户姓名
+	UserPost    string `orm:"user_post"    json:"userPost"`    // 岗位
+	UserPhone   string `orm:"user_phone"   json:"userPhone"`   // 电话
+	ProductCode string `orm:"product_code" json:"productCode"` // 产品线编码
+	ProductName string `orm:"product_name" json:"productName"` // 产品线名称
+}
+
+// BaseProductAuthSearchReq 产品线授权查询
 type BaseProductAuthSearchReq struct {
 	UserId      int    `orm:"user_id"      json:"userId"`      // 用户ID
 	UserName    string `orm:"user_name"    json:"userName"`    // 用户姓名
@@ -27,16 +37,16 @@ type BaseProductAuthSearchReq struct {
 
 // SaveBaseProductAuthReq 产品线更新
 type SaveBaseProductAuthReq struct {
-	UserId    int            `orm:"user_id"      json:"userId"      v:"required|min:1#用户ID不能为空|用户ID不能为空"` // 用户ID
-	UserName  string         `orm:"user_name"    json:"userName"    v:"required#用户姓名不能为空"`                    // 用户姓名
-	UserPost  string         `orm:"user_post"    json:"userPost"`                                                     // 岗位
-	UserPhone string         `orm:"user_phone"   json:"userPhone"`                                                    // 电话
-	Lines     []*ProductLine `json:"lines"    v:"required#产品线不能为空"`
+	UserId    int            `orm:"user_id"    json:"userId"      v:"required|min:1#用户ID不能为空|用户ID不能为空"` // 用户ID
+	UserName  string         `orm:"user_name"  json:"userName"    v:"required#用户姓名不能为空"`                // 用户姓名
+	UserPost  string         `orm:"user_post"  json:"userPost"`                                         // 岗位
+	UserPhone string         `orm:"user_phone" json:"userPhone"`                                        // 电话
+	Lines     []*ProductLine `json:"lines"     v:"required#产品线不能为空"`
 }
 
 // ProductLine 产品线
 type ProductLine struct {
 	ProductCode string `orm:"product_code" json:"productCode" v:"required#产品线编码不能为空"` // 产品线编码
 	ProductName string `orm:"product_name" json:"productName" v:"required#产品线名称不能为空"` // 产品线名称
-	Remark      string `orm:"remark"       json:"remark"`                                      // 备注
+	Remark      string `orm:"remark"       json:"remark"`                             // 备注
 }

+ 63 - 0
opms_admin/app/model/base_region_auth.go

@@ -0,0 +1,63 @@
+// ==========================================================================
+// This is auto-generated by gf cli tool. Fill this file as you wish.
+// ==========================================================================
+
+package model
+
+import (
+	"dashoo.cn/micro/app/model/internal"
+)
+
+// BaseRegionAuth is the golang structure for table base_region_auth.
+type BaseRegionAuth internal.BaseRegionAuth
+
+// Fill with you ideas below.
+
+// ReturnBaseRegionAuth 返回前端的数据
+type ReturnBaseRegionAuth struct {
+	UserId         int    `orm:"user_id"          json:"userId"`         // 用户ID
+	UserName       string `orm:"user_name"        json:"userName"`       // 姓名
+	UserPost       string `orm:"user_post"        json:"userPost"`       // 岗位
+	UserPhone      string `orm:"user_phone"       json:"userPhone"`      // 电话
+	SaleRegionId   string `orm:"sale_region_id"   json:"saleRegionId"`   // 销售区域ID
+	SaleRegionName string `orm:"sale_region_name" json:"saleRegionName"` // 销售区域名称
+	ProvinceId     string `orm:"province_id"      json:"provinceId"`     // 省ID
+	ProvinceName   string `orm:"province_name"    json:"provinceName"`   // 省名称
+	CityId         string `orm:"city_id"          json:"cityId"`         // 市ID
+	CityName       string `orm:"city_name"        json:"cityName"`       // 市名称
+	RegionInfo     string `json:"regionInfo"`                            // 显示区域信息
+}
+
+// BaseRegionAuthSearchReq 销售区域授权查询
+type BaseRegionAuthSearchReq struct {
+	UserId         int    `orm:"user_id"          json:"userId"`         // 用户ID
+	UserName       string `orm:"user_name"        json:"userName"`       // 用户姓名
+	UserPost       string `orm:"user_post"        json:"userPost"`       // 岗位
+	UserPhone      string `orm:"user_phone"       json:"userPhone"`      // 电话
+	SaleRegionId   int    `orm:"sale_region_id"   json:"saleRegionId"`   // 销售区域ID
+	SaleRegionName string `orm:"sale_region_name" json:"saleRegionName"` // 销售区域名称
+	ProvinceId     int    `orm:"province_id"      json:"provinceId"`     // 省ID
+	ProvinceName   string `orm:"province_name"    json:"provinceName"`   // 省名称
+	CityId         int    `orm:"city_id"          json:"cityId"`         // 市ID
+	CityName       string `orm:"city_name"        json:"cityName"`       // 市名称
+}
+
+// SaveBaseRegionAuthReq 销售区域线更新
+type SaveBaseRegionAuthReq struct {
+	SaleRegionId   int       `orm:"sale_region_id"   json:"saleRegionId"   v:"required|min:1#销售区域ID不能为空|销售区域ID不能为空"` // 销售区域ID
+	SaleRegionName string    `orm:"sale_region_name" json:"saleRegionName" v:"required#销售区域名称不能为空"`                  // 销售区域名称
+	UserId         int       `orm:"user_id"          json:"userId"         v:"required|min:1#用户ID不能为空|用户ID不能为空"`     // 用户ID
+	UserName       string    `orm:"user_name"        json:"userName"       v:"required#用户姓名不能为空"`                    // 用户姓名
+	UserPost       string    `orm:"user_post"        json:"userPost"`                                                // 岗位
+	UserPhone      string    `orm:"user_phone"       json:"userPhone"`                                               // 电话
+	Regions        []*Region `json:"regions"`
+}
+
+// Region 销售区域
+type Region struct {
+	ProvinceId   int    `orm:"province_id"      json:"provinceId" v:"required|min:1#省ID不能为空|省ID不能为空"` // 省ID
+	ProvinceName string `orm:"province_name"    json:"provinceName" v:"required#省名称不能为空"`             // 省名称
+	CityId       int    `orm:"city_id"          json:"cityId" v:"required|min:1#市ID不能为空|市ID不能为空"`     // 市ID
+	CityName     string `orm:"city_name"        json:"cityName" v:"required#市名称不能为空"`                 // 市名称
+	Remark       string `orm:"remark"           json:"remark"`                                        // 备注
+}

+ 32 - 0
opms_admin/app/model/internal/base_region_auth.go

@@ -0,0 +1,32 @@
+// ==========================================================================
+// This is auto-generated by gf cli tool. DO NOT EDIT THIS FILE MANUALLY.
+// ==========================================================================
+
+package internal
+
+import (
+	"github.com/gogf/gf/os/gtime"
+)
+
+// BaseRegionAuth is the golang structure for table base_region_auth.
+type BaseRegionAuth struct {
+	Id             int         `orm:"id,primary"       json:"id"`             // 主键
+	UserId         int         `orm:"user_id"          json:"userId"`         // 用户ID
+	UserName       string      `orm:"user_name"        json:"userName"`       // 姓名
+	UserPost       string      `orm:"user_post"        json:"userPost"`       // 岗位
+	UserPhone      string      `orm:"user_phone"       json:"userPhone"`      // 电话
+	SaleRegionId   int         `orm:"sale_region_id"   json:"saleRegionId"`   // 销售区域ID
+	SaleRegionName string      `orm:"sale_region_name" json:"saleRegionName"` // 销售区域名称
+	ProvinceId     int         `orm:"province_id"      json:"provinceId"`     // 省ID
+	ProvinceName   string      `orm:"province_name"    json:"provinceName"`   // 省名称
+	CityId         int         `orm:"city_id"          json:"cityId"`         // 市ID
+	CityName       string      `orm:"city_name"        json:"cityName"`       // 市名称
+	Remark         string      `orm:"remark"           json:"remark"`         // 备注
+	CreatedBy      int         `orm:"created_by"       json:"createdBy"`      // 创建者
+	CreatedName    string      `orm:"created_name"     json:"createdName"`    // 创建人
+	CreatedTime    *gtime.Time `orm:"created_time"     json:"createdTime"`    // 创建时间
+	UpdatedBy      int         `orm:"updated_by"       json:"updatedBy"`      // 更新者
+	UpdatedName    string      `orm:"updated_name"     json:"updatedName"`    // 更新人
+	UpdatedTime    *gtime.Time `orm:"updated_time"     json:"updatedTime"`    // 更新时间
+	DeletedTime    *gtime.Time `orm:"deleted_time"     json:"deletedTime"`    // 删除时间
+}

+ 3 - 9
opms_admin/app/service/base_product_auth.go

@@ -28,7 +28,7 @@ func NewLineService(ctx context.Context) (svc *lineService, err error) {
 }
 
 // GetList 用户产品线列表
-func (s *lineService) GetList(req *model.BaseProductAuthSearchReq) (total int, lines []*model.BaseProductAuth, err error) {
+func (s *lineService) GetList(req *model.BaseProductAuthSearchReq) (lines []*model.BaseProductAuth, err error) {
 	lineModel := s.Dao.M
 	if req.UserId != 0 {
 		lineModel = lineModel.Where("user_id", req.UserId)
@@ -49,12 +49,6 @@ func (s *lineService) GetList(req *model.BaseProductAuthSearchReq) (total int, l
 		lineModel = lineModel.Where("product_name", req.ProductName)
 	}
 
-	total, err = lineModel.Count()
-	if err != nil {
-		g.Log().Error(err)
-		err = gerror.New("获取总行数失败")
-	}
-
 	err = lineModel.Order("id ASC").Scan(&lines)
 	if err != nil {
 		g.Log().Error(err)
@@ -96,7 +90,7 @@ func (s *lineService) Save(req *model.SaveBaseProductAuthReq) (err error) {
 	return
 }
 
-func (s *lineService) GetProductLineUsers(req *model.SysUserSearchReq) (total int, lines []*model.BaseProductAuth, err error) {
+func (s *lineService) GetProductLineUsers(req *model.SysUserSearchReq) (total int, lines []*model.ReturnBaseProductAuth, err error) {
 	userService, err := NewUserService(s.Ctx)
 	if err != nil {
 		return 0, nil, err
@@ -117,7 +111,7 @@ func (s *lineService) GetProductLineUsers(req *model.SysUserSearchReq) (total in
 		return 0, nil, err
 	}
 	for _, user := range users {
-		var data model.BaseProductAuth
+		var data model.ReturnBaseProductAuth
 		data.UserId = user.Id
 		data.UserName = user.NickName
 		data.UserPost = "" // TODO 暂时为空

+ 187 - 0
opms_admin/app/service/base_region_auth.go

@@ -0,0 +1,187 @@
+package service
+
+import (
+	"context"
+	"dashoo.cn/micro/app/dao"
+	"dashoo.cn/micro/app/model"
+	"database/sql"
+	"fmt"
+	"github.com/gogf/gf/errors/gerror"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/os/gtime"
+	"github.com/gogf/gf/util/gconv"
+)
+
+type regionService struct {
+	*contextService
+
+	Dao *dao.BaseRegionAuthDao
+}
+
+func NewRegionService(ctx context.Context) (svc *regionService, err error) {
+	svc = new(regionService)
+	if svc.contextService, err = svc.Init(ctx); err != nil {
+		return nil, err
+	}
+	svc.Dao = dao.NewBaseRegionAuthDao(svc.Tenant)
+	svc.Table = svc.Dao.Table
+	return svc, nil
+}
+
+// GetList 用户产品线列表
+func (s *regionService) GetList(req *model.BaseRegionAuthSearchReq) (regions []*model.BaseRegionAuth, err error) {
+	regionModel := s.Dao.M
+	if req.UserId != 0 {
+		regionModel = regionModel.Where("user_id", req.UserId)
+	}
+	if req.UserName != "" {
+		regionModel = regionModel.Where("user_name", req.UserName)
+	}
+	if req.UserPost != "" {
+		regionModel = regionModel.Where("user_post", req.UserPost)
+	}
+	if req.UserPhone != "" {
+		regionModel = regionModel.Where("user_phone", req.UserPhone)
+	}
+	if req.SaleRegionId != 0 {
+		regionModel = regionModel.Where("sale_region_id", req.SaleRegionId)
+	}
+	if req.SaleRegionName != "" {
+		regionModel = regionModel.Where("sale_region_name", req.SaleRegionName)
+	}
+	if req.ProvinceId != 0 {
+		regionModel = regionModel.Where("province_id", req.ProvinceId)
+	}
+	if req.ProvinceName != "" {
+		regionModel = regionModel.Where("province_name", req.ProvinceName)
+	}
+	if req.CityId != 0 {
+		regionModel = regionModel.Where("city_id", req.CityId)
+	}
+	if req.CityName != "" {
+		regionModel = regionModel.Where("city_name", req.CityName)
+	}
+
+	err = regionModel.Order("id ASC").Scan(&regions)
+	if err != nil {
+		g.Log().Error(err)
+		err = gerror.New("获取数据失败")
+	}
+	return
+}
+
+// Save 创建或更新数据
+func (s *regionService) Save(req *model.SaveBaseRegionAuthReq) (err error) {
+	var newRegions []*model.BaseRegionAuth
+
+	// 标记删除旧数据
+	oldRegions, err := s.Dao.Where(fmt.Sprintf("user_id='%v' AND sale_region_id='%v'", req.UserId, req.SaleRegionId)).FindAll()
+	if err != nil {
+		return err
+	}
+
+	// 填入新数据
+	for _, region := range req.Regions {
+		isNew := true
+		for _, old := range oldRegions {
+			if region.ProvinceId == old.ProvinceId && region.CityId == old.CityId {
+				isNew = false
+				break
+			}
+		}
+		if isNew {
+			data := &model.BaseRegionAuth{
+				UserId:         req.UserId,
+				UserName:       req.UserName,
+				UserPhone:      req.UserPhone,
+				UserPost:       req.UserPost,
+				SaleRegionId:   req.SaleRegionId,
+				SaleRegionName: req.SaleRegionName,
+				ProvinceId:     region.ProvinceId,
+				ProvinceName:   region.ProvinceName,
+				CityId:         region.CityId,
+				CityName:       region.CityName,
+				Remark:         region.Remark,
+			}
+			SetCreatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+			SetUpdatedInfo(data, s.GetCxtUserId(), s.GetCxtUserName())
+
+			newRegions = append(newRegions, data)
+		}
+	}
+	// 标记删除旧数据
+	for index, old := range oldRegions {
+		isDelete := true
+		for _, region := range req.Regions {
+			if region.ProvinceId == old.ProvinceId && region.CityId == old.CityId {
+				isDelete = false
+				break
+			}
+		}
+		if isDelete {
+			// 标记删除
+			oldRegions[index].DeletedTime = gtime.Now()
+			// 将删除数据存入切片中
+			newRegions = append(newRegions, oldRegions[index])
+		}
+	}
+	if len(newRegions) > 0 {
+		_, err = s.Dao.Save(newRegions)
+	}
+
+	return
+}
+
+func (s *regionService) GetRegionUsers(req *model.SysUserSearchReq) (total int, regions []*model.ReturnBaseRegionAuth, err error) {
+	userService, err := NewUserService(s.Ctx)
+	if err != nil {
+		return 0, nil, err
+	}
+
+	total, users, err := userService.GetUsersByDeptEx(req)
+	if err != nil {
+		return 0, nil, err
+	}
+
+	var userIds []int
+	for _, user := range users {
+		userIds = append(userIds, user.Id)
+	}
+
+	allRegions, err := s.Dao.Where("user_id IN (?)", userIds).Order("user_id ASC, id ASC").FindAll()
+	if err != nil && err != sql.ErrNoRows {
+		return 0, nil, err
+	}
+	for _, user := range users {
+		var data model.ReturnBaseRegionAuth
+		data.UserId = user.Id
+		data.UserName = user.NickName
+		data.UserPost = "" // TODO 暂时为空
+		data.UserPhone = user.Phone
+		for _, region := range allRegions {
+			if user.Id == region.UserId {
+				if data.RegionInfo == "" {
+					data.SaleRegionId = gconv.String(region.SaleRegionId)
+					data.SaleRegionName = region.SaleRegionName
+					data.ProvinceId = gconv.String(region.ProvinceId)
+					data.ProvinceName = region.ProvinceName
+					data.CityId = gconv.String(region.CityId)
+					data.CityName = region.CityName
+					data.RegionInfo = region.SaleRegionName + "-" + region.ProvinceName + "-" + region.CityName
+				} else {
+					data.SaleRegionId += "," + gconv.String(region.SaleRegionId)
+					data.SaleRegionName += "," + region.SaleRegionName
+					data.ProvinceId += "," + gconv.String(region.ProvinceId)
+					data.ProvinceName += "," + region.ProvinceName
+					data.CityId += "," + gconv.String(region.CityId)
+					data.CityName += "," + region.CityName
+					data.RegionInfo += region.SaleRegionName + "-" + region.ProvinceName + "-" + region.CityName
+				}
+			}
+		}
+
+		regions = append(regions, &data)
+	}
+
+	return
+}

+ 1 - 0
opms_admin/main.go

@@ -26,6 +26,7 @@ func main() {
 	s.RegisterName("LoginLog", new(handler.LoginLogHandler), "")
 	s.RegisterName("Config", new(handler.ConfigHandler), "")
 	s.RegisterName("BaseProductAuth", new(handler.BaseProductAuthHandler), "")
+	s.RegisterName("BaseRegionAuth", new(handler.BaseRegionAuthHandler), "")
 
 	// 注册文件处理Service对象
 	//dynamic.BeanFactory.BeanRegister(service.NewRoleService())

+ 42 - 36
opms_parent/app/dao/base/internal/base_sales_region_detail.go

@@ -27,18 +27,20 @@ type BaseSalesRegionDetailDao struct {
 
 // BaseSalesRegionDetailColumns defines and stores column names for table base_sales_region_detail.
 type baseSalesRegionDetailColumns struct {
-	Id          string // 主键
-	RegionId    string // 关联销售区域
-	DistId      string // 行政区县ID
-	DistName    string // 行政区县名称
-	Remark      string // 备注
-	CreatedBy   string // 创建者
-	CreatedName string // 创建人
-	CreatedTime string // 创建时间
-	UpdatedBy   string // 更新者
-	UpdatedName string // 更新人
-	UpdatedTime string // 更新时间
-	DeletedTime string // 删除时间
+	Id             string // 主键
+	RegionId       string // 关联销售区域
+	CustProvinceId string // 所在省ID
+	CustProvince   string // 所在省
+	CustCityId     string // 所在市ID
+	CustCity       string // 所在市
+	Remark         string // 备注
+	CreatedBy      string // 创建者
+	CreatedName    string // 创建人
+	CreatedTime    string // 创建时间
+	UpdatedBy      string // 更新者
+	UpdatedName    string // 更新人
+	UpdatedTime    string // 更新时间
+	DeletedTime    string // 删除时间
 }
 
 var (
@@ -48,18 +50,20 @@ var (
 		DB:    g.DB("default"),
 		Table: "base_sales_region_detail",
 		Columns: baseSalesRegionDetailColumns{
-			Id:          "id",
-			RegionId:    "region_id",
-			DistId:      "dist_id",
-			DistName:    "dist_name",
-			Remark:      "remark",
-			CreatedBy:   "created_by",
-			CreatedName: "created_name",
-			CreatedTime: "created_time",
-			UpdatedBy:   "updated_by",
-			UpdatedName: "updated_name",
-			UpdatedTime: "updated_time",
-			DeletedTime: "deleted_time",
+			Id:             "id",
+			RegionId:       "region_id",
+			CustProvinceId: "cust_province_id",
+			CustProvince:   "cust_province",
+			CustCityId:     "cust_city_id",
+			CustCity:       "cust_city",
+			Remark:         "remark",
+			CreatedBy:      "created_by",
+			CreatedName:    "created_name",
+			CreatedTime:    "created_time",
+			UpdatedBy:      "updated_by",
+			UpdatedName:    "updated_name",
+			UpdatedTime:    "updated_time",
+			DeletedTime:    "deleted_time",
 		},
 	}
 )
@@ -71,18 +75,20 @@ func NewBaseSalesRegionDetailDao(tenant string) BaseSalesRegionDetailDao {
 		DB:    g.DB(tenant),
 		Table: "base_sales_region_detail",
 		Columns: baseSalesRegionDetailColumns{
-			Id:          "id",
-			RegionId:    "region_id",
-			DistId:      "dist_id",
-			DistName:    "dist_name",
-			Remark:      "remark",
-			CreatedBy:   "created_by",
-			CreatedName: "created_name",
-			CreatedTime: "created_time",
-			UpdatedBy:   "updated_by",
-			UpdatedName: "updated_name",
-			UpdatedTime: "updated_time",
-			DeletedTime: "deleted_time",
+			Id:             "id",
+			RegionId:       "region_id",
+			CustProvinceId: "cust_province_id",
+			CustProvince:   "cust_province",
+			CustCityId:     "cust_city_id",
+			CustCity:       "cust_city",
+			Remark:         "remark",
+			CreatedBy:      "created_by",
+			CreatedName:    "created_name",
+			CreatedTime:    "created_time",
+			UpdatedBy:      "updated_by",
+			UpdatedName:    "updated_name",
+			UpdatedTime:    "updated_time",
+			DeletedTime:    "deleted_time",
 		},
 	}
 	return dao

+ 1 - 1
opms_parent/app/dao/contract/internal/ctr_contract_invoice.go

@@ -35,7 +35,7 @@ type ctrContractInvoiceColumns struct {
 	InvoiceAmount     string // 开票金额
 	InvoiceDate       string // 开票日期
 	InvoiceType       string // 开票类型
-	ApproStatus       string // 审核状态
+	ApproStatus       string // 审核状态 10 待提交审核 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销
 	InvoiceCode       string // 发票号码
 	ActualInvoiceDate string // 实际开票日期
 	CourierCode       string // 快递单号

+ 14 - 0
opms_parent/app/handler/contract/ctr_contract_invoice.go

@@ -68,6 +68,20 @@ func (c *CtrContractInvoice) Update(ctx context.Context, req *model.CtrContractI
 	return nil
 }
 
+// Swagger:CtrContractInvoice 合同发票 提交发票申请
+func (c *CtrContractInvoice) InvoiceApply(ctx context.Context, req *model.CtrContractInvoiceInvoiceApplyReq, rsp *comm_def.CommonMsg) error {
+	g.Log().Infof("CtrContractInvoice.InvoiceApply request %#v ", *req)
+	s, err := service.NewCtrContractInvoiceService(ctx)
+	if err != nil {
+		return err
+	}
+	err = s.InvoiceApply(ctx, req)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
 // Swagger:CtrContractInvoice 合同发票 删除合同发票
 func (c *CtrContractInvoice) Delete(ctx context.Context, req *model.IdsReq, rsp *comm_def.CommonMsg) error {
 	g.Log().Infof("CtrContractInvoice.Delete request %#v ", *req)

+ 2 - 16
opms_parent/app/handler/cust/customer.go

@@ -151,13 +151,10 @@ func (c *CustomerHeader) TransCustomer(ctx context.Context, req *model.AssignCus
 	if err != nil {
 		return err
 	}
-	err = s.TransCustomer(req)
+	err = s.TransCustomerRequest(ctx, req)
 	if err != nil {
 		return err
 	}
-
-	//转移客户
-	s.CreateDynamics("转移客户", req, req.Ids...)
 	return nil
 }
 
@@ -170,17 +167,10 @@ func (c *CustomerHeader) AssignCustomer(ctx context.Context, req *model.AssignCu
 	if err != nil {
 		return err
 	}
-	var behavior string
-	if req.Receive == "" {
-		behavior = "分配客户"
-	} else {
-		behavior = "领取"
-	}
 	err = s.AssignCustomer(ctx, req)
 	if err != nil {
 		return err
 	}
-	s.CreateDynamics(behavior, req, req.Ids...)
 	return nil
 
 }
@@ -194,15 +184,11 @@ func (c *CustomerHeader) MoveToPubic(ctx context.Context, req *model.MoveToPubic
 	if err != nil {
 		return err
 	}
-	err = s.MoveToPubic(req.Ids)
+	err = s.MoveToPublicRequest(ctx, req)
 	if err != nil {
 
 		return err
 	}
-	if req.Remark == "" {
-		req.Remark = ""
-	}
-	s.CreateDynamics("移入公海", req, req.Ids...)
 	return nil
 }
 

+ 53 - 0
opms_parent/app/handler/dingtalk/ding_event.go

@@ -3,6 +3,7 @@ package dingtalk
 import (
 	"context"
 	model "dashoo.cn/micro/app/model/workflow"
+	contractSrv "dashoo.cn/micro/app/service/contract"
 	custServer "dashoo.cn/micro/app/service/cust"
 	"dashoo.cn/micro/app/service/dingtalk_log"
 	platServer "dashoo.cn/micro/app/service/plat"
@@ -116,6 +117,58 @@ func (h *DingHandler) handleBpmsInstanceChange(msg *message.MixMessage, ctx *din
 			return err.Error()
 		}
 		return "success"
+	case model.CustomerPublic:
+		if msg.ProcessType == "finish" || msg.ProcessType == "terminate" {
+			srv, err := custServer.NewCustomerService(ctx.SubsMessage.Ctx)
+			if err != nil {
+				glog.Error(err)
+				return err.Error()
+			}
+			err = srv.MoveToPublicApproval(instance, msg)
+			if err != nil {
+				glog.Error(err)
+				return err.Error()
+			}
+		}
+		err = s.Update(instance, msg)
+		if err != nil {
+			glog.Error(err)
+			return err.Error()
+		}
+		return "success"
+	case model.CustomerTrans:
+		if msg.ProcessType == "finish" || msg.ProcessType == "terminate" {
+			srv, err := custServer.NewCustomerService(ctx.SubsMessage.Ctx)
+			if err != nil {
+				glog.Error(err)
+				return err.Error()
+			}
+			err = srv.TransCustomerApproval(instance, msg)
+			if err != nil {
+				glog.Error(err)
+				return err.Error()
+			}
+		}
+		err = s.Update(instance, msg)
+		if err != nil {
+			glog.Error(err)
+			return err.Error()
+		}
+		return "success"
+	case model.ContractInvoice:
+		if msg.ProcessType == "finish" || msg.ProcessType == "terminate" {
+			err = contractSrv.InvoiceApplyApproval(ctx.SubsMessage.Ctx, instance, msg)
+			if err != nil {
+				glog.Error(err)
+				return err.Error()
+			}
+		}
+		err = s.Update(instance, msg)
+		if err != nil {
+			glog.Error(err)
+			return err.Error()
+		}
+		return "success"
 	case model.ProjectUpGrade:
 		if msg.ProcessType == "finish" || msg.ProcessType == "terminate" {
 			srv, err := projService.NewBusinessService(ctx.SubsMessage.Ctx)

+ 20 - 17
opms_parent/app/model/base/base_sales_region_detail.go

@@ -15,7 +15,7 @@ type BaseSalesRegionDetail internal.BaseSalesRegionDetail
 
 // Fill with you ideas below.
 
-// 条件搜索
+// SecBaseRegionDetailReq 条件搜索
 type SecBaseRegionDetailReq struct {
 	RegionId     int    `p:"regionId"    json:"regionId"`
 	CustCode     string `p:"custCode"    json:"custCode"`
@@ -24,28 +24,31 @@ type SecBaseRegionDetailReq struct {
 	request.PageReq
 }
 
-// 创建区域
+// AddBaseRegionDetailReq 创建区域
 type AddBaseRegionDetailReq struct {
-	RegionId int    `p:"regionId"        json:"regionId"   v:"required#关联销售区域"`
-	DistId   int    `json:"distId"  v:"required#区域编码不能为空"`   // 行政区县ID
-	DistName string `json:"distName"  v:"required#区域名称不能为空"` // 行政区县名称
-	Remark   string
+	RegionId       int    `p:"regionId"        json:"regionId"   v:"required|min:1#关联销售区域不能为空|关联销售区域不能为空"`
+	CustProvinceId int    `json:"custProvinceId"  v:"required|min:1#所在省ID不能为空|所在省ID不能为空"` // 所在省ID
+	CustProvince   string `json:"custProvince"  v:"required#所在省不能为空"`                     // 所在省
+	CustCityId     int    `json:"custCityId"  v:"required|min:1#所在市ID不能为空|所在市ID不能为空"`     // 所在市ID
+	CustCity       string `json:"custCity"  v:"required#所在市不能为空"`                         // 所在市
+	Remark         string
 }
 
-// 列表字段
+// BaseRegionDetailRep 列表字段
 type BaseRegionDetailRep struct {
-	Id          int        `p:"id"         json:"id"   `
-	RegionId    int        `p:"regionId"         json:"regionId"   `
-	DistId      int        `p:"distId"    json:"distId" `
-	DistName    string     `p:"distName"    json:"distName" `
-	Count       int        `p:"count"    json:"count" `
-	Remark      string     `p:"remark"    json:"remark" `
-	CreatedName string     `p:"createdName"    json:"createdName" `
-	CreatedTime gtime.Time `p:"createdTime"    json:"createdTime" `
+	Id             int        `p:"id"         json:"id"   `
+	RegionId       int        `p:"regionId"         json:"regionId"   `
+	CustProvinceId int        `p:"custProvinceId"    json:"custProvinceId" `
+	CustProvince   string     `p:"custProvince"    json:"custProvince" `
+	CustCityId     int        `p:"custCityId"    json:"custCityId" `
+	CustCity       string     `p:"custCity"    json:"custCity" `
+	Count          int        `p:"count"    json:"count" `
+	Remark         string     `p:"remark"    json:"remark" `
+	CreatedName    string     `p:"createdName"    json:"createdName" `
+	CreatedTime    gtime.Time `p:"createdTime"    json:"createdTime" `
 }
 
-//更新
-
+// UpdateBaseRegionDetailReq 更新
 type UpdateBaseRegionDetailReq struct {
 	*BaseSalesRegionDetail
 	Id int `p:"id"  json:"id" v:"required# id不能为空"`

+ 14 - 12
opms_parent/app/model/base/internal/base_sales_region_detail.go

@@ -10,16 +10,18 @@ import (
 
 // BaseSalesRegionDetail is the golang structure for table base_sales_region_detail.
 type BaseSalesRegionDetail struct {
-	Id          int         `orm:"id,primary"   json:"id"`          // 主键
-	RegionId    int         `orm:"region_id"    json:"regionId"`    // 关联销售区域
-	DistId      int         `orm:"dist_id"      json:"distId"`      // 行政区县ID
-	DistName    string      `orm:"dist_name"    json:"distName"`    // 行政区县名称
-	Remark      string      `orm:"remark"       json:"remark"`      // 备注
-	CreatedBy   int         `orm:"created_by"   json:"createdBy"`   // 创建者
-	CreatedName string      `orm:"created_name" json:"createdName"` // 创建人
-	CreatedTime *gtime.Time `orm:"created_time" json:"createdTime"` // 创建时间
-	UpdatedBy   int         `orm:"updated_by"   json:"updatedBy"`   // 更新者
-	UpdatedName string      `orm:"updated_name" json:"updatedName"` // 更新人
-	UpdatedTime *gtime.Time `orm:"updated_time" json:"updatedTime"` // 更新时间
-	DeletedTime *gtime.Time `orm:"deleted_time" json:"deletedTime"` // 删除时间
+	Id             int         `orm:"id,primary"       json:"id"`             // 主键
+	RegionId       int         `orm:"region_id"        json:"regionId"`       // 关联销售区域
+	CustProvinceId int         `orm:"cust_province_id" json:"custProvinceId"` // 所在省ID
+	CustProvince   string      `orm:"cust_province"    json:"custProvince"`   // 所在省
+	CustCityId     int         `orm:"cust_city_id"     json:"custCityId"`     // 所在市ID
+	CustCity       string      `orm:"cust_city"        json:"custCity"`       // 所在市
+	Remark         string      `orm:"remark"           json:"remark"`         // 备注
+	CreatedBy      int         `orm:"created_by"       json:"createdBy"`      // 创建者
+	CreatedName    string      `orm:"created_name"     json:"createdName"`    // 创建人
+	CreatedTime    *gtime.Time `orm:"created_time"     json:"createdTime"`    // 创建时间
+	UpdatedBy      int         `orm:"updated_by"       json:"updatedBy"`      // 更新者
+	UpdatedName    string      `orm:"updated_name"     json:"updatedName"`    // 更新人
+	UpdatedTime    *gtime.Time `orm:"updated_time"     json:"updatedTime"`    // 更新时间
+	DeletedTime    *gtime.Time `orm:"deleted_time"     json:"deletedTime"`    // 删除时间
 }

+ 6 - 0
opms_parent/app/model/contract/ctr_contract_invoice.go

@@ -63,3 +63,9 @@ type CtrContractInvoiceUpdateReq struct {
 	CourierCode       string      `json:"courierCode"`       // 快递单号
 	Remark            *string     `json:"remark"`
 }
+
+type CtrContractInvoiceInvoiceApplyReq struct {
+	Id            int     `json:"id" v:"required#请输入Id"`
+	AllReceive    bool    `json:"allReceive"`    // 是否已回全款
+	ReceiveAmount float64 `json:"receiveAmount"` // 回款金额(元)
+}

+ 1 - 1
opms_parent/app/model/contract/internal/ctr_contract_invoice.go

@@ -19,7 +19,7 @@ type CtrContractInvoice struct {
 	InvoiceAmount     float64     `orm:"invoice_amount"      json:"invoiceAmount"`     // 开票金额
 	InvoiceDate       *gtime.Time `orm:"invoice_date"        json:"invoiceDate"`       // 开票日期
 	InvoiceType       string      `orm:"invoice_type"        json:"invoiceType"`       // 开票类型
-	ApproStatus       string      `orm:"appro_status"        json:"approStatus"`       // 审核状态
+	ApproStatus       string      `orm:"appro_status"        json:"approStatus"`       // 审核状态 10 待提交审核 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销
 	InvoiceCode       string      `orm:"invoice_code"        json:"invoiceCode"`       // 发票号码
 	ActualInvoiceDate *gtime.Time `orm:"actual_invoice_date" json:"actualInvoiceDate"` // 实际开票日期
 	CourierCode       string      `orm:"courier_code"        json:"courierCode"`       // 快递单号

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

@@ -156,7 +156,7 @@ type UpdateCustomer struct {
 // 移入公海
 type MoveToPubicRep struct {
 	Ids    []int64 `json:"ids,omitempty"`
-	Remark string  `json:"remark,omitempty"`
+	Remark string  `json:"remark,omitempty"` // 移回原因
 }
 
 // 客户名称

+ 5 - 3
opms_parent/app/model/workflow/plat_workflow.go

@@ -9,17 +9,19 @@ import (
 	"dashoo.cn/opms_libary/request"
 )
 
-// BizType 业务类型(10领用20项目创建30合同创建)
+// BizType 业务类型(10客户20项目创建30合同创建)
 const (
 	CustomerReceive  = "11" // 领取公海客户
+	CustomerPublic   = "12" // 客户移回公海
+	CustomerTrans    = "13" // 转移客户
 	ProjectCreate    = "20" // 项目创建
 	ProjectUpGrade   = "21" // 项目升级审批
 	ProjectDownGrade = "22" // 项目降级审批
 	ProjectTransfer  = "23" // 项目转移项目审批
 	ProjectToReserve = "24" // 项目转为储备项目审批
 	ProjectPersonnel = "25" // 项目协同人员审批
-
-	ContractCreate = "30" // 合同创建
+	ContractCreate   = "30" // 合同创建
+	ContractInvoice  = "31" // 申请发票
 )
 
 // PlatWorkflow is the golang structure for table plat_workflow.

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

@@ -66,7 +66,7 @@ func (s *salesRegionService) GetRegionTree() (regionList []*model.Region, err er
 	}
 	detailDao := base.NewBaseSalesRegionDetailDao(s.Tenant)
 	regionDetailsList := ([]*model.District)(nil)
-	err = detailDao.Fields("region_id, dist_id as regionCode, dist_name as regionDesc").
+	err = detailDao.Fields("region_id, cust_province_id as regionCode, cust_province as regionDesc").Group("cust_province_id").
 		OrderAsc(detailDao.Columns.RegionId).Scan(&regionDetailsList)
 	if err != nil {
 		return

+ 2 - 2
opms_parent/app/service/base/base_sales_region_detail.go

@@ -44,7 +44,7 @@ func (s *salesRegionDetailService) GetList(req *model.SecBaseRegionDetailReq) (t
 	}
 	var districtList []int
 	for _, v := range RegionList {
-		districtList = append(districtList, v.DistId)
+		districtList = append(districtList, v.CustProvinceId)
 	}
 	//CustModel := p.CustomerDao.M
 	CustModel := s.CustomerDao.M.Fields("count(*) as count,cust_dist_code").Where("cust_dist_code in (?)", districtList)
@@ -62,7 +62,7 @@ func (s *salesRegionDetailService) GetList(req *model.SecBaseRegionDetailReq) (t
 
 	for _, v := range RegionList {
 		for _, v3 := range custDist {
-			if v.DistId == gconv.Int(v3["cust_dist_code"]) {
+			if v.CustProvinceId == gconv.Int(v3["cust_dist_code"]) {
 				v.Count = gconv.Int(v3["count"])
 			}
 		}

+ 3 - 5
opms_parent/app/service/contract/ctr_contract.go

@@ -39,8 +39,8 @@ type CtrContractService struct {
 func NewCtrContractService(ctx context.Context) (*CtrContractService, error) {
 	tenant, err := micro_srv.GetTenant(ctx)
 	if err != nil {
-		err = myerrors.TipsError(fmt.Sprintf("获取组合码异常:%s", err.Error()))
-		return nil, err //fmt.Errorf("获取组合码异常:%s", err.Error())
+		err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
+		return nil, err //fmt.Errorf("获取租户码异常:%s", err.Error())
 	}
 	// 获取用户信息
 	userInfo, err := micro_srv.GetUserInfo(ctx)
@@ -265,7 +265,6 @@ func (s CtrContractService) BindProduct(tx *gdb.TX, id int, product []model.CtrA
 			UpdatedBy:     int(s.userInfo.Id),
 			UpdatedName:   s.userInfo.NickName,
 			UpdatedTime:   gtime.Now(),
-			DeletedTime:   gtime.Now(),
 		})
 	}
 
@@ -366,7 +365,6 @@ func (s CtrContractService) Add(ctx context.Context, req *model.CtrContractAddRe
 		UpdatedBy:         int(s.userInfo.Id),
 		UpdatedName:       s.userInfo.NickName,
 		UpdatedTime:       gtime.Now(),
-		DeletedTime:       gtime.Now(),
 	}
 
 	var id int
@@ -584,7 +582,7 @@ func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
 		return err
 	}
 
-	v, err := tx.GetValue("select sum(invoice_amount) from ctr_contract_invoice where contract_id=? and appro_status='20' and deleted_time is null", id)
+	v, err := tx.GetValue("select sum(invoice_amount) from ctr_contract_invoice where contract_id=? and appro_status='30' and deleted_time is null", id)
 	if err != nil {
 		return err
 	}

+ 2 - 3
opms_parent/app/service/contract/ctr_contract_append.go

@@ -27,8 +27,8 @@ type CtrContractAppendService struct {
 func NewCtrContractAppendService(ctx context.Context) (*CtrContractAppendService, error) {
 	tenant, err := micro_srv.GetTenant(ctx)
 	if err != nil {
-		err = myerrors.TipsError(fmt.Sprintf("获取组合码异常:%s", err.Error()))
-		return nil, err //fmt.Errorf("获取组合码异常:%s", err.Error())
+		err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
+		return nil, err //fmt.Errorf("获取租户码异常:%s", err.Error())
 	}
 	// 获取用户信息
 	userInfo, err := micro_srv.GetUserInfo(ctx)
@@ -112,7 +112,6 @@ func (s CtrContractAppendService) Add(ctx context.Context, req *model.CtrContrac
 		UpdatedBy:   s.userInfo.Id,
 		UpdatedName: s.userInfo.NickName,
 		UpdatedTime: gtime.Now(),
-		DeletedTime: gtime.Now(),
 	}
 
 	var id int

+ 2 - 3
opms_parent/app/service/contract/ctr_contract_collection.go

@@ -29,8 +29,8 @@ type CtrContractCollectionService struct {
 func NewCtrContractCollectionService(ctx context.Context) (*CtrContractCollectionService, error) {
 	tenant, err := micro_srv.GetTenant(ctx)
 	if err != nil {
-		err = myerrors.TipsError(fmt.Sprintf("获取组合码异常:%s", err.Error()))
-		return nil, err // fmt.Errorf("获取组合码异常:%s", err.Error())
+		err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
+		return nil, err // fmt.Errorf("获取租户码异常:%s", err.Error())
 	}
 	// 获取用户信息
 	userInfo, err := micro_srv.GetUserInfo(ctx)
@@ -145,7 +145,6 @@ func (s CtrContractCollectionService) Add(ctx context.Context, req *model.CtrCon
 		UpdatedBy:          s.userInfo.Id,
 		UpdatedName:        s.userInfo.NickName,
 		UpdatedTime:        gtime.Now(),
-		DeletedTime:        gtime.Now(),
 	}
 	var id int
 	txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {

+ 2 - 3
opms_parent/app/service/contract/ctr_contract_collection_plan.go

@@ -29,8 +29,8 @@ type CtrContractCollectionPlanService struct {
 func NewCtrContractCollectionPlanService(ctx context.Context) (*CtrContractCollectionPlanService, error) {
 	tenant, err := micro_srv.GetTenant(ctx)
 	if err != nil {
-		err = myerrors.TipsError(fmt.Sprintf("获取组合码异常:%s", err.Error()))
-		return nil, err //fmt.Errorf("获取组合码异常:%s", err.Error())
+		err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
+		return nil, err //fmt.Errorf("获取租户码异常:%s", err.Error())
 	}
 	// 获取用户信息
 	userInfo, err := micro_srv.GetUserInfo(ctx)
@@ -156,7 +156,6 @@ func (s CtrContractCollectionPlanService) Add(ctx context.Context, req *model.Ct
 		UpdatedBy:      s.userInfo.Id,
 		UpdatedName:    s.userInfo.NickName,
 		UpdatedTime:    gtime.Now(),
-		DeletedTime:    gtime.Now(),
 	}
 
 	var id int

+ 228 - 5
opms_parent/app/service/contract/ctr_contract_invoice.go

@@ -3,13 +3,23 @@ package service
 import (
 	"context"
 	"database/sql"
+	"encoding/json"
 	"fmt"
+	"strconv"
+	"strings"
 
 	dao "dashoo.cn/micro/app/dao/contract"
+	customerDao "dashoo.cn/micro/app/dao/cust"
+	sysDao "dashoo.cn/micro/app/dao/sys"
 	model "dashoo.cn/micro/app/model/contract"
+	workflowModel "dashoo.cn/micro/app/model/workflow"
+	workflowService "dashoo.cn/micro/app/service/workflow"
+	"dashoo.cn/opms_libary/utils"
 
 	"dashoo.cn/opms_libary/micro_srv"
 	"dashoo.cn/opms_libary/myerrors"
+	"dashoo.cn/opms_libary/plugin/dingtalk/message"
+	"dashoo.cn/opms_libary/plugin/dingtalk/workflow"
 	"dashoo.cn/opms_libary/request"
 	"github.com/gogf/gf/database/gdb"
 	"github.com/gogf/gf/os/gtime"
@@ -19,6 +29,8 @@ import (
 type CtrContractInvoiceService struct {
 	Dao         *dao.CtrContractInvoiceDao
 	ContractDao *dao.CtrContractDao
+	CustomerDao *customerDao.CustCustomerDao
+	UserDao     *sysDao.SysUserDao
 	ctrSrv      *CtrContractService
 	Tenant      string
 	userInfo    request.UserInfo
@@ -28,7 +40,7 @@ func NewCtrContractInvoiceService(ctx context.Context) (*CtrContractInvoiceServi
 	tenant, err := micro_srv.GetTenant(ctx)
 	if err != nil {
 
-		return nil, myerrors.TipsError(fmt.Sprintf("获取组合码异常:%s", err.Error())) //fmt.Errorf("获取组合码异常:%s", err.Error())
+		return nil, myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error())) //fmt.Errorf("获取租户码异常:%s", err.Error())
 	}
 	// 获取用户信息
 	userInfo, err := micro_srv.GetUserInfo(ctx)
@@ -42,6 +54,8 @@ func NewCtrContractInvoiceService(ctx context.Context) (*CtrContractInvoiceServi
 	return &CtrContractInvoiceService{
 		Dao:         dao.NewCtrContractInvoiceDao(tenant),
 		ContractDao: dao.NewCtrContractDao(tenant),
+		CustomerDao: customerDao.NewCustCustomerDao(tenant),
+		UserDao:     sysDao.NewSysUserDao(tenant),
 		ctrSrv:      ctrSrv,
 		Tenant:      tenant,
 		userInfo:    userInfo,
@@ -162,7 +176,6 @@ func (s CtrContractInvoiceService) Add(ctx context.Context, req *model.CtrContra
 		UpdatedBy:         int(s.userInfo.Id),
 		UpdatedName:       s.userInfo.NickName,
 		UpdatedTime:       gtime.Now(),
-		DeletedTime:       gtime.Now(),
 	}
 	var id int
 	txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
@@ -286,6 +299,217 @@ func (s CtrContractInvoiceService) Update(ctx context.Context, req *model.CtrCon
 	return nil
 }
 
+var InvoiceApplyProcessCode = "PROC-D2F97FDE-6277-404D-89B5-91123FEBF1B8" // 申请发票
+
+func (s CtrContractInvoiceService) InvoiceApply(ctx context.Context, req *model.CtrContractInvoiceInvoiceApplyReq) error {
+	invoice, err := s.Dao.Where("id = ?", req.Id).One()
+	if err != nil {
+		return err
+	}
+	if invoice == nil {
+		return myerrors.TipsError("发票不存在")
+	}
+	if invoice.ApproStatus != "10" {
+		return myerrors.TipsError("发票当前状态不可提交审核")
+	}
+	contract, err := s.ContractDao.Where("id = ?", invoice.ContractId).One()
+	if err != nil {
+		return err
+	}
+	if contract == nil {
+		return myerrors.TipsError("发票所属合同不存在")
+	}
+	cust, err := s.CustomerDao.Where("id = ?", invoice.CustId).One()
+	if err != nil {
+		return err
+	}
+	if cust == nil {
+		return myerrors.TipsError("发票所属合同客户不存在")
+	}
+
+	allReceive := "未回全款"
+	if req.AllReceive {
+		allReceive = "已回全款"
+	}
+
+	product, err := s.ctrSrv.CtrProductDao.Where("contract_id = ?", contract.Id).All()
+	if err != nil {
+		return err
+	}
+	// productForm := []*workflow.StartProcessInstanceRequestFormComponentValuesDetails{}
+	// for _, p := range product {
+	// 	productForm = append(productForm, &workflow.StartProcessInstanceRequestFormComponentValuesDetails{
+	// 		Details: []*workflow.StartProcessInstanceRequestFormComponentValuesDetailsDetails{
+	// 			{
+	// 				Id:    utils.String("TextField_R967EJ9XVWW0"),
+	// 				Name:  utils.String("产品名称"),
+	// 				Value: utils.String(p.ProdName),
+	// 			},
+	// 			{
+	// 				Id:    utils.String("TextField_18AAHJYNVUBG0"),
+	// 				Name:  utils.String("产品型号"),
+	// 				Value: utils.String(p.ProdCode),
+	// 			},
+	// 			{
+	// 				Id:    utils.String("NumberField_1RFPF86Y699C0"),
+	// 				Name:  utils.String("产品数量"),
+	// 				Value: utils.String(strconv.Itoa(p.ProdNum)),
+	// 			},
+	// 		},
+	// 	})
+	// }
+	productForm := []interface{}{}
+	for _, p := range product {
+		productForm = append(productForm, []*workflow.StartProcessInstanceRequestFormComponentValuesDetailsDetails{
+			{
+				Id:    utils.String("TextField_R967EJ9XVWW0"),
+				Name:  utils.String("产品名称"),
+				Value: utils.String(p.ProdName),
+			},
+			{
+				Id:    utils.String("TextField_18AAHJYNVUBG0"),
+				Name:  utils.String("产品型号"),
+				Value: utils.String(p.ProdCode),
+			},
+			{
+				Id:    utils.String("NumberField_1RFPF86Y699C0"),
+				Name:  utils.String("产品数量"),
+				Value: utils.String(strconv.Itoa(p.ProdNum)),
+			},
+		})
+	}
+	productFormByte, err := json.Marshal(productForm)
+	if err != nil {
+		return err
+	}
+
+	workflowSrv, err := workflowService.NewFlowService(ctx)
+	if err != nil {
+		return err
+	}
+	bizCode := strings.Join([]string{
+		strconv.Itoa(invoice.Id),
+		strconv.Itoa(s.userInfo.Id),
+	}, ":")
+	_, err = workflowSrv.StartProcessInstance(bizCode, "31", &workflow.StartProcessInstanceRequest{
+		ProcessCode: &InvoiceApplyProcessCode,
+		FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
+			{
+				Id:    utils.String("DDSelectField_FSWX8IG61HC0"),
+				Name:  utils.String("单选框"),
+				Value: utils.String(allReceive),
+			},
+			{
+				Id:    utils.String("TextField_LUZ9EQ3IJB40"),
+				Name:  utils.String("合同编号"),
+				Value: utils.String(contract.ContractCode),
+			},
+			{
+				Id:    utils.String("TextField_A0V5RQK1BC80"),
+				Name:  utils.String("客户编号"),
+				Value: utils.String(cust.CustCode),
+			},
+			{
+				Id:    utils.String("TextField_1E2J1LS6H9HC0"),
+				Name:  utils.String("客户名称"),
+				Value: utils.String(cust.CustName),
+			},
+			{
+				Id:   utils.String("TableField_1IGTG9NX08U80"),
+				Name: utils.String("表格"),
+				// Details: productForm,
+				Value: utils.String(string(productFormByte)),
+			},
+			{
+				Id:    utils.String("MoneyField_1D8481FCI5FK0"),
+				Name:  utils.String("合同金额(元)"),
+				Value: utils.String(strconv.FormatFloat(contract.ContractAmount, 'f', 2, 64)),
+			},
+			{
+				Id:    utils.String("MoneyField_BQ2E2JGXHGO0"),
+				Name:  utils.String("回款金额(元)"),
+				Value: utils.String(strconv.FormatFloat(req.ReceiveAmount, 'f', 2, 64)),
+			},
+			{
+				Id:    utils.String("MoneyField_V47BSZICHIO0"),
+				Name:  utils.String("开票金额(元)"),
+				Value: utils.String(strconv.FormatFloat(invoice.InvoiceAmount, 'f', 2, 64)),
+			},
+		},
+	})
+	if err != nil {
+		return err
+	}
+
+	_, err = s.Dao.Where("id = ?", invoice.Id).Data(map[string]interface{}{
+		"appro_status": 20,
+	}).Update()
+	return err
+}
+
+func InvoiceApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
+	tenant, err := micro_srv.GetTenant(ctx)
+	if err != nil {
+		return fmt.Errorf("获取租户码异常:%s", err.Error())
+	}
+	invoiceDao := dao.NewCtrContractInvoiceDao(tenant)
+	userDao := sysDao.NewSysUserDao(tenant)
+
+	bizCode := strings.Split(flow.BizCode, ":")
+	if len(bizCode) != 2 {
+		return fmt.Errorf("申请发票审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	invoiceId, err := strconv.Atoi(bizCode[0])
+	if err != nil {
+		return fmt.Errorf("申请发票审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	userId, err := strconv.Atoi(bizCode[1])
+	if err != nil {
+		return fmt.Errorf("申请发票审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	user, err := userDao.Where("id = ?", userId).One()
+	if err != nil {
+		return err
+	}
+	if user == nil {
+		return fmt.Errorf("用户不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	invoice, err := invoiceDao.Where("id = ?", invoiceId).One()
+	if err != nil {
+		return err
+	}
+	if invoice == nil {
+		return fmt.Errorf("发票不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+
+	if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
+		return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
+	}
+	if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
+		return fmt.Errorf("无法识别的 Result :%s", msg.Result)
+	}
+
+	if msg.ProcessType == "terminate" {
+		_, err = invoiceDao.Where("id = ?", invoiceId).Data(map[string]interface{}{
+			"appro_status": "50",
+		}).Update()
+		return err
+	}
+
+	pass := msg.Result == "agree"
+	if !pass {
+		_, err = invoiceDao.Where("id = ?", invoiceId).Data(map[string]interface{}{
+			"appro_status": "40",
+		}).Update()
+		return err
+	}
+
+	_, err = invoiceDao.Where("id = ?", invoiceId).Data(map[string]interface{}{
+		"appro_status": "30",
+	}).Update()
+	return err
+}
+
 func (s CtrContractInvoiceService) Delete(ctx context.Context, id []int) error {
 	if len(id) == 0 {
 		return nil
@@ -301,10 +525,9 @@ func (s CtrContractInvoiceService) Delete(ctx context.Context, id []int) error {
 			if err != nil {
 				return err
 			}
-			if ent.ApproStatus != "20" {
-				continue
+			if ent.ApproStatus == "30" {
+				contractId[ent.ContractId] = true
 			}
-			contractId[ent.ContractId] = true
 		}
 
 		_, err := tx.Delete("ctr_contract_invoice", "id in (?)", id)

+ 39 - 0
opms_parent/app/service/contract/ctr_contract_test.go

@@ -0,0 +1,39 @@
+package service
+
+import (
+	"context"
+	"testing"
+
+	modelWorkflow "dashoo.cn/micro/app/model/workflow"
+	"dashoo.cn/opms_libary/plugin/dingtalk/message"
+	"github.com/gogf/gf/frame/g"
+	"github.com/smallnest/rpcx/share"
+)
+
+var testTenant = "default"
+
+func fakeCtx(parent context.Context, tenant string) context.Context {
+	ctx := context.WithValue(parent, share.ReqMetaDataKey, map[string]string{
+		"tenant": tenant,
+	})
+	return ctx
+}
+
+func TestAssignInvoiceApplyApproval(t *testing.T) {
+	ctx := fakeCtx(context.Background(), testTenant)
+
+	instance := modelWorkflow.PlatWorkflow{}
+	err := g.DB(testTenant).Table("plat_workflow").Where("id = ?", 47).Struct(&instance)
+	if err != nil {
+		panic(err)
+	}
+	err = InvoiceApplyApproval(ctx, &instance, &message.MixMessage{
+		ProcessType: "finish",
+		// ProcessType: "terminate",
+		// Result: "agree",
+		Result: "refuse",
+	})
+	if err != nil {
+		panic(err)
+	}
+}

+ 429 - 75
opms_parent/app/service/cust/cust_customer.go

@@ -3,13 +3,15 @@ package cust
 import (
 	"bytes"
 	"context"
-	"dashoo.cn/opms_libary/plugin/dingtalk/workflow"
-	"dashoo.cn/opms_libary/utils"
 	"fmt"
 	"math"
 	"strconv"
 	"strings"
 
+	"dashoo.cn/opms_libary/plugin/dingtalk/workflow"
+	"dashoo.cn/opms_libary/request"
+	"dashoo.cn/opms_libary/utils"
+
 	"dashoo.cn/opms_libary/myerrors"
 	"dashoo.cn/opms_libary/plugin/dingtalk/message"
 	"github.com/360EntSecGroup-Skylar/excelize"
@@ -290,52 +292,9 @@ func (s *CustomerService) UpdateById(req *model.UpdateCustomer) (err error) {
 	return
 }
 
-// MoveToPubic 移入公海
-func (s *CustomerService) MoveToPubic(Ids []int64) (err error) {
-	count, err := s.Dao.WhereIn(s.Dao.Columns.Id, Ids).Count()
-	if err != nil {
-		g.Log().Error(err)
-		return
-	}
-	if count == 0 {
-		err = myerrors.TipsError("没有要移除的数据")
-		return
-	}
-	userName := s.GetCxtUserName()
-	currentTime := gtime.Now() //  当前时间
-	s.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
-		//更新客户信息
-		_, err = s.Dao.TX(tx).Data(g.Map{
-			"is_public":    isPublic,
-			"sales_id":     0,
-			"dept_id":      0,
-			"dept_name":    "",
-			"create_time":  currentTime,
-			"updated_by":   s.GetCxtUserId(),
-			"updated_name": userName,
-			"updated_time": currentTime,
-		}).WhereIn(s.ContactDao.Columns.Id, Ids).Update()
-		if err != nil {
-			g.Log().Error(err)
-			return err
-		}
-		//更新销售归属表结束时间
-		_, err = s.BelongDao.TX(tx).Data(
-			g.Map{
-				"updated_by":   s.GetCxtUserId(),
-				"updated_name": userName,
-				"end_date":     currentTime,
-			}).WhereIn(s.BelongDao.Columns.CustId, Ids).Update()
-		if err != nil {
-			g.Log().Error(err)
-			return err
-		}
-		return nil
-	})
-	return
-}
-
-var AssignCustomerRequestProcessCode = "PROC-FE42B2D1-6097-4DE8-8AC5-23541B7D5C8A"
+var AssignCustomerRequestProcessCode = "PROC-FE42B2D1-6097-4DE8-8AC5-23541B7D5C8A" // BizCode: 11
+var MoveToPubicRequestProcessCode = "PROC-C030BD3D-74A3-4FE5-9EBA-DF3BA9F8AEF9"    // BizCode: 12
+var TransCustomerRequestProcessCode = "PROC-03BE93D3-9A44-43A1-BA6D-D1BB75702542"  // BizCode: 13
 
 // AssignCustomerRequest 领取客户申请
 func (s *CustomerService) AssignCustomerRequest(ctx context.Context, req *model.AssignCustomerReq) error {
@@ -354,6 +313,15 @@ func (s *CustomerService) AssignCustomerRequest(ctx context.Context, req *model.
 		if v.CustStatus != "10" {
 			return myerrors.TipsError(fmt.Sprintf("客户: %s 已被领取", v.CustName))
 		}
+		if v.CustProvince == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的所在省信息", v.CustName))
+		}
+		if v.CustCity == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的所在市信息", v.CustName))
+		}
+		if v.CustIndustry == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的客户类型信息", v.CustName))
+		}
 	}
 
 	workflowSrv, err := workflowService.NewFlowService(ctx)
@@ -375,6 +343,21 @@ func (s *CustomerService) AssignCustomerRequest(ctx context.Context, req *model.
 					Name:  utils.String("客户名称"),
 					Value: utils.String(u.CustName),
 				},
+				{
+					Id:    utils.String("TextField_Q32G87K9Y680"),
+					Name:  utils.String("所在省"),
+					Value: utils.String(u.CustProvince),
+				},
+				{
+					Id:    utils.String("TextField_1C81AAVZELY80"),
+					Name:  utils.String("所在市"),
+					Value: utils.String(u.CustCity),
+				},
+				{
+					Id:    utils.String("TextField_7EF74WG6AJ40"),
+					Name:  utils.String("客户类别"),
+					Value: utils.String(u.CustIndustry),
+				},
 				{
 					Id:    utils.String("TextField_1ZY48VZY6WG00"),
 					Name:  utils.String("申请人"),
@@ -454,20 +437,392 @@ func (s *CustomerService) AssignCustomerRequestApproval(flow *workflowModel.Plat
 		return err
 	}
 
+	s.CxtUser = &request.UserInfo{Id: user.Id, UserName: user.NickName}
 	err = s.ChangeCustBelong([]int64{int64(custId)}, int64(userId), user.NickName)
 	if err != nil {
 		return err
 	}
-	s.BatchCreatebelong([]*model.CustCustomer{cust}, &model.AssignCustomerReq{
+	err = s.BatchCreatebelong([]*model.CustCustomer{cust}, &model.AssignCustomerReq{
 		Ids:       []int64{int64(custId)},
 		SalesId:   int64(user.Id),
 		SalesName: user.NickName,
 		Remark:    "",
 		Receive:   Receive,
 	})
+	if err != nil {
+		return err
+	}
+
+	s.CxtUser = &request.UserInfo{Id: user.Id, UserName: user.NickName}
+	return s.CreateDynamics("领取客户", map[string]interface{}{
+		"userId": user.Id,
+		"custId": cust.Id,
+	}, int64(cust.Id))
+}
+
+// 移回公海
+func (s *CustomerService) MoveToPublicRequest(ctx context.Context, req *model.MoveToPubicRep) error {
+	if req.Remark == "" {
+		return myerrors.TipsError("请输入移回原因")
+	}
+	data, err := s.Dao.Where("id in (?)", req.Ids).All()
+	if err != nil {
+		return err
+	}
+	if len(data) == 0 {
+		return myerrors.TipsError("移回用户不能为空")
+	}
+
+	for _, v := range data {
+		if v.CustStatus == "10" {
+			return myerrors.TipsError(fmt.Sprintf("客户: %s 已被移回公海", v.CustName))
+		}
+		if v.CustStatus == "20" {
+			return myerrors.TipsError(fmt.Sprintf("客户: %s 正在等待审批", v.CustName))
+		}
+		if v.CustProvince == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的所在省信息", v.CustName))
+		}
+		if v.CustCity == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的所在市信息", v.CustName))
+		}
+		if v.CustIndustry == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的客户类型信息", v.CustName))
+		}
+	}
+
+	workflowSrv, err := workflowService.NewFlowService(ctx)
+	if err != nil {
+		return err
+	}
+	for _, u := range data {
+		bizCode := strconv.Itoa(u.Id) + ":" + strconv.Itoa(s.GetCxtUserId())
+		_, err = workflowSrv.StartProcessInstance(bizCode, "12", &workflow.StartProcessInstanceRequest{
+			ProcessCode: &MoveToPubicRequestProcessCode,
+			FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
+				{
+					Id:    utils.String("TextField_JFWRAP0D1IO0"),
+					Name:  utils.String("客户编码"),
+					Value: utils.String(u.CustCode),
+				},
+				{
+					Id:    utils.String("TextField-K2AD4O5B"),
+					Name:  utils.String("客户名称"),
+					Value: utils.String(u.CustName),
+				},
+				{
+					Id:    utils.String("TextField_1THUAFLY5RGG0"),
+					Name:  utils.String("所在省"),
+					Value: utils.String(u.CustProvince),
+				},
+				{
+					Id:    utils.String("TextField_15SRKAQIYY680"),
+					Name:  utils.String("所在市"),
+					Value: utils.String(u.CustCity),
+				},
+				{
+					Id:    utils.String("TextField_S966SSJHCCG0"),
+					Name:  utils.String("客户类别"),
+					Value: utils.String(u.CustIndustry),
+				},
+				{
+					Id:    utils.String("TextField_Y3EQ11P49LC0"),
+					Name:  utils.String("申请人"),
+					Value: utils.String(s.GetCxtUserName()),
+				},
+				{
+					Id:    utils.String("TextareaField_1790F8J2SPJ40"),
+					Name:  utils.String("移回原因"),
+					Value: utils.String(req.Remark),
+				},
+			},
+		})
+		if err != nil {
+			return err
+		}
+
+		_, err = s.Dao.Where("id = ?", u.Id).Data(map[string]interface{}{
+			"cust_status": "20",
+		}).Update()
+		if err != nil {
+			return err
+		}
+	}
 	return nil
 }
 
+// 移入公海回调
+func (s *CustomerService) MoveToPublicApproval(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
+	bizCode := strings.Split(flow.BizCode, ":")
+	if len(bizCode) != 2 {
+		return fmt.Errorf("客户移回审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	custId, err := strconv.Atoi(bizCode[0])
+	if err != nil {
+		return fmt.Errorf("客户移回审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	userId, err := strconv.Atoi(bizCode[1])
+	if err != nil {
+		return fmt.Errorf("客户移回审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	user, err := s.UserDao.Where("id = ?", userId).One()
+	if err != nil {
+		return err
+	}
+	if user == nil {
+		return fmt.Errorf("用户不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	cust, err := s.Dao.Where("id = ?", custId).One()
+	if err != nil {
+		return err
+	}
+	if cust == nil {
+		return fmt.Errorf("客户不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+
+	if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
+		return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
+	}
+	if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
+		return fmt.Errorf("无法识别的 Result :%s", msg.Result)
+	}
+
+	if msg.ProcessType == "terminate" {
+		_, err = s.Dao.Where("id = ?", custId).Data(map[string]interface{}{
+			"cust_status": "30",
+		}).Update()
+		return err
+	}
+
+	pass := msg.Result == "agree"
+	if !pass {
+		_, err = s.Dao.Where("id = ?", custId).Data(map[string]interface{}{
+			"cust_status": "30",
+		}).Update()
+		return err
+	}
+
+	now := gtime.Now()
+	err = s.Dao.Transaction(context.TODO(), func(ctx context.Context, tx *gdb.TX) error {
+		//更新客户信息
+		_, err = s.Dao.TX(tx).Data(g.Map{
+			"cust_status":  "10",
+			"is_public":    isPublic,
+			"sales_id":     0,
+			"dept_id":      0,
+			"dept_name":    "",
+			"create_time":  now,
+			"updated_by":   user.Id,
+			"updated_name": user.NickName,
+			"updated_time": now,
+		}).Where("id = ?", cust.Id).Update()
+		if err != nil {
+			return err
+		}
+		//更新销售归属表结束时间
+		_, err = s.BelongDao.TX(tx).Data(
+			g.Map{
+				"updated_by":   user.Id,
+				"updated_name": user.NickName,
+				"end_date":     now,
+			}).Where("cust_id = ?", cust.Id).Update()
+		if err != nil {
+			return err
+		}
+		return nil
+	})
+	if err != nil {
+		return err
+	}
+
+	s.CxtUser = &request.UserInfo{Id: user.Id, UserName: user.NickName}
+	return s.CreateDynamics("移入公海", map[string]interface{}{
+		"userId": user.Id,
+		"custId": cust.Id,
+	}, int64(cust.Id))
+}
+
+// 转移客户
+func (s *CustomerService) TransCustomerRequest(ctx context.Context, req *model.AssignCustomerReq) error {
+	if req.Remark == "" {
+		return myerrors.TipsError("请输入转移原因")
+	}
+	data, err := s.Dao.Where("id in (?)", req.Ids).All()
+	if err != nil {
+		return err
+	}
+	if len(data) == 0 {
+		return myerrors.TipsError("转移用户不能为空")
+	}
+
+	for _, v := range data {
+		if v.CustStatus == "10" {
+			return myerrors.TipsError(fmt.Sprintf("客户: %s 为公海客户", v.CustName))
+		}
+		if v.CustStatus == "20" {
+			return myerrors.TipsError(fmt.Sprintf("客户: %s 正在等待审批", v.CustName))
+		}
+		if v.CustProvince == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的所在省信息", v.CustName))
+		}
+		if v.CustCity == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的所在市信息", v.CustName))
+		}
+		if v.CustIndustry == "" {
+			return myerrors.TipsError(fmt.Sprintf("请先完善客户: %s 的客户类型信息", v.CustName))
+		}
+	}
+
+	workflowSrv, err := workflowService.NewFlowService(ctx)
+	if err != nil {
+		return err
+	}
+	for _, u := range data {
+		bizCode := strings.Join([]string{
+			strconv.Itoa(u.Id),
+			strconv.Itoa(s.GetCxtUserId()),
+			strconv.FormatInt(req.SalesId, 10),
+		}, ":")
+		_, err = workflowSrv.StartProcessInstance(bizCode, "13", &workflow.StartProcessInstanceRequest{
+			ProcessCode: &TransCustomerRequestProcessCode,
+			FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
+				{
+					Id:    utils.String("TextField-K2AD4O5B"),
+					Name:  utils.String("客户编码"),
+					Value: utils.String(u.CustCode),
+				},
+				{
+					Id:    utils.String("TextField_HMF1CTLP55S0"),
+					Name:  utils.String("客户名称"),
+					Value: utils.String(u.CustName),
+				},
+				{
+					Id:    utils.String("TextField_SAITVT7MNF40"),
+					Name:  utils.String("所在省"),
+					Value: utils.String(u.CustProvince),
+				},
+				{
+					Id:    utils.String("TextField_12DGEUTR74NK0"),
+					Name:  utils.String("所在市"),
+					Value: utils.String(u.CustCity),
+				},
+				{
+					Id:    utils.String("TextField_16FDRGG3URCW0"),
+					Name:  utils.String("客户类别"),
+					Value: utils.String(u.CustIndustry),
+				},
+				{
+					Id:    utils.String("TextField_1JSO6EU9XQCG0"),
+					Name:  utils.String("申请人"),
+					Value: utils.String(s.GetCxtUserName()),
+				},
+				{
+					Id:    utils.String("TextareaField_1ZSSTZFCT0G00"),
+					Name:  utils.String("转移原因"),
+					Value: utils.String(req.Remark),
+				},
+			},
+		})
+		if err != nil {
+			return err
+		}
+
+		_, err = s.Dao.Where("id = ?", u.Id).Data(map[string]interface{}{
+			"cust_status": "20",
+		}).Update()
+		if err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// 转移客户回调
+func (s *CustomerService) TransCustomerApproval(flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
+	bizCode := strings.Split(flow.BizCode, ":")
+	if len(bizCode) != 3 {
+		return fmt.Errorf("转移客户审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	custId, err := strconv.Atoi(bizCode[0])
+	if err != nil {
+		return fmt.Errorf("转移客户审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	userId, err := strconv.Atoi(bizCode[1])
+	if err != nil {
+		return fmt.Errorf("转移客户审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	toUserId, err := strconv.Atoi(bizCode[2])
+	if err != nil {
+		return fmt.Errorf("转移客户审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	user, err := s.UserDao.Where("id = ?", userId).One()
+	if err != nil {
+		return err
+	}
+	if user == nil {
+		return fmt.Errorf("用户不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	toUser, err := s.UserDao.Where("id = ?", toUserId).One()
+	if err != nil {
+		return err
+	}
+	if toUser == nil {
+		return fmt.Errorf("用户不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+	cust, err := s.Dao.Where("id = ?", custId).One()
+	if err != nil {
+		return err
+	}
+	if cust == nil {
+		return fmt.Errorf("客户不存在:%s Id: %d", flow.BizCode, flow.Id)
+	}
+
+	if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
+		return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
+	}
+	if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
+		return fmt.Errorf("无法识别的 Result :%s", msg.Result)
+	}
+
+	if msg.ProcessType == "terminate" {
+		_, err = s.Dao.Where("id = ?", custId).Data(map[string]interface{}{
+			"cust_status": "30",
+		}).Update()
+		return err
+	}
+
+	pass := msg.Result == "agree"
+	if !pass {
+		_, err = s.Dao.Where("id = ?", custId).Data(map[string]interface{}{
+			"cust_status": "30",
+		}).Update()
+		return err
+	}
+
+	s.CxtUser = &request.UserInfo{Id: user.Id, UserName: user.NickName}
+	err = s.ChangeCustBelong([]int64{int64(custId)}, int64(toUserId), toUser.NickName)
+	if err != nil {
+		return err
+	}
+	err = s.BatchCreatebelong([]*model.CustCustomer{cust}, &model.AssignCustomerReq{
+		Ids:       []int64{int64(custId)},
+		SalesId:   int64(toUser.Id),
+		SalesName: toUser.NickName,
+		Remark:    "",
+		Receive:   OperaTion,
+	})
+	if err != nil {
+		return err
+	}
+
+	s.CxtUser = &request.UserInfo{Id: user.Id, UserName: user.NickName}
+	return s.CreateDynamics("转移客户", map[string]interface{}{
+		"userId":   user.Id,
+		"custId":   cust.Id,
+		"toUserId": toUser.Id,
+	}, int64(cust.Id))
+}
+
 // AssignCustomer 分配客户
 func (s *CustomerService) AssignCustomer(ctx context.Context, req *model.AssignCustomerReq) (err error) {
 	if req.Receive != "" {
@@ -493,13 +848,12 @@ func (s *CustomerService) AssignCustomer(ctx context.Context, req *model.AssignC
 	if err != nil {
 		return
 	}
-	if req.Receive != "" {
-		req.Receive = Receive
-	} else {
-		req.Receive = AllocaTion
+	req.Receive = AllocaTion
+	err = s.BatchCreatebelong(data, req)
+	if err != nil {
+		return err
 	}
-	s.BatchCreatebelong(data, req)
-	return
+	return s.CreateDynamics("分配客户", req, req.Ids...)
 }
 
 // GetEntityById 客户详情
@@ -568,26 +922,26 @@ func (s *CustomerService) CustAbstract(Id int64) (followInfo *model.Follow, err
 	return
 }
 
-// TransCustomer 转移客户
-func (s *CustomerService) TransCustomer(req *model.AssignCustomerReq) (err error) {
-	data, err := s.Dao.Fields("sales_id,sales_name,id").Where("id in (?)", req.Ids).All()
-	if err != nil {
-		g.Log().Error(err)
-		return err
-	}
-
-	if len(data) == 0 {
-		return myerrors.TipsError("数据不存在")
-	}
-	err = s.ChangeCustBelong(req.Ids, req.SalesId, req.SalesName)
-	if err != nil {
-		g.Log().Error(err)
-		return
-	}
-	req.Receive = OperaTion
-	s.BatchCreatebelong(data, req)
-	return
-}
+// // TransCustomer 转移客户
+// func (s *CustomerService) TransCustomer(req *model.AssignCustomerReq) (err error) {
+// 	data, err := s.Dao.Fields("sales_id,sales_name,id").Where("id in (?)", req.Ids).All()
+// 	if err != nil {
+// 		g.Log().Error(err)
+// 		return err
+// 	}
+
+// 	if len(data) == 0 {
+// 		return myerrors.TipsError("数据不存在")
+// 	}
+// 	err = s.ChangeCustBelong(req.Ids, req.SalesId, req.SalesName)
+// 	if err != nil {
+// 		g.Log().Error(err)
+// 		return
+// 	}
+// 	req.Receive = OperaTion
+// 	s.BatchCreatebelong(data, req)
+// 	return
+// }
 
 // ChangeCustBelong 变更客户所属关系
 func (s *CustomerService) ChangeCustBelong(Ids []int64, salesId int64, salesName string) (err error) {

+ 86 - 0
opms_parent/app/service/cust/cust_customer_test.go

@@ -0,0 +1,86 @@
+package cust
+
+import (
+	"context"
+	"testing"
+
+	modelWorkflow "dashoo.cn/micro/app/model/workflow"
+	"dashoo.cn/opms_libary/plugin/dingtalk/message"
+	"github.com/gogf/gf/frame/g"
+	"github.com/smallnest/rpcx/share"
+)
+
+var testTenant = "default"
+
+func fakeCtx(parent context.Context, tenant string) context.Context {
+	ctx := context.WithValue(parent, share.ReqMetaDataKey, map[string]string{
+		"tenant": tenant,
+	})
+	return ctx
+}
+
+func TestAssignCustomerRequestApproval(t *testing.T) {
+	ctx := fakeCtx(context.Background(), testTenant)
+	srv, err := NewCustomerService(ctx)
+	if err != nil {
+		panic(err)
+	}
+	instance := modelWorkflow.PlatWorkflow{}
+	err = g.DB(testTenant).Table("plat_workflow").Where("id = ?", 33).Struct(&instance)
+	if err != nil {
+		panic(err)
+	}
+	err = srv.AssignCustomerRequestApproval(&instance, &message.MixMessage{
+		ProcessType: "finish",
+		// ProcessType: "terminate",
+		Result: "agree",
+		// Result: "refuse",
+	})
+	if err != nil {
+		panic(err)
+	}
+}
+
+func TestAssignMoveToPublicApproval(t *testing.T) {
+	ctx := fakeCtx(context.Background(), testTenant)
+	srv, err := NewCustomerService(ctx)
+	if err != nil {
+		panic(err)
+	}
+	instance := modelWorkflow.PlatWorkflow{}
+	err = g.DB(testTenant).Table("plat_workflow").Where("id = ?", 25).Struct(&instance)
+	if err != nil {
+		panic(err)
+	}
+	err = srv.MoveToPublicApproval(&instance, &message.MixMessage{
+		ProcessType: "finish",
+		// ProcessType: "terminate",
+		Result: "agree",
+		// Result: "refuse",
+	})
+	if err != nil {
+		panic(err)
+	}
+}
+
+func TestAssignTransCustomerApproval(t *testing.T) {
+	ctx := fakeCtx(context.Background(), testTenant)
+	srv, err := NewCustomerService(ctx)
+	if err != nil {
+		panic(err)
+	}
+	instance := modelWorkflow.PlatWorkflow{}
+	err = g.DB(testTenant).Table("plat_workflow").Where("id = ?", 27).Struct(&instance)
+	if err != nil {
+		panic(err)
+	}
+	err = srv.TransCustomerApproval(&instance, &message.MixMessage{
+		ProcessType: "finish",
+		// ProcessType: "terminate",
+		Result: "agree",
+		// Result: "refuse",
+	})
+	if err != nil {
+		panic(err)
+	}
+}

+ 1 - 1
opms_parent/app/service/workflow/work_flow.go

@@ -50,7 +50,6 @@ func (s *workflowService) GetProcessInstanceDetail(instId string) (*workflow.Que
 // bizType:业务类型(10领用20项目创建30合同创建
 // 详情参照文档:https://open.dingtalk.com/document/orgapp/create-an-approval-instance
 func (s *workflowService) StartProcessInstance(bizCode, bizType string, flow *workflow.StartProcessInstanceRequest) (insertId int64, err error) {
-	g.Log().Info("搜索值", flow)
 	// 参数调整
 	if flow.OriginatorUserId == nil {
 		flow.OriginatorUserId = utils.String(s.GetCxtUserDingtalkUid())
@@ -58,6 +57,7 @@ func (s *workflowService) StartProcessInstance(bizCode, bizType string, flow *wo
 	if flow.DeptId == nil {
 		flow.DeptId = utils.Int64(435711466)
 	}
+	g.Log().Info("搜索值", flow)
 	// 调用钉钉接口
 	client := dingtalk.NewClient()
 	w := client.GetWorkflow()

+ 1 - 1
opms_parent/schema/contract.sql

@@ -100,7 +100,7 @@ CREATE TABLE `ctr_contract_invoice` (
     `invoice_amount` decimal(24, 6) NOT NULL COMMENT '开票金额',
     `invoice_date` datetime NOT NULL COMMENT '开票日期',
     `invoice_type` varchar(4) DEFAULT NULL COMMENT '开票类型',
-    `appro_status` varchar(4) DEFAULT NULL COMMENT '审核状态 10 未通过 20 已通过',
+    `appro_status` varchar(4) DEFAULT NULL COMMENT '审核状态 10 待提交审核 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销',
     `invoice_code` varchar(32) DEFAULT NULL COMMENT '发票号码',
     `actual_invoice_date` datetime DEFAULT NULL COMMENT '实际开票日期',
     `courier_code` varchar(32) DEFAULT NULL COMMENT '快递单号',

+ 1 - 0
opms_parent/schema/tmp.sql

@@ -6,3 +6,4 @@ alter table cust_customer add `cust_region_id` INT(11) COMMENT '所在区县ID'
 alter table cust_customer add `cust_region` VARCHAR(90) COMMENT '所在区县' after cust_region_id;
 alter table cust_customer modify `cust_status` VARCHAR(4) DEFAULT 10 COMMENT '客户状态(10 待领取 20 领取审批 30 已领取)';
 alter table cust_customer add `follow_up_man` VARCHAR(90) COMMENT '最后跟进人' after follow_up_date;
+alter table ctr_contract_invoice modify `appro_status` varchar(4) DEFAULT NULL COMMENT '审核状态 10 待提交审核 20 待审核 30 审核已同意 40 审核已拒绝 50 审核已撤销',