作者 唐旭辉

部门修改

... ... @@ -2,11 +2,8 @@ package models
import (
"encoding/json"
"errors"
"fmt"
"oppmg/common/log"
"reflect"
"strings"
"time"
"github.com/astaxie/beego/orm"
... ... @@ -42,6 +39,11 @@ func (t *Department) GetManagesIds() []int64 {
return r
}
func (t *Department) ParseManagesIds(v []int64) string {
bt, _ := json.Marshal(v)
return string(bt)
}
// AddDepartment insert a new Department into database and returns
// last inserted Id on success.
func AddDepartment(m *Department) (id int64, err error) {
... ... @@ -61,93 +63,20 @@ func GetDepartmentById(id int64) (v *Department, err error) {
return nil, err
}
// GetAllDepartment retrieves all Department matches certain condition. Returns empty list if
// no records exist
func GetAllDepartment(query map[string]string, fields []string, sortby []string, order []string,
offset int64, limit int64) (ml []interface{}, err error) {
o := orm.NewOrm()
qs := o.QueryTable(new(Department))
// query k=v
for k, v := range query {
// rewrite dot-notation to Object__Attribute
k = strings.Replace(k, ".", "__", -1)
if strings.Contains(k, "isnull") {
qs = qs.Filter(k, (v == "true" || v == "1"))
} else {
qs = qs.Filter(k, v)
}
}
// order by:
var sortFields []string
if len(sortby) != 0 {
if len(sortby) == len(order) {
// 1) for each sort field, there is an associated order
for i, v := range sortby {
orderby := ""
if order[i] == "desc" {
orderby = "-" + v
} else if order[i] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
qs = qs.OrderBy(sortFields...)
} else if len(sortby) != len(order) && len(order) == 1 {
// 2) there is exactly one order, all the sorted fields will be sorted by this order
for _, v := range sortby {
orderby := ""
if order[0] == "desc" {
orderby = "-" + v
} else if order[0] == "asc" {
orderby = v
} else {
return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
}
sortFields = append(sortFields, orderby)
}
} else if len(sortby) != len(order) && len(order) != 1 {
return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
}
} else {
if len(order) != 0 {
return nil, errors.New("Error: unused 'order' fields")
}
}
var l []Department
qs = qs.OrderBy(sortFields...)
if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
if len(fields) == 0 {
for _, v := range l {
ml = append(ml, v)
}
} else {
// trim unused fields
for _, v := range l {
m := make(map[string]interface{})
val := reflect.ValueOf(v)
for _, fname := range fields {
m[fname] = val.FieldByName(fname).Interface()
}
ml = append(ml, m)
}
}
return ml, nil
}
return nil, err
}
// UpdateDepartment updates Department by Id and returns error if
// the record to be updated doesn't exist
func UpdateDepartmentById(m *Department) (err error) {
o := orm.NewOrm()
func UpdateDepartmentById(m *Department, col []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
v := Department{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
if num, err = o.Update(m, col...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
... ... @@ -168,3 +97,25 @@ func DeleteDepartment(id int64) (err error) {
}
return
}
func GetDepartmentSubsetByRelation(relation string, om ...orm.Ormer) ([]Department, error) {
dataSql := `SELECT company_id,parent_id,name,create_at,relation,member,managers
FROM department
WHERE relation LIKE ? AND delete_at = 0`
var (
o orm.Ormer
result []Department
err error
)
like := relation + "%"
if len(om) == 0 {
o = orm.NewOrm()
} else {
o = om[0]
}
_, err = o.Raw(dataSql, like).QueryRows(&result)
if err != nil {
return nil, err
}
return result, nil
}
... ...
... ... @@ -10,6 +10,8 @@ import (
type Role struct {
Id int `orm:"column(id);auto"`
Name string `orm:"column(name);size(30)"`
Pid int `orm:"column(pid)"`
Types int8 `orm:"column(types)"`
CompanyId int `orm:"column(company_id)"`
Descript string `orm:"column(descript)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)"`
... ...
... ... @@ -6,6 +6,8 @@ import (
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
... ... @@ -17,57 +19,105 @@ func DepartmentAdd(param protocol.RequestDepartmentAdd) (protocol.ResponseDepart
}
func DepartmentEdit(param protocol.RequestDepartmentEdit) (protocol.ResponseDepartmentInfo, error) {
func DepartmentEdit(param protocol.RequestDepartmentEdit) error {
var (
depart *models.Department
err error
result protocol.ResponseDepartmentInfo
departUpdate *models.Department
err error
)
result = protocol.ResponseDepartmentInfo{
ID: param.ID,
Name: param.Name,
ParantID: param.ParantID,
}
depart, err = models.GetDepartmentById(param.ID)
departUpdate, err = models.GetDepartmentById(param.ID)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ID, err)
log.Error(e.Error())
return result, protocol.NewErrWithMessage("1", e)
return protocol.NewErrWithMessage("1", e)
}
if depart.CompanyId != param.CompanyID {
e := fmt.Errorf("depart.CompanyId(%d) !=param.CompanyID(%d)", depart.CompanyId, param.CompanyID)
if departUpdate.CompanyId != param.CompanyID {
e := fmt.Errorf("depart.CompanyId(%d) !=param.CompanyID(%d)", departUpdate.CompanyId, param.CompanyID)
log.Error(e.Error())
return result, protocol.NewErrWithMessage("1", e)
return protocol.NewErrWithMessage("1", e)
}
//确认部门主管变更情况
var (
oldmanage []int64
)
oldmanage = depart.GetManagesIds()
oldmanage = departUpdate.GetManagesIds()
diffmanage := utils.ArrayInt64Diff(param.Managers, oldmanage)
for i := range diffmanage {
_, err = models.GetUserCompanyBy(diffmanage[i], param.CompanyID)
if err != nil {
e := fmt.Errorf("GetUserCompanyBy(%d,%d) err:%s", diffmanage[i], param.CompanyID, err)
log.Error(e.Error())
return result, protocol.NewErrWithMessage("1", e)
return protocol.NewErrWithMessage("1", e)
}
}
//处理部门上级发生变化的情况
if depart.ParentId != param.ParantID {
//oldRelation := strings.Split(depart.Relation, "")
var (
newparent *models.Department
)
if departUpdate.ParentId != param.ParantID {
newparent, err = models.GetDepartmentById(param.ParantID)
if err != nil {
e := fmt.Errorf("GetDepartmentById(%d) err:%s", param.ParantID, err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
}
//更新部门数据
departmentInfoUpdate(depart, &param)
return result, nil
departUpdate.Manages = departUpdate.ParseManagesIds(param.Managers)
departUpdate.Name = param.Name
departUpdate.UpdateAt = time.Now()
err = models.UpdateDepartmentById(departUpdate, []string{"Manages", "Name", "UpdateAt"})
if err != nil {
e := fmt.Errorf("UpdateDepartmentById err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
//更新部门关系数据
err = departmentRelationUpdate(departUpdate, newparent)
if err != nil {
e := fmt.Errorf(" departmentRelationUpdate err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
return nil
}
//DepartmentParentChange 处理部门上级发生变化的情况
func departmentInfoUpdate(old *models.Department, new *protocol.RequestDepartmentEdit) error {
func departmentRelationUpdate(old *models.Department, newparent *models.Department) error {
if newparent == nil {
return nil
}
const (
//获取某个部门的下级部门 select ... for update
dataSql0 string = `SELECT id,relation FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE`
dataSql2 string = `update department set relation=? where id=?`
)
var (
departSubset []models.Department //子级部门
err error
oldrelation string = old.Relation
relationLike string = oldrelation + "%"
newRelation string = fmt.Sprintf("%s/%d", newparent.Relation, old.Id)
)
o := orm.NewOrm()
o.Begin()
err = utils.ExcuteQueryAllWithOrmer(o, &departSubset, dataSql0, relationLike)
if err != nil {
o.Rollback()
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
for i := range departSubset {
s := strings.TrimPrefix(departSubset[i].Relation, oldrelation)
departSubset[i].Relation = strings.TrimSpace(fmt.Sprintf("%s%s", newRelation, s))
err := utils.ExcuteSQLWithOrmer(o, dataSql2, departSubset[i].Relation, departSubset[i].Id)
if err != nil {
o.Rollback()
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1", e)
}
}
o.Commit()
return nil
}
... ...
... ... @@ -56,6 +56,20 @@ func ExcuteQueryAllWithOrmer(o orm.Ormer, result interface{}, sqlstr string, par
return nil
}
func ExcuteSQLWithOrmer(o orm.Ormer, sqlstr string, param ...interface{}) error {
PrintLogSql(sqlstr, param...)
var (
err error
)
r, err := o.Raw(sqlstr, param...).Exec()
if err != nil {
return err
}
num, _ := r.RowsAffected()
log.Debug("RowsAffected:%d", num)
return nil
}
type QueryDataByPage struct {
CountSql string
DataSql string
... ...