作者 唐旭辉

更新部门职位管理

@@ -11,7 +11,7 @@ AdminPort = 8088 @@ -11,7 +11,7 @@ AdminPort = 8088
11 #---自定义配置 开始---- 11 #---自定义配置 开始----
12 ##数据库连接 12 ##数据库连接
13 # sqlconn ="${MYSQL_CONN||root:root@tcp(127.0.0.1:3306)/opportunity_dev?charset=utf8}" 13 # sqlconn ="${MYSQL_CONN||root:root@tcp(127.0.0.1:3306)/opportunity_dev?charset=utf8}"
14 -sqlconn ="${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8}" 14 +sqlconn ="${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8&loc=Asia%2FShanghai}"
15 ##redis相关配置 15 ##redis相关配置
16 redis_add_port = "127.0.0.1:6379" 16 redis_add_port = "127.0.0.1:6379"
17 redis_auth = "" 17 redis_auth = ""
@@ -10,7 +10,7 @@ AdminPort = 8088 @@ -10,7 +10,7 @@ AdminPort = 8088
10 10
11 #---自定义配置 开始---- 11 #---自定义配置 开始----
12 #数据库连接 12 #数据库连接
13 -sqlconn = "root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8" 13 +sqlconn = "root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8&loc=Asia%2FShanghai"
14 #redis相关配置 14 #redis相关配置
15 redis_add_port = "127.0.0.1:6379" 15 redis_add_port = "127.0.0.1:6379"
16 redis_auth = "" 16 redis_auth = ""
@@ -8,7 +8,7 @@ httpport = 8080 @@ -8,7 +8,7 @@ httpport = 8080
8 8
9 #---自定义配置 开始---- 9 #---自定义配置 开始----
10 #数据库连接 10 #数据库连接
11 -sqlconn = "${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8}" 11 +sqlconn = "${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8&loc=Asia%2FShanghai}"
12 #redis相关配置 12 #redis相关配置
13 redis_add_port = "127.0.0.1:6379" 13 redis_add_port = "127.0.0.1:6379"
14 redis_auth = "" 14 redis_auth = ""
  1 +package controllers
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "oppmg/common/log"
  6 + "oppmg/protocol"
  7 + servecompany "oppmg/services/company"
  8 +)
  9 +
  10 +type CompanyController struct {
  11 + BaseController
  12 +}
  13 +
  14 +//URLMapping 实现ControllerInterface中的URLMapping
  15 +func (c *CompanyController) URLMapping() {
  16 + //c.Mapping("AccessToken", c.AccessToken)
  17 +}
  18 +
  19 +// DepartmentAdd 添加部门
  20 +// @router /department [post]
  21 +func (c *CompanyController) DepartmentAdd() {
  22 + var msg *protocol.ResponseMessage
  23 + defer func() {
  24 + c.ResposeJson(msg)
  25 + }()
  26 + var param protocol.RequestDepartmentAdd
  27 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  28 + log.Error("json 解析失败 err:%s", err)
  29 + msg = protocol.BadRequestParam("1")
  30 + return
  31 + }
  32 + if param.CompanyID <= 0 {
  33 + log.Error("param.CompanyID <= 0")
  34 + msg = protocol.BadRequestParam("1")
  35 + return
  36 + }
  37 + //err := protocol.NewErrWithMessage("101", nil)
  38 + err := servecompany.DepartmentAdd(param)
  39 + msg = protocol.NewReturnResponse(nil, err)
  40 + return
  41 +}
  42 +
  43 +// DepartmentUpdate 更新部门
  44 +// @router /department [put]
  45 +func (c *CompanyController) DepartmentUpdate() {
  46 + var msg *protocol.ResponseMessage
  47 + defer func() {
  48 + c.ResposeJson(msg)
  49 + }()
  50 +
  51 + var param protocol.RequestDepartmentEdit
  52 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  53 + log.Error("json 解析失败 err:%s", err)
  54 + msg = protocol.BadRequestParam("1")
  55 + return
  56 + }
  57 + if param.ID <= 0 {
  58 + log.Error(" param.ID <= 0 ")
  59 + msg = protocol.BadRequestParam("1")
  60 + return
  61 + }
  62 + err := servecompany.DepartmentEdit(param)
  63 + msg = protocol.NewReturnResponse(nil, err)
  64 + return
  65 +}
  66 +
  67 +// DepartmentUpdate 删除部门
  68 +// @router /department [delete]
  69 +func (c *CompanyController) DepartmentDelete() {
  70 + var msg *protocol.ResponseMessage
  71 + defer func() {
  72 + c.ResposeJson(msg)
  73 + }()
  74 +
  75 + var param protocol.RequestDepartmentDelete
  76 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  77 + log.Error("json 解析失败 err:%s", err)
  78 + msg = protocol.BadRequestParam("1")
  79 + return
  80 + }
  81 + if param.ID <= 0 {
  82 + log.Error(" param.ID <= 0 ")
  83 + msg = protocol.BadRequestParam("1")
  84 + return
  85 + }
  86 + err := servecompany.DepartmentDelete(param)
  87 + msg = protocol.NewReturnResponse(nil, err)
  88 + return
  89 +}
@@ -16,6 +16,7 @@ func main() { @@ -16,6 +16,7 @@ func main() {
16 common.ResetCommonConfig() 16 common.ResetCommonConfig()
17 log.Debug("加载配置%s", config.MConfig.ConfigName) 17 log.Debug("加载配置%s", config.MConfig.ConfigName)
18 orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn) 18 orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn)
  19 + // orm.Debug = true
19 if beego.BConfig.RunMode == "dev" { 20 if beego.BConfig.RunMode == "dev" {
20 beego.BConfig.WebConfig.DirectoryIndex = true 21 beego.BConfig.WebConfig.DirectoryIndex = true
21 beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" 22 beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
@@ -40,9 +40,10 @@ func (t *Department) GetManagesIds() []int64 { @@ -40,9 +40,10 @@ func (t *Department) GetManagesIds() []int64 {
40 return r 40 return r
41 } 41 }
42 42
43 -func (t *Department) ParseManagesIds(v []int64) string { 43 +func (t *Department) SetManages(v []int64) {
44 bt, _ := json.Marshal(v) 44 bt, _ := json.Marshal(v)
45 - return string(bt) 45 + t.Manages = string(bt)
  46 + return
46 } 47 }
47 48
48 func (t *Department) SetRelation(parent *Department) error { 49 func (t *Department) SetRelation(parent *Department) error {
@@ -59,8 +60,14 @@ func (t *Department) SetRelation(parent *Department) error { @@ -59,8 +60,14 @@ func (t *Department) SetRelation(parent *Department) error {
59 60
60 // AddDepartment insert a new Department into database and returns 61 // AddDepartment insert a new Department into database and returns
61 // last inserted Id on success. 62 // last inserted Id on success.
62 -func AddDepartment(m *Department) (id int64, err error) {  
63 - o := orm.NewOrm() 63 +func AddDepartment(m *Department, om ...orm.Ormer) (id int64, err error) {
  64 + var o orm.Ormer
  65 + if len(om) > 0 {
  66 + o = om[0]
  67 + } else {
  68 + o = orm.NewOrm()
  69 + }
  70 + m.DeleteAt = time.Unix(0, 0)
64 id, err = o.Insert(m) 71 id, err = o.Insert(m)
65 return 72 return
66 } 73 }
@@ -89,6 +96,7 @@ func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err err @@ -89,6 +96,7 @@ func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err err
89 // ascertain id exists in the database 96 // ascertain id exists in the database
90 if err = o.Read(&v); err == nil { 97 if err = o.Read(&v); err == nil {
91 var num int64 98 var num int64
  99 + m.UpdateAt = time.Now()
92 if num, err = o.Update(m, col...); err == nil { 100 if num, err = o.Update(m, col...); err == nil {
93 fmt.Println("Number of records updated in database:", num) 101 fmt.Println("Number of records updated in database:", num)
94 } 102 }
@@ -96,21 +104,6 @@ func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err err @@ -96,21 +104,6 @@ func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err err
96 return 104 return
97 } 105 }
98 106
99 -// DeleteDepartment deletes Department by Id and returns error if  
100 -// the record to be deleted doesn't exist  
101 -func DeleteDepartment(id int64) (err error) {  
102 - o := orm.NewOrm()  
103 - v := Department{Id: id}  
104 - // ascertain id exists in the database  
105 - if err = o.Read(&v); err == nil {  
106 - var num int64  
107 - if num, err = o.Delete(&Department{Id: id}); err == nil {  
108 - fmt.Println("Number of records deleted in database:", num)  
109 - }  
110 - }  
111 - return  
112 -}  
113 -  
114 func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Department, error) { 107 func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Department, error) {
115 dataSql := `SELECT company_id,parent_id,name,create_at,relation,member,managers 108 dataSql := `SELECT company_id,parent_id,name,create_at,relation,member,managers
116 FROM department 109 FROM department
@@ -132,3 +125,15 @@ func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Departme @@ -132,3 +125,15 @@ func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Departme
132 } 125 }
133 return result, nil 126 return result, nil
134 } 127 }
  128 +
  129 +func GetDepartmentByCompanyId(companyId int64) ([]Department, error) {
  130 + var (
  131 + result []Department
  132 + err error
  133 + )
  134 + o := orm.NewOrm()
  135 + _, err = o.QueryTable(&Department{}).
  136 + Filter("company_id", companyId).
  137 + All(&result)
  138 + return result, err
  139 +}
  1 +package models
  2 +
  3 +import (
  4 + "errors"
  5 + "fmt"
  6 + "time"
  7 +
  8 + "github.com/astaxie/beego/orm"
  9 +)
  10 +
  11 +type Position struct {
  12 + Id int64 `orm:"column(id);auto" description:"职位表id"`
  13 + CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
  14 + Name string `orm:"column(name);size(100)" description:"职位名称"`
  15 + ParentId int64 `orm:"column(parent_id)" description:"父级id"`
  16 + Relation string `orm:"column(relation);size(1000)" description:"父子级关系树"`
  17 + CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
  18 + UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
  19 + EnableStatus string `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"`
  20 +}
  21 +
  22 +func (t *Position) TableName() string {
  23 + return "position"
  24 +}
  25 +
  26 +func init() {
  27 + orm.RegisterModel(new(Position))
  28 +}
  29 +
  30 +func (t *Position) SetRelation(parent *Position) error {
  31 + if t.Id == 0 {
  32 + return errors.New("Id==0")
  33 + }
  34 + if parent == nil {
  35 + t.Relation = fmt.Sprintf("%d", t.Id)
  36 + } else {
  37 + t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id)
  38 + }
  39 + return nil
  40 +}
  41 +func (t *Position) ValidatePid() error {
  42 + roledata, err := GetPositionById(t.ParentId)
  43 + if err != nil {
  44 + return err
  45 + }
  46 + if roledata.CompanyId != t.CompanyId {
  47 + return errors.New("validate companyId err")
  48 + }
  49 + return nil
  50 +}
  51 +
  52 +// AddPosition insert a new Position into database and returns
  53 +// last inserted Id on success.
  54 +func AddPosition(m *Position, om ...orm.Ormer) (id int64, err error) {
  55 + var o orm.Ormer
  56 + if len(om) > 0 {
  57 + o = om[0]
  58 + } else {
  59 + o = orm.NewOrm()
  60 + }
  61 + m.CreateAt = time.Now()
  62 + m.UpdateAt = time.Now()
  63 + id, err = o.Insert(m)
  64 + return
  65 +}
  66 +
  67 +// GetPositionById retrieves Position by Id. Returns error if
  68 +// Id doesn't exist
  69 +func GetPositionById(id int64) (v *Position, err error) {
  70 + o := orm.NewOrm()
  71 + v = &Position{Id: id}
  72 + if err = o.Read(v); err == nil {
  73 + return v, nil
  74 + }
  75 + return nil, err
  76 +}
  77 +
  78 +// UpdatePositionById updates Department by Id and returns error if
  79 +// the record to be updated doesn't exist
  80 +func UpdatePositionById(m *Position, col []string, om ...orm.Ormer) (err error) {
  81 + var o orm.Ormer
  82 + if len(om) > 0 {
  83 + o = om[0]
  84 + } else {
  85 + o = orm.NewOrm()
  86 + }
  87 + v := Position{Id: m.Id}
  88 + // ascertain id exists in the database
  89 + if err = o.Read(&v); err == nil {
  90 + var num int64
  91 + m.UpdateAt = time.Now()
  92 + if num, err = o.Update(m, col...); err == nil {
  93 + fmt.Println("Number of records updated in database:", num)
  94 + }
  95 + }
  96 + return
  97 +}
@@ -33,7 +33,7 @@ const ( @@ -33,7 +33,7 @@ const (
33 ) 33 )
34 34
35 func (t *Role) ValidateTypes() bool { 35 func (t *Role) ValidateTypes() bool {
36 - switch i { 36 + switch t.Types {
37 case ROLETYPES_GROUP: 37 case ROLETYPES_GROUP:
38 return true 38 return true
39 case ROLETYPES_ROLE: 39 case ROLETYPES_ROLE:
@@ -4,8 +4,8 @@ package protocol @@ -4,8 +4,8 @@ package protocol
4 type RequestDepartmentAdd struct { 4 type RequestDepartmentAdd struct {
5 CompanyID int64 `json:"company_id"` //公司 5 CompanyID int64 `json:"company_id"` //公司
6 Name string `json:"name"` //部门名字 6 Name string `json:"name"` //部门名字
7 - ParantID int64 `json:"parant_id"` //父级部门Id  
8 - Managers []int64 `json:"admin_id"` //主管userid 7 + ParentID int64 `json:"parent_id"` //父级部门Id
  8 + Managers []int64 `json:"manages"` //主管userid
9 } 9 }
10 10
11 //ResponseDepartmentInfo ... 11 //ResponseDepartmentInfo ...
@@ -40,3 +40,16 @@ type RequestDepartmentDelete struct { @@ -40,3 +40,16 @@ type RequestDepartmentDelete struct {
40 type ResponseDepartmentList struct { 40 type ResponseDepartmentList struct {
41 List []ResponseDepartmentInfo 41 List []ResponseDepartmentInfo
42 } 42 }
  43 +
  44 +//RequestPositionAdd 添加职位
  45 +type RequestPositionAdd struct {
  46 + CompanyID int64 `json:"company_id"`
  47 + Name string `json:"name"`
  48 + ParentID int64 `json:"parent_id"`
  49 +}
  50 +
  51 +//RequestPositionEdit 编辑职位
  52 +type RequestPositionEdit struct {
  53 + ID int `json:"id"`
  54 + RequestPositionAdd
  55 +}
@@ -88,14 +88,14 @@ func (e ErrWithMessage) ParseToMessage() *ResponseMessage { @@ -88,14 +88,14 @@ func (e ErrWithMessage) ParseToMessage() *ResponseMessage {
88 func SearchErr(code string) ErrorCode { 88 func SearchErr(code string) ErrorCode {
89 return errmessge.Search(code) 89 return errmessge.Search(code)
90 } 90 }
91 -func NewReturnResponse(data interface{}, eRR error) *ResponseMessage {  
92 - var msg *ResponseMessage 91 +
  92 +func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
  93 + // var msg *ResponseMessage
93 if eRR == nil { 94 if eRR == nil {
94 - msg = NewMesage("0") 95 + msg = NewMesage("00000")
95 msg.Data = data 96 msg.Data = data
96 return msg 97 return msg
97 } 98 }
98 - // fmt.Println("日志:" + eRR.Error())  
99 if x, ok := eRR.(CustomErrParse); ok { 99 if x, ok := eRR.(CustomErrParse); ok {
100 return x.ParseToMessage() 100 return x.ParseToMessage()
101 } 101 }
@@ -10,7 +10,12 @@ import ( @@ -10,7 +10,12 @@ import (
10 10
11 func init() { 11 func init() {
12 nsV1 := beego.NewNamespace("v1", 12 nsV1 := beego.NewNamespace("v1",
13 - beego.NSBefore(middleware.AuthToken), 13 + beego.NSBefore(middleware.LogRequestData, middleware.AuthToken),
  14 + beego.NSNamespace("/company",
  15 + beego.NSRouter("/department", &controllers.CompanyController{}, "post:DepartmentAdd"),
  16 + beego.NSRouter("/department", &controllers.CompanyController{}, "put:DepartmentUpdate"),
  17 + beego.NSRouter("/department", &controllers.CompanyController{}, "delete:DepartmentDelete"),
  18 + ),
14 ) 19 )
15 20
16 nsAuth := beego.NewNamespace("/auth", 21 nsAuth := beego.NewNamespace("/auth",
@@ -17,10 +17,10 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) error { @@ -17,10 +17,10 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) error {
17 parentDepart *models.Department 17 parentDepart *models.Department
18 err error 18 err error
19 ) 19 )
20 - if param.ParantID > 0 {  
21 - parentDepart, err = models.GetDepartmentById(param.ParantID) 20 + if param.ParentID > 0 {
  21 + parentDepart, err = models.GetDepartmentById(param.ParentID)
22 if err != nil { 22 if err != nil {
23 - e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParantID, err) 23 + e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParentID, err)
24 log.Error(e.Error()) 24 log.Error(e.Error())
25 return protocol.NewErrWithMessage("1", e) 25 return protocol.NewErrWithMessage("1", e)
26 } 26 }
@@ -42,16 +42,35 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) error { @@ -42,16 +42,35 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) error {
42 CompanyId: param.CompanyID, 42 CompanyId: param.CompanyID,
43 Name: param.Name, 43 Name: param.Name,
44 CreateAt: time.Now(), 44 CreateAt: time.Now(),
45 - ParentId: param.ParantID, 45 + UpdateAt: time.Now(),
  46 + ParentId: param.ParentID,
46 Member: 0, 47 Member: 0,
47 } 48 }
48 - departmentAdd.SetRelation(parentDepart)  
49 - _, err = models.AddDepartment(departmentAdd) 49 + departmentAdd.SetManages(param.Managers)
  50 + o := orm.NewOrm()
  51 + o.Begin()
  52 + _, err = models.AddDepartment(departmentAdd, o)
50 if err != nil { 53 if err != nil {
  54 + o.Rollback()
51 e := fmt.Errorf("AddDepartment err:%s", err) 55 e := fmt.Errorf("AddDepartment err:%s", err)
52 log.Error(e.Error()) 56 log.Error(e.Error())
53 return protocol.NewErrWithMessage("1", e) 57 return protocol.NewErrWithMessage("1", e)
54 } 58 }
  59 + err = departmentAdd.SetRelation(parentDepart)
  60 + if err != nil {
  61 + o.Rollback()
  62 + e := fmt.Errorf("SetRelation err:%s", err)
  63 + log.Error(e.Error())
  64 + return protocol.NewErrWithMessage("1", e)
  65 + }
  66 + err = models.UpdateDepartmentById(departmentAdd, []string{"Relation"}, o)
  67 + if err != nil {
  68 + o.Rollback()
  69 + e := fmt.Errorf("UpdateDepartmentById err:%s", err)
  70 + log.Error(e.Error())
  71 + return protocol.NewErrWithMessage("1", e)
  72 + }
  73 + o.Commit()
55 return nil 74 return nil
56 75
57 } 76 }
@@ -87,27 +106,27 @@ func DepartmentEdit(param protocol.RequestDepartmentEdit) error { @@ -87,27 +106,27 @@ func DepartmentEdit(param protocol.RequestDepartmentEdit) error {
87 return protocol.NewErrWithMessage("1", e) 106 return protocol.NewErrWithMessage("1", e)
88 } 107 }
89 } 108 }
  109 + departUpdate.SetManages(param.Managers)
  110 + departUpdate.Name = param.Name
  111 + departUpdate.UpdateAt = time.Now()
  112 + err = models.UpdateDepartmentById(departUpdate, []string{"Manages", "Name", "UpdateAt"})
  113 + if err != nil {
  114 + e := fmt.Errorf("UpdateDepartmentById err:%s", err)
  115 + log.Error(e.Error())
  116 + return protocol.NewErrWithMessage("1", e)
  117 + }
90 //处理部门上级发生变化的情况 118 //处理部门上级发生变化的情况
91 var ( 119 var (
92 newparent *models.Department 120 newparent *models.Department
93 ) 121 )
94 - if departUpdate.ParentId != param.ParantID {  
95 - newparent, err = models.GetDepartmentById(param.ParantID) 122 + if departUpdate.ParentId != param.ParentID {
  123 + newparent, err = models.GetDepartmentById(param.ParentID)
96 if err != nil { 124 if err != nil {
97 - e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParantID, err) 125 + e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParentID, err)
98 log.Error(e.Error()) 126 log.Error(e.Error())
99 return protocol.NewErrWithMessage("1", e) 127 return protocol.NewErrWithMessage("1", e)
100 } 128 }
101 } 129 }
102 - departUpdate.Manages = departUpdate.ParseManagesIds(param.Managers)  
103 - departUpdate.Name = param.Name  
104 - departUpdate.UpdateAt = time.Now()  
105 - err = models.UpdateDepartmentById(departUpdate, []string{"Manages", "Name", "UpdateAt"})  
106 - if err != nil {  
107 - e := fmt.Errorf("UpdateDepartmentById err:%s", err)  
108 - log.Error(e.Error())  
109 - return protocol.NewErrWithMessage("1", e)  
110 - }  
111 //更新部门关系数据 130 //更新部门关系数据
112 err = departmentRelationUpdate(departUpdate, newparent) 131 err = departmentRelationUpdate(departUpdate, newparent)
113 if err != nil { 132 if err != nil {
@@ -119,32 +138,44 @@ func DepartmentEdit(param protocol.RequestDepartmentEdit) error { @@ -119,32 +138,44 @@ func DepartmentEdit(param protocol.RequestDepartmentEdit) error {
119 } 138 }
120 139
121 //DepartmentParentChange 处理部门上级发生变化的情况 140 //DepartmentParentChange 处理部门上级发生变化的情况
122 -func departmentRelationUpdate(old *models.Department, newparent *models.Department) error { 141 +func departmentRelationUpdate(departUpdate *models.Department, newparent *models.Department) error {
123 if newparent == nil { 142 if newparent == nil {
124 return nil 143 return nil
125 } 144 }
126 const ( 145 const (
127 //获取某个部门的下级部门 select ... for update 146 //获取某个部门的下级部门 select ... for update
128 dataSql0 string = `SELECT id,relation FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE` 147 dataSql0 string = `SELECT id,relation FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE`
  148 + //更新关系树
129 dataSql2 string = `update department set relation=? where id=?` 149 dataSql2 string = `update department set relation=? where id=?`
  150 + //更新departUpdate的parent_id
  151 + dataSql3 string = `update department set parent_id=? where id =?`
130 ) 152 )
131 var ( 153 var (
132 departSubset []models.Department //子级部门 154 departSubset []models.Department //子级部门
133 err error 155 err error
134 - oldrelation string = old.Relation  
135 - relationLike string = oldrelation + "%"  
136 - newRelation string = fmt.Sprintf("%s/%d", newparent.Relation, old.Id) 156 + oldRelation string = departUpdate.Relation
  157 + relationLike string = oldRelation + "%"
  158 + newRelation string = fmt.Sprintf("%s/%d", newparent.Relation, departUpdate.Id)
137 ) 159 )
138 o := orm.NewOrm() 160 o := orm.NewOrm()
139 o.Begin() 161 o.Begin()
140 - err = utils.ExcuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike) 162 + //修改部门的parent_id
  163 + err = utils.ExecuteSQLWithOrmer(o, dataSql3, newparent.Id, departUpdate.Id)
141 if err != nil { 164 if err != nil {
142 o.Rollback() 165 o.Rollback()
143 e := fmt.Errorf("EXECUTE SQL err:%s", err) 166 e := fmt.Errorf("EXECUTE SQL err:%s", err)
144 log.Error(e.Error()) 167 log.Error(e.Error())
145 return protocol.NewErrWithMessage("1", e) 168 return protocol.NewErrWithMessage("1", e)
146 } 169 }
147 - 170 + //获取部门及子级部门的relation和id
  171 + err = utils.ExecuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike)
  172 + if err != nil {
  173 + o.Rollback()
  174 + e := fmt.Errorf("EXECUTE SQL err:%s", err)
  175 + log.Error(e.Error())
  176 + return protocol.NewErrWithMessage("1", e)
  177 + }
  178 + //修改部门及子级部门的relation
148 for i := range departSubset { 179 for i := range departSubset {
149 if departSubset[i].Id == newparent.Id { 180 if departSubset[i].Id == newparent.Id {
150 //确认新的父级id是否合法 181 //确认新的父级id是否合法
@@ -154,9 +185,9 @@ func departmentRelationUpdate(old *models.Department, newparent *models.Departme @@ -154,9 +185,9 @@ func departmentRelationUpdate(old *models.Department, newparent *models.Departme
154 return protocol.NewErrWithMessage("1", e) 185 return protocol.NewErrWithMessage("1", e)
155 } 186 }
156 //重建关系树 187 //重建关系树
157 - s := strings.TrimPrefix(departSubset[i].Relation, oldrelation) 188 + s := strings.TrimPrefix(departSubset[i].Relation, oldRelation)
158 departSubset[i].Relation = strings.TrimSpace(fmt.Sprintf("%s%s", newRelation, s)) 189 departSubset[i].Relation = strings.TrimSpace(fmt.Sprintf("%s%s", newRelation, s))
159 - err := utils.ExcuteSQLWithOrmer(o, dataSql2, departSubset[i].Relation, departSubset[i].Id) 190 + err = utils.ExecuteSQLWithOrmer(o, dataSql2, departSubset[i].Relation, departSubset[i].Id)
160 if err != nil { 191 if err != nil {
161 o.Rollback() 192 o.Rollback()
162 e := fmt.Errorf("EXECUTE SQL err:%s", err) 193 e := fmt.Errorf("EXECUTE SQL err:%s", err)
@@ -164,15 +195,68 @@ func departmentRelationUpdate(old *models.Department, newparent *models.Departme @@ -164,15 +195,68 @@ func departmentRelationUpdate(old *models.Department, newparent *models.Departme
164 return protocol.NewErrWithMessage("1", e) 195 return protocol.NewErrWithMessage("1", e)
165 } 196 }
166 } 197 }
  198 +
167 o.Commit() 199 o.Commit()
168 return nil 200 return nil
169 } 201 }
170 202
171 -func DepartmentDelete(parm protocol.RequestDepartmentDelete) error { 203 +//DepartmentDelete 部门删除,删除整个分枝
  204 +func DepartmentDelete(param protocol.RequestDepartmentDelete) error {
  205 + var (
  206 + departDelete *models.Department
  207 + err error
  208 + )
  209 + departDelete, err = models.GetDepartmentById(param.ID)
  210 + if err != nil {
  211 + e := fmt.Errorf("GetDepartmentById err:%s", err)
  212 + log.Error(e.Error())
  213 + return protocol.NewErrWithMessage("1", e)
  214 + }
  215 + if departDelete.CompanyId != param.CompanyID {
  216 + e := fmt.Errorf("departDelete.CompanyId != param.CompanyID")
  217 + log.Error(e.Error())
  218 + return protocol.NewErrWithMessage("1", e)
  219 + }
  220 + const (
  221 + //获取部门子集 锁数据 select ... for update,
  222 + dataSql0 string = `SELECT id,relation,member FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE`
  223 + dataSql2 string = `update department set delete_at=? where relation LIKE ?`
  224 + )
  225 + var (
  226 + departSubset []models.Department
  227 + relationLike string = departDelete.Relation + "%"
  228 + nowTime string = time.Now().String()
  229 + )
  230 + o := orm.NewOrm()
  231 + o.Begin()
  232 + err = utils.ExecuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike)
  233 + if err != nil {
  234 + o.Rollback()
  235 + e := fmt.Errorf("")
  236 + log.Error(e.Error())
  237 + return protocol.NewErrWithMessage("1", e)
  238 + }
  239 + for _, v := range departSubset {
  240 + if v.Member > 0 {
  241 + o.Rollback()
  242 + e := fmt.Errorf("Member > 0 ")
  243 + log.Error(e.Error())
  244 + return protocol.NewErrWithMessage("1", e)
  245 + }
  246 + }
  247 + err = utils.ExecuteSQLWithOrmer(o, dataSql2, nowTime, relationLike)
  248 + if err != nil {
  249 + o.Rollback()
  250 + e := fmt.Errorf("EXECUTE SQL err:%s", err)
  251 + log.Error(e.Error())
  252 + return protocol.NewErrWithMessage("1", e)
  253 + }
  254 + o.Commit()
172 return nil 255 return nil
173 } 256 }
174 257
175 -func DepartmentListAll() (protocol.ResponseDepartmentList, error) { 258 +func DepartmentListAll(companyId int64) (protocol.ResponseDepartmentList, error) {
  259 +
176 r := protocol.ResponseDepartmentList{} 260 r := protocol.ResponseDepartmentList{}
177 return r, nil 261 return r, nil
178 } 262 }
  1 +package company
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/common/log"
  6 + "oppmg/models"
  7 + "oppmg/protocol"
  8 + "time"
  9 +
  10 + "github.com/astaxie/beego/orm"
  11 +)
  12 +
  13 +//PositionAdd 添加职位
  14 +func PositionAdd(param protocol.RequestDepartmentAdd) error {
  15 + var (
  16 + parentPosition *models.Position
  17 + err error
  18 + )
  19 + if param.ParentID > 0 {
  20 + parentPosition, err = models.GetPositionById(param.ParentID)
  21 + if err != nil {
  22 + e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParentID, err)
  23 + log.Error(e.Error())
  24 + return protocol.NewErrWithMessage("1", e)
  25 + }
  26 + if parentPosition.CompanyId != param.CompanyID {
  27 + e := fmt.Errorf("parentDepart.CompanyId != param.CompanyID")
  28 + log.Error(e.Error())
  29 + return protocol.NewErrWithMessage("1", e)
  30 + }
  31 + }
  32 + positionAdd := &models.Position{
  33 + CompanyId: param.CompanyID,
  34 + Name: param.Name,
  35 + CreateAt: time.Now(),
  36 + UpdateAt: time.Now(),
  37 + ParentId: param.ParentID,
  38 + }
  39 +
  40 + o := orm.NewOrm()
  41 + o.Begin()
  42 + _, err = models.AddPosition(positionAdd, o)
  43 + if err != nil {
  44 + o.Rollback()
  45 + e := fmt.Errorf("AddPosition err:%s", err)
  46 + log.Error(e.Error())
  47 + return protocol.NewErrWithMessage("1", e)
  48 + }
  49 + err = positionAdd.SetRelation(parentPosition)
  50 + if err != nil {
  51 + o.Rollback()
  52 + e := fmt.Errorf("SetRelation err:%s", err)
  53 + log.Error(e.Error())
  54 + return protocol.NewErrWithMessage("1", e)
  55 + }
  56 + err = models.UpdatePositionById(positionAdd, []string{"Relation"}, o)
  57 + if err != nil {
  58 + o.Rollback()
  59 + e := fmt.Errorf("UpdatePositionById err:%s", err)
  60 + log.Error(e.Error())
  61 + return protocol.NewErrWithMessage("1", e)
  62 + }
  63 + o.Commit()
  64 + return nil
  65 +
  66 +}
@@ -128,6 +128,10 @@ func RoleGetByPage(param protocol.RequestRoleList) (*protocol.ResponseRoleList, @@ -128,6 +128,10 @@ func RoleGetByPage(param protocol.RequestRoleList) (*protocol.ResponseRoleList,
128 return r, nil 128 return r, nil
129 } 129 }
130 130
  131 +func GetRoleGroup() error {
  132 +
  133 +}
  134 +
131 func RoleHasPermission() error { 135 func RoleHasPermission() error {
132 return nil 136 return nil
133 } 137 }
@@ -4,59 +4,65 @@ import ( @@ -4,59 +4,65 @@ import (
4 "fmt" 4 "fmt"
5 "oppmg/common/log" 5 "oppmg/common/log"
6 "oppmg/protocol" 6 "oppmg/protocol"
  7 + "strings"
7 8
8 "github.com/astaxie/beego/orm" 9 "github.com/astaxie/beego/orm"
9 ) 10 )
10 11
11 //PrintLogSql 打印sql语句 12 //PrintLogSql 打印sql语句
12 func PrintLogSql(sql string, param ...interface{}) { 13 func PrintLogSql(sql string, param ...interface{}) {
13 - format := `SQL EXCUTE:[%s]-%s`  
14 - log.Debug(format, sql, fmt.Sprint(param...)) 14 + format := `SQL EXCEUTE:[%s]-%s`
  15 + parmformat := `[%v]`
  16 + var p strings.Builder
  17 + for i := range param {
  18 + p.WriteString(fmt.Sprintf(parmformat, param[i]))
  19 + }
  20 + log.Debug(format, sql, p.String())
15 } 21 }
16 22
17 -//ExcuteQueryOne 执行原生sql查询单条记录;结果用结构体接收  
18 -func ExcuteQueryOne(result interface{}, sqlstr string, param ...interface{}) error { 23 +//ExecuteQueryOne 执行原生sql查询单条记录;结果用结构体接收
  24 +func ExecuteQueryOne(result interface{}, sqlstr string, param ...interface{}) error {
19 PrintLogSql(sqlstr, param...) 25 PrintLogSql(sqlstr, param...)
20 var err error 26 var err error
21 o := orm.NewOrm() 27 o := orm.NewOrm()
22 - err = ExcuteQueryOneWithOrmer(o, result, sqlstr, param) 28 + err = ExecuteQueryOneWithOrmer(o, result, sqlstr, param)
23 return err 29 return err
24 } 30 }
25 31
26 -//ExcuteQueryOneWithOrmer 执行原生sql查询单条  
27 -func ExcuteQueryOneWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error { 32 +//ExecuteQueryOneWithOrmer 执行原生sql查询单条
  33 +func ExecuteQueryOneWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
28 PrintLogSql(sqlstr, param...) 34 PrintLogSql(sqlstr, param...)
29 var err error 35 var err error
30 err = o.Raw(sqlstr, param).QueryRow(result) 36 err = o.Raw(sqlstr, param).QueryRow(result)
31 if err != nil { 37 if err != nil {
32 - return fmt.Errorf("SQL EXCUTE err:%s", err) 38 + return fmt.Errorf("SQL Execute err:%s", err)
33 } 39 }
34 return nil 40 return nil
35 } 41 }
36 42
37 -//ExcuteQuerySql 执行原生sql查询多条记录  
38 -func ExcuteQueryAll(result interface{}, sqlstr string, param ...interface{}) error { 43 +//ExecuteQuerySql 执行原生sql查询多条记录
  44 +func ExecuteQueryAll(result interface{}, sqlstr string, param ...interface{}) error {
39 PrintLogSql(sqlstr, param...) 45 PrintLogSql(sqlstr, param...)
40 var err error 46 var err error
41 o := orm.NewOrm() 47 o := orm.NewOrm()
42 - err = ExcuteQueryOneWithOrmer(o, result, sqlstr, param) 48 + err = ExecuteQueryOneWithOrmer(o, result, sqlstr, param)
43 return err 49 return err
44 } 50 }
45 51
46 -//ExcuteQueryOneWithOrmer 执行原生sql查询多条记录  
47 -func ExcuteQueryAllWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error { 52 +//ExecuteQueryOneWithOrmer 执行原生sql查询多条记录
  53 +func ExecuteQueryAllWithOrmer(o orm.Ormer, result interface{}, sqlstr string, param ...interface{}) error {
48 PrintLogSql(sqlstr, param...) 54 PrintLogSql(sqlstr, param...)
49 var ( 55 var (
50 err error 56 err error
51 ) 57 )
52 _, err = o.Raw(sqlstr, param).QueryRows(result) 58 _, err = o.Raw(sqlstr, param).QueryRows(result)
53 if err != nil { 59 if err != nil {
54 - return fmt.Errorf("SQL EXCUTE err:%s", err) 60 + return fmt.Errorf("SQL Execute err:%s", err)
55 } 61 }
56 return nil 62 return nil
57 } 63 }
58 64
59 -func ExcuteSQLWithOrmer(o orm.Ormer, sqlstr string, param ...interface{}) error { 65 +func ExecuteSQLWithOrmer(o orm.Ormer, sqlstr string, param ...interface{}) error {
60 PrintLogSql(sqlstr, param...) 66 PrintLogSql(sqlstr, param...)
61 var ( 67 var (
62 err error 68 err error
@@ -105,7 +111,7 @@ func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponseP @@ -105,7 +111,7 @@ func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponseP
105 total int 111 total int
106 ) 112 )
107 o := orm.NewOrm() 113 o := orm.NewOrm()
108 - err = ExcuteQueryOneWithOrmer(o, &total, q.CountSql, q.Param...) 114 + err = ExecuteQueryOneWithOrmer(o, &total, q.CountSql, q.Param...)
109 if err != nil { 115 if err != nil {
110 return 116 return
111 } 117 }
@@ -113,7 +119,7 @@ func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponseP @@ -113,7 +119,7 @@ func (q *QueryDataByPage) Query(result interface{}) (pageinfo protocol.ResponseP
113 return protocol.ResponsePageInfo{CurrentPage: q.offset, TotalPage: total}, nil 119 return protocol.ResponsePageInfo{CurrentPage: q.offset, TotalPage: total}, nil
114 } 120 }
115 q.DataSql = fmt.Sprintf("%s limit %d,%d", q.DataSql, pagebegin, q.num) 121 q.DataSql = fmt.Sprintf("%s limit %d,%d", q.DataSql, pagebegin, q.num)
116 - err = ExcuteQueryAllWithOrmer(o, result, q.DataSql, q.Param...) 122 + err = ExecuteQueryAllWithOrmer(o, result, q.DataSql, q.Param...)
117 if err != nil { 123 if err != nil {
118 return 124 return
119 } 125 }