作者 唐旭辉

日常提交存储

package controllers
import (
"encoding/json"
"oppmg/common/log"
"oppmg/protocol"
servecommon "oppmg/services/common"
)
//公共接口
type CommonController struct {
BaseController
}
func (c *CommonController) URLMapping() {
}
//SelectorDepartment 下拉列表 -部门
//@router /department [post]
func (c *CommonController) SelectorDepartment() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
companyid := c.GetCompanyId()
departs := servecommon.SelectorDepartment(companyid)
msg = protocol.NewReturnResponse(departs, nil)
return
}
//SelectorRole 下拉列表 -角色
//@router /role [post]
func (c *CommonController) SelectorRole() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
For string `json:"for"`
}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
companyid := c.GetCompanyId()
userid := c.GetUserId()
if companyid <= 0 || userid <= 0 {
msg = protocol.BadRequestParam("1")
return
}
var roles []protocol.RoleBase
switch param.For {
case "user":
list := servecommon.SelectorRoleAll(companyid)
roles = servecommon.FilterRoleAll(userid, companyid, list)
case "role":
list := servecommon.SelectorRoleAll(companyid)
roles = servecommon.FilterRoleGroup(userid, companyid, list)
case "all":
roles = servecommon.SelectorRoleAll(companyid)
default:
roles = servecommon.SelectorRoleAll(companyid)
}
msg = protocol.NewReturnResponse(roles, nil)
return
}
//SelectorPosition 下拉列表 -职位
//@router /position [post]
func (c *CommonController) SelectorPosition() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
companyid := c.GetCompanyId()
departs := servecommon.SelectorPosition(companyid)
msg = protocol.NewReturnResponse(departs, nil)
return
}
... ...
... ... @@ -5,7 +5,10 @@ import (
"oppmg/common/log"
"oppmg/protocol"
servecompany "oppmg/services/company"
"oppmg/storage/redisdata"
"oppmg/utils"
"strconv"
"strings"
)
type CompanyController struct {
... ... @@ -226,13 +229,35 @@ func (c *CompanyController) UserAdd() {
msg = protocol.BadRequestParam("1")
return
}
name := []rune(strings.TrimSpace(param.Name))
if len(name) == 0 {
msg = protocol.BadRequestParam("10035")
return
}
if len(name) > 10 {
msg = protocol.BadRequestParam("10034")
return
}
ok := utils.PhoneMatch.MatchString(param.Phone)
if !ok {
msg = protocol.BadRequestParam("10036")
return
}
if len(param.Departments) == 0 {
msg = protocol.BadRequestParam("10037")
return
}
if len(param.Roles) == 0 {
msg = protocol.BadRequestParam("10038")
return
}
param.CompanyId = c.GetCompanyId()
err := servecompany.UserAdd(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
//UserAdd 添加用户
//UserEdit 编辑用户
//@Router /user/edit [post]
func (c *CompanyController) UserEdit() {
var msg *protocol.ResponseMessage
... ... @@ -245,8 +270,95 @@ func (c *CompanyController) UserEdit() {
msg = protocol.BadRequestParam("1")
return
}
name := []rune(strings.TrimSpace(param.Name))
if len(name) == 0 {
msg = protocol.BadRequestParam("10035")
return
}
if len(name) > 10 {
msg = protocol.BadRequestParam("10034")
return
}
if len(param.Departments) == 0 {
msg = protocol.BadRequestParam("10037")
return
}
if len(param.Roles) == 0 {
msg = protocol.BadRequestParam("10038")
return
}
param.CompanyId = c.GetCompanyId()
err := servecompany.UserEdit(param)
msg = protocol.NewReturnResponse(nil, err)
return
}
//UserDelete 删除用户
//@Router /user/delete [post]
func (c *CompanyController) UserDelete() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Userid int64 `json:"user_id"`
}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
companyId := c.GetCompanyId()
err := servecompany.UserDelete(param.Userid, companyId)
if err == nil {
e := redisdata.DeleteLoginToken(param.Userid)
if e != nil {
log.Error(e.Error())
}
}
msg = protocol.NewReturnResponse(nil, err)
return
}
//UserEdit 禁用、启用用户 TODO
//@Router /user/enable [post]
func (c *CompanyController) UserEnable() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestUserEdit
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
param.CompanyId = c.GetCompanyId()
err := servecompany.UserEdit(param)
redisdata.DeleteLoginToken(0)
msg = protocol.NewReturnResponse(nil, err)
return
}
//UserEdit用户列表
//@Router /user/list [post]
func (c *CompanyController) UserList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestUserList
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
param.Companyid = c.GetCompanyId()
result, err := servecompany.UserList(param)
msg = protocol.NewPageDataResponse(result, err)
return
}
... ...
... ... @@ -10,7 +10,7 @@ import (
type Company struct {
Id int64 `orm:"column(id);auto"`
Name string `orm:"column(name);size(40)"`
Admin_id int64 `orm:"column(admin_id)"`
AdminId int64 `orm:"column(admin_id)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);auto_now"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)"`
... ...
... ... @@ -62,7 +62,9 @@ func AddUser(m *User, om ...orm.Ormer) (id int64, err error) {
} else {
o = orm.NewOrm()
}
m.DeleteAt = time.Unix(0, 0)
m.EnableStatus = USER_ENABLE_YES
m.CreateAt = time.Now()
id, err = o.Insert(m)
return
}
... ... @@ -80,15 +82,16 @@ func GetUserById(id int64) (v *User, err error) {
// UpdateUser updates User by Id and returns error if
// the record to be updated doesn't exist
func UpdateUserById(m *User) (err error) {
o := orm.NewOrm()
v := User{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 {
fmt.Println("Number of records updated in database:", num)
}
func UpdateUserById(m *User, col []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) == 0 {
o = orm.NewOrm()
} else {
o = om[0]
}
var num int64
if num, err = o.Update(m, col...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
return
}
... ...
... ... @@ -92,3 +92,23 @@ func GetUserCompanyBy(userid int64, companyId int64) (*UserCompany, error) {
}
return data[0], nil
}
func ExistUserCompany(userid int64, companyId int64) bool {
o := orm.NewOrm()
ok := o.QueryTable(&UserCompany{}).
Filter("UserId", userid).
Filter("CompanyId", companyId).
Exist()
return ok
}
func EnableUserCompany(userid int64, companyid int64) error {
o := orm.NewOrm()
_, err := o.QueryTable(&UserCompany{}).
Filter("UserId", userid).
Filter("CompanyId", companyid).Update(orm.Params{
"enable": USERCOMPANY_ENABLE_YES,
"delete_at": 0,
})
return err
}
... ...
... ... @@ -85,18 +85,16 @@ func UpdateUserDepartmentById(m *UserDepartment) (err error) {
}
return
}
// DeleteUserDepartment deletes UserDepartment by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUserDepartment(id int64) (err error) {
func GetUserDepartment(userid, companyid int64) ([]*UserDepartment, error) {
o := orm.NewOrm()
v := UserDepartment{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&UserDepartment{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
var (
err error
result []*UserDepartment
)
_, err = o.QueryTable(&UserDepartment{}).
Filter("user_id", userid).
Filter("company_id", companyid).
Filter("enable_status", 1).
All(&result)
return result, err
}
... ...
... ... @@ -60,43 +60,16 @@ func AddUserPosition(m *UserPosition) (id int64, err error) {
return
}
// GetUserPositionById retrieves UserPosition by Id. Returns error if
// Id doesn't exist
func GetUserPositionById(id int64) (v *UserPosition, err error) {
func GetUserPosition(userid, companyid int64) ([]*UserPosition, error) {
o := orm.NewOrm()
v = &UserPosition{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateUserPosition updates UserPosition by Id and returns error if
// the record to be updated doesn't exist
func UpdateUserPositionById(m *UserPosition) (err error) {
o := orm.NewOrm()
v := UserPosition{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 {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteUserPosition deletes UserPosition by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUserPosition(id int64) (err error) {
o := orm.NewOrm()
v := UserPosition{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&UserPosition{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
var (
err error
result []*UserPosition
)
_, err = o.QueryTable(&UserPosition{}).
Filter("user_id", userid).
Filter("company_id", companyid).
Filter("enable_status", 1).
All(&result)
return result, err
}
... ...
... ... @@ -58,43 +58,16 @@ func AddUserRole(m *UserRole) (id int64, err error) {
return
}
// GetUserRoleById retrieves UserRole by Id. Returns error if
// Id doesn't exist
func GetUserRoleById(id int) (v *UserRole, err error) {
func GetUserRole(userid, companyid int64) ([]*UserRole, error) {
o := orm.NewOrm()
v = &UserRole{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateUserRole updates UserRole by Id and returns error if
// the record to be updated doesn't exist
func UpdateUserRoleById(m *UserRole) (err error) {
o := orm.NewOrm()
v := UserRole{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 {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteUserRole deletes UserRole by Id and returns error if
// the record to be deleted doesn't exist
func DeleteUserRole(id int) (err error) {
o := orm.NewOrm()
v := UserRole{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&UserRole{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
var (
err error
result []*UserRole
)
_, err = o.QueryTable(&UserRole{}).
Filter("user_id", userid).
Filter("company_id", companyid).
Filter("enable_status", 1).
All(&result)
return result, err
}
... ...
... ... @@ -12,3 +12,26 @@ type ResponsePageInfo struct {
CurrentPage int `json:"pageNumber"`
// ListData interface{} `json:"list"`
}
// DepartmentBase下拉选择列表-部门
type DepartmentBase struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
ParentId int64 `json:"parent_id" orm:"column(parent_id)"`
}
//RoleBase 下拉选择列表-角色
type RoleBase struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
IsDefault int8 `json:"is_default" orm:"column(is_default)"`
ParentId int64 `json:"parent_id" orm:"column(pid)"`
Types int8 `json:"types" orm:"column(types)"`
}
//PositionBase 下拉选择列表-职位
type PositionBase struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
ParentId int64 `json:"parent_id" orm:"column(parent_id)"`
}
... ...
... ... @@ -89,7 +89,8 @@ type RequestUserEdit struct {
//RequestUserList 获取用户列表
type RequestUserList struct {
RequestPageInfo
NickName string `json:"nick_name"`
NickName string `json:"nick_name"`
Companyid int64 `json:"company_id"`
}
//ResponseUserList 响应的用户列表
... ... @@ -99,10 +100,10 @@ type ResponseUserList struct {
}
type UserListItem struct {
Id int64 `json:"id"`
NickName string `json:"nick_name"`
Position string `json:"position"`
Role string `json:"role"`
Department string `json:"department"`
Status int8 `json:"status"`
UserId int64 `json:"user_id" orm:"column(user_id)"`
NickName string `json:"nick_name" orm:"column(nick_name)"`
Positions string `json:"positions" orm:"-"`
Roles string `json:"roles" orm:"-"`
Departments string `json:"departments" orm:"-"`
Enable int8 `json:"enable" orm:"column(enable)"`
}
... ...
... ... @@ -21,6 +21,11 @@ var errmessge ErrorMap = map[string]string{
"10031": "无效角色",
"10032": "无效部门",
"10033": "无效职位",
"10034": "名字限制10个字符以内",
"10035": "名字是必填项",
"10036": "请输入正确的手机格式",
"10037": "用户的部门必填",
"10038": "用户的角色必填",
}
//错误码转换 ,兼容需要
... ...
... ... @@ -12,7 +12,7 @@ func init() {
nsV1 := beego.NewNamespace("v1",
beego.NSBefore(middleware.AllowOption),
beego.NSBefore(middleware.LogRequestData),
beego.NSBefore(middleware.AuthToken),
//beego.NSBefore(middleware.AuthToken),
beego.NSNamespace("/department",
beego.NSRouter("/list", &controllers.CompanyController{}, "get:DepartmentList"),
beego.NSRouter("/add", &controllers.CompanyController{}, "post:DepartmentAdd"),
... ... @@ -35,10 +35,10 @@ func init() {
beego.NSRouter("/role", &controllers.RbacController{}, "get:RoleList"),
),
beego.NSNamespace("/user/",
// beego.NSRouter("/list", &controllers.CompanyController{}, "post:UserList"),
beego.NSRouter("/list", &controllers.CompanyController{}, "post:UserList"),
beego.NSRouter("/add", &controllers.CompanyController{}, "post:UserAdd"),
beego.NSRouter("/edit", &controllers.CompanyController{}, "post:UserEdit"),
// beego.NSRouter("/delete", &controllers.CompanyController{}, "post:PositionDelete"),
beego.NSRouter("/delete", &controllers.CompanyController{}, "post:UserDelete"),
),
beego.NSNamespace("/auth",
beego.NSRouter("/change_company", &controllers.AuthController{}, "post:ChangeCompany"),
... ... @@ -50,6 +50,11 @@ func init() {
beego.NSRouter("/:id([0-9]+)", &controllers.BulletinController{}, "get:GetBulletin"),
beego.NSRouter("/update", &controllers.BulletinController{}, "post:UpdateBulletin"),
),
beego.NSNamespace("common",
beego.NSRouter("/department", &controllers.CommonController{}, "post:SelectorDepartment"),
beego.NSRouter("/role", &controllers.CommonController{}, "post:SelectorRole"),
beego.NSRouter("/position", &controllers.CommonController{}, "post:SelectorPosition"),
),
)
nsAuth := beego.NewNamespace("/auth",
... ...
package common
import (
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
)
func SelectorDepartment(companyid int64) []protocol.DepartmentBase {
const dataSql string = `SELECT id,name,parent_id FROM department WHERE company_id = ? AND delete_at = 0`
var (
err error
departs []protocol.DepartmentBase
)
err = utils.ExecuteQueryAll(&departs, dataSql, companyid)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
}
return departs
}
func SelectorRoleAll(companyid int64) []protocol.RoleBase {
const datasql string = `SELECT id,pid,name,types,is_default FROM role WHERE company_id = ? AND delete_at =0`
var (
err error
roles []protocol.RoleBase
)
err = utils.ExecuteQueryAll(&roles, datasql, companyid)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
}
return roles
}
func FilterRoleAll(adminid int64, companyid int64, list []protocol.RoleBase) []protocol.RoleBase {
var (
newlist []protocol.RoleBase
admingoroupId int64
)
companyInfo, err := models.GetCompanyById(companyid)
if err != nil {
e := fmt.Errorf("GetCompanyById(%d) err:%s", companyid, err)
log.Error(e.Error())
return newlist
}
if companyInfo.AdminId == adminid {
return list
}
for _, v := range list {
if v.IsDefault == models.ROLE_DEFAULR && v.Types == models.ROLETYPES_GROUP {
admingoroupId = v.Id
}
}
for k, v := range list {
if v.Id == admingoroupId || v.ParentId == admingoroupId {
continue
}
newlist = append(newlist, list[k])
}
return newlist
}
func FilterRoleGroup(adminid int64, companyid int64, list []protocol.RoleBase) []protocol.RoleBase {
var (
newlist []protocol.RoleBase
)
companyInfo, err := models.GetCompanyById(companyid)
if err != nil {
e := fmt.Errorf("GetCompanyById(%d) err:%s", companyid, err)
log.Error(e.Error())
return newlist
}
if companyInfo.AdminId != adminid {
for k, v := range list {
if v.Types == models.ROLETYPES_GROUP && v.IsDefault == models.ROLE_DEFAULR_NOT {
newlist = append(newlist, list[k])
}
}
return newlist
}
for k, v := range list {
if v.Types == models.ROLETYPES_GROUP {
newlist = append(newlist, list[k])
}
}
return newlist
}
func SelectorPosition(companyid int64) []protocol.PositionBase {
const datasql string = `SELECT id,parent_id,name FROM position WHERE company_id =? AND delete_at =0`
var (
err error
positions []protocol.PositionBase
)
err = utils.ExecuteQueryAll(&positions, datasql, companyid)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
}
return positions
}
... ...
... ... @@ -137,32 +137,41 @@ func validCompanyPosition(companyid int64, positionid []int64) error {
//registUser 注册用户
func registUser(userIn *models.User, companyid int64, o orm.Ormer) error {
var (
err error
// usrData *models.User
err error
usrData *models.User
)
_, err = models.GetUserByPhone(userIn.Phone)
if err == nil {
return nil
}
usrData, err = models.GetUserByPhone(userIn.Phone)
if err != nil && err != orm.ErrNoRows {
return err
}
if err == orm.ErrNoRows {
//用户不存在 添加用户
_, err := models.AddUser(userIn, o)
if err != nil {
return err
}
}
if err == nil {
// 用户存在,更新用户
usrData.NickName = userIn.NickName
err = models.UpdateUserById(usrData, []string{"NickName"}, o)
if err != nil {
return err
}
}
musercompany := &models.UserCompany{
CompanyId: companyid,
UserId: userIn.Id,
}
_, err = models.AddUserCompany(musercompany, o)
if err != nil {
return err
ok := models.ExistUserCompany(usrData.Id, companyid)
if !ok {
_, err = models.AddUserCompany(musercompany, o)
if err != nil {
return err
}
}
//更新
return nil
err = models.EnableUserCompany(usrData.Id, companyid)
return err
}
func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Ormer) error {
... ... @@ -338,10 +347,77 @@ func UserEdit(param protocol.RequestUserEdit) error {
return nil
}
func UserDelete(param protocol.RequestUserAdd) error {
func UserDelete(userid, companyid int64) error {
ok := models.ExistUserCompany(userid, companyid)
if !ok {
e := fmt.Errorf("ExistUserCompany(userid, companyid) [%d,%d] ==false ", userid, companyid)
log.Error(e.Error())
return protocol.NewErrWithMessage("1")
}
o := orm.NewOrm()
_, err := o.QueryTable(&models.UserCompany{}).
Filter("user_id", userid).
Filter("company_id").
Update(orm.Params{
"delete_at": time.Now().String(),
})
if err != nil {
e := fmt.Errorf("UserDelete err:%s", err)
log.Error(e.Error())
return protocol.NewErrWithMessage("1")
}
return nil
}
func UserList() error {
return nil
func UserList(param protocol.RequestUserList) (protocol.ResponseUserList, error) {
datasql := `SELECT a.company_id,a.user_id,a.enable, b.phone,b.nick_name
FROM user_company AS a
LEFT JOIN user AS b ON a.user_id = b.id
WHERE a.company_id=? AND a.delete_at = 0 `
countSql := `SELECT count(*)
FROM user_company AS a
LEFT JOIN user AS b ON a.user_id = b.id
WHERE a.company_id=? AND a.delete_at = 0 `
var (
whereString string
cond []interface{}
)
cond = append(cond, param.Companyid)
if len(param.NickName) > 0 {
whereString += ` AND b.nick_name LIKE ? `
likeCond := "%" + param.NickName + "%"
cond = append(cond, likeCond)
}
var (
result []protocol.UserListItem
pageInfo protocol.ResponsePageInfo
err error
responseData protocol.ResponseUserList
)
p := utils.NewQueryDataByPage(countSql+whereString, datasql+whereString)
p.AddParam(cond...)
p.LimitPage(param.PageIndex, param.PageSize)
pageInfo, err = p.Query(&result)
if err != nil {
e := fmt.Errorf("page data err:%s", err)
log.Error(e.Error())
return responseData, protocol.NewErrWithMessage("0")
}
// for k, v := range result {
// positions, _ := models.GetUserPosition(v.UserId, param.Companyid)
// departments, _ := models.GetUserDepartment(v.UserId, param.Companyid)
// roles, _ := models.GetUserRole(v.UserId, param.Companyid)
// }
responseData.ResponsePageInfo = pageInfo
responseData.List = result
return responseData, nil
}
func GetUserDepartment(user int64, companyid int64) {
}
func GetUserPosition(user int64, companyid int64) {
}
... ...
... ... @@ -64,4 +64,11 @@ func ExistLoginToken(userid int64) bool {
return false
}
func DeleteLoginToken(userid int64) error {
client := redis.GetRedis()
key := fmt.Sprintf("%s%s:%d", KEY_PREFIX, KEY_USER_TOKEN, userid)
err:=client.Del(key).Err()
return err
}
//消息发布订阅
... ...
package utils
import (
"regexp"
)
var (
PhoneMatch, _ = regexp.Compile(`^1[0-9]{10}$`)
EmailMatch, _ = regexp.Compile(`^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$`)
ChineseMatch, _ = regexp.Compile(`[\u4e00-\u9fa5]`)
)
... ...