作者 tangxvhui

Merge branch 'test' into dev

要显示太多修改。

为保证性能只显示 48 of 48+ 个文件。

#app的名称
appname = ability
#运行模式
runmode =${RUN_MODE||test}
runmode =${RUN_MODE||dev}
#是否自动渲染页面
autorender = false
#是否复制请求body
... ...
package controllers
import (
"encoding/json"
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
serveachievement "oppmg/services/achievement"
"github.com/astaxie/beego/orm"
)
type AchievementController struct {
BaseController
}
//AchievementList 成果列表
//@router /achievement/list
func (c AchievementController) AchievementList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
protocol.RequestPageInfo
Status int `json:"status"`
}
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()
rspdata := serveachievement.GetAchievementList(param.PageIndex, param.PageSize, companyid, param.Status)
msg = protocol.NewPageDataResponse(rspdata, nil)
return
}
//AddAchievement 添加成果列表
//@router /achievement/add
func (c AchievementController) AddAchievement() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestAddAchievement
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if len(param.ChanceData) == 0 {
log.Error("len(param.ChanceData) == 0 ")
msg = protocol.BadRequestParam("10109")
return
}
if param.ChanceTypeId == 0 {
log.Error(" param.ChanceTypeId == 0 ")
msg = protocol.BadRequestParam("10108")
return
}
if param.GraspScore < 0 || param.GraspScore > 100 {
log.Error(" param.GraspScore < 0 || param.GraspScore > 100 ")
msg = protocol.BadRequestParam("10121")
return
}
if param.UserGraspScore < 0 || param.UserGraspScore > 100 {
log.Error("param.UserGraspScore < 0 || param.UserGraspScore > 100")
msg = protocol.BadRequestParam("10122")
}
var providerScore float64
for _, v := range param.Provider {
providerScore += v.UserGraspScore
}
remainScore := param.GraspScore - param.UserGraspScore - providerScore
if remainScore < 0 {
log.Error("分配的总分不可大于把握分")
msg = protocol.BadRequestParam("10122")
return
}
companyid := c.GetCompanyId()
err := serveachievement.AddAchievement(&param, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//EditAchievement 编辑成果
//@router /achievement/edit
func (c AchievementController) EditAchievement() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestEditAchievement
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if len(param.ChanceData) == 0 {
log.Error("len(param.ChanceData) == 0 ")
msg = protocol.BadRequestParam("10109")
return
}
if param.ChanceTypeId == 0 {
log.Error(" param.ChanceTypeId == 0 ")
msg = protocol.BadRequestParam("10108")
return
}
if param.GraspScore < 0 || param.GraspScore > 100 {
log.Error(" param.GraspScore < 0 || param.GraspScore > 100 ")
msg = protocol.BadRequestParam("10121")
return
}
if param.UserGraspScore < 0 || param.UserGraspScore > 100 {
log.Error("param.UserGraspScore < 0 || param.UserGraspScore > 100")
msg = protocol.BadRequestParam("10122")
}
var providerScore float64
for _, v := range param.Provider {
providerScore += v.UserGraspScore
}
remainScore := param.GraspScore - param.UserGraspScore - providerScore
if remainScore < 0 {
log.Error("分配的总分不可大于把握分")
msg = protocol.BadRequestParam("10122")
return
}
companyid := c.GetCompanyId()
err := serveachievement.EditAchievement(&param, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//EditAchievement 成果详情
//@router /achievement/info
func (c AchievementController) AchievementInfo() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"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()
rspData := serveachievement.GetAchievementInfo(param.Id, companyid)
msg = protocol.NewReturnResponse(rspData, nil)
return
}
//EditAchievement 删除成果
//@router /achievement/delete
func (c AchievementController) DeleteAchievement() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"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()
var (
err error
achievementData *models.Achievement
)
achievementData, err = models.GetAchievementById(param.Id)
if err != nil {
log.Error("获取achievement数据失败:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if achievementData.CompanyId != companyid {
log.Error("achievement数据公司不匹配")
msg = protocol.BadRequestParam("1")
return
}
achievementData.Status = models.ACHIEVEMENT_STATUS_DEL
o := orm.NewOrm()
o.Begin()
err = models.UpdateAchievementById(achievementData, []string{"Status"})
if err != nil {
o.Rollback()
log.Error("更新achievement数据失败:%s", err)
}
err = models.IncreaseAchevementScore(companyid, -achievementData.GraspScoreRemain, o)
if err != nil {
o.Rollback()
log.Error("更新福利池失败数据失败:%s", err)
}
o.Commit()
msg = protocol.NewReturnResponse(nil, nil)
return
}
//EditAchievement 显示隐藏成果
//@router /achievement/forbid_allow
func (c AchievementController) ForbidAllowAchievement() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"id"`
Status int8 `json:"status"` //[1:显示][2:隐藏]
}
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
}
if param.Status != 1 && param.Status != 2 {
msg = protocol.BadRequestParam("1")
return
}
companyid := c.GetCompanyId()
var (
err error
achievementData *models.Achievement
)
achievementData, err = models.GetAchievementById(param.Id)
if err != nil {
log.Error("获取achievement数据失败:%s", err)
msg = protocol.BadRequestParam("1")
return
}
if achievementData.CompanyId != companyid {
log.Error("achievement数据公司不匹配")
msg = protocol.BadRequestParam("1")
return
}
achievementData.Status = param.Status
err = models.UpdateAchievementById(achievementData, []string{"Status"})
if err != nil {
log.Error("更新achievement数据失败:%s", err)
}
msg = protocol.NewReturnResponse(nil, nil)
return
}
//AchievementScoreRemain 获取福利池分数
//@router /achievement/remain/score
func (c AchievementController) AchievementScoreRemain() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
companyid := c.GetCompanyId()
scoreData, err := models.GetAchevementScoreByCompanyId(companyid)
rspData := map[string]string{
"score": "0",
}
if err == nil {
rspData["score"] = fmt.Sprintf("%.1f", scoreData.GraspScoreRemain)
}
msg = protocol.NewReturnResponse(rspData, nil)
return
}
... ...
... ... @@ -142,3 +142,29 @@ func (c *AuditController) AllowForbidAudit() {
msg = protocol.NewReturnResponse(nil, err)
return
}
//GetChanceReviseLog
//@router /v1/audit/revise/info
func (c *AuditController) GetChanceReviseLog() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
FlowLogId int64 `json:"flow_log_id"`
ChanceId string `json:"chance_id"`
}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败", err)
msg = protocol.BadRequestParam("1")
return
}
chanceId, _ := strconv.ParseInt(param.ChanceId, 10, 64)
companyId := c.GetCompanyId()
rspData, err := serveaudit.GetChanceReviseLog(param.FlowLogId, chanceId, companyId)
msg = protocol.NewReturnResponse(rspData, err)
return
}
// GetChanceReviseLog
... ...
... ... @@ -134,6 +134,49 @@ func (c *AuthController) LoginSms() {
return
}
// LoginSecret 使用秘钥进行登录
// @router /login [post]
func (c *AuthController) LoginSecretKey() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Secret string `json:"secret"`
}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败", err)
msg = protocol.BadRequestParam("1")
return
}
if len(param.Secret) == 0 {
msg = protocol.BadRequestParam("10080")
return
}
logintoken, err := serveauth.LoginAuthBySecretKey(param.Secret)
if err != nil {
msg = &protocol.ResponseMessage{
Errno: -1,
Errmsg: err.Error(),
}
return
}
err = serveauth.ResetLoginToken(logintoken)
if err != nil {
log.Error("token 信息记录数据库失败")
}
err = serveauth.ResetLoginTokenRedis(logintoken)
if err != nil {
log.Error("token 信息记录redis失败")
}
data := protocol.ResponseLogin{
Access: logintoken,
}
msg = protocol.NewReturnResponse(data, nil)
return
}
//SmsCode 发送验证码短信
//@router /auth/smscode
func (c *AuthController) SmsCode() {
... ...
... ... @@ -183,3 +183,66 @@ func (c *CommonController) SelectorRoleUser() {
msg = protocol.NewReturnResponse(list, err)
return
}
//SelectorChanceType 获取机会类型列表
func (c *CommonController) SelectorChanceType() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
companyid := c.GetCompanyId()
templatelist := servecommon.SelectGetTemplateList(companyid)
chanceTypeList := servecommon.SeleteGetChanceTypeList(companyid)
data := map[string]interface{}{
"template": templatelist,
"chance_type": chanceTypeList,
}
msg = protocol.NewReturnResponse(data, nil)
return
}
//SelectCompanyUserList 下拉选择框 获取公司成员列表
func (c *CommonController) SelectCompanyUserList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
protocol.RequestPageInfo
UserName string `json:"user_name"`
}
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()
listData := servecommon.SelectCompanyUserList(param.PageIndex, param.PageSize, companyid, param.UserName)
msg = protocol.NewPageDataResponse(listData, nil)
return
}
//SelectChanceList 下拉选择框 获取机会列表
func (c *CommonController) SelectChanceList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
protocol.RequestPageInfo
SearchType int `json:"search_type"` //1:根据机会编码搜索 2:根据提交人搜索
ChanceCode string `json:"chance_code"`
}
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()
listData := servecommon.SelectChanceList(param.PageIndex, param.PageSize, companyid, param.SearchType, param.ChanceCode)
msg = protocol.NewPageDataResponse(listData, nil)
return
}
... ...
package controllers
import (
"encoding/json"
"fmt"
"oppmg/common/log"
"oppmg/protocol"
"oppmg/services/platform"
)
type PlatformController struct {
BaseController
}
//
func (c PlatformController) UpdateData() {
defer func() {
c.Data["json"] = map[string]interface{}{
"code": 0,
"msg": "ok",
}
c.ServeJSON()
}()
var param platform.CommonProtocol
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败 err:%s", err)
return
}
m, err := platform.NewPlatformAction(param.Module)
if err != nil {
log.Error("同步数据发生错误,err%s", err)
return
}
bt, err := json.Marshal(param.Data)
if err != nil {
log.Error("解析param.data数据失败")
}
err = m.DoAction(param.Action, bt)
if err != nil {
log.Error("同步数据发生错误,module=%s,action=%s,err:%s", param.Module, param.Action, err)
}
return
}
func (c PlatformController) CompanyAdminChance() {
type Parameter struct {
CompanyId int64 `json:"company_id"`
Phone string `json:"phone"`
}
var msg = protocol.ErrWithMessage{}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
e := fmt.Errorf("json 解析失败 err:%s", err)
log.Error(e.Error())
msg.Errmsg = e.Error()
return
}
err := platform.AdminChance(param.CompanyId, param.Phone)
if err != nil {
log.Error("总后台调用CompanyAdminChance发生错误;%s", err)
msg.Errmsg = err.Error()
}
c.Data["json"] = msg
c.ServeJSON()
return
}
... ...
package controllers
import (
"encoding/json"
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
serverank "oppmg/services/rank"
"strings"
"time"
)
type RankController struct {
BaseController
}
//GetRankType 榜单类型列表
//@router /rank/list
func (c RankController) GetRankType() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
companyid := c.GetCompanyId()
rspData := serverank.GetRankList(companyid)
msg = protocol.NewReturnResponse(rspData, nil)
return
}
//EditRankType 榜单类型列表添加
//@router /rank/edit
func (c RankController) EditRankType() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
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
}
param.Name = strings.TrimSpace(param.Name)
n := []rune(param.Name)
if len(n) > 5 || len(n) == 0 {
msg = protocol.BadRequestParam("10103")
return
}
companyid := c.GetCompanyId()
err := serverank.UpdateRankType(param.Id, param.Name, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//EditRankType ...
//@router /rank/forbid_allow
func (c RankController) RankTypeForbidAllow() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"id"`
Status int `json:"status"`
}
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
}
var err error
companyid := c.GetCompanyId()
switch param.Status {
case 1:
err = serverank.ForbidRank(param.Id, companyid)
case 2:
err = serverank.AllowRank(param.Id, companyid)
default:
err = protocol.NewErrWithMessage("1")
}
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankSeasonList 赛季列表
//@router /rank/season/list
func (c RankController) RankSeasonList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
protocol.RequestPageInfo
RankTypeId int64 `json:"rank_type_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()
rspData, err := serverank.RankSeasonList(param.PageIndex, param.PageSize, param.RankTypeId, companyid)
msg = protocol.NewPageDataResponse(rspData, err)
return
}
//RankSeasonAdd 赛季列表添加
//@router /rank/season/add
func (c RankController) RankSeasonAdd() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_id"`
Name string `json:"name"`
BeginTime string `json:"begin_time"`
EndTime string `json:"end_time"`
}
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
}
param.Name = strings.TrimSpace(param.Name)
if len(param.Name) == 0 {
msg = protocol.BadRequestParam("10104")
return
}
param.BeginTime = strings.TrimSpace(param.BeginTime)
if len(param.BeginTime) == 0 {
msg = protocol.BadRequestParam("10105")
return
}
param.EndTime = strings.TrimSpace(param.EndTime)
if len(param.EndTime) == 0 {
msg = protocol.BadRequestParam("10106")
return
}
var (
beginTime int64
endTime int64
)
t1, err := time.ParseInLocation("2006-01-02", param.BeginTime, time.Local)
if err != nil {
msg = protocol.BadRequestParam("10105")
return
}
beginTime = t1.Unix()
t2, err := time.ParseInLocation("2006-01-02", param.EndTime, time.Local)
if err != nil {
msg = protocol.BadRequestParam("10106")
return
}
endTime = t2.Unix() + 86399 //60*60*24-1
if beginTime > endTime {
msg = protocol.BadRequestParam("1")
return
}
ok := serverank.RankPeriodCheckTime(param.RankTypeId, beginTime, endTime, 0)
if !ok {
msg = protocol.BadRequestParam("10101")
return
}
companyid := c.GetCompanyId()
err = serverank.AddRankPeriod(param.RankTypeId, beginTime, endTime, param.Name, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankSeasonEdit ...
//@router /rank/season/edit
func (c RankController) RankSeasonEdit() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"id"`
Name string `json:"name"`
RankTypeId int64 `json:"rank_type_id"`
BeginTime string `json:"begin_time"`
EndTime string `json:"end_time"`
}
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
}
param.Name = strings.TrimSpace(param.Name)
if len(param.Name) == 0 {
msg = protocol.BadRequestParam("1")
return
}
param.BeginTime = strings.TrimSpace(param.BeginTime)
if len(param.BeginTime) == 0 {
msg = protocol.BadRequestParam("10105")
return
}
param.EndTime = strings.TrimSpace(param.EndTime)
if len(param.EndTime) == 0 {
msg = protocol.BadRequestParam("10106")
return
}
var (
beginTime int64
endTime int64
)
t1, err := time.ParseInLocation("2006-01-02", param.BeginTime, time.Local)
if err != nil {
log.Error(err.Error())
msg = protocol.BadRequestParam("10105")
return
}
beginTime = t1.Unix()
t2, err := time.ParseInLocation("2006-01-02", param.EndTime, time.Local)
if err != nil {
log.Error(err.Error())
msg = protocol.BadRequestParam("10106")
return
}
endTime = t2.Unix() + 86399 //60*60*24-1
if beginTime > endTime {
msg = protocol.BadRequestParam("1")
return
}
ok := serverank.RankPeriodCheckTime(param.RankTypeId, beginTime, endTime, param.Id)
if !ok {
msg = protocol.BadRequestParam("10101")
return
}
companyid := c.GetCompanyId()
fmt.Println(beginTime, endTime)
err = serverank.EditRankPeriod(param.Id, beginTime, endTime, param.Name, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankRangeList 赛季榜单参与人列表
//@router /rank/range/list
func (c RankController) RankRangeList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_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()
rspData := serverank.GetRankRangeList(companyid, param.RankTypeId)
msg = protocol.NewReturnResponse(rspData, nil)
return
}
//RankRangeAdd 赛季榜单参与人列表添加
//@router /rank/range/add
func (c RankController) RankRangeAdd() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_id"`
Name string `json:"name"`
RangeType int8 `json:"range_type"`
RelationId []int64 `json:"relation_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
}
param.Name = strings.TrimSpace(param.Name)
n := []rune(param.Name)
if len(n) == 0 || len(n) > 5 {
msg = protocol.BadRequestParam("10107")
return
}
ok := serverank.RankRangeNameOnlyOne(param.RankTypeId, 0, param.Name)
if !ok {
msg = protocol.BadRequestParam("10125")
return
}
switch param.RangeType {
case 1:
param.RangeType = models.RANK_RANGE_TYPE_EMPLAYEE
case 2:
param.RangeType = models.RANK_RANGE_TYPE_DEPARTMENT
default:
log.Error("param.RangeType err")
msg = protocol.BadRequestParam("1")
return
}
companyid := c.GetCompanyId()
err := serverank.AddRankRange(param.RankTypeId, param.Name, param.RangeType, param.RelationId, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankRangeEdit 赛季榜单参与人编辑
//@router /rank/range/edit
func (c RankController) RankRangeEdit() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"id"`
Name string `json:"name"`
RangeType int8 `json:"range_type"`
RelationId []int64 `json:"relation_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
}
param.Name = strings.TrimSpace(param.Name)
n := []rune(param.Name)
if len(n) == 0 || len(n) > 5 {
msg = protocol.BadRequestParam("10107")
return
}
switch param.RangeType {
case 1:
param.RangeType = models.RANK_RANGE_TYPE_EMPLAYEE
case 2:
param.RangeType = models.RANK_RANGE_TYPE_DEPARTMENT
default:
log.Error("param.RangeType err")
msg = protocol.BadRequestParam("1")
return
}
companyid := c.GetCompanyId()
err := serverank.EditRankRange(param.Id, param.Name, param.RangeType, param.RelationId, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankRangeForbidAllow ...
//@router /rank/range/forbid_allow
func (c RankController) RankRangeForbidAllow() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"id"`
Status int `json:"status"`
}
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
}
var err error
companyid := c.GetCompanyId()
switch param.Status {
case 1:
err = serverank.ForbidRankRange(param.Id, companyid)
case 2:
err = serverank.AllowRankRange(param.Id, companyid)
default:
err = protocol.NewErrWithMessage("1")
}
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankRangeInfo 赛季榜单参与人详情
//@router /rank/range/info
func (c RankController) RankRangeInfo() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
Id int64 `json:"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()
rspData := serverank.GetRankRangeInfo(param.Id)
switch rspData.RangeType {
case models.RANK_RANGE_TYPE_DEPARTMENT, models.RANK_RANGE_TYPE_DEPARTMENTALL:
//部门
rspData.RangeType = 2
case models.RANK_RANGE_TYPE_EMPLAYEE, models.RANK_RANGE_TYPE_EMPLAYEEALL:
//员工
rspData.RangeType = 1
}
msg = protocol.NewReturnResponse(rspData, nil)
return
}
//RankRangeSort ...
//@router /rank/range/sort
func (c RankController) RankRangeSort() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_id"`
Id []int64 `json:"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
}
err := serverank.RankRangeSort(param.Id)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankItemList 评比项列表
//@router /rank/item/list
func (c RankController) RankItemList() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_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()
items := serverank.GetRankItemList(companyid, param.RankTypeId)
rspdata := map[string][]protocol.RankItemInfo{
"all": serverank.AllRankItem,
"checked": items,
}
msg = protocol.NewReturnResponse(rspdata, nil)
return
}
//RankItemEdit ...
//@router /rank/item/edit
func (c RankController) RankItemEdit() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_id"`
ItemKey []string `json:"item_key"`
}
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
}
if len(param.ItemKey) > 4 {
msg = protocol.BadRequestParam("10123")
return
}
companyid := c.GetCompanyId()
err := serverank.GetRankItemEdit(companyid, param.RankTypeId, param.ItemKey)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankRangeMove 赛季榜单参与人分组 批量移动
//@router /rank/range/move
func (c RankController) RankRangeMove() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
FromId int64 `json:"from_id"`
ToId int64 `json:"to_id"`
RelationId []int64 `json:"relation_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 := serverank.RankRangeMove(param.FromId, param.ToId, param.RelationId, companyid)
msg = protocol.NewReturnResponse(nil, err)
return
}
//RankTypeConfig 赛季榜单的一些特殊配置(自动创建赛季)
//@router /rank/type/config_set
func (c RankController) RankTypeConfigSet() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_id"`
AutoCreate int8 `json:"auto_create"` //【0:不自动创建】【1:自动创建】
AutoCreateDay int `json:"auto_create_day"` //赛季时间, 单位:天
}
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()
var (
err error
rankType *models.RankType
)
rankType, err = models.GetRankById(param.RankTypeId)
if err != nil {
log.Error("获取rank_type数据失败:%s", err)
e := protocol.NewErrWithMessage("1")
msg = protocol.NewReturnResponse(nil, e)
return
}
if rankType.CompanyId != companyid {
log.Error("公司不匹配")
e := protocol.NewErrWithMessage("1")
msg = protocol.NewReturnResponse(nil, e)
return
}
if param.AutoCreate > 1 || param.AutoCreate < 0 {
e := protocol.NewErrWithMessage("1")
msg = protocol.NewReturnResponse(nil, e)
return
}
rankType.AutoCreate = param.AutoCreate
rankType.AutoPeriod = param.AutoCreateDay
err = models.UpdateRankById(rankType, []string{"AutoCreate", "AutoPeriod"})
if err != nil {
log.Error("更新rank_type数据失败;%s", err)
e := protocol.NewErrWithMessage("1")
msg = protocol.NewReturnResponse(nil, e)
return
}
msg = protocol.NewReturnResponse(nil, nil)
return
}
//RankTypeConfig 赛季榜单的一些特殊配置(自动创建赛季)
//@router /rank/type/config_show
func (c RankController) RankTypeConfigShow() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
RankTypeId int64 `json:"rank_type_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()
var (
err error
rankType *models.RankType
)
rankType, err = models.GetRankById(param.RankTypeId)
if err != nil {
log.Error("获取rank_type数据失败:%s", err)
e := protocol.NewErrWithMessage("1")
msg = protocol.NewReturnResponse(nil, e)
return
}
if rankType.CompanyId != companyid {
log.Error("公司不匹配")
e := protocol.NewErrWithMessage("1")
msg = protocol.NewReturnResponse(nil, e)
return
}
v := struct {
AutoCreate int8 `json:"auto_create"`
AutoCreateDay int `json:"auto_create_day"`
}{
AutoCreate: rankType.AutoCreate,
AutoCreateDay: rankType.AutoPeriod,
}
msg = protocol.NewReturnResponse(v, nil)
return
}
... ...
... ... @@ -8,6 +8,8 @@ import (
"oppmg/common/config"
"oppmg/common/log"
"oppmg/services/crontab"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
... ... @@ -23,5 +25,6 @@ func init() {
func main() {
log.Debug("%s 应用启动", time.Now().String())
crontab.Run()
beego.Run()
}
... ...
package models
import (
"time"
"github.com/astaxie/beego/orm"
)
type AchevementScore struct {
Id int64 `orm:"column(id);auto"`
GraspScoreRemain float64 `orm:"column(grasp_score_remain);null;digits(10);decimals(1)" description:"福利池总分 ,来源achievement中的评分"`
CompanyId int64 `orm:"column(company_id)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null"`
}
func (t *AchevementScore) TableName() string {
return "achevement_score"
}
func init() {
orm.RegisterModel(new(AchevementScore))
}
// AddAchevementScore insert a new AchevementScore into database and returns
// last inserted Id on success.
func AddAchevementScore(m *AchevementScore, o orm.Ormer) (id int64, err error) {
id, err = o.Insert(m)
return
}
// GetAchevementScoreById retrieves AchevementScore by Id. Returns error if
// Id doesn't exist
func GetAchevementScoreById(id int64) (v *AchevementScore, err error) {
o := orm.NewOrm()
v = &AchevementScore{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
func GetAchevementScoreByCompanyId(companyid int64) (v *AchevementScore, err error) {
o := orm.NewOrm()
v = &AchevementScore{}
ok := o.QueryTable(&AchevementScore{}).
Filter("company_id", companyid).
Exist()
if !ok {
return v, nil
}
err = o.QueryTable(&AchevementScore{}).
Filter("company_id", companyid).
One(v)
return v, err
}
func IncreaseAchevementScore(companyid int64, addScore float64, o orm.Ormer) error {
v := &AchevementScore{}
ok := o.QueryTable(&AchevementScore{}).
Filter("company_id", companyid).
Exist()
if ok {
nowTime := time.Now().Format("2006-01-02 15:04:05")
sql := `update achevement_score set grasp_score_remain=grasp_score_remain+?,update_at=? where company_id=?`
//存在,更新
_, err := o.Raw(sql, addScore, nowTime, companyid).Exec()
return err
}
//不存在
v.CompanyId = companyid
v.GraspScoreRemain = addScore
v.CreateAt = time.Now()
_, err := o.Insert(v)
return err
}
... ...
package models
import (
"fmt"
"oppmg/common/log"
"time"
"github.com/astaxie/beego/orm"
)
type Achievement struct {
Id int64 `orm:"column(id);auto" description:"id 主键"`
CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
DepartmentId int64 `orm:"column(department_id);null" description:"表department.id 部门id (创建成果指定的部门)"`
UserCompanyId int64 `orm:"column(user_company_id)" description:"把握人 表user_company.id id"`
ChanceTypeId int64 `orm:"column(chance_type_id);null" description:"表chance_type.id 机会类型 "`
AuditTemplateId int64 `orm:"column(audit_template_id);null" description:"表audit_template.id 所属审批模板编号"`
SourceContent string `orm:"column(source_content);null" description:"成果详情文本"`
GraspScore float64 `orm:"column(grasp_score);digits(4);decimals(1)" description:"把握分"`
UserGraspScore float64 `orm:"column(user_grasp_score);digits(4);decimals(1)" description:"把握人得分"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
ViewTotal int `orm:"column(view_total);null" description:"查看总数"`
CommentTotal int `orm:"column(comment_total);null" description:"评论总数"`
ZanTotal int `orm:"column(zan_total);null" description:"点赞总数"`
Status int8 `orm:"column(status);null" description:"机会状态 1:开启 2:关闭 0:删除"`
Images string `orm:"column(images);null" description:"图片 json"`
GraspScoreRemain float64 `orm:"column(grasp_score_remain);digits(4);decimals(1)" `
}
func (t *Achievement) TableName() string {
return "achievement"
}
func init() {
orm.RegisterModel(new(Achievement))
}
//机会状态 1:开启 2:关闭 0:删除
const (
ACHIEVEMENT_STATUS_DEL int8 = 0 //删除
ACHIEVEMENT_STATUS_YES int8 = 1 //开启
ACHIEVEMENT_STATUS_NO int8 = 2 //关闭
)
// AddAchievement insert a new Achievement into database and returns
// last inserted Id on success.
func AddAchievement(m *Achievement, om ...orm.Ormer) (id int64, err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
id, err = o.Insert(m)
return
}
// GetAchievementById retrieves Achievement by Id. Returns error if
// Id doesn't exist
func GetAchievementById(id int64) (v *Achievement, err error) {
o := orm.NewOrm()
v = &Achievement{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateAchievement updates Achievement by Id and returns error if
// the record to be updated doesn't exist
func UpdateAchievementById(m *Achievement, cols []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
m.UpdateAt = time.Now()
if len(cols) > 0 {
cols = append(cols, "UpdateAt")
}
var num int64
if num, err = o.Update(m, cols...); err == nil {
log.Info("Number of records updated in database:", num)
}
return
}
// DeleteAchievement deletes Achievement by Id and returns error if
// the record to be deleted doesn't exist
func DeleteAchievement(id int64) (err error) {
o := orm.NewOrm()
v := Achievement{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&Achievement{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"fmt"
"time"
"github.com/astaxie/beego/orm"
)
type AchievementChance struct {
Id int64 `orm:"column(id);auto"`
AchievementId int64 `orm:"column(achievement_id);null" description:"成果编号 表achievement.id"`
ChanceId int64 `orm:"column(chance_id);null" description:"机会编号 表chance.id"`
ChanceCode string `orm:"column(chance_code);size(255);null" description:"机会编号 表chance.code"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
}
func (t *AchievementChance) TableName() string {
return "achievement_chance"
}
func init() {
orm.RegisterModel(new(AchievementChance))
}
// AddAchievementChance insert a new AchievementChance into database and returns
// last inserted Id on success.
func AddAchievementChance(m *AchievementChance) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetAchievementChanceById retrieves AchievementChance by Id. Returns error if
// Id doesn't exist
func GetAchievementChanceById(id int64) (v *AchievementChance, err error) {
o := orm.NewOrm()
v = &AchievementChance{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateAchievementChance updates AchievementChance by Id and returns error if
// the record to be updated doesn't exist
func UpdateAchievementChanceById(m *AchievementChance) (err error) {
o := orm.NewOrm()
v := AchievementChance{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
}
func GetAchievementChanceByAchieve(achievementid int64) ([]AchievementChance, error) {
var (
err error
data []AchievementChance
)
o := orm.NewOrm()
_, err = o.QueryTable(&AchievementChance{}).
Filter("achievement_id", achievementid).
All(&data)
if err == orm.ErrNoRows {
return data, nil
}
return data, err
}
... ...
package models
import (
"fmt"
"time"
"github.com/astaxie/beego/orm"
)
type AchievementProvider struct {
Id int64 `orm:"column(id);auto" description:"主键id"`
AchievementId int64 `orm:"column(achievement_id);null" description:"表achievement.id"`
UserCompanyId int64 `orm:"column(user_company_id);null" description:"user_company.id"`
UserGraspScore float64 `orm:"column(user_grasp_score);null;digits(4);decimals(1)" description:"把握人得分"`
DepartmentId int64 `orm:"column(department_id)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
}
func (t *AchievementProvider) TableName() string {
return "achievement_provider"
}
func init() {
orm.RegisterModel(new(AchievementProvider))
}
// AddAchievementProvider insert a new AchievementProvider into database and returns
// last inserted Id on success.
func AddAchievementProvider(m *AchievementProvider) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetAchievementProviderById retrieves AchievementProvider by Id. Returns error if
// Id doesn't exist
func GetAchievementProviderById(id int64) (v *AchievementProvider, err error) {
o := orm.NewOrm()
v = &AchievementProvider{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateAchievementProvider updates AchievementProvider by Id and returns error if
// the record to be updated doesn't exist
func UpdateAchievementProviderById(m *AchievementProvider) (err error) {
o := orm.NewOrm()
v := AchievementProvider{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
}
func GetAchievementProviderByAchieve(achievementid int64) ([]AchievementProvider, error) {
var (
err error
data []AchievementProvider
)
o := orm.NewOrm()
_, err = o.QueryTable(&AchievementProvider{}).
Filter("achievement_id", achievementid).
All(&data)
if err == orm.ErrNoRows {
return data, nil
}
return data, err
}
... ...
... ... @@ -36,7 +36,7 @@ type ChanceDataSpeechs struct {
}
type ChanceDataVideos struct {
Path string
Path string `json:"path"`
Cover ChanceDataImage `json:"cover"`
Duration int `json:"duration"`
}
... ...
package models
import (
"encoding/json"
"time"
"github.com/astaxie/beego/orm"
)
type ChanceReviseLog struct {
Id int64 `orm:"column(id);pk" description:"id 主键"`
ChanceId int64 `orm:"column(chance_id)" description:"机会编号"`
UserCompanyId int64 `orm:"column(user_company_id);null" description:"用户编号 编辑机会的人"`
Data string `orm:"column(data);null" description:"机会数据"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
AuditFlowLogId int64 `orm:"column(audit_flow_log_id);null" description:"表audit_flow_log.id "`
}
func (t *ChanceReviseLog) TableName() string {
return "chance_revise_log"
}
func init() {
orm.RegisterModel(new(ChanceReviseLog))
}
type ReviseContentsItem struct {
Content string `json:"content"`
}
type ChanceReviseLogData struct {
ReviseContents []ReviseContentsItem `json:"reviseContents"`
Speechs []ChanceDataSpeechs `json:"speechs"`
Pictures []ChanceDataImage `json:"pictures"`
Videos []ChanceDataVideos `json:"videos"`
RemoveAllPhotoVideo bool `json:"removeAllPhotoVideo"`
RemoveAllSpeech bool `json:"removeAllSpeech"`
}
// GetChanceReviseLogById retrieves ChanceReviseLog by Id. Returns error if
// Id doesn't exist
func GetChanceReviseLogById(id int64) (v *ChanceReviseLog, err error) {
o := orm.NewOrm()
v = &ChanceReviseLog{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
func GetChanceReviseLogData(flowLogId int64) (*ChanceReviseLog, *ChanceReviseLogData, error) {
o := orm.NewOrm()
var (
err error
)
reviseLog := &ChanceReviseLog{}
err = o.QueryTable(&ChanceReviseLog{}).
Filter("audit_flow_log_id", flowLogId).
One(reviseLog)
if err != nil {
return nil, nil, err
}
reviseLogData := &ChanceReviseLogData{
ReviseContents: make([]ReviseContentsItem, 0),
Speechs: make([]ChanceDataSpeechs, 0),
Pictures: make([]ChanceDataImage, 0),
Videos: make([]ChanceDataVideos, 0),
}
json.Unmarshal([]byte(reviseLog.Data), reviseLogData)
return reviseLog, reviseLogData, err
}
... ...
... ... @@ -17,6 +17,7 @@ type Company struct {
Logo string `orm:"column(logo);size(255)"`
Enable int8 `orm:"column(enable)"`
UserCenterId int64 `orm:"column(user_center_id)"`
Remark string `orm:"column(remark)"`
}
func (t *Company) TableName() string {
... ...
... ... @@ -12,16 +12,18 @@ import (
)
type Department struct {
Id int64 `orm:"column(id);auto"`
CompanyId int64 `orm:"column(company_id)" description:"公司id"`
Name string `orm:"column(name);size(30)" description:"部门名称"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
ParentId int64 `orm:"column(parent_id)" description:"父级id"`
Relation string `orm:"column(relation);size(1024)" description:"父子级关系树"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
Manages string `orm:"column(managers)" description:"部门负责人id列表 json 数组 []"` //存user_company_id
IsTop int8 `orm:"column(is_top)" `
Id int64 `orm:"column(id);auto"`
CompanyId int64 `orm:"column(company_id)" description:"公司id"`
Name string `orm:"column(name);size(30)" description:"部门名称"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
ParentId int64 `orm:"column(parent_id)" description:"父级id"`
Relation string `orm:"column(relation);size(1024)" description:"父子级关系树"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
Manages string `orm:"column(managers)" description:"部门负责人id列表 json 数组 []"` //存user_company_id
IsTop int8 `orm:"column(is_top)" `
Level int `orm:"column(level)" `
BusinessDepartmentId int64 `orm:"column(business_department_id)"`
}
func (t *Department) TableName() string {
... ... @@ -55,9 +57,11 @@ func (t *Department) SetRelation(parent *Department) error {
return errors.New("Id==0")
}
if parent == nil {
t.Relation = fmt.Sprintf("%d", t.Id)
t.Relation = fmt.Sprintf(",%d,", t.Id)
} else if parent.Id == 0 {
t.Relation = fmt.Sprintf(",%d,", t.Id)
} else {
t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id)
t.Relation = fmt.Sprintf("%s%d,", parent.Relation, t.Id)
}
return nil
}
... ... @@ -187,11 +191,15 @@ func GetDepartmentByCompanyId(companyId int64) ([]Department, error) {
o := orm.NewOrm()
_, err = o.QueryTable(&Department{}).
Filter("company_id", companyId).
Filter("delete_at", 0).
All(&result)
return result, err
}
func GetDepartmentByIds(departmentIds []int64) ([]Department, error) {
if len(departmentIds) == 0 {
return nil, nil
}
var (
result []Department
err error
... ... @@ -215,3 +223,25 @@ func ExistDepartmentName(parentId int64, dname string) bool {
Exist()
return ok
}
func GetDepartmentByBusinessId(businessId int64) (v *Department, err error) {
v = &Department{}
o := orm.NewOrm()
err = o.QueryTable(&Department{}).
Filter("business_department_id", businessId).
Filter("delete_at", 0).
One(v)
return v, err
}
func GetTopDepartmentByCompany(companyid int64) (v *Department, err error) {
v = &Department{}
o := orm.NewOrm()
err = o.QueryTable(&Department{}).
Filter("company_id", companyid).
Filter("is_top", 1).
Filter("delete_at", 0).
One(v)
return v, err
}
... ...
package models
import (
"fmt"
"oppmg/utils"
"time"
"github.com/astaxie/beego/orm"
)
type DepartmentCharge struct {
Id int64 `orm:"column(id);auto"`
CompanyId int64 `orm:"column(company_id)" description:"公司id"`
DepartmentId int64 `orm:"column(department_id)" description:"部门id"`
UserCompanyId int64 `orm:"column(user_company_id)" description:"用户id"`
CreateTime time.Time `orm:"column(create_time);type(timestamp)"`
Enabled int8 `orm:"column(enabled)"`
}
func (t *DepartmentCharge) TableName() string {
return "department_charge"
}
func init() {
orm.RegisterModel(new(DepartmentCharge))
}
const (
DEPARTMENT_CHARGE_ENABLE_YES int8 = 1
DEPARTMENT_CHARGE_ENABLE_NO int8 = 2
)
// AddDepartmentCharge insert a new DepartmentCharge into database and returns
// last inserted Id on success.
func AddDepartmentCharge(m *DepartmentCharge, o orm.Ormer) (id int64, err error) {
id, err = o.Insert(m)
return
}
// UpdateDepartmentCharge updates DepartmentCharge by Id and returns error if
// the record to be updated doesn't exist
func UpdateDepartmentChargeById(m *DepartmentCharge) (err error) {
o := orm.NewOrm()
v := DepartmentCharge{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
}
func GetDepartmentCharge(departmentId int64) ([]DepartmentCharge, error) {
var (
data []DepartmentCharge
err error
)
o := orm.NewOrm()
_, err = o.QueryTable(&DepartmentCharge{}).
Filter("department_id", departmentId).
Filter("enabled", 1).
All(&data)
if err == orm.ErrNoRows {
return data, nil
}
return data, err
}
//ChangeDepartmentCharge 变更部门的主管
func ChangeDepartmentCharge(companyId int64, departmentId int64, userCompanyid []int64, om orm.Ormer) error {
var (
err error
charges []DepartmentCharge
oldChargeIds []int64
)
charges, err = GetDepartmentCharge(departmentId)
if err != nil {
return fmt.Errorf("获取部门主管数据失败:%s", err)
}
for _, v := range charges {
oldChargeIds = append(oldChargeIds, v.Id)
}
var (
delIds []int64
addIds []int64
addCharges []DepartmentCharge
)
delIds = utils.ArrayInt64Diff(oldChargeIds, userCompanyid)
addIds = utils.ArrayInt64Diff(userCompanyid, oldChargeIds)
nowTime := time.Now()
for _, v := range addIds {
m := DepartmentCharge{
CompanyId: companyId,
UserCompanyId: v,
DepartmentId: departmentId,
Enabled: DEPARTMENT_CHARGE_ENABLE_YES,
CreateTime: nowTime,
}
addCharges = append(addCharges, m)
}
if len(delIds) > 0 {
_, err = om.QueryTable(&DepartmentCharge{}).
Filter("department_id", departmentId).
Filter("user_company_id__in", delIds).
Update(orm.Params{
"enable": DEPARTMENT_CHARGE_ENABLE_NO,
})
if err != nil {
return fmt.Errorf("更新department_charge数据失败,err:%s", err)
}
}
if len(addCharges) > 0 {
_, err = om.InsertMulti(10, addCharges)
if err != nil {
return fmt.Errorf("添加department_charge数据失败,err:%s", err)
}
}
return nil
}
... ...
package models
import (
"errors"
"fmt"
"time"
... ... @@ -9,17 +8,20 @@ import (
)
type Position struct {
Id int64 `orm:"column(id);auto" description:"职位表id"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
Name string `orm:"column(name);size(100)" description:"职位名称"`
ParentId int64 `orm:"column(parent_id)" description:"父级id"`
Relation string `orm:"column(relation);size(1000)" description:"父子级关系树"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
EnableStatus string `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"`
Id int64 `orm:"column(id);auto" description:"职位表id"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
Name string `orm:"column(name);size(100)" description:"职位名称"`
ParentId int64 `orm:"column(parent_id)" description:"父级id"`
Relation string `orm:"column(relation);size(1000)" description:"父子级关系树"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
EnableStatus string `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"`
Level int `orm:"column(level)"`
BusinessPositionId int64 `orm:"column(business_position_id)"`
}
//关联企业总后台的id
func (t *Position) TableName() string {
return "position"
}
... ... @@ -29,13 +31,10 @@ func init() {
}
func (t *Position) SetRelation(parent *Position) error {
if t.Id == 0 {
return errors.New("Id==0")
}
if parent == nil {
t.Relation = fmt.Sprintf("%d", t.Id)
t.Relation = fmt.Sprintf(",%d,", t.Id)
} else {
t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id)
t.Relation = fmt.Sprintf("%s%d,", parent.Relation, t.Id)
}
return nil
}
... ... @@ -82,6 +81,7 @@ func UpdatePositionById(m *Position, col []string, om ...orm.Ormer) (err error)
if err = o.Read(&v); err == nil {
var num int64
m.UpdateAt = time.Now()
col = append(col, "UpdateAt")
if num, err = o.Update(m, col...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
... ... @@ -102,3 +102,13 @@ func ExistPositiontName(companyid int64, parentId int64, dname string) bool {
Exist()
return ok
}
func GetPositionByBusinessId(businessId int64) (v *Position, err error) {
o := orm.NewOrm()
v = &Position{}
err = o.QueryTable(&Position{}).
Filter("business_position_id", businessId).
Filter("delete_at", 0).
One(v)
return v, err
}
... ...
package models
import (
"oppmg/common/log"
"time"
"github.com/astaxie/beego/orm"
)
type RankItem struct {
Id int64 `orm:"column(id);auto"`
CompanyId int64 `orm:"column(company_id);null" description:"公司编号 company.id"`
RankTypeId int64 `orm:"column(rank_type_id)" description:"表rank_type.id 榜单类型编号"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
SortNum int `orm:"column(sort_num);null" description:"序号"`
ItemName string `orm:"column(item_name);size(50);null" description:"评比项名称"`
ItemKey string `orm:"column(item_key);size(50);null" description:"评比项键值(排行榜排序使用)"`
}
func (t *RankItem) TableName() string {
return "rank_item"
}
func init() {
orm.RegisterModel(new(RankItem))
}
// AddRankItem insert a new NewRankItem into database and returns
// last inserted Id on success.
func AddRankItem(m []RankItem, om orm.Ormer) (successSum int64, err error) {
nowTime := time.Now()
for i := range m {
m[i].CreateAt = nowTime
m[i].UpdateAt = nowTime
}
successSum, err = om.InsertMulti(10, &m)
return
}
// GetRankItemById retrieves NewRankItem by Id. Returns error if
// Id doesn't exist
func GetRankItemById(id int64) (v *RankItem, err error) {
o := orm.NewOrm()
v = &RankItem{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
func GetRankItemByCompanyid(companyid int64, rankTypeId int64) ([]RankItem, error) {
var (
data []RankItem
err error
)
o := orm.NewOrm()
_, err = o.QueryTable(&RankItem{}).
Filter("company_id", companyid).
Filter("rank_type_id", rankTypeId).
All(&data)
if err == orm.ErrNoRows {
return data, nil
}
return data, err
}
func DeleteRanKItemByIds(ids []int64, om orm.Ormer) error {
_, err := om.QueryTable(&RankItem{}).Filter("id__in", ids).Delete()
return err
}
// UpdateRankItem updates RankItem by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankItemById(m *RankItem, cols []string, om orm.Ormer) (err error) {
if len(cols) > 0 {
cols = append(cols, "UpdateAt")
}
m.UpdateAt = time.Now()
var num int64
if num, err = om.Update(m, cols...); err == nil {
log.Info("Number of records updated in database:%d", num)
}
return
}
... ...
package models
import (
"oppmg/common/log"
"time"
"github.com/astaxie/beego/orm"
)
type RankPeriod struct {
Id int64 `orm:"column(id);auto" description:"主键"`
CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
SeasonName string `orm:"column(season_name);size(50);null" description:"赛季名称"`
RankTypeId int64 `orm:"column(rank_type_id);size(50);null" description:"赛季类型id"`
BeginTime time.Time `orm:"column(begin_time);type(timestamp);null" description:"开始时间"`
EndTime time.Time `orm:"column(end_time);type(timestamp);null" description:"结束时间"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
Status int8 `orm:"column(status);null" description:"状态 0:未开始 1:开始 2:结束 "`
RankRangeBack string `orm:"column(rank_range_back)" description:"赛季结束时,备份赛季参与人设置"`
RankItemBack string `orm:"column(rank_item_back)" description:"赛季结束时,备份赛季评比项设置"`
IsAuto int `orm:"column(is_auto)" description:"是否是自动创建的赛季【0:不是】【1:是】"`
}
func (t *RankPeriod) TableName() string {
return "rank_period"
}
func init() {
orm.RegisterModel(new(RankPeriod))
}
//状态 0:未开始 1:开始 2:结束
const (
RANKPERIOD_STATUS_NOT int8 = 0
RANKPERIOD_STATUS_BEGIN int8 = 1
RANKPERIOD_STATUS_END int8 = 2
)
// AddNewRankPeriod insert a new RankPeriod into database and returns
// last inserted Id on success.
func AddRankPeriod(m *RankPeriod) (id int64, err error) {
o := orm.NewOrm()
m.CreateAt = time.Now()
m.UpdateAt = time.Now()
id, err = o.Insert(m)
return
}
// GetNewRankPeriodById retrieves RankPeriod by Id. Returns error if
// Id doesn't exist
func GetRankPeriodById(id int64) (v *RankPeriod, err error) {
o := orm.NewOrm()
v = &RankPeriod{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateNewRankPeriod updates RankPeriod by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankPeriodById(m *RankPeriod, cols []string) (err error) {
o := orm.NewOrm()
m.UpdateAt = time.Now()
if len(cols) > 0 {
cols = append(cols, "UpdateAt")
}
var num int64
if num, err = o.Update(m, cols...); err == nil {
log.Info("Number of records updated in database:", num)
}
return
}
... ...
package models
import (
"fmt"
"oppmg/common/log"
"time"
"github.com/astaxie/beego/orm"
)
type RankRange struct {
Id int64 `orm:"column(id);auto"`
Name string `orm:"column(name);size(50);null" description:"名称"`
CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
RankTypeId int64 `orm:"column(rank_type_id);null" description:""`
Type int8 `orm:"column(type);null" description:"1:所有员工 2:指定员工 3:所有部门 4:指定部门"`
Data string `orm:"column(data);size(1000);null" description:"人员范围数据(type:2,4 有值 对于人员数据/部门数据)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
SortNum int `orm:"column(sort_num)"`
Status int8 `orm:"column(status)"`
}
func (t *RankRange) TableName() string {
return "rank_range"
}
func init() {
orm.RegisterModel(new(RankRange))
}
//1:所有员工 2:指定员工 3:所有部门 4:指定部门
const (
RANK_RANGE_TYPE_EMPLAYEEALL int8 = 1
RANK_RANGE_TYPE_EMPLAYEE int8 = 2
RANK_RANGE_TYPE_DEPARTMENTALL int8 = 3
RANK_RANGE_TYPE_DEPARTMENT int8 = 4
)
// AddRankRange insert a new RankRange into database and returns
// last inserted Id on success.
func AddRankRange(m *RankRange, om ...orm.Ormer) (id int64, err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
m.CreateAt = time.Now()
m.UpdateAt = time.Now()
id, err = o.Insert(m)
return
}
// GetRankRangeById retrieves RankRange by Id. Returns error if
// Id doesn't exist
func GetRankRangeById(id int64) (v *RankRange, err error) {
o := orm.NewOrm()
v = &RankRange{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRankRangeById updates RankRange by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankRangeById(m *RankRange, cols []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
var num int64
m.UpdateAt = time.Now()
if len(cols) > 0 {
cols = append(cols, "UpdateAt")
}
if num, err = o.Update(m, cols...); err == nil {
log.Info("Number of records updated in database:%d", num)
}
return
}
// DeleteRankRange deletes RankRange by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankRange(id int64) (err error) {
o := orm.NewOrm()
v := RankRange{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&RankRange{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
... ...
package models
import (
"github.com/astaxie/beego/orm"
)
type RankRangeData struct {
Id int64 `orm:"column(id);auto"`
RankRangeId int64 `orm:"column(rank_range_id)"`
RangeType int8 `orm:"column(range_type);" description:"类型"`
RelationId int64 `orm:"column(relation_id);"`
RankTypeId int64 `orm:"column(rank_type_id)"`
}
func (t *RankRangeData) TableName() string {
return "rank_range_data"
}
func init() {
orm.RegisterModel(new(RankRangeData))
}
// AddRankRangeData insert a new RankRangeData into database and returns
// last inserted Id on success.
func AddRankRangeDataMulti(m []RankRangeData, om ...orm.Ormer) (successNums int64, err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
successNums, err = o.InsertMulti(20, m)
return
}
// GetRankRangeDataById retrieves RankRangeData by Id. Returns error if
// Id doesn't exist
func GetRankRangeDataById(id int64) (v *RankRangeData, err error) {
o := orm.NewOrm()
v = &RankRangeData{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// DeleteRankRangeData deletes RankRangeData by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankRangeData(id []int64, om orm.Ormer) (err error) {
_, err = om.QueryTable(&RankRangeData{}).
Filter("id__in", id).
Delete()
return err
}
func GetRankRangeDataByRangeId(id int64) ([]RankRangeData, error) {
var (
data = make([]RankRangeData, 0)
err error
)
o := orm.NewOrm()
_, err = o.QueryTable(&RankRangeData{}).
Filter("rank_range_id", id).
All(&data)
if err == orm.ErrNoRows {
return data, nil
}
if err != nil {
return nil, err
}
return data, nil
}
... ...
package models
import (
"fmt"
"time"
"github.com/astaxie/beego/orm"
)
type RankType struct {
Id int64 `orm:"column(id);pk"`
CompanyId int64 `orm:"column(company_id)"`
Name string `orm:"column(name)"`
EnableStatus int8 `orm:"column(enable_status)"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
Type int8 `orm:"column(type)"`
AutoCreate int8 `orm:"column(auto_create)"` //是否自动创建赛季 【0:否】【1:是】
AutoPeriod int `orm:"column(auto_period)"`
}
func (t *RankType) TableName() string {
return "rank_type"
}
func init() {
orm.RegisterModel(new(RankType))
}
//榜单类型
const (
RANK_TYPE_SEASON int8 = 1 //季赛榜
RANK_TYPE_YEAR int8 = 2 //年榜
)
//榜单状态
const (
RANK_STATUS_YES int8 = 2 //启用
RANK_STATUS_NO int8 = 1 //禁用
)
// AddRank insert a new Rank into database and returns
// last inserted Id on success.
func AddRank(m *RankType) (id int64, err error) {
o := orm.NewOrm()
nowTime := time.Now()
m.CreateAt = nowTime
m.UpdateAt = nowTime
id, err = o.Insert(m)
return
}
// GetRankById retrieves Rank by Id. Returns error if
// Id doesn't exist
func GetRankById(id int64) (v *RankType, err error) {
o := orm.NewOrm()
v = &RankType{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRank updates Rank by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankById(m *RankType, cols []string, om ...orm.Ormer) (err error) {
var o orm.Ormer
if len(om) > 0 {
o = om[0]
} else {
o = orm.NewOrm()
}
m.UpdateAt = time.Now()
if len(cols) > 0 {
cols = append(cols, "UpdateAt")
}
var num int64
if num, err = o.Update(m, cols...); err == nil {
fmt.Println("Number of records updated in database:", num)
}
return
}
... ...
... ... @@ -19,6 +19,21 @@ type UserCompany struct {
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
Enable int8 `orm:"column(enable)"`
DeleteAt time.Time `orm:"column(delete_at)"`
OpenId int64 `orm:"column(open_id)" description:"统一用户中心uid"`
Sex int8 `orm:"column(sex)" description:"性别:0保密 1男 2女"`
JobNum string `orm:"column(job_num);size(255)" description:"员工工号"`
Phone string `orm:"column(phone);size(11)" description:"用户手机,登录手机号"`
PrivatePhone string `orm:"column(private_phone);size(11)" description:"私人手机"`
Email string `orm:"column(email);size(255)" description:"邮箱"`
ExtensionNum string `orm:"column(extension_num);size(255)" description:"分机号"`
EntryTime time.Time `orm:"column(entry_time);type(date);null" description:"入职时间"`
Workspace string `orm:"column(workspace);size(255)" description:"工作地点"`
IsBusiness int8 `orm:"column(is_business)" description:"是否开启业务状态 1是 0否"`
Avatar string `orm:"column(avatar);size(255)" description:"头像"`
Remarks string `orm:"column(remarks);size(255)" description:"备注"`
AdminType int8 `orm:"column(admin_type)" description:"1普通用户 2主管理员"`
ChargeStatus int8 `orm:"column(charge_status)" description:"是否为当前公司主管 1 是2 否"`
ExtraText string `orm:"column(extra_text);null" description:"自定义参数数据"`
}
func (t *UserCompany) TableName() string {
... ... @@ -31,6 +46,20 @@ const (
USERCOMPANY_ENABLE_NO int8 = 2 // 无效
)
//是否为当前公司主管 1 是2 否
const (
USERCOMPANY_CHARGE_YES int8 = 1
USERCOMPANY_CHARGE_NO int8 = 2
)
//
// 1普通用户 2主管理员
const (
USERCOMPANY_ADMIN_SUBSET int8 = 1
USERCOMPANY_ADMIN_MAIN int8 = 2
)
func (t *UserCompany) IsEnable() bool {
switch t.Enable {
case USERCOMPANY_ENABLE_YES:
... ... @@ -62,6 +91,17 @@ func GetUserCompanyById(id int64) (v *UserCompany, err error) {
return nil, err
}
func GetUserCompanyByIds(ids []int64) (v []UserCompany, err error) {
if len(ids) == 0 {
return nil, nil
}
o := orm.NewOrm()
_, err = o.QueryTable(&UserCompany{}).
Filter("id__in", ids).
All(&v)
return v, err
}
// AddUserCompany insert a new UserCompany into database and returns
// last inserted Id on success.
func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
... ... @@ -148,8 +188,8 @@ func GetUserCompanyReal(ids []int64) ([]UserCompany, error) {
func GetUserCompanyAll(companyId int64) (v []*UserCompany, err error) {
o := orm.NewOrm()
sql := `select a.*,b.nick_name from (
select id,user_id from user_company where company_id=? and enable=1
)a inner join user b on a.user_id = b.id`
select id,user_id from user_company where company_id=? and enable=1
)a inner join user b on a.user_id = b.id`
if _, err = o.Raw(sql, companyId).QueryRows(&v); err == nil {
return v, nil
}
... ...
... ... @@ -105,3 +105,14 @@ func ExistUserDepart(departid int64, usercompanyid int64) bool {
Exist()
return ok
}
func GetUserDepartment(departId, usercompanyid int64) (*UserDepartment, error) {
m := &UserDepartment{}
o := orm.NewOrm()
err := o.QueryTable(&UserDepartment{}).
Filter("department_id", departId).
Filter("user_company_id", usercompanyid).
Filter("enable_status", USER_DEPARTMENT_ENABLE_YES).
One(m)
return m, err
}
... ...
... ... @@ -8,8 +8,7 @@ import (
)
type UserPosition struct {
Id int64 `orm:"column(id)" description:"唯一键值"`
//UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
Id int64 `orm:"column(id)" description:"唯一键值"`
PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
... ...
package protocol
//ProviderData 成果提供者
type AchievementProvider struct {
UserDepartmentId int64 `json:"user_department_id" orm:"-"` //前端需要的唯一id标识,使用user_department表的id
UserCompanyId int64 `json:"user_company_id" orm:"column(user_company_id)"` //用户的id
NickName string `json:"nick_name" orm:"column(nick_name)"`
DepartmentId int64 `json:"department_id" orm:"column(department_id)" ` //部门id
DepartmentName string `json:"department_name" orm:"column(department_name)"`
UserGraspScore float64 `json:"user_grasp_score" orm:"column(user_grasp_score)"` //把握人得分
}
//AchievementChance 成果的机会列表
type AchievementChance struct {
Id string `json:"id"` //大整数特别处理
Code string `json:"code"`
}
type AchievementImage struct {
Path string `json:"path"`
W int `json:"-"`
H int `json:"-"`
}
//RequestAddAchievement 添加成果
type RequestAddAchievement struct {
ChanceData []AchievementChance `json:"chance_data"`
ChanceTypeId int64 `json:"chance_type_id"` //机会一级分类 chance_type
AuditTemplateId int64 `json:"audit_template_id"` //机会二级分类
DepartmentId int64 `json:"department_id"` //把握人的部门
UserCompanyId int64 `json:"user_company_id"` //把握人的id
GraspScore float64 `json:"grasp_score"` //把握分
UserGraspScore float64 `json:"user_grasp_score"` //把握人总得分
Provider []AchievementProvider `json:"provider"` //机会提供者
SourceContent string `json:"source_content"` //成果描述文本
Images []AchievementImage `json:"image"` //图片
}
//RequestAddAchievement 添加成果
type RequestEditAchievement struct {
AchievementId int64 `json:"achievement_id"`
ChanceData []AchievementChance `json:"chance_data"`
ChanceTypeId int64 `json:"chance_type_id"` //机会一级分类 chance_type
AuditTemplateId int64 `json:"audit_template_id"` //机会二级分类
GraspScore float64 `json:"grasp_score"` //把握分
UserGraspScore float64 `json:"user_grasp_score"` //把握人总得分
SourceContent string `json:"source_content"` //成果描述文本
Provider []AchievementProvider `json:"provider"` //机会提供者
Images []AchievementImage `json:"image"` //图片
}
// ResponseRankSeasonList 赛季列表
type AchievementList struct {
ResponsePageInfo
List []AchievementListItem `json:"lists"`
}
//AchievementListItem 成果列表
type AchievementListItem struct {
Id int64 `json:"id"`
CreateTime string `json:"create_time"`
TypeA string `json:"type_a"`
TypeB string `json:"type_b"`
GraspScore string `json:"grasp_score"`
Status int `json:"status"`
UserGrasp string `json:"user_grasp"`
}
//ResponseAchievementInfo 成果详情
type ResponseAchievementInfo struct {
AchievementId int64 `json:"achievement_id"`
ChanceData []AchievementChance `json:"chance_data"`
ChanceTypeId int64 `json:"chance_type_id"` //机会一级分类 chance_type
AuditTemplateId int64 `json:"audit_template_id"` //机会二级分类
ChanceTypeName string `json:"chance_type_name"` //机会一级分类 chance_type
AuditTemplateName string `json:"audit_template_name"` //机会二级分类
DepartmentId int64 `json:"department_id"` //把握人的部门
DeparmentName string `json:"department_name"`
UserCompanyId int64 `json:"user_company_id"` //把握人的id
NickName string `json:"nick_name"`
UserDepartmentId int64 `json:"user_department_id"` //前端需要的把握人唯一id标识
GraspScore float64 `json:"grasp_score"` //把握分
UserGraspScore float64 `json:"user_grasp_score"` //把握人总得分
Provider []AchievementProvider `json:"provider"` //机会提供者
SourceContent string `json:"source_content"` //成果描述文本
Images []AchievementImage `json:"image"` //图片
CrreateAt string `json:"create_at"`
}
... ...
... ... @@ -271,8 +271,10 @@ type RspAuditList struct {
}
type ChanceFlowLog struct {
Id int64 `json:"id" orm:"column(id)"`
ChanceId string `json:"chance_id" orm:"column(chance_id)"`
CreateAt string `json:"create_at" orm:"column(create_at)"`
Content string `json:"content" orm:"column(content)"`
NickName string `json:"nick_name" orm:"column(nick_name)"`
Code int `json:"code" orm:"column(code)"`
}
... ...
... ... @@ -77,3 +77,37 @@ type ChanceTypeBase struct {
ChanceTypeId int64 `orm:"column(chance_type_id)" json:"chance_type_id"`
Name string `orm:"column(name)" json:"name"`
}
type SelectCompanyUserListItem struct {
Id int64 `json:"id" orm:"column(id)"`
UserCompanyId int64 `json:"user_company_id" orm:"column(user_company_id)"`
NickName string `json:"nick_name" orm:"column(nick_name)"`
DepartmentId int64 `json:"department_id" orm:"column(department_id)"`
DepartmentName string `json:"department_name" orm:"column(department_name)"`
}
//下拉选择公司员工
type SelectCompanyUserList struct {
ResponsePageInfo
List []SelectCompanyUserListItem `json:"lists"`
}
type SelectChanceListItem struct {
Id string `json:"id" orm:"column(id)"`
DepartmentId int64 `json:"deparment_id" orm:"column(department_id)"`
DepartmentName string `json:"department_name" orm:"-"`
ChanceTypeId int `json:"chance_type_id" orm:"column(chance_type_id)"`
ChanceTypeName string `json:"chance_type_name" orm:"-"`
AuditTemplateId int64 `json:"audit_template_id" orm:"column(audit_template_id)"`
AuditTemplateName string `json:"audit_template_name" orm:"-"`
UserId int64 `json:"user_id" orm:"column(user_id)"`
UserName string `json:"user_name" orm:"column(nick_name)"`
Code string `json:"code" orm:"column(code)"`
CreateAt string `json:"create_at" orm:"column(create_at)"`
}
//下拉选择机会
type SelectChanceList struct {
ResponsePageInfo
List []SelectChanceListItem `json:"lists"`
}
... ...
... ... @@ -110,8 +110,8 @@ func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
if x, ok := eRR.(CustomErrParse); ok {
return x.ParseToMessage()
}
return NewMessage("1")
msg = NewMessage("1")
return
}
//BadRequestParam 控制层响应返回
... ...
... ... @@ -36,6 +36,7 @@ var errmessge ErrorMap = map[string]string{
"10028": "请输入正确的验证码",
"10029": "获取验证码失败",
"10080": "无操作权限",
"10111": "获取公司信息失败",
//用户相关
"10031": "无效角色",
... ... @@ -106,6 +107,22 @@ var errmessge ErrorMap = map[string]string{
"12102": "评分规则不符合要求",
//权限配置相关
"10091": "至少选择一个特定部门",
"10101": "赛季周期设置与其他赛季重叠",
"10102": "参与人类型不一致",
"10103": "排行榜名称最多5个字符",
"10104": "赛季名称最多输入20个字符",
"10105": "赛季开始时间必填",
"10106": "赛季结束时间必填",
"10107": "参与范围名称最多输入5个字符",
"10108": "成果一级分类必填",
"10109": "成果来源必填",
"10110": "把握人得分不可大于把握得分",
"10121": "把握得分必填,0.1-100",
"10122": "分配的总分不可大于把握分",
"10123": "排行榜评比项最多4项",
"10124": "公司未启用该模块",
"10125": "参与范围名称不能重复",
}
//错误码转换 ,兼容需要
... ...
package protocol
//获取公司的榜单类型列表
type ResponseRankType struct {
Id int `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
EnableStatus int8 `json:"enable_status" orm:"column(enable_status)"`
Type int8 `json:"type" orm:"column(type)"`
}
// ResponseRankSeasonList 赛季列表
type ResponseRankSeasonList struct {
ResponsePageInfo
List []RankSeasonItem `json:"lists"`
}
type RankSeasonItem struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(season_name)"`
BeginTime string `json:"begin_time" orm:"column(begin_time)"`
EndTime string `json:"end_time" orm:"column(end_time)"`
Status int8 `json:"status" orm:"column(status)"`
}
//RankRangeListItem 赛季参与人列表项
type RankRangeListItem struct {
Id int64 `json:"id" orm:"column(id)"`
Name string `json:"name" orm:"column(name)"`
RangeType int8 `json:"range_type" orm:"column(type)"`
Status int8 `json:"status" orm:"column(status)"`
RangeData string `json:"range_data" orm:"-"`
SortNum int `json:"sort_num"`
}
type RankRangeList []RankRangeListItem
func (a RankRangeList) Len() int { return len(a) }
func (a RankRangeList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a RankRangeList) Less(i, j int) bool {
return a[i].SortNum < a[j].SortNum
}
//ResponseRankRangeInfo 赛季参与人详情
type ResponseRankRangeInfo struct {
Id int64 `json:"id"`
Name string `json:"name"`
RangeType int8 `json:"range_type"`
Relation []RankRangeRelation `json:"relation"`
}
type RankRangeRelation struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//排行榜评比项
type RankItemInfo struct {
ItemName string `json:"item_name"`
ItemKey string `json:"item_key"`
SortNum int `json:"sort_num"`
}
type RankItemAll []RankItemInfo
func (a RankItemAll) Len() int { return len(a) }
func (a RankItemAll) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a RankItemAll) Less(i, j int) bool {
return a[i].SortNum < a[j].SortNum
}
... ...
... ... @@ -75,6 +75,10 @@ func init() {
beego.NSRouter("/user_and_department", &controllers.CommonController{}, "post:SelectorUserAndDepart"),
beego.NSRouter("/default_image", &controllers.CommonController{}, "post:DefaultImage"),
beego.NSRouter("/role/user", &controllers.CommonController{}, "post:SelectorRoleUser"),
beego.NSRouter("/chance_type", &controllers.CommonController{}, "post:SelectorChanceType"),
beego.NSRouter("/user", &controllers.CommonController{}, "post:SelectCompanyUserList"),
beego.NSRouter("/chance", &controllers.CommonController{}, "post:SelectChanceList"),
beego.NSRouter("/department/list", &controllers.CompanyController{}, "post:DepartmentList"),
),
beego.NSNamespace("/template",
beego.NSRouter("/add", &controllers.TemplateController{}, "post:TemplateAdd"),
... ... @@ -102,13 +106,43 @@ func init() {
beego.NSRouter("/list/before", &controllers.AuditController{}, "post:AuditListBefore"),
beego.NSRouter("/info", &controllers.AuditController{}, "post:AuditInfo"),
beego.NSRouter("/allow_forbid", &controllers.AuditController{}, "post:AllowForbidAudit"),
beego.NSRouter("/revise/info", &controllers.AuditController{}, "post:GetChanceReviseLog"),
),
beego.NSNamespace("/rank",
beego.NSRouter("/type/list", &controllers.RankController{}, "post:GetRankType"),
beego.NSRouter("/type/edit", &controllers.RankController{}, "post:EditRankType"),
beego.NSRouter("/type/forbid_allow", &controllers.RankController{}, "post:RankTypeForbidAllow"),
beego.NSRouter("/type/config_set", &controllers.RankController{}, "post:RankTypeConfigSet"),
beego.NSRouter("/type/config_show", &controllers.RankController{}, "post:RankTypeConfigShow"),
beego.NSRouter("/season/add", &controllers.RankController{}, "post:RankSeasonAdd"),
beego.NSRouter("/season/list", &controllers.RankController{}, "post:RankSeasonList"),
beego.NSRouter("/season/edit", &controllers.RankController{}, "post:RankSeasonEdit"),
beego.NSRouter("/range/list", &controllers.RankController{}, "post:RankRangeList"),
beego.NSRouter("/range/edit", &controllers.RankController{}, "post:RankRangeEdit"),
beego.NSRouter("/range/add", &controllers.RankController{}, "post:RankRangeAdd"),
beego.NSRouter("/range/forbid_allow", &controllers.RankController{}, "post:RankRangeForbidAllow"),
beego.NSRouter("/range/info", &controllers.RankController{}, "post:RankRangeInfo"),
beego.NSRouter("/range/sort", &controllers.RankController{}, "post:RankRangeSort"),
beego.NSRouter("/range/move", &controllers.RankController{}, "post:RankRangeMove"),
beego.NSRouter("/item/list", &controllers.RankController{}, "post:RankItemList"),
beego.NSRouter("/item/edit", &controllers.RankController{}, "post:RankItemEdit"),
),
beego.NSNamespace("/achievement",
beego.NSRouter("/list", &controllers.AchievementController{}, "post:AchievementList"),
beego.NSRouter("/add", &controllers.AchievementController{}, "post:AddAchievement"),
beego.NSRouter("/edit", &controllers.AchievementController{}, "post:EditAchievement"),
beego.NSRouter("/info", &controllers.AchievementController{}, "post:AchievementInfo"),
beego.NSRouter("/delete", &controllers.AchievementController{}, "post:DeleteAchievement"),
beego.NSRouter("/forbid_allow", &controllers.AchievementController{}, "post:ForbidAllowAchievement"),
beego.NSRouter("/remain/score", &controllers.AchievementController{}, "post:AchievementScoreRemain"),
),
)
nsAuth := beego.NewNamespace("/auth",
beego.NSBefore(middleware.AllowOption),
beego.NSBefore(middleware.LogRequestData),
beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"),
beego.NSRouter("/login_account", &controllers.AuthController{}, "post:Login"),
beego.NSRouter("/login", &controllers.AuthController{}, "post:LoginSecretKey"),
beego.NSRouter("/startCaptcha", &controllers.AuthController{}, "post:RegisterGeetest"),
beego.NSRouter("/verifyCaptcha", &controllers.AuthController{}, "post:ValidateGeetest"),
beego.NSRouter("/login_sms", &controllers.AuthController{}, "post:LoginSms"),
... ... @@ -118,9 +152,9 @@ func init() {
)
nsUcenter := beego.NewNamespace("/ucenter",
beego.NSBefore(middleware.LogRequestData),
beego.NSRouter("/company", &controllers.CompanyController{}, "post:InitCompany"),
//beego.NSRouter("/company", &controllers.CompanyController{}, "post:InitCompany"),(废弃)
beego.NSRouter("/company/info", &controllers.CompanyController{}, "post:GetCompanyForUCenter"),
beego.NSRouter("/company/edit", &controllers.CompanyController{}, "post:EditCompanyForUCenter"),
//beego.NSRouter("/company/edit", &controllers.CompanyController{}, "post:EditCompanyForUCenter"),(废弃)
beego.NSRouter("/user/revoke", &controllers.CompanyController{}, "post:UserRevoke"),
beego.NSRouter("/user/changePhone", &controllers.CompanyController{}, "post:UserChangePhone"),
beego.NSRouter("/company/allow_forbid", &controllers.CompanyController{}, "post:AllowForidCompanyForUCenter"),
... ... @@ -129,6 +163,7 @@ func init() {
beego.AddNamespace(nsV1)
beego.AddNamespace(nsAuth)
beego.AddNamespace(nsUcenter)
beego.SetStaticPath("/log", beego.AppConfig.String("log_filename"))
beego.SetStaticPath("/file/opp", beego.AppConfig.String("file_save_path"))
beego.SetStaticPath("/static", "./static")
... ...
package routers
import (
"oppmg/controllers"
"oppmg/middleware"
"github.com/astaxie/beego"
)
//从公司管理平台同步数据用
func init() {
//路由
nsPlatform := beego.NewNamespace("/platform",
beego.NSBefore(middleware.LogRequestData),
beego.NSRouter("/action", &controllers.PlatformController{}, "post:UpdateData"),
beego.NSRouter("/admins_change", &controllers.PlatformController{}, "post:CompanyAdminChance"),
)
beego.AddNamespace(nsPlatform)
}
... ...
package routers
import (
"oppmg/services/crontab"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
)
func init() {
testNs := beego.NewNamespace("/test",
beego.NSCond(func(ctx *context.Context) bool {
if beego.BConfig.RunMode == "prod" {
return false
}
return true
}),
beego.NSGet("/create_rank_peroid",
func(ctx *context.Context) {
crontab.AutoCreateRankPeriod()
}),
)
beego.AddNamespace(testNs)
}
... ...
package achievement
import (
"encoding/json"
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/utils"
"strconv"
"time"
"github.com/astaxie/beego/orm"
)
//addAchievementProvider 操作achievement_provider 成果提供人表
func addAchievementProvider(addData []protocol.AchievementProvider, achievementId int64, om orm.Ormer) error {
var (
providerList []models.AchievementProvider
err error
)
nowTime := time.Now()
for _, v := range addData {
m := models.AchievementProvider{
AchievementId: achievementId,
UserCompanyId: v.UserCompanyId,
UserGraspScore: v.UserGraspScore,
DepartmentId: v.DepartmentId,
CreateAt: nowTime,
}
providerList = append(providerList, m)
}
_, err = om.InsertMulti(10, providerList)
return err
}
//addAchievementChance 操作 achievement_chance 机会来源表
func addAchievementChance(addData []protocol.AchievementChance, achievementId int64, om orm.Ormer) error {
var (
chanceList []models.AchievementChance
err error
)
nowTime := time.Now()
for _, v := range addData {
chanceId, _ := strconv.ParseInt(v.Id, 10, 64)
m := models.AchievementChance{
AchievementId: achievementId,
ChanceId: chanceId,
ChanceCode: v.Code,
CreateAt: nowTime,
}
chanceList = append(chanceList, m)
}
_, err = om.InsertMulti(10, chanceList)
return err
}
//计算剩余的分数
func achievementGraspScoreRemain(graspScore, userGraspScore, providerScoreAll float64) float64 {
return graspScore - userGraspScore - providerScoreAll
}
//AddAchievement 添加成果
func AddAchievement(addData *protocol.RequestAddAchievement, companyid int64) error {
var (
achievementData *models.Achievement
err error
)
nowTime := time.Now()
var providerScore float64
for _, v := range addData.Provider {
providerScore += v.UserGraspScore
}
scoreRemain := achievementGraspScoreRemain(addData.GraspScore, addData.UserGraspScore, providerScore)
achievementData = &models.Achievement{
CompanyId: companyid,
DepartmentId: addData.DepartmentId,
UserCompanyId: addData.UserCompanyId,
ChanceTypeId: addData.ChanceTypeId,
AuditTemplateId: addData.AuditTemplateId,
SourceContent: addData.SourceContent,
GraspScore: addData.GraspScore,
UserGraspScore: addData.UserGraspScore,
CreateAt: nowTime,
UpdateAt: nowTime,
Status: models.ACHIEVEMENT_STATUS_YES,
GraspScoreRemain: scoreRemain,
}
if imgData, err := json.Marshal(addData.Images); err == nil {
achievementData.Images = string(imgData)
} else {
achievementData.Images = "[]"
}
o := orm.NewOrm()
o.Begin()
//操作achievement 成果表
achievementId, err := models.AddAchievement(achievementData, o)
if err != nil {
log.Error("添加Achievement数据失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
//操作 achievement_chance 机会来源表
err = addAchievementChance(addData.ChanceData, achievementId, o)
if err != nil {
log.Error("添加achievement_chance失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
//操作achievement_provider 成果提供人表
if len(addData.Provider) > 0 {
err = addAchievementProvider(addData.Provider, achievementId, o)
if err != nil {
log.Error("添加achievement_provider失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
}
//操作achievement_score福利池数据
err = models.IncreaseAchevementScore(companyid, scoreRemain, o)
if err != nil {
o.Rollback()
log.Error("更新福利池分数achevement_score失败")
return protocol.NewErrWithMessage("1")
}
o.Commit()
return nil
}
func EditAchievement(editData *protocol.RequestEditAchievement, companyid int64) error {
var (
achievementData *models.Achievement
err error
)
achievementData, err = models.GetAchievementById(editData.AchievementId)
if err != nil {
log.Error("获取achievement失败:%s", err)
return protocol.NewErrWithMessage("1")
}
var (
oldRemain float64
newRamain float64
providerScore float64
)
oldRemain = achievementData.GraspScoreRemain
for _, v := range editData.Provider {
providerScore += v.UserGraspScore
}
newRamain = achievementGraspScoreRemain(editData.GraspScore, editData.UserGraspScore, providerScore)
nowTime := time.Now()
achievementData.UpdateAt = nowTime
achievementData.ChanceTypeId = editData.ChanceTypeId
achievementData.AuditTemplateId = editData.AuditTemplateId
achievementData.SourceContent = editData.SourceContent
achievementData.GraspScore = editData.GraspScore
achievementData.UserGraspScore = editData.UserGraspScore
achievementData.GraspScoreRemain = newRamain
if imgData, err := json.Marshal(editData.Images); err == nil {
achievementData.Images = string(imgData)
} else {
achievementData.Images = "[]"
}
cols := []string{
"UpdateAt", "ChanceTypeId", "AuditTemplateId", "SourceContent", "GraspScore",
"UserGraspScore", "GraspScoreRemain", "Images",
}
o := orm.NewOrm()
o.Begin()
//更新Achievement 数据
err = models.UpdateAchievementById(achievementData, cols, o)
if err != nil {
o.Rollback()
log.Info("更新Achievement数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
//删除achievement_chance旧数据
_, err = o.QueryTable(&models.AchievementChance{}).
Filter("achievement_id", editData.AchievementId).
Delete()
if err != nil {
o.Rollback()
log.Info("删除achievement_chance数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
err = addAchievementChance(editData.ChanceData, achievementData.Id, o)
if err != nil {
log.Error("添加achievement_chance失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
//删除提供者分数
_, err = o.QueryTable(&models.AchievementProvider{}).
Filter("achievement_id", editData.AchievementId).
Delete()
if err != nil {
o.Rollback()
log.Info("删除achievement_provider数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
if len(editData.Provider) > 0 {
err = addAchievementProvider(editData.Provider, achievementData.Id, o)
if err != nil {
log.Error("添加achievement_provider失败:%s", err)
o.Rollback()
return protocol.NewErrWithMessage("1")
}
}
err = models.IncreaseAchevementScore(companyid, newRamain-oldRemain, o)
if err != nil {
o.Rollback()
log.Error("更新福利池分数achevement_score失败")
return protocol.NewErrWithMessage("1")
}
o.Commit()
return nil
}
func GetAchievementList(pageIndex int, pageSize int, companyId int64, status int) protocol.AchievementList {
dataSql := `SELECT a.id,a.chance_type_id,a.grasp_score,user_company_id
,a.create_at,a.status,a.audit_template_id
FROM achievement AS a WHERE a.company_id=? `
countSql := ` SELECT COUNT(*) FROM achievement AS a WHERE a.company_id=? `
pageStart := (pageIndex - 1) * pageSize
cond := []interface{}{companyId}
if status > 0 {
dataSql += ` AND a.status=? `
countSql += ` AND a.status=? `
cond = append(cond, status)
} else {
dataSql += ` AND a.status>0 `
countSql += ` AND a.status>0 `
}
dataSql = fmt.Sprintf("%s ORDER BY a.create_at DESC LIMIT %d,%d", dataSql, pageStart, pageSize)
type SqlData struct {
Id int64 `orm:"column(id)"`
ChanceTypeId int `orm:"column(chance_type_id)"`
GraspScore string `orm:"column(grasp_score)"`
UserCompanyId int64 `orm:"column(user_company_id)"`
CreateAt string `orm:"column(create_at)"`
Status int `orm:"column(status)"`
AuditTemplateId int64 `orm:"column(audit_template_id)"`
}
var (
sqldata []SqlData
cnt int
err error
)
rspData := protocol.AchievementList{
ResponsePageInfo: protocol.ResponsePageInfo{
TotalPage: 0, CurrentPage: pageIndex,
},
List: make([]protocol.AchievementListItem, 0),
}
err = utils.ExecuteQueryOne(&cnt, countSql, cond...)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
return rspData
}
rspData.TotalPage = cnt
if cnt == 0 {
return rspData
}
err = utils.ExecuteQueryAll(&sqldata, dataSql, cond...)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
return rspData
}
for i := range sqldata {
m := protocol.AchievementListItem{
Id: sqldata[i].Id,
CreateTime: sqldata[i].CreateAt,
GraspScore: sqldata[i].GraspScore,
Status: sqldata[i].Status,
}
var (
chanceTypeA *models.ChanceType //一级分类
chanceTypeB *models.AuditTemplate //二级分类
usercompany *models.UserCompany
err error
)
chanceTypeA, err = models.GetChanceTypeById(sqldata[i].ChanceTypeId)
if err == nil {
m.TypeA = chanceTypeA.Name
} else {
log.Error(err.Error())
}
chanceTypeB, err = models.GetAuditTemplateById(sqldata[i].AuditTemplateId)
if err == nil {
m.TypeB = chanceTypeB.Name
} else {
log.Error(err.Error())
}
usercompany, err = models.GetUserCompanyById(sqldata[i].UserCompanyId)
if err == nil {
usr, err := models.GetUserById(usercompany.UserId)
if err == nil {
m.UserGrasp = usr.NickName
} else {
log.Error(err.Error())
}
} else {
log.Error(err.Error())
}
rspData.List = append(rspData.List, m)
}
return rspData
}
func GetAchievementInfo(id int64, companyId int64) *protocol.ResponseAchievementInfo {
rspData := &protocol.ResponseAchievementInfo{
Images: make([]protocol.AchievementImage, 0),
Provider: make([]protocol.AchievementProvider, 0),
ChanceData: make([]protocol.AchievementChance, 0),
}
var (
achievementData *models.Achievement
chanceData []models.AchievementChance
err error
)
achievementData, err = models.GetAchievementById(id)
if err == nil {
rspData.AchievementId = achievementData.Id
rspData.AuditTemplateId = achievementData.AuditTemplateId
rspData.ChanceTypeId = achievementData.ChanceTypeId
rspData.DepartmentId = achievementData.DepartmentId
rspData.SourceContent = achievementData.SourceContent
img := make([]protocol.AchievementImage, 0)
json.Unmarshal([]byte(achievementData.Images), &img)
rspData.Images = img
rspData.GraspScore = achievementData.GraspScore
rspData.UserGraspScore = achievementData.UserGraspScore
rspData.UserCompanyId = achievementData.UserCompanyId
rspData.CrreateAt = achievementData.CreateAt.Format("2006-01-02 15:04:05")
ud, err := models.GetUserDepartment(rspData.DepartmentId, rspData.UserCompanyId)
if err == nil {
rspData.UserDepartmentId = ud.Id
}
} else {
log.Error("获取achievement数据失败:%s", err)
}
chanceData, err = models.GetAchievementChanceByAchieve(id)
if err == nil {
for _, v := range chanceData {
m := protocol.AchievementChance{
Id: fmt.Sprint(v.ChanceId),
Code: v.ChanceCode,
}
rspData.ChanceData = append(rspData.ChanceData, m)
}
} else {
log.Error("获取achievement_chance数据失败:%s", err)
}
rspData.Provider = getAchievementProvider(rspData.AchievementId)
var (
usercompanyData *models.UserCompany
departmentData *models.Department
chaneTypeData *models.ChanceType
auditTempData *models.AuditTemplate
)
departmentData, err = models.GetDepartmentById(rspData.DepartmentId)
if err == nil {
rspData.DepartmentId = departmentData.Id
rspData.DeparmentName = departmentData.Name
}
usercompanyData, err = models.GetUserCompanyById(rspData.UserCompanyId)
if err == nil {
rspData.UserCompanyId = usercompanyData.Id
rspData.NickName = usercompanyData.NickName
}
chaneTypeData, err = models.GetChanceTypeById(int(rspData.ChanceTypeId))
if err == nil {
rspData.ChanceTypeId = int64(chaneTypeData.Id)
rspData.ChanceTypeName = chaneTypeData.Name
}
auditTempData, err = models.GetAuditTemplateById(rspData.AuditTemplateId)
if err == nil {
rspData.AuditTemplateId = auditTempData.Id
rspData.AuditTemplateName = auditTempData.Name
}
return rspData
}
func getAchievementProvider(achievementId int64) []protocol.AchievementProvider {
sql := `SELECT a.achievement_id,a.department_id,a.user_company_id,a.user_grasp_score
,b.nick_name,c.name As department_name
FROM achievement_provider AS a
LEFT JOIN user_company AS b on a.user_company_id = b.id
LEFT JOIN department AS c ON a.department_id = c.id
WHERE achievement_id=? `
var (
err error
sqldata = make([]protocol.AchievementProvider, 0)
)
err = utils.ExecuteQueryAll(&sqldata, sql, achievementId)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
}
for i := range sqldata {
userDepartment, err := models.GetUserDepartment(sqldata[i].DepartmentId, sqldata[i].UserCompanyId)
if err == nil {
sqldata[i].UserDepartmentId = userDepartment.Id
}
}
return sqldata
}
... ...
... ... @@ -98,33 +98,7 @@ func buildSqlForAuditList(usercompanyid int64, companyid int64, userid int64) st
unionsql = sql1 + " UNION " + sql2
return fmt.Sprintf(allsql, unionsql)
}
// //获取权限
// if ok := redisdata.ExistUserPermission(userid); !ok {
// //尝试重数据库获取
// log.Debug("从数据库读取权限")
// permissionMap, err := serverabc.GetUserPermission(usercompanyid, serverabc.M_SYSTEM_OPPORTUNITY)
// if err != nil {
// log.Debug("从数据库未获得对应权限 :%s", err)
// unionsql = sql1 + " UNION " + sql2
// return fmt.Sprintf(allsql, unionsql)
// }
// if v, ok := permissionMap[serverabc.M_SYSTEM_OPPORTUNITY]; !ok {
// unionsql = sql1 + " UNION " + sql2
// return fmt.Sprintf(allsql, unionsql)
// } else {
// permissionObject = v
// }
// } else {
// //使用缓存
// log.Debug("从缓存读取权限")
// permissionObject, err = redisdata.GetUserPermission(userid, serverabc.M_SYSTEM_OPPORTUNITY)
// if err != nil {
// log.Debug("从缓存未获得对应权限 :%s", err)
// unionsql = sql1 + " UNION " + sql2
// return fmt.Sprintf(allsql, unionsql)
// }
// }
// -------------------------
var (
usrPermission *serverabc.OptionOpportunity
ok bool
... ... @@ -451,12 +425,17 @@ func getAuditFlowLog(chanceid int64) ([]protocol.ChanceFlowLog, error) {
flowLogs = make([]protocol.ChanceFlowLog, 0)
err error
)
const datasql string = `SELECT a.chance_id,a.content,a.create_at,c.nick_name
const datasql string = `SELECT a.id, a.chance_id,a.content,a.create_at,c.nick_name,a.code
FROM audit_flow_log AS a
LEFT JOIN user_company AS b ON a.approve_user_id=b.id
LEFT JOIN user AS c ON b.user_id = c.id
WHERE chance_id =? `
err = utils.ExecuteQueryAll(&flowLogs, datasql, chanceid)
for i := range flowLogs {
if flowLogs[i].Code == 6 { //系统自动审核通过
flowLogs[i].NickName = "系统"
}
}
return flowLogs, err
}
... ... @@ -551,3 +530,50 @@ func GetPermissionInAuditPage(userid int64, companyid int64) serverabc.OptionOpp
}
return option
}
type ChanceReviseLogInfo struct {
UserName string `json:"user_name"`
UserComapnyId int64 `json:"user_company_id"`
CreateTime string `json:"create_time"`
models.ChanceReviseLogData
}
//GetChanceReviseLog 获取对机会的操作记录,补充机会的详情
func GetChanceReviseLog(flowLogId int64, chanceId int64, companyId int64) (*ChanceReviseLogInfo, error) {
var (
reviseLog *models.ChanceReviseLog
reviseLogData *models.ChanceReviseLogData
usercompanyData *models.UserCompany
chanceData *models.Chance
err error
)
chanceData, err = models.GetChanceById(chanceId)
if err != nil {
log.Error("获取机会数据chance失败:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if chanceData.CompanyId != companyId {
log.Error("机会的公司不匹配")
}
reviseLog, reviseLogData, err = models.GetChanceReviseLogData(flowLogId)
if err != nil {
log.Error("获取chance_revise_log失败,err:%s", err)
return nil, protocol.NewErrWithMessage("1")
}
if reviseLog.ChanceId != chanceId {
log.Error("日志与机会不匹配")
return nil, protocol.NewErrWithMessage("1")
}
rspData := &ChanceReviseLogInfo{
UserComapnyId: reviseLog.UserCompanyId,
CreateTime: reviseLog.CreateAt.Format("2006-01-02 15:04:05"),
ChanceReviseLogData: *reviseLogData,
}
usercompanyData, err = models.GetUserCompanyById(reviseLog.UserCompanyId)
if err != nil {
log.Error("获取用户数据user_company失败;%s", err)
} else {
rspData.UserName = usercompanyData.NickName
}
return rspData, nil
}
... ...
... ... @@ -505,6 +505,7 @@ func TemplateDelete(uid, companyId int64, request *protocol.TemplateDeleteReques
template *models.AuditTemplate
num int
sql1 string = `select count(0) from chance where audit_template_id = ? limit 1`
sql2 string = `select count(0) from achievement where audit_template_id = ? and status in (1,2)`
)
if template, err = models.GetAuditTemplateById(int64(request.TemplateId)); err != nil {
log.Error(err.Error())
... ... @@ -519,6 +520,11 @@ func TemplateDelete(uid, companyId int64, request *protocol.TemplateDeleteReques
err = protocol.NewErrWithMessage("10062")
return
}
//3.判断是否有对应发布的成果
if err = utils.ExecuteQueryOne(&num, sql2, request.TemplateId); err == nil && num > 0 {
err = protocol.NewErrWithMessage("10062")
return
}
//删除数据
if err = models.DeleteAuditTemplate(int64(request.TemplateId)); err != nil {
... ... @@ -643,6 +649,7 @@ func TemplateDeleteCategory(uid, companyId int64, request *protocol.TemplateDele
num int
sql1 string = `select count(0) from audit_template where chance_type_id =? limit 1`
sql2 string = `select count(0) from chance where chance_type_id = ? limit 1`
sql3 string = `select count(0) from achievement where chance_type_id = ? and status in (1,2)`
)
rsp = &protocol.TemplateDeleteCategoryResponse{}
if chanceType, err = models.GetChanceTypeById(request.ChanceTypeId); err != nil {
... ... @@ -667,6 +674,11 @@ func TemplateDeleteCategory(uid, companyId int64, request *protocol.TemplateDele
err = protocol.NewErrWithMessage("10062")
return
}
//3.判断是否有对应发布的成果
if err = utils.ExecuteQueryOne(&num, sql3, request.ChanceTypeId); err == nil && num > 0 {
err = protocol.NewErrWithMessage("10062")
return
}
//删除数据
if err = models.DeleteChanceType(request.ChanceTypeId); err != nil {
... ...
... ... @@ -571,3 +571,63 @@ func ValidUserPermission(urlPath string, userid int64, companyid int64) bool {
}
return false
}
//LoginAuthBySecretKey 使用秘钥进行登录
func LoginAuthBySecretKey(secretKey string) (protocol.LoginAuthToken, error) {
var (
err error
logintoken protocol.LoginAuthToken
usercompanyid int64
userdata *models.User
companyData *models.Company
)
var uclientReturn *ucenter.ResponseLogin
uclientReturn, err = ucenter.RequestUCenterLoginBySecret(secretKey)
if err != nil {
return logintoken, protocol.ErrWithMessage{
ErrorCode: protocol.ErrorCode{
Errno: "-1",
Errmsg: uclientReturn.Msg,
},
}
}
userdata, err = models.GetUserByPhone(uclientReturn.Data.Phone)
if err != nil {
log.Debug("GetUserByPhone(%d) err:%s", uclientReturn.Data.Phone, err)
return logintoken, protocol.NewErrWithMessage("10021")
}
companyData, err = models.GetCompanyByUCenter(uclientReturn.Data.CompanyId)
if err != nil {
log.Error("获取company数据失败:%s", err)
return logintoken, protocol.NewErrWithMessage("10111")
}
if companyData.Enable == models.COMPANY_ENABLE_NO {
log.Error("公司未启用机会模块")
return logintoken, protocol.NewErrWithMessage("10124")
}
ucompany, err := models.GetUserCompanyBy(userdata.Id, companyData.Id)
if err != nil {
log.Error("获取user_company失败;%s", err)
return logintoken, protocol.NewErrWithMessage("10022")
}
logintoken, _ = GenerateAuthToken(userdata.Id, companyData.Id, ucompany.Id)
//更新用户数据
userdata.Accid = uclientReturn.Data.Accid
userdata.Icon = uclientReturn.Data.Avatar
userdata.ImToken = uclientReturn.Data.Imtoken
userdata.NickName = uclientReturn.Data.NickName
userdata.CsAccount = uclientReturn.Data.CustomerAccount
userdata.LastLoginTime = time.Now()
err = models.UpdateUserById(userdata, []string{"Accid", "Icon", "ImToken", "NickName", "CsAccount", "LastLoginTime"})
if err != nil {
log.Error("更新用户user数据失败:%s", err)
}
ucompany.NickName = uclientReturn.Data.NickName
err = models.UpdateUserCompanyById(ucompany, []string{"NickName"})
if err != nil {
log.Error("更新用户user_company数据失败:%s", err)
}
InitPermission(usercompanyid, userdata.Id)
return logintoken, err
}
... ...
... ... @@ -182,3 +182,136 @@ func SeleteGetChanceTypeList(companyid int64) []protocol.ChanceTypeBase {
}
return data
}
func SelectCompanyUserList(pageIndex int, pageSize int, companyid int64, userName string) protocol.SelectCompanyUserList {
datasql := `SELECT b.id,a.id as user_company_id,d.nick_name,c.name AS department_name,c.id AS department_id
FROM user_company AS a
LEFT JOIN user_department AS b ON a.id = b.user_company_id AND b.enable_status=1
LEFT JOIN department AS c ON b.department_id = c.id
LEFT JOIN user AS d ON a.user_id = d.id
WHERE a.delete_at = 0 AND a.enable=1 AND a.company_id = ? `
countsql := `SELECT count(*)
FROM user_company AS a
LEFT JOIN user_department AS b ON a.id = b.user_company_id AND b.enable_status=1
LEFT JOIN department AS c ON b.department_id = c.id
LEFT JOIN user AS d ON a.user_id = d.id
WHERE a.delete_at = 0 AND a.enable=1 AND a.company_id =? `
cond := []interface{}{companyid}
where := ""
if len(userName) > 0 {
where += ` And d.nick_name like ? `
cond = append(cond, "%"+userName+"%")
}
datasql += where
countsql += where
pageStart := (pageIndex - 1) * pageSize
datasql += fmt.Sprintf(` limit %d,%d `, pageStart, pageSize)
var (
err error
cnt int
sqlData = make([]protocol.SelectCompanyUserListItem, 0)
)
rspData := protocol.SelectCompanyUserList{
ResponsePageInfo: protocol.ResponsePageInfo{
TotalPage: 0, CurrentPage: pageIndex,
},
List: make([]protocol.SelectCompanyUserListItem, 0),
}
err = utils.ExecuteQueryOne(&cnt, countsql, cond...)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
return rspData
}
if cnt == 0 {
return rspData
}
err = utils.ExecuteQueryAll(&sqlData, datasql, cond...)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
return rspData
}
rspData.List = sqlData
rspData.TotalPage = cnt
return rspData
}
func SelectChanceList(pageIndex int, pageSize int, companyid int64, searchType int, chanceCode string) protocol.SelectChanceList {
datasql := ` SELECT a.id ,a.department_id,a.chance_type_id,a.audit_template_id
,a.user_id,a.create_at,a.code,c.nick_name
FROM chance as a
LEFT JOIN user_company AS b ON a.user_id = b.id
JOIN user AS c ON b.user_id = c.id
WHERE a.company_id =? AND a.status=1 AND a.enable_status=1 AND a.review_status=3 `
countsql := `SELECT count(*)
FROM chance as a
LEFT JOIN user_company AS b ON a.user_id = b.id
JOIN user AS c ON b.user_id = c.id
WHERE a.company_id =? AND a.status=1 AND a.enable_status=1 AND a.review_status=3 `
cond := []interface{}{companyid}
where := ""
if len(chanceCode) > 0 {
switch searchType {
case 1:
//根据机会编码
where += ` And a.code like ? `
cond = append(cond, "%"+chanceCode+"%")
case 2:
//根据提交人
where += ` And c.nick_name like ? `
cond = append(cond, "%"+chanceCode+"%")
}
}
datasql += where
countsql += where
pageStart := (pageIndex - 1) * pageSize
datasql += fmt.Sprintf(` ORDER BY create_at DESC limit %d,%d `, pageStart, pageSize)
var (
err error
cnt int
sqldata []protocol.SelectChanceListItem
)
rspData := protocol.SelectChanceList{
ResponsePageInfo: protocol.ResponsePageInfo{
TotalPage: 0, CurrentPage: pageIndex,
},
List: make([]protocol.SelectChanceListItem, 0),
}
err = utils.ExecuteQueryOne(&cnt, countsql, cond...)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
return rspData
}
if cnt == 0 {
return rspData
}
err = utils.ExecuteQueryAll(&sqldata, datasql, cond...)
if err != nil {
log.Error("SQL EXECUTE ERR:%s", err)
return rspData
}
for i, v := range sqldata {
d, err := models.GetDepartmentById(v.DepartmentId)
if err == nil {
sqldata[i].DepartmentName = d.Name
}
ct, err := models.GetChanceTypeById(v.ChanceTypeId)
if err == nil {
sqldata[i].ChanceTypeName = ct.Name
}
at, err := models.GetAuditTemplateById(v.AuditTemplateId)
if err == nil {
sqldata[i].AuditTemplateName = at.Name
}
uc, err := models.GetUserCompanyById(v.UserId)
if err == nil {
u, err := models.GetUserById(uc.UserId)
if err == nil {
sqldata[i].UserName = u.NickName
}
}
}
rspData.List = sqldata
rspData.TotalPage = cnt
return rspData
}
... ...
... ... @@ -116,6 +116,7 @@ func initCompany(centerCompany protocol.CenterCompanyInfo, admininfo *models.Use
}
} else if err == orm.ErrNoRows {
newCompany = &models.Company{
Id: centerCompany.CompanyId,
Name: centerCompany.CompanyName,
AdminId: admininfo.Id,
UserCenterId: centerCompany.CompanyId,
... ... @@ -209,8 +210,11 @@ func initUserCompany(newcompany *models.Company, newuser *models.User, o orm.Orm
}
} else if err == orm.ErrNoRows {
uc = &models.UserCompany{
UserId: newuser.Id,
CompanyId: newcompany.Id,
UserId: newuser.Id,
CompanyId: newcompany.Id,
OpenId: newuser.UserCenterId,
Enable: models.USERCOMPANY_ENABLE_YES,
ChargeStatus: models.USERCOMPANY_CHARGE_YES,
}
_, err = models.AddUserCompany(uc, o)
if err != nil {
... ...
... ... @@ -388,8 +388,8 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs
}
const dataSql string = `SELECT a.user_company_id,b.user_id
FROM user_department AS a
LEFT JOIN user_company AS b ON a.user_company_id = b.id
WHERE a.department_id=? AND b.delete_at=0 AND a.enable_status = 1 `
JOIN user_company AS b ON a.user_company_id = b.id
WHERE a.department_id=? AND b.delete_at=0 AND a.enable_status = 1 AND b.enable = 1 `
err = utils.ExecuteQueryAll(&returnData, dataSql, department.Id)
if err != nil {
... ...
package crontab
import (
"github.com/astaxie/beego/toolbox"
)
//定时任务
func Run() {
//自动创建赛季 每隔一小时执行一次
taskRankPeriod := toolbox.NewTask("AutoCreateRankPeriod", " 0 1 * * * *", AutoCreateRankPeriod)
toolbox.AddTask("AutoCreateRankPeriod", taskRankPeriod)
toolbox.StartTask()
}
... ...
package crontab
import (
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/utils"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
//rankTypeAutoPeriod 榜单配置:自动创建赛季
type RankTypeAutoPeriod struct {
RankTypeId int64 `orm:"column(rank_type_id)"`
CompanyId int64 `orm:"column(company_id)"`
AutoPeriod int64 `orm:"column(auto_period)"`
CreateTime int64 `orm:"column(create_time)"`
RankType int8 `orm:"column(rank_type)`
}
//
type RankPeriodEndTime struct {
RankTypeId int64 `orm:"column(rank_type_id)"`
EndTime time.Time `orm:"column(end_time)"`
}
func AutoCreateRankPeriod() error {
log.Info("计划任务:【自动创建赛季】")
//获取需要执行自动创建的榜单记录
sql1 := `SELECT a.id AS rank_type_id,a.type AS rank_type,a.auto_period,UNIX_TIMESTAMP(a.create_at) AS create_time
,a.company_id
FROM rank_type AS a
JOIN company AS b ON a.company_id=b.id AND b.enable=1 AND b.delete_at=0
WHERE a.auto_create = 1 AND a.auto_period>0
AND NOT EXISTS(
SELECT 1 FROM rank_period AS c WHERE a.id=c.rank_type_id AND c.status<2
)
AND UNIX_TIMESTAMP(a.create_at)>?
LIMIT 1000`
//获取自动创建赛季时需要的开始时间
sql2 := `SELECT a.rank_type_id,MAX(a.end_time) AS end_time
FROM rank_period AS a
WHERE a.status = 2 AND a.rank_type_id IN (%s)
GROUP BY a.rank_type_id `
var (
rankTypeCreateAt int64
err error
)
o := orm.NewOrm()
LOOP0:
for {
var (
rankTypeList []RankTypeAutoPeriod
)
log.Info("【自动创建赛季】,获取需要执行自动创建的榜单记录")
err = utils.ExecuteQueryAll(&rankTypeList, sql1, rankTypeCreateAt)
if err != nil {
log.Error("【自动创建赛季】,获取需要执行自动创建的榜单记录失败,err:%s", err)
break LOOP0
}
if len(rankTypeList) == 0 {
log.Info("【自动创建赛季】,获取需要执行自动创建的榜单记录数0,结束任务")
break LOOP0
}
log.Info("【自动创建赛季】,获取需要执行自动创建的榜单记录数%d", len(rankTypeList))
var rankTypeIds []string
for i := range rankTypeList {
rankTypeIds = append(rankTypeIds, fmt.Sprintf("%d", rankTypeList[i].RankTypeId))
rankTypeCreateAt = rankTypeList[i].CreateTime
}
log.Info("【自动创建赛季】,获取自动创建赛季时需要的开始时间")
runsql2 := fmt.Sprintf(sql2, strings.Join(rankTypeIds, ","))
var (
rankPeriodList []RankPeriodEndTime
)
rankPeriodMap := make(map[int64]time.Time)
err = utils.ExecuteQueryAll(&rankPeriodList, runsql2)
if err != nil {
log.Error("【自动创建赛季】,获取自动创建赛季时需要的开始时间失败:%s")
break LOOP0
}
for _, v := range rankPeriodList {
rankPeriodMap[v.RankTypeId] = v.EndTime
}
//开始循环rankTypeList,创建赛季
var (
successNum int64
addRankPeriod []models.RankPeriod
)
nowTime := time.Now()
LOOP1:
for _, v := range rankTypeList {
m := models.RankPeriod{
CompanyId: v.CompanyId,
RankTypeId: v.RankTypeId,
CreateAt: nowTime,
UpdateAt: nowTime,
Status: models.RANKPERIOD_STATUS_NOT,
IsAuto: 1,
}
if t, ok := rankPeriodMap[v.RankTypeId]; ok {
s := t.Format("2006-01-02")
dayTime, err := time.ParseInLocation("2006-01-02", s, time.Local)
if err != nil {
log.Error("【自动创建赛季】,格式化rank_period的end_time失败,id=%d,end_time=%d", v.RankTypeId, t)
continue LOOP1
}
begin := dayTime.Unix() + 24*60*60
end := begin + v.AutoPeriod*24*60*60 - 1
m.BeginTime = time.Unix(begin, 0).Local()
m.EndTime = time.Unix(end, 0).Local()
// m.SeasonName = fmt.Sprintf("自动创建赛季%s", s)
} else {
s := nowTime.Format("2006-01-02")
dayTime, _ := time.ParseInLocation("2006-01-02", s, time.Local)
begin := dayTime.Unix() + 24*60*60
end := begin + v.AutoPeriod*24*60*60 - 1
m.BeginTime = time.Unix(begin, 0).Local()
m.EndTime = time.Unix(end, 0).Local()
// m.SeasonName = fmt.Sprintf("自动创建赛季%s", s)
}
if v.RankType == models.RANK_TYPE_YEAR {
//年榜
m.SeasonName = fmt.Sprintf("%d%s", nowTime.Year(), "年赛季")
} else if v.RankType == models.RANK_TYPE_SEASON {
//季榜
m.SeasonName = fmt.Sprintf("%d%s", nowTime.Month(), "月赛季")
}
addRankPeriod = append(addRankPeriod, m)
}
successNum, err = o.InsertMulti(100, addRankPeriod)
if err != nil {
log.Error("【自动创建赛季】,创建赛季出现错误,添加rank_period数据发生错误:%s", err)
}
log.Info("【自动创建赛季】,添加rank_period记录数量:%d", successNum)
}
return nil
}
... ...
package platform
import "errors"
type PlatformAction interface {
DoAction(string, []byte) error
}
//从主管理平台接收数据数据并处理数据
type CommonProtocol struct {
Module string `json:"module"` //模块
Action string `json:"action"` //动作
Data interface{} `json:"data"` //实际的未知数据结构
}
var actionmap = map[string]PlatformAction{
"department": ModuleDeparmentData{},
"position": ModulePositionData{},
"employee": ModuleEmployee{},
"company": ModuleCompanytData{},
}
func NewPlatformAction(module string) (PlatformAction, error) {
if v, ok := actionmap[module]; ok {
return v, nil
}
return nil, errors.New("module cannot found")
}
... ...
package platform
import (
"fmt"
"oppmg/common/log"
"oppmg/models"
"github.com/astaxie/beego/orm"
)
// AdminChance g更换公司主管
//companyid 总管理后台的公司id
func AdminChance(companyid int64, phone string) error {
var (
companyData *models.Company
userData *models.User
err error
newCharge *models.UserCompany
oldCharge *models.UserCompany
)
companyData, err = models.GetCompanyByUCenter(companyid)
if err != nil {
e := fmt.Errorf("获取公司数据失败,总后台company_id:%d", companyid)
log.Error(err.Error())
return e
}
userData, err = models.GetUserByPhone(phone)
if err != nil {
e := fmt.Errorf("获取用户数据失败,phone:%s", phone)
log.Error(err.Error())
return e
}
newCharge, err = models.GetUserCompanyBy(userData.Id, companyData.Id)
if err != nil {
e := fmt.Errorf("获取用户和公司的对应关系数据失败,user_id:%d,company_id:%d", userData.Id, companyData.Id)
log.Error(e.Error())
return e
}
oldCharge, err = models.GetUserCompanyBy(companyData.AdminId, companyData.Id)
if err != nil {
e := fmt.Errorf("获取公司原来的主管对应数据失败,user_id:%d,company_id:%d", companyData.AdminId, companyData.Id)
log.Error(e.Error())
return e
}
o := orm.NewOrm()
o.Begin()
companyData.AdminId = userData.Id
err = models.UpdateCompanyById(companyData, []string{"AdminId"}, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("更新公司数据失败,err:%s", err)
log.Error(e.Error())
return e
}
newCharge.ChargeStatus = models.USERCOMPANY_CHARGE_YES
oldCharge.ChargeStatus = models.USERCOMPANY_CHARGE_NO
err = models.UpdateUserCompanyById(newCharge, []string{"ChargeStatus"}, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("更新原公司主管理员数据失败,user_company_id=%d,err:%s", oldCharge.Id, err)
log.Error(e.Error())
return e
}
err = models.UpdateUserCompanyById(oldCharge, []string{"ChargeStatus"}, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("更新新公司主管理员数据失败,user_company_id=%d , err:%s", newCharge.Id, err)
log.Error(e.Error())
return e
}
o.Commit()
return nil
}
... ...
package platform
import (
"encoding/json"
"errors"
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/protocol"
"oppmg/services/ucenter"
"oppmg/utils"
"time"
"github.com/astaxie/beego/orm"
)
type CompanyBase struct {
Id int64 `json:"id"` //id
Name string `json:"name"` //公司名称名称
AdminCompanyId int64 `json:"admin_company_id"`
Logo string `json:"logo"`
Remarks string `json:"remarks"`
}
// ModuleCompanytData 主管理平台发送过来的数据
type ModuleCompanytData struct {
Company CompanyBase `json:"company"`
User ModuleEmployee `json:"user"`
}
type CompanyCharge struct {
Id int64 `json:"id"`
Charge []int64 `json:"charge"`
}
var _ PlatformAction = ModuleCompanytData{}
func (m ModuleCompanytData) DoAction(code string, jsondata []byte) error {
switch code {
case "add":
var (
data ModuleCompanytData
err error
)
err = json.Unmarshal(jsondata, &data)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
return AddCompanyData(data)
case "edit":
var (
data ModuleCompanytData
err error
)
err = json.Unmarshal(jsondata, &data)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
return UpdateCompanyData(data)
case "setCompanyCharge":
var (
data CompanyCharge
err error
)
err = json.Unmarshal(jsondata, &data)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
return SetCompanyCharge(data)
default:
return errors.New("action not found")
}
// return nil
}
// SetCompanyCharge 更新公司那一级的部门的管理员
func SetCompanyCharge(data CompanyCharge) error {
var (
err error
companyData *models.Company
departmentData *models.Department
)
companyData, err = models.GetCompanyByUCenter(data.Id)
if err != nil {
log.Error("获取公司数据失败,user_center_id=%d,err:%s", data.Id, err)
return errors.New("获取公司数据失败")
}
departmentData, err = models.GetTopDepartmentByCompany(companyData.Id)
if err != nil {
log.Error("获取公司一级部门数据失败,company_id=%d, err:%s", companyData.Id, err)
return errors.New("获取公司一级部门数据失败")
}
// 获取公司管理员
o := orm.NewOrm()
o.Begin()
err = models.ChangeDepartmentCharge(data.Id, departmentData.Id, data.Charge, o)
if err != nil {
o.Rollback()
log.Error("变更公司管理员失败,err:%s", err)
return errors.New("变更公司管理员失败")
}
//更新department数据
bt, _ := json.Marshal(data.Charge)
departmentData.Manages = string(bt)
err = models.UpdateDepartmentById(departmentData, []string{"Manages"}, o)
if err != nil {
o.Rollback()
log.Error("变更公司管理员失败,err:%s", err)
return errors.New("变更公司管理员失败")
}
o.Commit()
return nil
}
func UpdateCompanyData(data ModuleCompanytData) error {
var (
companyData *models.Company
err error
)
newCompanyData := data.Company
companyData, err = models.GetCompanyByUCenter(newCompanyData.AdminCompanyId)
if err == orm.ErrNoRows {
log.Error("编辑操作,未找到数据,执行添加操作")
return AddCompanyData(data)
}
if err != nil {
log.Error("获取企业数据失败,user_center_id:%d ,err:%s", newCompanyData.AdminCompanyId, err)
return errors.New("获取企业数据失败")
}
var (
oldAdminData *models.UserCompany
)
oldAdminData, err = models.GetUserCompanyBy(companyData.AdminId, companyData.Id)
if err != nil {
log.Error("获取公司主管理员user_company数据失败,company_id=%d,user_id=%d,err:%s", companyData.Id, companyData.AdminId, err)
return errors.New("获取公司主管理员数据失败")
}
o := orm.NewOrm()
o.Begin()
if data.User.Id != oldAdminData.Id {
//更新公司主管理员
oldAdminData.ChargeStatus = models.USERCOMPANY_CHARGE_NO
err = models.UpdateUserCompanyById(oldAdminData, []string{"ChargeStatus"}, o)
if err != nil {
o.Rollback()
log.Error("去除旧的主管理员失败:user_company_id=%d,err:%s", oldAdminData.Id, err)
return errors.New("去除旧的更主管理员失败")
}
var newAdminData *models.UserCompany
newAdminData, err = models.GetUserCompanyById(data.User.Id)
if err != nil {
o.Rollback()
log.Error("获取新的主管理员失败,user_company_id=%d,err:%s", data.User.Id, err)
return errors.New("获取新的主管理员")
}
newAdminData.ChargeStatus = models.USERCOMPANY_CHARGE_YES
err = models.UpdateUserCompanyById(newAdminData, []string{"ChargeStatus"}, o)
if err != nil {
o.Rollback()
log.Error("变更更主管理员失败:user_company_id=%d,err:%s", newAdminData.Id, err)
return errors.New("变更主管理员失败")
}
companyData.AdminId = newAdminData.UserId
}
companyData.Logo = newCompanyData.Logo
companyData.Name = newCompanyData.Name
companyData.Remark = newCompanyData.Remarks
err = models.UpdateCompanyById(companyData, []string{"Logo", "Name", "AdminId", "Remark"}, o)
if err != nil {
o.Rollback()
log.Error("更新公司数据失败:%s", err)
return errors.New("更新公司数据失败")
}
o.Commit()
return nil
}
//AddCompanyData 新增公司 初始化公司
func AddCompanyData(data ModuleCompanytData) error {
var (
newDeparment *models.Department
newRoleGroup *models.Role
newRole *models.Role
newUser *models.User
newCompany *models.Company
newUserCompany *models.UserCompany
err error
)
log.Info("获取统一户中心的数据")
ucenterReturn, err := ucenter.RequestUCenterAddUser(data.User.Phone, data.User.Name, "")
if err != nil {
log.Error("请求统一用户中心数据失败:%s", err)
return errors.New("获取统一用户中心数据失败")
}
data.User.OpenId = ucenterReturn.Data.Id
o := orm.NewOrm()
o.Begin()
//处理用户数据
log.Info("添加user表数据")
newUser, err = AddAdminUser(&data, o)
if err != nil {
o.Rollback()
log.Error("处理公司主管数据失败:%s", err)
return errors.New("处理公司主管数据失败")
}
//处理公司数据
log.Info("添加company表数据")
newCompany, err = AddCompanyBase(&data, newUser, o)
if err != nil {
o.Rollback()
log.Error("处理公司数据失败:%s", err)
return errors.New("处理公司数据失败")
}
//处理评分配置数据 初始化
log.Info("添加sys_config表数据")
err = iniSysConfig(int(newCompany.Id), o)
if err != nil {
o.Rollback()
log.Error("处理评分配置数据失败:%s", err)
return errors.New("处理评分配置数据")
}
//添加user_company
log.Info("添加user_copmany表数据")
newUserCompany, err = AddUserCompanyData(&data, newCompany, newUser, o)
if err != nil {
o.Rollback()
log.Error("处理user_company数据失败:%s", err)
return errors.New("处理user_company数据失败")
}
//添加部门
log.Info("添加department表数据")
newDeparment, err = AddFirstDepartment(newCompany, newUserCompany, o)
if err != nil {
o.Rollback()
log.Error("处理部门数据失败:%s", err)
return errors.New("处理部门数据失败")
}
//添加用户部门数据
log.Info("添加user_department表数据")
_, err = initUserDedaprtmet(newDeparment, newUserCompany, o)
if err != nil {
o.Rollback()
log.Error("处理user_department数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加部门主管
log.Info("添加department_charge表数据")
err = AddFirstDepartmentCharge(newDeparment, newUserCompany, newCompany, o)
if err != nil {
o.Rollback()
log.Error("处理部门主管数据,err:%s", err)
return errors.New("处理部门主管数据")
}
//添加角色组
log.Info("添加role表数据")
newRoleGroup, err = initRoleGroup(newCompany, o)
if err != nil {
o.Rollback()
log.Error("处理角色组数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加角色
log.Info("添加role表数据")
newRole, err = initRole(newCompany, newRoleGroup, o)
if err != nil {
o.Rollback()
log.Error("处理角色数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
//添加用户的角色
log.Info("添加user_role表数据")
_, err = initUserRole(newUserCompany, newRole, o)
if err != nil {
o.Rollback()
log.Error("处理user_role数据失败:%s", err)
return protocol.NewErrWithMessage("1")
}
o.Commit()
return nil
}
func AddAdminUser(centerCompany *ModuleCompanytData, o orm.Ormer) (*models.User, error) {
var (
err error
newUser = &models.User{}
)
companyAdminData := centerCompany.User
err = o.QueryTable(&models.User{}).
Filter("phone", companyAdminData.Phone).
One(newUser)
if err == nil {
return newUser, nil
}
//添加用户
newUser = &models.User{
Id: companyAdminData.Id,
Phone: companyAdminData.Phone,
NickName: companyAdminData.Name,
UserCenterId: companyAdminData.OpenId,
}
_, err = models.AddUser(newUser, o)
if err != nil {
log.Error("添加用户数据失败:%s", err)
return nil, err
}
return newUser, nil
}
func AddCompanyBase(centerCompany *ModuleCompanytData, admininfo *models.User, o orm.Ormer) (*models.Company, error) {
var (
err error
)
companybase := centerCompany.Company
newCompany := &models.Company{
Id: companybase.Id,
Name: companybase.Name,
AdminId: admininfo.Id,
UserCenterId: companybase.AdminCompanyId,
Enable: models.COMPANY_ENABLE_NO,
Logo: companybase.Logo,
Remark: companybase.Remarks,
}
_, err = models.AddCompany(newCompany, o)
if err != nil {
log.Error("添加公司数据失败:%s", err)
return nil, err
}
return newCompany, nil
}
func AddUserCompanyData(centerCompany *ModuleCompanytData, newcompany *models.Company, newuser *models.User, o orm.Ormer) (*models.UserCompany, error) {
var (
err error
uc = &models.UserCompany{}
)
adminUserData := centerCompany.User
err = o.QueryTable(&models.UserCompany{}).
Filter("company_id", newcompany.Id).
Filter("user_id", newuser.Id).
Filter("delete_at", 0).
One(uc)
if err == nil {
return uc, nil
}
uc = &models.UserCompany{
UserId: newuser.Id,
CompanyId: newcompany.Id,
Enable: models.USERCOMPANY_ENABLE_YES,
ChargeStatus: adminUserData.ChargeStatus,
Id: adminUserData.Id,
NickName: adminUserData.Name,
OpenId: adminUserData.OpenId,
Sex: adminUserData.Sex,
JobNum: adminUserData.JobNum,
Phone: adminUserData.Phone,
PrivatePhone: adminUserData.PrivatePhone,
Email: adminUserData.Email,
ExtensionNum: adminUserData.ExtensionNum,
Workspace: adminUserData.WorkSpace,
IsBusiness: adminUserData.IsBusiness,
Avatar: adminUserData.Avatar,
Remarks: adminUserData.Remarks,
AdminType: adminUserData.AdminType,
ExtraText: adminUserData.ExtraText,
}
_, err = models.AddUserCompany(uc, o)
if err != nil {
log.Error("添加user_company数据失败:%s", err)
return nil, err
}
return uc, nil
}
//AddFirstDepartment 创建公司的一级部门
func AddFirstDepartment(newCompany *models.Company, newusercompany *models.UserCompany, o orm.Ormer) (*models.Department, error) {
var (
newDepartment = &models.Department{}
err error
)
err = o.QueryTable(&models.Department{}).
Filter("company_id", newCompany.Id).
Filter("is_top", 1).
One(newDepartment)
if err == nil {
return newDepartment, nil
} else if err == orm.ErrNoRows {
//添加部门
newDepartment = &models.Department{
CompanyId: newCompany.Id,
Name: newCompany.Name,
IsTop: 1,
ParentId: 0,
Relation: fmt.Sprint(utils.GenerateIDBySonyflake()),
Id: utils.GenerateID14(),
}
_, err = models.AddDepartment(newDepartment, o)
if err != nil {
log.Error("添加部门数据失败:%s", err)
return nil, err
}
newDepartment.SetRelation(nil)
err = models.UpdateDepartmentById(newDepartment, []string{"Relation"}, o)
if err != nil {
log.Error("更新部门关系树数据失败:%s", err)
return nil, err
}
} else {
log.Error("查询部门数据失败:%s", err)
return nil, err
}
return newDepartment, nil
}
func AddFirstDepartmentCharge(newDepartment *models.Department, newUserCompany *models.UserCompany, newCompany *models.Company, o orm.Ormer) error {
var (
err error
)
departmentCharg := &models.DepartmentCharge{
CompanyId: newCompany.Id,
DepartmentId: newDepartment.Id,
UserCompanyId: newUserCompany.Id,
}
_, err = models.AddDepartmentCharge(departmentCharg, o)
if err != nil {
log.Error("设置部门主管失败,err:%s", err)
return err
}
newDepartment.SetManages([]int64{newUserCompany.Id})
err = models.UpdateDepartmentById(newDepartment, []string{"Manages"}, o)
if err != nil {
log.Error("设置部门主管失败,err:%s", err)
return err
}
return nil
}
func UpdateCompany(centerCompany *ModuleCompanytData, admininfo *models.User, o orm.Ormer) (*models.Company, error) {
var (
err error
newCompany = &models.Company{}
)
err = o.QueryTable(&models.Company{}).
Filter("user_center_id", centerCompany.Company.AdminCompanyId).
One(newCompany)
if err == nil {
_, err = o.QueryTable(&models.Company{}).
Filter("user_center_id", centerCompany.Company.AdminCompanyId).
Update(orm.Params{
"name": centerCompany.Company.Name,
"admin_id": admininfo.Id,
"delete_at": 0,
})
if err != nil {
log.Error("更新公司数据失败:%s", err)
return nil, err
}
} else {
log.Error("查询公司数据失败:%s", err)
return nil, err
}
return newCompany, nil
}
// func initAdminUser(centerCompany *ModuleCompanytData, o orm.Ormer) (*models.User, error) {
// var (
// err error
// newUser = &models.User{}
// )
// companyAdminData := centerCompany.User
// err = o.QueryTable(&models.User{}).
// Filter("phone", companyAdminData.Phone).
// Filter("delete_at", 0).
// One(newUser)
// if err == nil {
// // 更新数据
// _, err = o.QueryTable(&models.User{}).
// Filter("user_center_id", companyAdminData.OpenId).
// Filter("delete_at", 0).
// Update(orm.Params{
// "nick_name": companyAdminData.Name,
// "phone": companyAdminData.Phone,
// "enable_status": models.USER_ENABLE_YES,
// })
// if err != nil {
// log.Error("数据操作失败:%s", err)
// return nil, err
// }
// } else if err == orm.ErrNoRows {
// var (
// ucenterUser = &ucenter.ResponseAddUser{}
// err error
// )
// ucenterUser, err = ucenter.RequestUCenterAddUser(companyAdminData.Phone, companyAdminData.Name, "")
// if err != nil {
// log.Error("获取统一用户中心数据失败 :%s", err)
// return nil, err
// }
// //添加用户
// newUser = &models.User{
// Id: companyAdminData.Id,
// Phone: companyAdminData.Phone,
// NickName: companyAdminData.Name,
// Icon: ucenterUser.Data.Avatar,
// Accid: ucenterUser.Data.Accid,
// UserCenterId: ucenterUser.Data.Id,
// CsAccount: ucenterUser.Data.CustomerAccount,
// }
// _, err = models.AddUser(newUser, o)
// if err != nil {
// log.Error("添加用户数据失败:%s", err)
// return nil, err
// }
// } else {
// log.Error("查询用户数据失败:%s", err)
// return nil, err
// }
// return newUser, nil
// }
// func initUserCompany(newcompany *models.Company, newuser *models.User, o orm.Ormer) (*models.UserCompany, error) {
// var (
// err error
// uc = &models.UserCompany{}
// )
// err = o.QueryTable(&models.UserCompany{}).
// Filter("user_id", newuser.Id).
// Filter("company_id", newcompany.Id).
// Filter("delete_at", 0).
// One(uc)
// if err == nil {
// _, err = o.QueryTable(&models.UserCompany{}).
// Filter("id", uc.Id).
// Update(orm.Params{
// "enable": models.USERCOMPANY_ENABLE_YES,
// })
// if err != nil {
// log.Error("更新user_company数据失败:%s", err)
// return nil, err
// }
// } else if err == orm.ErrNoRows {
// uc = &models.UserCompany{
// UserId: newuser.Id,
// CompanyId: newcompany.Id,
// OpenId: newuser.UserCenterId,
// Enable: models.USERCOMPANY_ENABLE_YES,
// ChargeStatus: models.USERCOMPANY_CHARGE_YES,
// }
// _, err = models.AddUserCompany(uc, o)
// if err != nil {
// log.Error("添加user_company数据失败:%s", err)
// return nil, err
// }
// } else {
// log.Error("获取user_company数据失败:%s", err)
// return nil, err
// }
// return uc, nil
// }
// func initDepartment(newCompany *models.Company, newusercompany *models.UserCompany, o orm.Ormer) (*models.Department, error) {
// var (
// newDepartment = &models.Department{}
// err error
// )
// err = o.QueryTable(&models.Department{}).
// Filter("company_id", newCompany.Id).
// Filter("is_top", 1).
// One(newDepartment)
// if err == nil {
// newDepartment.Name = newCompany.Name
// err = models.UpdateDepartmentById(newDepartment, []string{"Name"}, o)
// if err != nil {
// log.Error("更新部门关系树数据失败:%s", err)
// return nil, err
// }
// return newDepartment, nil
// } else if err == orm.ErrNoRows {
// //添加部门
// newDepartment = &models.Department{
// CompanyId: newCompany.Id,
// Name: newCompany.Name,
// IsTop: 1,
// ParentId: 0,
// Relation: fmt.Sprint(utils.GenerateIDBySonyflake()),
// }
// newDepartment.SetManages([]int64{newusercompany.Id})
// _, err = models.AddDepartment(newDepartment, o)
// if err != nil {
// log.Error("添加部门数据失败:%s", err)
// return nil, err
// }
// newDepartment.SetRelation(nil)
// err = models.UpdateDepartmentById(newDepartment, []string{"Relation"}, o)
// if err != nil {
// log.Error("更新部门关系树数据失败:%s", err)
// return nil, err
// }
// } else {
// log.Error("查询部门数据失败:%s", err)
// return nil, err
// }
// return newDepartment, nil
// }
//initUserDedaprtmet 设置用户和部门关系
func initUserDedaprtmet(newDepartment *models.Department, newUserCompany *models.UserCompany, o orm.Ormer) (*models.UserDepartment, error) {
var (
newUserDepartment = &models.UserDepartment{}
err error
)
err = o.QueryTable(&models.UserDepartment{}).
Filter("department_id", newDepartment.Id).
Filter("user_company_id", newUserCompany.Id).
Filter("enable_status", models.USER_DEPARTMENT_ENABLE_YES).
One(newUserDepartment)
if err == nil {
return newUserDepartment, nil
} else if err == orm.ErrNoRows {
//添加部门
newUserDepartment = &models.UserDepartment{
UserCompanyId: newUserCompany.Id,
//UserId: newUserCompany.UserId,
CompanyId: newUserCompany.CompanyId,
DepartmentId: newDepartment.Id,
}
_, err = models.AddUserDepartment(newUserDepartment, o)
if err != nil {
log.Error("添加部门数据失败:%s", err)
return nil, err
}
} else {
log.Error("查询部门数据失败:%s", err)
return nil, err
}
return newUserDepartment, nil
}
//initRoleGroup 设置初始的角色组
func initRoleGroup(newCompany *models.Company, o orm.Ormer) (*models.Role, error) {
var (
newRoleGroup = &models.Role{}
err error
)
err = o.QueryTable(&models.Role{}).
Filter("delete_at", 0).
Filter("is_default", models.ROLE_DEFAULR).
Filter("types", models.ROLETYPES_GROUP).
Filter("company_id", newCompany.Id).
One(newRoleGroup)
if err == nil {
return newRoleGroup, nil
} else if err == orm.ErrNoRows {
//添加部角色组
newRoleGroup = &models.Role{
Types: models.ROLETYPES_GROUP,
CompanyId: newCompany.Id,
IsDefault: models.ROLE_DEFAULR,
Name: "管理员",
}
_, err = models.AddRole(newRoleGroup, o)
if err != nil {
log.Error("添加角色组数据失败:%s", err)
return nil, err
}
} else {
log.Error("查询角色组数据失败:%s", err)
return nil, err
}
return newRoleGroup, nil
}
//initRole 初始化公司的角色
func initRole(newCompany *models.Company, newRoleGroup *models.Role, o orm.Ormer) (*models.Role, error) {
var (
newRole = &models.Role{}
err error
)
err = o.QueryTable(&models.Role{}).
Filter("delete_at", 0).
Filter("is_default", models.ROLE_DEFAULR).
Filter("types", models.ROLETYPES_ROLE).
Filter("company_id", newCompany.Id).
One(newRole)
if err == nil {
return newRole, nil
} else if err == orm.ErrNoRows {
//添加部门
newRole = &models.Role{
Types: models.ROLETYPES_ROLE,
CompanyId: newCompany.Id,
IsDefault: models.ROLE_DEFAULR,
Name: "主管理员",
Pid: newRoleGroup.Id,
}
_, err = models.AddRole(newRole, o)
if err != nil {
log.Error("添加角色数据失败:%s", err)
return nil, err
}
} else {
log.Error("查询角色数据失败:%s", err)
return nil, err
}
return newRole, nil
}
//initUserRole 初始化第一个用户和角色的关系
func initUserRole(newUserCompany *models.UserCompany, newRole *models.Role, o orm.Ormer) (*models.UserRole, error) {
var (
newUserRole = &models.UserRole{}
err error
)
err = o.QueryTable(&models.UserRole{}).
Filter("enable_status", models.USER_ROLE_ENABLE_YES).
Filter("user_company_id", newUserCompany.Id).
Filter("role_id", newRole.Id).
One(newUserRole)
if err == nil {
return newUserRole, nil
} else if err == orm.ErrNoRows {
//添加UserRole
newUserRole = &models.UserRole{
RoleId: newRole.Id,
UserCompanyId: newUserCompany.Id,
CompanyId: newUserCompany.CompanyId,
}
_, err = models.AddUserRole(newUserRole, o)
if err != nil {
log.Error("添加user_role数据失败:%s", err)
return nil, err
}
} else {
log.Error("查询user_role数据失败:%s", err)
return nil, err
}
return newUserRole, nil
}
//iniSysConfig 初始化公司的系统配置
func iniSysConfig(companyid int, o orm.Ormer) error {
var (
m *models.SysConfig
err error
)
m, err = models.GetSysConfigByCompanyId(companyid, models.KeyScore)
if err == nil {
return nil
}
v := protocol.ScoreConfig{
DiscoveryScore: &protocol.DiscoveryScore{
BasicFactor: 1,
ExtraFactor: 1,
ValueFactor: 1,
},
SumScore: &protocol.SumScore{
DiscoveryFactor: 1,
CatchFactor: 1,
},
BasicScore: &protocol.ScoreRange{
Max: 10000,
Min: 0,
Step: 1,
},
ExtraScore: &protocol.ScoreRange{
Max: 10000,
Min: 0,
Step: 1,
},
ValueScore: &protocol.ScoreRange{
Max: 10000,
Min: 0,
Step: 1,
},
}
bt, _ := json.Marshal(v)
m = &models.SysConfig{
Key: models.KeyScore,
CompanyId: companyid,
CreateAt: time.Now(),
UpdateAt: time.Now(),
Content: string(bt),
}
_, err = models.AddSysConfig(m, o)
return err
}
... ...
package platform
import (
"encoding/json"
"errors"
"fmt"
"oppmg/common/log"
"oppmg/models"
"oppmg/utils"
"sort"
"strings"
"time"
"github.com/astaxie/beego/orm"
)
// ModuleDeparmentData 主管理平台发送过来的数据
type ModuleDeparmentData struct {
Id int64 `json:"id"` //id
Name string `json:"name"` //部门名称
ParentId int64 `json:"parent_id"` //父级id
CompanyId int64 `json:"company_id"`
Path string `json:"path"`
Level int `json:"level"`
Charge []int64 `json:"charge"` //部门主管
}
type SortDepartmentByLevel []ModuleDeparmentData
func (a SortDepartmentByLevel) Len() int { return len(a) }
func (a SortDepartmentByLevel) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a SortDepartmentByLevel) Less(i, j int) bool { return a[i].Level < a[j].Level }
var _ PlatformAction = ModuleDeparmentData{}
//DoAction PlatformAction 的接口实现
func (m ModuleDeparmentData) DoAction(code string, jsondata []byte) error {
switch code {
case "edit":
var (
data ModuleDeparmentData
err error
)
err = json.Unmarshal(jsondata, &data)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
return UpdateDepartmentData(data)
case "add":
var (
data ModuleDeparmentData
err error
)
err = json.Unmarshal(jsondata, &data)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
datas := []ModuleDeparmentData{data}
return AddDepartmentData(datas)
case "batchDelete":
var (
err error
)
ids := struct {
Ids []int64 `json:"ids"`
}{}
err = json.Unmarshal(jsondata, &ids)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
if len(ids.Ids) == 0 {
return fmt.Errorf("参数错误")
}
return DeleteDepartmentData(ids.Ids)
case "import":
var (
data []ModuleDeparmentData
err error
)
err = json.Unmarshal(jsondata, &data)
if err != nil {
return fmt.Errorf("数据解析失败:%s", err)
}
return AddDepartmentData(data)
default:
return errors.New("action not found")
}
// return nil
}
//同步 部门数据
//UpdateDepartmentData ....
func UpdateDepartmentData(data ModuleDeparmentData) error {
var (
departmentData *models.Department
err error
)
departmentData, err = models.GetDepartmentById(data.Id)
if err == orm.ErrNoRows {
log.Error("编辑操作,未找到数据,执行添加操作")
return AddDepartmentData([]ModuleDeparmentData{data})
}
if err != nil {
e := fmt.Errorf("获取部门数据失败,err:%s", err)
log.Error(e.Error())
return errors.New("获取部门数据失败")
}
departmentData.Name = data.Name
o := orm.NewOrm()
o.Begin()
err = models.UpdateDepartmentById(departmentData, []string{"Name"}, o)
if err != nil {
o.Rollback()
e := fmt.Errorf("更新部门数据失败,err:%s", err)
log.Error(e.Error())
return errors.New("更新部门数据失败")
}
//更新部门管理员
err = models.ChangeDepartmentCharge(data.Id, departmentData.Id, data.Charge, o)
if err != nil {
o.Rollback()
log.Error("变更公司管理员失败,err:%s", err)
return errors.New("变更公司管理员失败")
}
o.Commit()
var (
newParentDepart *models.Department
)
if data.ParentId == 0 {
newParentDepart, err = models.GetTopDepartmentByCompany(departmentData.CompanyId)
if err != nil {
log.Error("获取公司一级部门数据失败:company_id=%d,err:%s", departmentData.CompanyId, err)
return errors.New("获取公司一级部门数据失败")
}
} else {
newParentDepart, err = models.GetDepartmentByBusinessId(data.ParentId)
if err != nil {
log.Error("获取父级数据失败,business_admin_id=%d,err:%s", data.ParentId, err)
}
}
if departmentData.ParentId != newParentDepart.Id {
//更新父级
err = departmentRelationUpdate(*departmentData, *newParentDepart)
if err != nil {
return err
}
}
return nil
}
//positionRelationUpdate 处理职位上级发生变化的情况
func departmentRelationUpdate(departmentUpdate models.Department, newparent models.Department) error {
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=?`
//更新departUpdate的parent_id
//dataSql3 string = `update department set parent_id=? where id=?`
)
var (
departmentSubset []*models.Department //子级部门
err error
oldRelation string = departmentUpdate.Relation
relationLike string = oldRelation + "%"
newRelation string
)
if newparent.Id == 0 {
//修改节点为顶层节点的情况
newRelation = fmt.Sprintf(",%d,", departmentUpdate.Id)
} else {
newRelation = fmt.Sprintf("%s%d,", newparent.Relation, departmentUpdate.Id)
}
o := orm.NewOrm()
o.Begin()
//获取部门及子级部门的relation和id
err = utils.ExecuteQueryAllWithOrmer(o, &departmentSubset, dataSql0, relationLike)
if err != nil {
e := fmt.Errorf("EXECUTE SQL err:%s", err)
log.Error(e.Error())
return errors.New("获取部门及子级部门失败")
}
for i := range departmentSubset {
if departmentSubset[i].Id == departmentUpdate.Id {
departmentSubset[i].ParentId = newparent.Id
}
//重建关系树
s := strings.TrimLeft(departmentSubset[i].Relation, oldRelation)
departmentSubset[i].Relation = fmt.Sprintf("%s%s", newRelation, s)
departmentSubset[i].Level = setDepartmentLevel(departmentSubset[i].Relation)
}
//修改部门及子级部门的relation
for i := range departmentSubset {
err = models.UpdateDepartmentById(departmentSubset[i], []string{"ParentId", "Relation", "Level"}, o)
if err != nil {
log.Error("更新position发生错误,bussiness_admin_id=%d,id=%d,err:%s", departmentSubset[i].BusinessDepartmentId, departmentSubset[i].Id, err)
o.Rollback()
return fmt.Errorf("更新position发生错误,bussiness_admin_id=%d", departmentSubset[i].BusinessDepartmentId)
}
}
o.Commit()
return nil
}
func setDepartmentLevel(relation string) int {
s := strings.Split(relation, ",")
return len(s) - 3
}
//AddDepartmentData ...
func AddDepartmentData(data []ModuleDeparmentData) error {
if len(data) == 0 {
return nil
}
sort.Sort(SortDepartmentByLevel(data))
var (
err error
companyData *models.Company
topDepartment *models.Department
)
companyData, err = models.GetCompanyByUCenter(data[0].CompanyId)
if err != nil {
log.Error("获取公司数据失败,user_center_id=%d,err:%s", data[0].CompanyId, err)
return errors.New("获取公司数据失败")
}
topDepartment, err = models.GetTopDepartmentByCompany(companyData.Id)
if err != nil {
log.Error("获取公司一级部门数据失败;company_id=%d,err:%s", companyData.Id, err)
return errors.New("获取公司一级部门数据失败")
}
o := orm.NewOrm()
o.Begin()
for _, v := range data {
departmentData := &models.Department{
Id: v.Id,
CompanyId: companyData.Id,
Name: v.Name,
Manages: "[]",
BusinessDepartmentId: v.Id,
DeleteAt: time.Unix(0, 0),
CreateAt: time.Now(),
Level: v.Level,
}
if v.ParentId > 0 {
parentDepart := &models.Department{}
err = o.QueryTable(&models.Department{}).
Filter("business_department_id", v.ParentId).
Filter("delete_at", 0).
One(parentDepart)
if err != nil {
log.Error("获取父级职位数据失败,business_admin_id=%d,err:%s", v.ParentId, err)
return errors.New("获取父级职位数据失败")
}
departmentData.ParentId = parentDepart.Id
departmentData.SetRelation(parentDepart)
}
if v.ParentId == 0 {
departmentData.ParentId = topDepartment.Id
departmentData.SetRelation(topDepartment)
}
// departmentData.Level = setDepartmentLevel(departmentData.Relation)
_, err = models.AddDepartment(departmentData, o)
if err != nil {
e := fmt.Errorf("存储部门数据失败,err:%s", err)
o.Rollback()
log.Error(e.Error())
return errors.New("存储部门数据失败")
}
}
o.Commit()
return nil
}
//DeleteDepartmentData ...
func DeleteDepartmentData(ids []int64) error {
o := orm.NewOrm()
_, err := o.QueryTable(&models.Department{}).
Filter("business_department_id__in", ids).
Update(orm.Params{
"delete_at": time.Now().Format("2006-01-02 15:04:05"),
})
if err != nil {
log.Error("更新position数据失败,err:%s", err)
return errors.New("删除职位数据失败")
}
return nil
}
... ...