作者 tangxvhui

Merge branch 'test' into dev

要显示太多修改。

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

1 #app的名称 1 #app的名称
2 appname = ability 2 appname = ability
3 #运行模式 3 #运行模式
4 -runmode =${RUN_MODE||test} 4 +runmode =${RUN_MODE||dev}
5 #是否自动渲染页面 5 #是否自动渲染页面
6 autorender = false 6 autorender = false
7 #是否复制请求body 7 #是否复制请求body
  1 +package controllers
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + "oppmg/common/log"
  7 + "oppmg/models"
  8 + "oppmg/protocol"
  9 + serveachievement "oppmg/services/achievement"
  10 +
  11 + "github.com/astaxie/beego/orm"
  12 +)
  13 +
  14 +type AchievementController struct {
  15 + BaseController
  16 +}
  17 +
  18 +//AchievementList 成果列表
  19 +//@router /achievement/list
  20 +func (c AchievementController) AchievementList() {
  21 + var msg *protocol.ResponseMessage
  22 + defer func() {
  23 + c.ResposeJson(msg)
  24 + }()
  25 + type Parameter struct {
  26 + protocol.RequestPageInfo
  27 + Status int `json:"status"`
  28 + }
  29 + var param Parameter
  30 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  31 + log.Error("json 解析失败 err:%s", err)
  32 + msg = protocol.BadRequestParam("1")
  33 + return
  34 + }
  35 + companyid := c.GetCompanyId()
  36 + rspdata := serveachievement.GetAchievementList(param.PageIndex, param.PageSize, companyid, param.Status)
  37 + msg = protocol.NewPageDataResponse(rspdata, nil)
  38 + return
  39 +}
  40 +
  41 +//AddAchievement 添加成果列表
  42 +//@router /achievement/add
  43 +func (c AchievementController) AddAchievement() {
  44 + var msg *protocol.ResponseMessage
  45 + defer func() {
  46 + c.ResposeJson(msg)
  47 + }()
  48 +
  49 + var param protocol.RequestAddAchievement
  50 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  51 + log.Error("json 解析失败 err:%s", err)
  52 + msg = protocol.BadRequestParam("1")
  53 + return
  54 + }
  55 + if len(param.ChanceData) == 0 {
  56 + log.Error("len(param.ChanceData) == 0 ")
  57 + msg = protocol.BadRequestParam("10109")
  58 + return
  59 + }
  60 + if param.ChanceTypeId == 0 {
  61 + log.Error(" param.ChanceTypeId == 0 ")
  62 + msg = protocol.BadRequestParam("10108")
  63 + return
  64 + }
  65 + if param.GraspScore < 0 || param.GraspScore > 100 {
  66 + log.Error(" param.GraspScore < 0 || param.GraspScore > 100 ")
  67 + msg = protocol.BadRequestParam("10121")
  68 + return
  69 + }
  70 + if param.UserGraspScore < 0 || param.UserGraspScore > 100 {
  71 + log.Error("param.UserGraspScore < 0 || param.UserGraspScore > 100")
  72 + msg = protocol.BadRequestParam("10122")
  73 + }
  74 + var providerScore float64
  75 + for _, v := range param.Provider {
  76 + providerScore += v.UserGraspScore
  77 + }
  78 + remainScore := param.GraspScore - param.UserGraspScore - providerScore
  79 + if remainScore < 0 {
  80 + log.Error("分配的总分不可大于把握分")
  81 + msg = protocol.BadRequestParam("10122")
  82 + return
  83 + }
  84 +
  85 + companyid := c.GetCompanyId()
  86 + err := serveachievement.AddAchievement(&param, companyid)
  87 + msg = protocol.NewReturnResponse(nil, err)
  88 + return
  89 +}
  90 +
  91 +//EditAchievement 编辑成果
  92 +//@router /achievement/edit
  93 +func (c AchievementController) EditAchievement() {
  94 + var msg *protocol.ResponseMessage
  95 + defer func() {
  96 + c.ResposeJson(msg)
  97 + }()
  98 + var param protocol.RequestEditAchievement
  99 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  100 + log.Error("json 解析失败 err:%s", err)
  101 + msg = protocol.BadRequestParam("1")
  102 + return
  103 + }
  104 + if len(param.ChanceData) == 0 {
  105 + log.Error("len(param.ChanceData) == 0 ")
  106 + msg = protocol.BadRequestParam("10109")
  107 + return
  108 + }
  109 + if param.ChanceTypeId == 0 {
  110 + log.Error(" param.ChanceTypeId == 0 ")
  111 + msg = protocol.BadRequestParam("10108")
  112 + return
  113 + }
  114 + if param.GraspScore < 0 || param.GraspScore > 100 {
  115 + log.Error(" param.GraspScore < 0 || param.GraspScore > 100 ")
  116 + msg = protocol.BadRequestParam("10121")
  117 + return
  118 + }
  119 + if param.UserGraspScore < 0 || param.UserGraspScore > 100 {
  120 + log.Error("param.UserGraspScore < 0 || param.UserGraspScore > 100")
  121 + msg = protocol.BadRequestParam("10122")
  122 + }
  123 + var providerScore float64
  124 + for _, v := range param.Provider {
  125 + providerScore += v.UserGraspScore
  126 + }
  127 + remainScore := param.GraspScore - param.UserGraspScore - providerScore
  128 + if remainScore < 0 {
  129 + log.Error("分配的总分不可大于把握分")
  130 + msg = protocol.BadRequestParam("10122")
  131 + return
  132 + }
  133 + companyid := c.GetCompanyId()
  134 + err := serveachievement.EditAchievement(&param, companyid)
  135 + msg = protocol.NewReturnResponse(nil, err)
  136 + return
  137 +}
  138 +
  139 +//EditAchievement 成果详情
  140 +//@router /achievement/info
  141 +func (c AchievementController) AchievementInfo() {
  142 + var msg *protocol.ResponseMessage
  143 + defer func() {
  144 + c.ResposeJson(msg)
  145 + }()
  146 + type Parameter struct {
  147 + Id int64 `json:"id"`
  148 + }
  149 + var param Parameter
  150 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  151 + log.Error("json 解析失败 err:%s", err)
  152 + msg = protocol.BadRequestParam("1")
  153 + return
  154 + }
  155 + companyid := c.GetCompanyId()
  156 + rspData := serveachievement.GetAchievementInfo(param.Id, companyid)
  157 + msg = protocol.NewReturnResponse(rspData, nil)
  158 + return
  159 +}
  160 +
  161 +//EditAchievement 删除成果
  162 +//@router /achievement/delete
  163 +func (c AchievementController) DeleteAchievement() {
  164 + var msg *protocol.ResponseMessage
  165 + defer func() {
  166 + c.ResposeJson(msg)
  167 + }()
  168 + type Parameter struct {
  169 + Id int64 `json:"id"`
  170 + }
  171 + var param Parameter
  172 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  173 + log.Error("json 解析失败 err:%s", err)
  174 + msg = protocol.BadRequestParam("1")
  175 + return
  176 + }
  177 + companyid := c.GetCompanyId()
  178 + var (
  179 + err error
  180 + achievementData *models.Achievement
  181 + )
  182 + achievementData, err = models.GetAchievementById(param.Id)
  183 + if err != nil {
  184 + log.Error("获取achievement数据失败:%s", err)
  185 + msg = protocol.BadRequestParam("1")
  186 + return
  187 + }
  188 + if achievementData.CompanyId != companyid {
  189 + log.Error("achievement数据公司不匹配")
  190 + msg = protocol.BadRequestParam("1")
  191 + return
  192 + }
  193 + achievementData.Status = models.ACHIEVEMENT_STATUS_DEL
  194 + o := orm.NewOrm()
  195 + o.Begin()
  196 + err = models.UpdateAchievementById(achievementData, []string{"Status"})
  197 + if err != nil {
  198 + o.Rollback()
  199 + log.Error("更新achievement数据失败:%s", err)
  200 + }
  201 + err = models.IncreaseAchevementScore(companyid, -achievementData.GraspScoreRemain, o)
  202 + if err != nil {
  203 + o.Rollback()
  204 + log.Error("更新福利池失败数据失败:%s", err)
  205 + }
  206 + o.Commit()
  207 + msg = protocol.NewReturnResponse(nil, nil)
  208 + return
  209 +}
  210 +
  211 +//EditAchievement 显示隐藏成果
  212 +//@router /achievement/forbid_allow
  213 +func (c AchievementController) ForbidAllowAchievement() {
  214 + var msg *protocol.ResponseMessage
  215 + defer func() {
  216 + c.ResposeJson(msg)
  217 + }()
  218 + type Parameter struct {
  219 + Id int64 `json:"id"`
  220 + Status int8 `json:"status"` //[1:显示][2:隐藏]
  221 + }
  222 + var param Parameter
  223 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  224 + log.Error("json 解析失败 err:%s", err)
  225 + msg = protocol.BadRequestParam("1")
  226 + return
  227 + }
  228 + if param.Status != 1 && param.Status != 2 {
  229 + msg = protocol.BadRequestParam("1")
  230 + return
  231 + }
  232 + companyid := c.GetCompanyId()
  233 + var (
  234 + err error
  235 + achievementData *models.Achievement
  236 + )
  237 + achievementData, err = models.GetAchievementById(param.Id)
  238 + if err != nil {
  239 + log.Error("获取achievement数据失败:%s", err)
  240 + msg = protocol.BadRequestParam("1")
  241 + return
  242 + }
  243 + if achievementData.CompanyId != companyid {
  244 + log.Error("achievement数据公司不匹配")
  245 + msg = protocol.BadRequestParam("1")
  246 + return
  247 + }
  248 +
  249 + achievementData.Status = param.Status
  250 + err = models.UpdateAchievementById(achievementData, []string{"Status"})
  251 + if err != nil {
  252 + log.Error("更新achievement数据失败:%s", err)
  253 + }
  254 + msg = protocol.NewReturnResponse(nil, nil)
  255 + return
  256 +}
  257 +
  258 +//AchievementScoreRemain 获取福利池分数
  259 +//@router /achievement/remain/score
  260 +func (c AchievementController) AchievementScoreRemain() {
  261 + var msg *protocol.ResponseMessage
  262 + defer func() {
  263 + c.ResposeJson(msg)
  264 + }()
  265 + companyid := c.GetCompanyId()
  266 + scoreData, err := models.GetAchevementScoreByCompanyId(companyid)
  267 + rspData := map[string]string{
  268 + "score": "0",
  269 + }
  270 + if err == nil {
  271 + rspData["score"] = fmt.Sprintf("%.1f", scoreData.GraspScoreRemain)
  272 + }
  273 + msg = protocol.NewReturnResponse(rspData, nil)
  274 + return
  275 +}
@@ -142,3 +142,29 @@ func (c *AuditController) AllowForbidAudit() { @@ -142,3 +142,29 @@ func (c *AuditController) AllowForbidAudit() {
142 msg = protocol.NewReturnResponse(nil, err) 142 msg = protocol.NewReturnResponse(nil, err)
143 return 143 return
144 } 144 }
  145 +
  146 +//GetChanceReviseLog
  147 +//@router /v1/audit/revise/info
  148 +func (c *AuditController) GetChanceReviseLog() {
  149 + var msg *protocol.ResponseMessage
  150 + defer func() {
  151 + c.ResposeJson(msg)
  152 + }()
  153 + type Parameter struct {
  154 + FlowLogId int64 `json:"flow_log_id"`
  155 + ChanceId string `json:"chance_id"`
  156 + }
  157 + var param Parameter
  158 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  159 + log.Error("json 解析失败", err)
  160 + msg = protocol.BadRequestParam("1")
  161 + return
  162 + }
  163 + chanceId, _ := strconv.ParseInt(param.ChanceId, 10, 64)
  164 + companyId := c.GetCompanyId()
  165 + rspData, err := serveaudit.GetChanceReviseLog(param.FlowLogId, chanceId, companyId)
  166 + msg = protocol.NewReturnResponse(rspData, err)
  167 + return
  168 +}
  169 +
  170 +// GetChanceReviseLog
@@ -134,6 +134,49 @@ func (c *AuthController) LoginSms() { @@ -134,6 +134,49 @@ func (c *AuthController) LoginSms() {
134 return 134 return
135 } 135 }
136 136
  137 +// LoginSecret 使用秘钥进行登录
  138 +// @router /login [post]
  139 +func (c *AuthController) LoginSecretKey() {
  140 + var msg *protocol.ResponseMessage
  141 + defer func() {
  142 + c.ResposeJson(msg)
  143 + }()
  144 + type Parameter struct {
  145 + Secret string `json:"secret"`
  146 + }
  147 + var param Parameter
  148 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  149 + log.Error("json 解析失败", err)
  150 + msg = protocol.BadRequestParam("1")
  151 + return
  152 + }
  153 + if len(param.Secret) == 0 {
  154 + msg = protocol.BadRequestParam("10080")
  155 + return
  156 + }
  157 + logintoken, err := serveauth.LoginAuthBySecretKey(param.Secret)
  158 + if err != nil {
  159 + msg = &protocol.ResponseMessage{
  160 + Errno: -1,
  161 + Errmsg: err.Error(),
  162 + }
  163 + return
  164 + }
  165 + err = serveauth.ResetLoginToken(logintoken)
  166 + if err != nil {
  167 + log.Error("token 信息记录数据库失败")
  168 + }
  169 + err = serveauth.ResetLoginTokenRedis(logintoken)
  170 + if err != nil {
  171 + log.Error("token 信息记录redis失败")
  172 + }
  173 + data := protocol.ResponseLogin{
  174 + Access: logintoken,
  175 + }
  176 + msg = protocol.NewReturnResponse(data, nil)
  177 + return
  178 +}
  179 +
137 //SmsCode 发送验证码短信 180 //SmsCode 发送验证码短信
138 //@router /auth/smscode 181 //@router /auth/smscode
139 func (c *AuthController) SmsCode() { 182 func (c *AuthController) SmsCode() {
@@ -183,3 +183,66 @@ func (c *CommonController) SelectorRoleUser() { @@ -183,3 +183,66 @@ func (c *CommonController) SelectorRoleUser() {
183 msg = protocol.NewReturnResponse(list, err) 183 msg = protocol.NewReturnResponse(list, err)
184 return 184 return
185 } 185 }
  186 +
  187 +//SelectorChanceType 获取机会类型列表
  188 +func (c *CommonController) SelectorChanceType() {
  189 + var msg *protocol.ResponseMessage
  190 + defer func() {
  191 + c.ResposeJson(msg)
  192 + }()
  193 +
  194 + companyid := c.GetCompanyId()
  195 + templatelist := servecommon.SelectGetTemplateList(companyid)
  196 + chanceTypeList := servecommon.SeleteGetChanceTypeList(companyid)
  197 + data := map[string]interface{}{
  198 + "template": templatelist,
  199 + "chance_type": chanceTypeList,
  200 + }
  201 + msg = protocol.NewReturnResponse(data, nil)
  202 + return
  203 +}
  204 +
  205 +//SelectCompanyUserList 下拉选择框 获取公司成员列表
  206 +func (c *CommonController) SelectCompanyUserList() {
  207 + var msg *protocol.ResponseMessage
  208 + defer func() {
  209 + c.ResposeJson(msg)
  210 + }()
  211 + type Parameter struct {
  212 + protocol.RequestPageInfo
  213 + UserName string `json:"user_name"`
  214 + }
  215 + var param Parameter
  216 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  217 + log.Error("json 解析失败 err:%s", err)
  218 + msg = protocol.BadRequestParam("1")
  219 + return
  220 + }
  221 + companyid := c.GetCompanyId()
  222 + listData := servecommon.SelectCompanyUserList(param.PageIndex, param.PageSize, companyid, param.UserName)
  223 + msg = protocol.NewPageDataResponse(listData, nil)
  224 + return
  225 +}
  226 +
  227 +//SelectChanceList 下拉选择框 获取机会列表
  228 +func (c *CommonController) SelectChanceList() {
  229 + var msg *protocol.ResponseMessage
  230 + defer func() {
  231 + c.ResposeJson(msg)
  232 + }()
  233 + type Parameter struct {
  234 + protocol.RequestPageInfo
  235 + SearchType int `json:"search_type"` //1:根据机会编码搜索 2:根据提交人搜索
  236 + ChanceCode string `json:"chance_code"`
  237 + }
  238 + var param Parameter
  239 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  240 + log.Error("json 解析失败 err:%s", err)
  241 + msg = protocol.BadRequestParam("1")
  242 + return
  243 + }
  244 + companyid := c.GetCompanyId()
  245 + listData := servecommon.SelectChanceList(param.PageIndex, param.PageSize, companyid, param.SearchType, param.ChanceCode)
  246 + msg = protocol.NewPageDataResponse(listData, nil)
  247 + return
  248 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + "oppmg/common/log"
  7 + "oppmg/protocol"
  8 + "oppmg/services/platform"
  9 +)
  10 +
  11 +type PlatformController struct {
  12 + BaseController
  13 +}
  14 +
  15 +//
  16 +func (c PlatformController) UpdateData() {
  17 + defer func() {
  18 + c.Data["json"] = map[string]interface{}{
  19 + "code": 0,
  20 + "msg": "ok",
  21 + }
  22 + c.ServeJSON()
  23 + }()
  24 + var param platform.CommonProtocol
  25 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  26 + log.Error("json 解析失败 err:%s", err)
  27 + return
  28 + }
  29 + m, err := platform.NewPlatformAction(param.Module)
  30 + if err != nil {
  31 + log.Error("同步数据发生错误,err%s", err)
  32 + return
  33 + }
  34 + bt, err := json.Marshal(param.Data)
  35 + if err != nil {
  36 + log.Error("解析param.data数据失败")
  37 + }
  38 + err = m.DoAction(param.Action, bt)
  39 + if err != nil {
  40 + log.Error("同步数据发生错误,module=%s,action=%s,err:%s", param.Module, param.Action, err)
  41 + }
  42 + return
  43 +}
  44 +
  45 +func (c PlatformController) CompanyAdminChance() {
  46 + type Parameter struct {
  47 + CompanyId int64 `json:"company_id"`
  48 + Phone string `json:"phone"`
  49 + }
  50 + var msg = protocol.ErrWithMessage{}
  51 + var param Parameter
  52 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  53 + e := fmt.Errorf("json 解析失败 err:%s", err)
  54 + log.Error(e.Error())
  55 + msg.Errmsg = e.Error()
  56 + return
  57 + }
  58 + err := platform.AdminChance(param.CompanyId, param.Phone)
  59 + if err != nil {
  60 + log.Error("总后台调用CompanyAdminChance发生错误;%s", err)
  61 + msg.Errmsg = err.Error()
  62 + }
  63 + c.Data["json"] = msg
  64 + c.ServeJSON()
  65 + return
  66 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + "oppmg/common/log"
  7 + "oppmg/models"
  8 + "oppmg/protocol"
  9 + serverank "oppmg/services/rank"
  10 + "strings"
  11 + "time"
  12 +)
  13 +
  14 +type RankController struct {
  15 + BaseController
  16 +}
  17 +
  18 +//GetRankType 榜单类型列表
  19 +//@router /rank/list
  20 +func (c RankController) GetRankType() {
  21 + var msg *protocol.ResponseMessage
  22 + defer func() {
  23 + c.ResposeJson(msg)
  24 + }()
  25 + companyid := c.GetCompanyId()
  26 + rspData := serverank.GetRankList(companyid)
  27 + msg = protocol.NewReturnResponse(rspData, nil)
  28 + return
  29 +}
  30 +
  31 +//EditRankType 榜单类型列表添加
  32 +//@router /rank/edit
  33 +func (c RankController) EditRankType() {
  34 + var msg *protocol.ResponseMessage
  35 + defer func() {
  36 + c.ResposeJson(msg)
  37 + }()
  38 + type Parameter struct {
  39 + Id int64 `json:"id"`
  40 + Name string `json:"name"`
  41 + }
  42 + var param Parameter
  43 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  44 + log.Error("json 解析失败 err:%s", err)
  45 + msg = protocol.BadRequestParam("1")
  46 + return
  47 + }
  48 + param.Name = strings.TrimSpace(param.Name)
  49 + n := []rune(param.Name)
  50 + if len(n) > 5 || len(n) == 0 {
  51 + msg = protocol.BadRequestParam("10103")
  52 + return
  53 + }
  54 + companyid := c.GetCompanyId()
  55 + err := serverank.UpdateRankType(param.Id, param.Name, companyid)
  56 + msg = protocol.NewReturnResponse(nil, err)
  57 + return
  58 +}
  59 +
  60 +//EditRankType ...
  61 +//@router /rank/forbid_allow
  62 +func (c RankController) RankTypeForbidAllow() {
  63 + var msg *protocol.ResponseMessage
  64 + defer func() {
  65 + c.ResposeJson(msg)
  66 + }()
  67 + type Parameter struct {
  68 + Id int64 `json:"id"`
  69 + Status int `json:"status"`
  70 + }
  71 + var param Parameter
  72 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  73 + log.Error("json 解析失败 err:%s", err)
  74 + msg = protocol.BadRequestParam("1")
  75 + return
  76 + }
  77 + var err error
  78 + companyid := c.GetCompanyId()
  79 + switch param.Status {
  80 + case 1:
  81 + err = serverank.ForbidRank(param.Id, companyid)
  82 + case 2:
  83 + err = serverank.AllowRank(param.Id, companyid)
  84 + default:
  85 + err = protocol.NewErrWithMessage("1")
  86 + }
  87 + msg = protocol.NewReturnResponse(nil, err)
  88 + return
  89 +}
  90 +
  91 +//RankSeasonList 赛季列表
  92 +//@router /rank/season/list
  93 +func (c RankController) RankSeasonList() {
  94 + var msg *protocol.ResponseMessage
  95 + defer func() {
  96 + c.ResposeJson(msg)
  97 + }()
  98 + type Parameter struct {
  99 + protocol.RequestPageInfo
  100 + RankTypeId int64 `json:"rank_type_id"`
  101 + }
  102 + var param Parameter
  103 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  104 + log.Error("json 解析失败 err:%s", err)
  105 + msg = protocol.BadRequestParam("1")
  106 + return
  107 + }
  108 + companyid := c.GetCompanyId()
  109 + rspData, err := serverank.RankSeasonList(param.PageIndex, param.PageSize, param.RankTypeId, companyid)
  110 + msg = protocol.NewPageDataResponse(rspData, err)
  111 + return
  112 +}
  113 +
  114 +//RankSeasonAdd 赛季列表添加
  115 +//@router /rank/season/add
  116 +func (c RankController) RankSeasonAdd() {
  117 + var msg *protocol.ResponseMessage
  118 + defer func() {
  119 + c.ResposeJson(msg)
  120 + }()
  121 + type Parameter struct {
  122 + RankTypeId int64 `json:"rank_type_id"`
  123 + Name string `json:"name"`
  124 + BeginTime string `json:"begin_time"`
  125 + EndTime string `json:"end_time"`
  126 + }
  127 + var param Parameter
  128 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  129 + log.Error("json 解析失败 err:%s", err)
  130 + msg = protocol.BadRequestParam("1")
  131 + return
  132 + }
  133 + param.Name = strings.TrimSpace(param.Name)
  134 + if len(param.Name) == 0 {
  135 + msg = protocol.BadRequestParam("10104")
  136 + return
  137 + }
  138 + param.BeginTime = strings.TrimSpace(param.BeginTime)
  139 + if len(param.BeginTime) == 0 {
  140 + msg = protocol.BadRequestParam("10105")
  141 + return
  142 + }
  143 + param.EndTime = strings.TrimSpace(param.EndTime)
  144 + if len(param.EndTime) == 0 {
  145 + msg = protocol.BadRequestParam("10106")
  146 + return
  147 + }
  148 + var (
  149 + beginTime int64
  150 + endTime int64
  151 + )
  152 + t1, err := time.ParseInLocation("2006-01-02", param.BeginTime, time.Local)
  153 + if err != nil {
  154 + msg = protocol.BadRequestParam("10105")
  155 + return
  156 + }
  157 + beginTime = t1.Unix()
  158 + t2, err := time.ParseInLocation("2006-01-02", param.EndTime, time.Local)
  159 + if err != nil {
  160 + msg = protocol.BadRequestParam("10106")
  161 + return
  162 + }
  163 + endTime = t2.Unix() + 86399 //60*60*24-1
  164 + if beginTime > endTime {
  165 + msg = protocol.BadRequestParam("1")
  166 + return
  167 + }
  168 + ok := serverank.RankPeriodCheckTime(param.RankTypeId, beginTime, endTime, 0)
  169 + if !ok {
  170 + msg = protocol.BadRequestParam("10101")
  171 + return
  172 + }
  173 + companyid := c.GetCompanyId()
  174 + err = serverank.AddRankPeriod(param.RankTypeId, beginTime, endTime, param.Name, companyid)
  175 + msg = protocol.NewReturnResponse(nil, err)
  176 + return
  177 +}
  178 +
  179 +//RankSeasonEdit ...
  180 +//@router /rank/season/edit
  181 +func (c RankController) RankSeasonEdit() {
  182 + var msg *protocol.ResponseMessage
  183 + defer func() {
  184 + c.ResposeJson(msg)
  185 + }()
  186 + type Parameter struct {
  187 + Id int64 `json:"id"`
  188 + Name string `json:"name"`
  189 + RankTypeId int64 `json:"rank_type_id"`
  190 + BeginTime string `json:"begin_time"`
  191 + EndTime string `json:"end_time"`
  192 + }
  193 + var param Parameter
  194 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  195 + log.Error("json 解析失败 err:%s", err)
  196 + msg = protocol.BadRequestParam("1")
  197 + return
  198 + }
  199 + param.Name = strings.TrimSpace(param.Name)
  200 + if len(param.Name) == 0 {
  201 + msg = protocol.BadRequestParam("1")
  202 + return
  203 + }
  204 + param.BeginTime = strings.TrimSpace(param.BeginTime)
  205 + if len(param.BeginTime) == 0 {
  206 + msg = protocol.BadRequestParam("10105")
  207 + return
  208 + }
  209 + param.EndTime = strings.TrimSpace(param.EndTime)
  210 + if len(param.EndTime) == 0 {
  211 + msg = protocol.BadRequestParam("10106")
  212 + return
  213 + }
  214 + var (
  215 + beginTime int64
  216 + endTime int64
  217 + )
  218 + t1, err := time.ParseInLocation("2006-01-02", param.BeginTime, time.Local)
  219 + if err != nil {
  220 + log.Error(err.Error())
  221 + msg = protocol.BadRequestParam("10105")
  222 + return
  223 + }
  224 + beginTime = t1.Unix()
  225 + t2, err := time.ParseInLocation("2006-01-02", param.EndTime, time.Local)
  226 + if err != nil {
  227 + log.Error(err.Error())
  228 + msg = protocol.BadRequestParam("10106")
  229 + return
  230 + }
  231 +
  232 + endTime = t2.Unix() + 86399 //60*60*24-1
  233 + if beginTime > endTime {
  234 + msg = protocol.BadRequestParam("1")
  235 + return
  236 + }
  237 + ok := serverank.RankPeriodCheckTime(param.RankTypeId, beginTime, endTime, param.Id)
  238 + if !ok {
  239 + msg = protocol.BadRequestParam("10101")
  240 + return
  241 + }
  242 + companyid := c.GetCompanyId()
  243 + fmt.Println(beginTime, endTime)
  244 + err = serverank.EditRankPeriod(param.Id, beginTime, endTime, param.Name, companyid)
  245 + msg = protocol.NewReturnResponse(nil, err)
  246 + return
  247 +}
  248 +
  249 +//RankRangeList 赛季榜单参与人列表
  250 +//@router /rank/range/list
  251 +func (c RankController) RankRangeList() {
  252 + var msg *protocol.ResponseMessage
  253 + defer func() {
  254 + c.ResposeJson(msg)
  255 + }()
  256 + type Parameter struct {
  257 + RankTypeId int64 `json:"rank_type_id"`
  258 + }
  259 + var param Parameter
  260 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  261 + log.Error("json 解析失败 err:%s", err)
  262 + msg = protocol.BadRequestParam("1")
  263 + return
  264 + }
  265 + companyid := c.GetCompanyId()
  266 + rspData := serverank.GetRankRangeList(companyid, param.RankTypeId)
  267 + msg = protocol.NewReturnResponse(rspData, nil)
  268 + return
  269 +}
  270 +
  271 +//RankRangeAdd 赛季榜单参与人列表添加
  272 +//@router /rank/range/add
  273 +func (c RankController) RankRangeAdd() {
  274 + var msg *protocol.ResponseMessage
  275 + defer func() {
  276 + c.ResposeJson(msg)
  277 + }()
  278 + type Parameter struct {
  279 + RankTypeId int64 `json:"rank_type_id"`
  280 + Name string `json:"name"`
  281 + RangeType int8 `json:"range_type"`
  282 + RelationId []int64 `json:"relation_id"`
  283 + }
  284 + var param Parameter
  285 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  286 + log.Error("json 解析失败 err:%s", err)
  287 + msg = protocol.BadRequestParam("1")
  288 + return
  289 + }
  290 + param.Name = strings.TrimSpace(param.Name)
  291 + n := []rune(param.Name)
  292 + if len(n) == 0 || len(n) > 5 {
  293 + msg = protocol.BadRequestParam("10107")
  294 + return
  295 + }
  296 + ok := serverank.RankRangeNameOnlyOne(param.RankTypeId, 0, param.Name)
  297 + if !ok {
  298 + msg = protocol.BadRequestParam("10125")
  299 + return
  300 + }
  301 + switch param.RangeType {
  302 + case 1:
  303 + param.RangeType = models.RANK_RANGE_TYPE_EMPLAYEE
  304 + case 2:
  305 +
  306 + param.RangeType = models.RANK_RANGE_TYPE_DEPARTMENT
  307 +
  308 + default:
  309 + log.Error("param.RangeType err")
  310 + msg = protocol.BadRequestParam("1")
  311 + return
  312 + }
  313 + companyid := c.GetCompanyId()
  314 + err := serverank.AddRankRange(param.RankTypeId, param.Name, param.RangeType, param.RelationId, companyid)
  315 + msg = protocol.NewReturnResponse(nil, err)
  316 + return
  317 +}
  318 +
  319 +//RankRangeEdit 赛季榜单参与人编辑
  320 +//@router /rank/range/edit
  321 +func (c RankController) RankRangeEdit() {
  322 + var msg *protocol.ResponseMessage
  323 + defer func() {
  324 + c.ResposeJson(msg)
  325 + }()
  326 + type Parameter struct {
  327 + Id int64 `json:"id"`
  328 + Name string `json:"name"`
  329 + RangeType int8 `json:"range_type"`
  330 + RelationId []int64 `json:"relation_id"`
  331 + }
  332 + var param Parameter
  333 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  334 + log.Error("json 解析失败 err:%s", err)
  335 + msg = protocol.BadRequestParam("1")
  336 + return
  337 + }
  338 +
  339 + param.Name = strings.TrimSpace(param.Name)
  340 + n := []rune(param.Name)
  341 + if len(n) == 0 || len(n) > 5 {
  342 + msg = protocol.BadRequestParam("10107")
  343 + return
  344 + }
  345 +
  346 + switch param.RangeType {
  347 + case 1:
  348 + param.RangeType = models.RANK_RANGE_TYPE_EMPLAYEE
  349 + case 2:
  350 + param.RangeType = models.RANK_RANGE_TYPE_DEPARTMENT
  351 +
  352 + default:
  353 + log.Error("param.RangeType err")
  354 + msg = protocol.BadRequestParam("1")
  355 + return
  356 + }
  357 + companyid := c.GetCompanyId()
  358 + err := serverank.EditRankRange(param.Id, param.Name, param.RangeType, param.RelationId, companyid)
  359 + msg = protocol.NewReturnResponse(nil, err)
  360 + return
  361 +}
  362 +
  363 +//RankRangeForbidAllow ...
  364 +//@router /rank/range/forbid_allow
  365 +func (c RankController) RankRangeForbidAllow() {
  366 + var msg *protocol.ResponseMessage
  367 + defer func() {
  368 + c.ResposeJson(msg)
  369 + }()
  370 + type Parameter struct {
  371 + Id int64 `json:"id"`
  372 + Status int `json:"status"`
  373 + }
  374 + var param Parameter
  375 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  376 + log.Error("json 解析失败 err:%s", err)
  377 + msg = protocol.BadRequestParam("1")
  378 + return
  379 + }
  380 + var err error
  381 + companyid := c.GetCompanyId()
  382 + switch param.Status {
  383 + case 1:
  384 + err = serverank.ForbidRankRange(param.Id, companyid)
  385 + case 2:
  386 + err = serverank.AllowRankRange(param.Id, companyid)
  387 + default:
  388 + err = protocol.NewErrWithMessage("1")
  389 + }
  390 + msg = protocol.NewReturnResponse(nil, err)
  391 + return
  392 +}
  393 +
  394 +//RankRangeInfo 赛季榜单参与人详情
  395 +//@router /rank/range/info
  396 +func (c RankController) RankRangeInfo() {
  397 + var msg *protocol.ResponseMessage
  398 + defer func() {
  399 + c.ResposeJson(msg)
  400 + }()
  401 + type Parameter struct {
  402 + Id int64 `json:"id"`
  403 + }
  404 + var param Parameter
  405 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  406 + log.Error("json 解析失败 err:%s", err)
  407 + msg = protocol.BadRequestParam("1")
  408 + return
  409 + }
  410 + // companyid := c.GetCompanyId()
  411 + rspData := serverank.GetRankRangeInfo(param.Id)
  412 + switch rspData.RangeType {
  413 + case models.RANK_RANGE_TYPE_DEPARTMENT, models.RANK_RANGE_TYPE_DEPARTMENTALL:
  414 + //部门
  415 + rspData.RangeType = 2
  416 + case models.RANK_RANGE_TYPE_EMPLAYEE, models.RANK_RANGE_TYPE_EMPLAYEEALL:
  417 + //员工
  418 + rspData.RangeType = 1
  419 +
  420 + }
  421 + msg = protocol.NewReturnResponse(rspData, nil)
  422 + return
  423 +}
  424 +
  425 +//RankRangeSort ...
  426 +//@router /rank/range/sort
  427 +func (c RankController) RankRangeSort() {
  428 + var msg *protocol.ResponseMessage
  429 + defer func() {
  430 + c.ResposeJson(msg)
  431 + }()
  432 + type Parameter struct {
  433 + RankTypeId int64 `json:"rank_type_id"`
  434 + Id []int64 `json:"id"`
  435 + }
  436 + var param Parameter
  437 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  438 + log.Error("json 解析失败 err:%s", err)
  439 + msg = protocol.BadRequestParam("1")
  440 + return
  441 + }
  442 + err := serverank.RankRangeSort(param.Id)
  443 + msg = protocol.NewReturnResponse(nil, err)
  444 + return
  445 +}
  446 +
  447 +//RankItemList 评比项列表
  448 +//@router /rank/item/list
  449 +func (c RankController) RankItemList() {
  450 + var msg *protocol.ResponseMessage
  451 + defer func() {
  452 + c.ResposeJson(msg)
  453 + }()
  454 + type Parameter struct {
  455 + RankTypeId int64 `json:"rank_type_id"`
  456 + }
  457 + var param Parameter
  458 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  459 + log.Error("json 解析失败 err:%s", err)
  460 + msg = protocol.BadRequestParam("1")
  461 + return
  462 + }
  463 + companyid := c.GetCompanyId()
  464 + items := serverank.GetRankItemList(companyid, param.RankTypeId)
  465 + rspdata := map[string][]protocol.RankItemInfo{
  466 + "all": serverank.AllRankItem,
  467 + "checked": items,
  468 + }
  469 + msg = protocol.NewReturnResponse(rspdata, nil)
  470 + return
  471 +}
  472 +
  473 +//RankItemEdit ...
  474 +//@router /rank/item/edit
  475 +func (c RankController) RankItemEdit() {
  476 + var msg *protocol.ResponseMessage
  477 + defer func() {
  478 + c.ResposeJson(msg)
  479 + }()
  480 + type Parameter struct {
  481 + RankTypeId int64 `json:"rank_type_id"`
  482 + ItemKey []string `json:"item_key"`
  483 + }
  484 + var param Parameter
  485 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  486 + log.Error("json 解析失败 err:%s", err)
  487 + msg = protocol.BadRequestParam("1")
  488 + return
  489 + }
  490 + if len(param.ItemKey) > 4 {
  491 + msg = protocol.BadRequestParam("10123")
  492 + return
  493 + }
  494 + companyid := c.GetCompanyId()
  495 + err := serverank.GetRankItemEdit(companyid, param.RankTypeId, param.ItemKey)
  496 + msg = protocol.NewReturnResponse(nil, err)
  497 + return
  498 +}
  499 +
  500 +//RankRangeMove 赛季榜单参与人分组 批量移动
  501 +//@router /rank/range/move
  502 +func (c RankController) RankRangeMove() {
  503 + var msg *protocol.ResponseMessage
  504 + defer func() {
  505 + c.ResposeJson(msg)
  506 + }()
  507 + type Parameter struct {
  508 + FromId int64 `json:"from_id"`
  509 + ToId int64 `json:"to_id"`
  510 + RelationId []int64 `json:"relation_id"`
  511 + }
  512 + var param Parameter
  513 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  514 + log.Error("json 解析失败 err:%s", err)
  515 + msg = protocol.BadRequestParam("1")
  516 + return
  517 + }
  518 + companyid := c.GetCompanyId()
  519 + err := serverank.RankRangeMove(param.FromId, param.ToId, param.RelationId, companyid)
  520 + msg = protocol.NewReturnResponse(nil, err)
  521 + return
  522 +}
  523 +
  524 +//RankTypeConfig 赛季榜单的一些特殊配置(自动创建赛季)
  525 +//@router /rank/type/config_set
  526 +func (c RankController) RankTypeConfigSet() {
  527 + var msg *protocol.ResponseMessage
  528 + defer func() {
  529 + c.ResposeJson(msg)
  530 + }()
  531 + type Parameter struct {
  532 + RankTypeId int64 `json:"rank_type_id"`
  533 + AutoCreate int8 `json:"auto_create"` //【0:不自动创建】【1:自动创建】
  534 + AutoCreateDay int `json:"auto_create_day"` //赛季时间, 单位:天
  535 + }
  536 + var param Parameter
  537 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  538 + log.Error("json 解析失败 err:%s", err)
  539 + msg = protocol.BadRequestParam("1")
  540 + return
  541 + }
  542 + companyid := c.GetCompanyId()
  543 + var (
  544 + err error
  545 + rankType *models.RankType
  546 + )
  547 + rankType, err = models.GetRankById(param.RankTypeId)
  548 + if err != nil {
  549 + log.Error("获取rank_type数据失败:%s", err)
  550 + e := protocol.NewErrWithMessage("1")
  551 + msg = protocol.NewReturnResponse(nil, e)
  552 + return
  553 + }
  554 + if rankType.CompanyId != companyid {
  555 + log.Error("公司不匹配")
  556 + e := protocol.NewErrWithMessage("1")
  557 + msg = protocol.NewReturnResponse(nil, e)
  558 + return
  559 + }
  560 + if param.AutoCreate > 1 || param.AutoCreate < 0 {
  561 + e := protocol.NewErrWithMessage("1")
  562 + msg = protocol.NewReturnResponse(nil, e)
  563 + return
  564 + }
  565 + rankType.AutoCreate = param.AutoCreate
  566 + rankType.AutoPeriod = param.AutoCreateDay
  567 + err = models.UpdateRankById(rankType, []string{"AutoCreate", "AutoPeriod"})
  568 + if err != nil {
  569 + log.Error("更新rank_type数据失败;%s", err)
  570 + e := protocol.NewErrWithMessage("1")
  571 + msg = protocol.NewReturnResponse(nil, e)
  572 + return
  573 + }
  574 + msg = protocol.NewReturnResponse(nil, nil)
  575 + return
  576 +}
  577 +
  578 +//RankTypeConfig 赛季榜单的一些特殊配置(自动创建赛季)
  579 +//@router /rank/type/config_show
  580 +func (c RankController) RankTypeConfigShow() {
  581 + var msg *protocol.ResponseMessage
  582 + defer func() {
  583 + c.ResposeJson(msg)
  584 + }()
  585 + type Parameter struct {
  586 + RankTypeId int64 `json:"rank_type_id"`
  587 + }
  588 + var param Parameter
  589 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  590 + log.Error("json 解析失败 err:%s", err)
  591 + msg = protocol.BadRequestParam("1")
  592 + return
  593 + }
  594 + companyid := c.GetCompanyId()
  595 + var (
  596 + err error
  597 + rankType *models.RankType
  598 + )
  599 + rankType, err = models.GetRankById(param.RankTypeId)
  600 + if err != nil {
  601 + log.Error("获取rank_type数据失败:%s", err)
  602 + e := protocol.NewErrWithMessage("1")
  603 + msg = protocol.NewReturnResponse(nil, e)
  604 + return
  605 + }
  606 + if rankType.CompanyId != companyid {
  607 + log.Error("公司不匹配")
  608 + e := protocol.NewErrWithMessage("1")
  609 + msg = protocol.NewReturnResponse(nil, e)
  610 + return
  611 + }
  612 + v := struct {
  613 + AutoCreate int8 `json:"auto_create"`
  614 + AutoCreateDay int `json:"auto_create_day"`
  615 + }{
  616 + AutoCreate: rankType.AutoCreate,
  617 + AutoCreateDay: rankType.AutoPeriod,
  618 + }
  619 + msg = protocol.NewReturnResponse(v, nil)
  620 + return
  621 +}
@@ -8,6 +8,8 @@ import ( @@ -8,6 +8,8 @@ import (
8 "oppmg/common/config" 8 "oppmg/common/config"
9 "oppmg/common/log" 9 "oppmg/common/log"
10 10
  11 + "oppmg/services/crontab"
  12 +
11 "github.com/astaxie/beego" 13 "github.com/astaxie/beego"
12 "github.com/astaxie/beego/orm" 14 "github.com/astaxie/beego/orm"
13 _ "github.com/go-sql-driver/mysql" 15 _ "github.com/go-sql-driver/mysql"
@@ -23,5 +25,6 @@ func init() { @@ -23,5 +25,6 @@ func init() {
23 func main() { 25 func main() {
24 26
25 log.Debug("%s 应用启动", time.Now().String()) 27 log.Debug("%s 应用启动", time.Now().String())
  28 + crontab.Run()
26 beego.Run() 29 beego.Run()
27 } 30 }
  1 +package models
  2 +
  3 +import (
  4 + "time"
  5 +
  6 + "github.com/astaxie/beego/orm"
  7 +)
  8 +
  9 +type AchevementScore struct {
  10 + Id int64 `orm:"column(id);auto"`
  11 + GraspScoreRemain float64 `orm:"column(grasp_score_remain);null;digits(10);decimals(1)" description:"福利池总分 ,来源achievement中的评分"`
  12 + CompanyId int64 `orm:"column(company_id)"`
  13 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null"`
  14 + UpdateAt time.Time `orm:"column(update_at);type(timestamp);null"`
  15 +}
  16 +
  17 +func (t *AchevementScore) TableName() string {
  18 + return "achevement_score"
  19 +}
  20 +
  21 +func init() {
  22 + orm.RegisterModel(new(AchevementScore))
  23 +}
  24 +
  25 +// AddAchevementScore insert a new AchevementScore into database and returns
  26 +// last inserted Id on success.
  27 +func AddAchevementScore(m *AchevementScore, o orm.Ormer) (id int64, err error) {
  28 + id, err = o.Insert(m)
  29 + return
  30 +}
  31 +
  32 +// GetAchevementScoreById retrieves AchevementScore by Id. Returns error if
  33 +// Id doesn't exist
  34 +func GetAchevementScoreById(id int64) (v *AchevementScore, err error) {
  35 + o := orm.NewOrm()
  36 + v = &AchevementScore{Id: id}
  37 + if err = o.Read(v); err == nil {
  38 + return v, nil
  39 + }
  40 + return nil, err
  41 +}
  42 +
  43 +func GetAchevementScoreByCompanyId(companyid int64) (v *AchevementScore, err error) {
  44 + o := orm.NewOrm()
  45 + v = &AchevementScore{}
  46 + ok := o.QueryTable(&AchevementScore{}).
  47 + Filter("company_id", companyid).
  48 + Exist()
  49 + if !ok {
  50 + return v, nil
  51 + }
  52 + err = o.QueryTable(&AchevementScore{}).
  53 + Filter("company_id", companyid).
  54 + One(v)
  55 + return v, err
  56 +}
  57 +
  58 +func IncreaseAchevementScore(companyid int64, addScore float64, o orm.Ormer) error {
  59 + v := &AchevementScore{}
  60 + ok := o.QueryTable(&AchevementScore{}).
  61 + Filter("company_id", companyid).
  62 + Exist()
  63 + if ok {
  64 + nowTime := time.Now().Format("2006-01-02 15:04:05")
  65 + sql := `update achevement_score set grasp_score_remain=grasp_score_remain+?,update_at=? where company_id=?`
  66 + //存在,更新
  67 + _, err := o.Raw(sql, addScore, nowTime, companyid).Exec()
  68 + return err
  69 + }
  70 + //不存在
  71 + v.CompanyId = companyid
  72 + v.GraspScoreRemain = addScore
  73 + v.CreateAt = time.Now()
  74 + _, err := o.Insert(v)
  75 + return err
  76 +}
  1 +package models
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/common/log"
  6 + "time"
  7 +
  8 + "github.com/astaxie/beego/orm"
  9 +)
  10 +
  11 +type Achievement struct {
  12 + Id int64 `orm:"column(id);auto" description:"id 主键"`
  13 + CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
  14 + DepartmentId int64 `orm:"column(department_id);null" description:"表department.id 部门id (创建成果指定的部门)"`
  15 + UserCompanyId int64 `orm:"column(user_company_id)" description:"把握人 表user_company.id id"`
  16 + ChanceTypeId int64 `orm:"column(chance_type_id);null" description:"表chance_type.id 机会类型 "`
  17 + AuditTemplateId int64 `orm:"column(audit_template_id);null" description:"表audit_template.id 所属审批模板编号"`
  18 + SourceContent string `orm:"column(source_content);null" description:"成果详情文本"`
  19 + GraspScore float64 `orm:"column(grasp_score);digits(4);decimals(1)" description:"把握分"`
  20 + UserGraspScore float64 `orm:"column(user_grasp_score);digits(4);decimals(1)" description:"把握人得分"`
  21 + UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
  22 + CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
  23 + ViewTotal int `orm:"column(view_total);null" description:"查看总数"`
  24 + CommentTotal int `orm:"column(comment_total);null" description:"评论总数"`
  25 + ZanTotal int `orm:"column(zan_total);null" description:"点赞总数"`
  26 + Status int8 `orm:"column(status);null" description:"机会状态 1:开启 2:关闭 0:删除"`
  27 + Images string `orm:"column(images);null" description:"图片 json"`
  28 + GraspScoreRemain float64 `orm:"column(grasp_score_remain);digits(4);decimals(1)" `
  29 +}
  30 +
  31 +func (t *Achievement) TableName() string {
  32 + return "achievement"
  33 +}
  34 +
  35 +func init() {
  36 + orm.RegisterModel(new(Achievement))
  37 +}
  38 +
  39 +//机会状态 1:开启 2:关闭 0:删除
  40 +const (
  41 + ACHIEVEMENT_STATUS_DEL int8 = 0 //删除
  42 + ACHIEVEMENT_STATUS_YES int8 = 1 //开启
  43 + ACHIEVEMENT_STATUS_NO int8 = 2 //关闭
  44 +)
  45 +
  46 +// AddAchievement insert a new Achievement into database and returns
  47 +// last inserted Id on success.
  48 +func AddAchievement(m *Achievement, om ...orm.Ormer) (id int64, err error) {
  49 + var o orm.Ormer
  50 + if len(om) > 0 {
  51 + o = om[0]
  52 + } else {
  53 + o = orm.NewOrm()
  54 + }
  55 + id, err = o.Insert(m)
  56 + return
  57 +}
  58 +
  59 +// GetAchievementById retrieves Achievement by Id. Returns error if
  60 +// Id doesn't exist
  61 +func GetAchievementById(id int64) (v *Achievement, err error) {
  62 + o := orm.NewOrm()
  63 + v = &Achievement{Id: id}
  64 + if err = o.Read(v); err == nil {
  65 + return v, nil
  66 + }
  67 + return nil, err
  68 +}
  69 +
  70 +// UpdateAchievement updates Achievement by Id and returns error if
  71 +// the record to be updated doesn't exist
  72 +func UpdateAchievementById(m *Achievement, cols []string, om ...orm.Ormer) (err error) {
  73 + var o orm.Ormer
  74 + if len(om) > 0 {
  75 + o = om[0]
  76 + } else {
  77 + o = orm.NewOrm()
  78 + }
  79 + m.UpdateAt = time.Now()
  80 + if len(cols) > 0 {
  81 + cols = append(cols, "UpdateAt")
  82 + }
  83 + var num int64
  84 + if num, err = o.Update(m, cols...); err == nil {
  85 + log.Info("Number of records updated in database:", num)
  86 + }
  87 +
  88 + return
  89 +}
  90 +
  91 +// DeleteAchievement deletes Achievement by Id and returns error if
  92 +// the record to be deleted doesn't exist
  93 +func DeleteAchievement(id int64) (err error) {
  94 + o := orm.NewOrm()
  95 + v := Achievement{Id: id}
  96 + // ascertain id exists in the database
  97 + if err = o.Read(&v); err == nil {
  98 + var num int64
  99 + if num, err = o.Delete(&Achievement{Id: id}); err == nil {
  100 + fmt.Println("Number of records deleted in database:", num)
  101 + }
  102 + }
  103 + return
  104 +}
  1 +package models
  2 +
  3 +import (
  4 + "fmt"
  5 + "time"
  6 +
  7 + "github.com/astaxie/beego/orm"
  8 +)
  9 +
  10 +type AchievementChance struct {
  11 + Id int64 `orm:"column(id);auto"`
  12 + AchievementId int64 `orm:"column(achievement_id);null" description:"成果编号 表achievement.id"`
  13 + ChanceId int64 `orm:"column(chance_id);null" description:"机会编号 表chance.id"`
  14 + ChanceCode string `orm:"column(chance_code);size(255);null" description:"机会编号 表chance.code"`
  15 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  16 +}
  17 +
  18 +func (t *AchievementChance) TableName() string {
  19 + return "achievement_chance"
  20 +}
  21 +
  22 +func init() {
  23 + orm.RegisterModel(new(AchievementChance))
  24 +}
  25 +
  26 +// AddAchievementChance insert a new AchievementChance into database and returns
  27 +// last inserted Id on success.
  28 +func AddAchievementChance(m *AchievementChance) (id int64, err error) {
  29 + o := orm.NewOrm()
  30 + id, err = o.Insert(m)
  31 + return
  32 +}
  33 +
  34 +// GetAchievementChanceById retrieves AchievementChance by Id. Returns error if
  35 +// Id doesn't exist
  36 +func GetAchievementChanceById(id int64) (v *AchievementChance, err error) {
  37 + o := orm.NewOrm()
  38 + v = &AchievementChance{Id: id}
  39 + if err = o.Read(v); err == nil {
  40 + return v, nil
  41 + }
  42 + return nil, err
  43 +}
  44 +
  45 +// UpdateAchievementChance updates AchievementChance by Id and returns error if
  46 +// the record to be updated doesn't exist
  47 +func UpdateAchievementChanceById(m *AchievementChance) (err error) {
  48 + o := orm.NewOrm()
  49 + v := AchievementChance{Id: m.Id}
  50 + // ascertain id exists in the database
  51 + if err = o.Read(&v); err == nil {
  52 + var num int64
  53 + if num, err = o.Update(m); err == nil {
  54 + fmt.Println("Number of records updated in database:", num)
  55 + }
  56 + }
  57 + return
  58 +}
  59 +
  60 +func GetAchievementChanceByAchieve(achievementid int64) ([]AchievementChance, error) {
  61 + var (
  62 + err error
  63 + data []AchievementChance
  64 + )
  65 + o := orm.NewOrm()
  66 + _, err = o.QueryTable(&AchievementChance{}).
  67 + Filter("achievement_id", achievementid).
  68 + All(&data)
  69 + if err == orm.ErrNoRows {
  70 + return data, nil
  71 + }
  72 + return data, err
  73 +}
  1 +package models
  2 +
  3 +import (
  4 + "fmt"
  5 + "time"
  6 +
  7 + "github.com/astaxie/beego/orm"
  8 +)
  9 +
  10 +type AchievementProvider struct {
  11 + Id int64 `orm:"column(id);auto" description:"主键id"`
  12 + AchievementId int64 `orm:"column(achievement_id);null" description:"表achievement.id"`
  13 + UserCompanyId int64 `orm:"column(user_company_id);null" description:"user_company.id"`
  14 + UserGraspScore float64 `orm:"column(user_grasp_score);null;digits(4);decimals(1)" description:"把握人得分"`
  15 + DepartmentId int64 `orm:"column(department_id)"`
  16 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  17 +}
  18 +
  19 +func (t *AchievementProvider) TableName() string {
  20 + return "achievement_provider"
  21 +}
  22 +
  23 +func init() {
  24 + orm.RegisterModel(new(AchievementProvider))
  25 +}
  26 +
  27 +// AddAchievementProvider insert a new AchievementProvider into database and returns
  28 +// last inserted Id on success.
  29 +func AddAchievementProvider(m *AchievementProvider) (id int64, err error) {
  30 + o := orm.NewOrm()
  31 + id, err = o.Insert(m)
  32 + return
  33 +}
  34 +
  35 +// GetAchievementProviderById retrieves AchievementProvider by Id. Returns error if
  36 +// Id doesn't exist
  37 +func GetAchievementProviderById(id int64) (v *AchievementProvider, err error) {
  38 + o := orm.NewOrm()
  39 + v = &AchievementProvider{Id: id}
  40 + if err = o.Read(v); err == nil {
  41 + return v, nil
  42 + }
  43 + return nil, err
  44 +}
  45 +
  46 +// UpdateAchievementProvider updates AchievementProvider by Id and returns error if
  47 +// the record to be updated doesn't exist
  48 +func UpdateAchievementProviderById(m *AchievementProvider) (err error) {
  49 + o := orm.NewOrm()
  50 + v := AchievementProvider{Id: m.Id}
  51 + // ascertain id exists in the database
  52 + if err = o.Read(&v); err == nil {
  53 + var num int64
  54 + if num, err = o.Update(m); err == nil {
  55 + fmt.Println("Number of records updated in database:", num)
  56 + }
  57 + }
  58 + return
  59 +}
  60 +
  61 +func GetAchievementProviderByAchieve(achievementid int64) ([]AchievementProvider, error) {
  62 + var (
  63 + err error
  64 + data []AchievementProvider
  65 + )
  66 + o := orm.NewOrm()
  67 + _, err = o.QueryTable(&AchievementProvider{}).
  68 + Filter("achievement_id", achievementid).
  69 + All(&data)
  70 + if err == orm.ErrNoRows {
  71 + return data, nil
  72 + }
  73 + return data, err
  74 +}
@@ -36,7 +36,7 @@ type ChanceDataSpeechs struct { @@ -36,7 +36,7 @@ type ChanceDataSpeechs struct {
36 } 36 }
37 37
38 type ChanceDataVideos struct { 38 type ChanceDataVideos struct {
39 - Path string 39 + Path string `json:"path"`
40 Cover ChanceDataImage `json:"cover"` 40 Cover ChanceDataImage `json:"cover"`
41 Duration int `json:"duration"` 41 Duration int `json:"duration"`
42 } 42 }
  1 +package models
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "time"
  6 +
  7 + "github.com/astaxie/beego/orm"
  8 +)
  9 +
  10 +type ChanceReviseLog struct {
  11 + Id int64 `orm:"column(id);pk" description:"id 主键"`
  12 + ChanceId int64 `orm:"column(chance_id)" description:"机会编号"`
  13 + UserCompanyId int64 `orm:"column(user_company_id);null" description:"用户编号 编辑机会的人"`
  14 + Data string `orm:"column(data);null" description:"机会数据"`
  15 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  16 + AuditFlowLogId int64 `orm:"column(audit_flow_log_id);null" description:"表audit_flow_log.id "`
  17 +}
  18 +
  19 +func (t *ChanceReviseLog) TableName() string {
  20 + return "chance_revise_log"
  21 +}
  22 +
  23 +func init() {
  24 + orm.RegisterModel(new(ChanceReviseLog))
  25 +}
  26 +
  27 +type ReviseContentsItem struct {
  28 + Content string `json:"content"`
  29 +}
  30 +
  31 +type ChanceReviseLogData struct {
  32 + ReviseContents []ReviseContentsItem `json:"reviseContents"`
  33 + Speechs []ChanceDataSpeechs `json:"speechs"`
  34 + Pictures []ChanceDataImage `json:"pictures"`
  35 + Videos []ChanceDataVideos `json:"videos"`
  36 + RemoveAllPhotoVideo bool `json:"removeAllPhotoVideo"`
  37 + RemoveAllSpeech bool `json:"removeAllSpeech"`
  38 +}
  39 +
  40 +// GetChanceReviseLogById retrieves ChanceReviseLog by Id. Returns error if
  41 +// Id doesn't exist
  42 +func GetChanceReviseLogById(id int64) (v *ChanceReviseLog, err error) {
  43 + o := orm.NewOrm()
  44 + v = &ChanceReviseLog{Id: id}
  45 + if err = o.Read(v); err == nil {
  46 + return v, nil
  47 + }
  48 + return nil, err
  49 +}
  50 +
  51 +func GetChanceReviseLogData(flowLogId int64) (*ChanceReviseLog, *ChanceReviseLogData, error) {
  52 + o := orm.NewOrm()
  53 + var (
  54 + err error
  55 + )
  56 + reviseLog := &ChanceReviseLog{}
  57 + err = o.QueryTable(&ChanceReviseLog{}).
  58 + Filter("audit_flow_log_id", flowLogId).
  59 + One(reviseLog)
  60 + if err != nil {
  61 + return nil, nil, err
  62 + }
  63 + reviseLogData := &ChanceReviseLogData{
  64 + ReviseContents: make([]ReviseContentsItem, 0),
  65 + Speechs: make([]ChanceDataSpeechs, 0),
  66 + Pictures: make([]ChanceDataImage, 0),
  67 + Videos: make([]ChanceDataVideos, 0),
  68 + }
  69 + json.Unmarshal([]byte(reviseLog.Data), reviseLogData)
  70 + return reviseLog, reviseLogData, err
  71 +}
@@ -17,6 +17,7 @@ type Company struct { @@ -17,6 +17,7 @@ type Company struct {
17 Logo string `orm:"column(logo);size(255)"` 17 Logo string `orm:"column(logo);size(255)"`
18 Enable int8 `orm:"column(enable)"` 18 Enable int8 `orm:"column(enable)"`
19 UserCenterId int64 `orm:"column(user_center_id)"` 19 UserCenterId int64 `orm:"column(user_center_id)"`
  20 + Remark string `orm:"column(remark)"`
20 } 21 }
21 22
22 func (t *Company) TableName() string { 23 func (t *Company) TableName() string {
@@ -12,16 +12,18 @@ import ( @@ -12,16 +12,18 @@ import (
12 ) 12 )
13 13
14 type Department struct { 14 type Department struct {
15 - Id int64 `orm:"column(id);auto"`  
16 - CompanyId int64 `orm:"column(company_id)" description:"公司id"`  
17 - Name string `orm:"column(name);size(30)" description:"部门名称"`  
18 - CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`  
19 - ParentId int64 `orm:"column(parent_id)" description:"父级id"`  
20 - Relation string `orm:"column(relation);size(1024)" description:"父子级关系树"`  
21 - DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`  
22 - UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`  
23 - Manages string `orm:"column(managers)" description:"部门负责人id列表 json 数组 []"` //存user_company_id  
24 - IsTop int8 `orm:"column(is_top)" ` 15 + Id int64 `orm:"column(id);auto"`
  16 + CompanyId int64 `orm:"column(company_id)" description:"公司id"`
  17 + Name string `orm:"column(name);size(30)" description:"部门名称"`
  18 + CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
  19 + ParentId int64 `orm:"column(parent_id)" description:"父级id"`
  20 + Relation string `orm:"column(relation);size(1024)" description:"父子级关系树"`
  21 + DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
  22 + UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
  23 + Manages string `orm:"column(managers)" description:"部门负责人id列表 json 数组 []"` //存user_company_id
  24 + IsTop int8 `orm:"column(is_top)" `
  25 + Level int `orm:"column(level)" `
  26 + BusinessDepartmentId int64 `orm:"column(business_department_id)"`
25 } 27 }
26 28
27 func (t *Department) TableName() string { 29 func (t *Department) TableName() string {
@@ -55,9 +57,11 @@ func (t *Department) SetRelation(parent *Department) error { @@ -55,9 +57,11 @@ func (t *Department) SetRelation(parent *Department) error {
55 return errors.New("Id==0") 57 return errors.New("Id==0")
56 } 58 }
57 if parent == nil { 59 if parent == nil {
58 - t.Relation = fmt.Sprintf("%d", t.Id) 60 + t.Relation = fmt.Sprintf(",%d,", t.Id)
  61 + } else if parent.Id == 0 {
  62 + t.Relation = fmt.Sprintf(",%d,", t.Id)
59 } else { 63 } else {
60 - t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id) 64 + t.Relation = fmt.Sprintf("%s%d,", parent.Relation, t.Id)
61 } 65 }
62 return nil 66 return nil
63 } 67 }
@@ -187,11 +191,15 @@ func GetDepartmentByCompanyId(companyId int64) ([]Department, error) { @@ -187,11 +191,15 @@ func GetDepartmentByCompanyId(companyId int64) ([]Department, error) {
187 o := orm.NewOrm() 191 o := orm.NewOrm()
188 _, err = o.QueryTable(&Department{}). 192 _, err = o.QueryTable(&Department{}).
189 Filter("company_id", companyId). 193 Filter("company_id", companyId).
  194 + Filter("delete_at", 0).
190 All(&result) 195 All(&result)
191 return result, err 196 return result, err
192 } 197 }
193 198
194 func GetDepartmentByIds(departmentIds []int64) ([]Department, error) { 199 func GetDepartmentByIds(departmentIds []int64) ([]Department, error) {
  200 + if len(departmentIds) == 0 {
  201 + return nil, nil
  202 + }
195 var ( 203 var (
196 result []Department 204 result []Department
197 err error 205 err error
@@ -215,3 +223,25 @@ func ExistDepartmentName(parentId int64, dname string) bool { @@ -215,3 +223,25 @@ func ExistDepartmentName(parentId int64, dname string) bool {
215 Exist() 223 Exist()
216 return ok 224 return ok
217 } 225 }
  226 +
  227 +func GetDepartmentByBusinessId(businessId int64) (v *Department, err error) {
  228 + v = &Department{}
  229 + o := orm.NewOrm()
  230 + err = o.QueryTable(&Department{}).
  231 + Filter("business_department_id", businessId).
  232 + Filter("delete_at", 0).
  233 + One(v)
  234 + return v, err
  235 +
  236 +}
  237 +
  238 +func GetTopDepartmentByCompany(companyid int64) (v *Department, err error) {
  239 + v = &Department{}
  240 + o := orm.NewOrm()
  241 + err = o.QueryTable(&Department{}).
  242 + Filter("company_id", companyid).
  243 + Filter("is_top", 1).
  244 + Filter("delete_at", 0).
  245 + One(v)
  246 + return v, err
  247 +}
  1 +package models
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/utils"
  6 + "time"
  7 +
  8 + "github.com/astaxie/beego/orm"
  9 +)
  10 +
  11 +type DepartmentCharge struct {
  12 + Id int64 `orm:"column(id);auto"`
  13 + CompanyId int64 `orm:"column(company_id)" description:"公司id"`
  14 + DepartmentId int64 `orm:"column(department_id)" description:"部门id"`
  15 + UserCompanyId int64 `orm:"column(user_company_id)" description:"用户id"`
  16 + CreateTime time.Time `orm:"column(create_time);type(timestamp)"`
  17 + Enabled int8 `orm:"column(enabled)"`
  18 +}
  19 +
  20 +func (t *DepartmentCharge) TableName() string {
  21 + return "department_charge"
  22 +}
  23 +
  24 +func init() {
  25 + orm.RegisterModel(new(DepartmentCharge))
  26 +}
  27 +
  28 +const (
  29 + DEPARTMENT_CHARGE_ENABLE_YES int8 = 1
  30 + DEPARTMENT_CHARGE_ENABLE_NO int8 = 2
  31 +)
  32 +
  33 +// AddDepartmentCharge insert a new DepartmentCharge into database and returns
  34 +// last inserted Id on success.
  35 +func AddDepartmentCharge(m *DepartmentCharge, o orm.Ormer) (id int64, err error) {
  36 + id, err = o.Insert(m)
  37 + return
  38 +}
  39 +
  40 +// UpdateDepartmentCharge updates DepartmentCharge by Id and returns error if
  41 +// the record to be updated doesn't exist
  42 +func UpdateDepartmentChargeById(m *DepartmentCharge) (err error) {
  43 + o := orm.NewOrm()
  44 + v := DepartmentCharge{Id: m.Id}
  45 + // ascertain id exists in the database
  46 + if err = o.Read(&v); err == nil {
  47 + var num int64
  48 + if num, err = o.Update(m); err == nil {
  49 + fmt.Println("Number of records updated in database:", num)
  50 + }
  51 + }
  52 + return
  53 +}
  54 +
  55 +func GetDepartmentCharge(departmentId int64) ([]DepartmentCharge, error) {
  56 + var (
  57 + data []DepartmentCharge
  58 + err error
  59 + )
  60 + o := orm.NewOrm()
  61 + _, err = o.QueryTable(&DepartmentCharge{}).
  62 + Filter("department_id", departmentId).
  63 + Filter("enabled", 1).
  64 + All(&data)
  65 + if err == orm.ErrNoRows {
  66 + return data, nil
  67 + }
  68 + return data, err
  69 +}
  70 +
  71 +//ChangeDepartmentCharge 变更部门的主管
  72 +func ChangeDepartmentCharge(companyId int64, departmentId int64, userCompanyid []int64, om orm.Ormer) error {
  73 + var (
  74 + err error
  75 + charges []DepartmentCharge
  76 + oldChargeIds []int64
  77 + )
  78 + charges, err = GetDepartmentCharge(departmentId)
  79 + if err != nil {
  80 + return fmt.Errorf("获取部门主管数据失败:%s", err)
  81 + }
  82 + for _, v := range charges {
  83 + oldChargeIds = append(oldChargeIds, v.Id)
  84 + }
  85 + var (
  86 + delIds []int64
  87 + addIds []int64
  88 + addCharges []DepartmentCharge
  89 + )
  90 + delIds = utils.ArrayInt64Diff(oldChargeIds, userCompanyid)
  91 + addIds = utils.ArrayInt64Diff(userCompanyid, oldChargeIds)
  92 + nowTime := time.Now()
  93 + for _, v := range addIds {
  94 + m := DepartmentCharge{
  95 + CompanyId: companyId,
  96 + UserCompanyId: v,
  97 + DepartmentId: departmentId,
  98 + Enabled: DEPARTMENT_CHARGE_ENABLE_YES,
  99 + CreateTime: nowTime,
  100 + }
  101 + addCharges = append(addCharges, m)
  102 +
  103 + }
  104 + if len(delIds) > 0 {
  105 + _, err = om.QueryTable(&DepartmentCharge{}).
  106 + Filter("department_id", departmentId).
  107 + Filter("user_company_id__in", delIds).
  108 + Update(orm.Params{
  109 + "enable": DEPARTMENT_CHARGE_ENABLE_NO,
  110 + })
  111 + if err != nil {
  112 + return fmt.Errorf("更新department_charge数据失败,err:%s", err)
  113 + }
  114 + }
  115 + if len(addCharges) > 0 {
  116 + _, err = om.InsertMulti(10, addCharges)
  117 + if err != nil {
  118 + return fmt.Errorf("添加department_charge数据失败,err:%s", err)
  119 + }
  120 + }
  121 +
  122 + return nil
  123 +}
1 package models 1 package models
2 2
3 import ( 3 import (
4 - "errors"  
5 "fmt" 4 "fmt"
6 "time" 5 "time"
7 6
@@ -9,17 +8,20 @@ import ( @@ -9,17 +8,20 @@ import (
9 ) 8 )
10 9
11 type Position struct { 10 type Position struct {
12 - Id int64 `orm:"column(id);auto" description:"职位表id"`  
13 - CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`  
14 - Name string `orm:"column(name);size(100)" description:"职位名称"`  
15 - ParentId int64 `orm:"column(parent_id)" description:"父级id"`  
16 - Relation string `orm:"column(relation);size(1000)" description:"父子级关系树"`  
17 - CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`  
18 - UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`  
19 - DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`  
20 - EnableStatus string `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"` 11 + Id int64 `orm:"column(id);auto" description:"职位表id"`
  12 + CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
  13 + Name string `orm:"column(name);size(100)" description:"职位名称"`
  14 + ParentId int64 `orm:"column(parent_id)" description:"父级id"`
  15 + Relation string `orm:"column(relation);size(1000)" description:"父子级关系树"`
  16 + CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
  17 + UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
  18 + DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
  19 + EnableStatus string `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"`
  20 + Level int `orm:"column(level)"`
  21 + BusinessPositionId int64 `orm:"column(business_position_id)"`
21 } 22 }
22 23
  24 +//关联企业总后台的id
23 func (t *Position) TableName() string { 25 func (t *Position) TableName() string {
24 return "position" 26 return "position"
25 } 27 }
@@ -29,13 +31,10 @@ func init() { @@ -29,13 +31,10 @@ func init() {
29 } 31 }
30 32
31 func (t *Position) SetRelation(parent *Position) error { 33 func (t *Position) SetRelation(parent *Position) error {
32 - if t.Id == 0 {  
33 - return errors.New("Id==0")  
34 - }  
35 if parent == nil { 34 if parent == nil {
36 - t.Relation = fmt.Sprintf("%d", t.Id) 35 + t.Relation = fmt.Sprintf(",%d,", t.Id)
37 } else { 36 } else {
38 - t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id) 37 + t.Relation = fmt.Sprintf("%s%d,", parent.Relation, t.Id)
39 } 38 }
40 return nil 39 return nil
41 } 40 }
@@ -82,6 +81,7 @@ func UpdatePositionById(m *Position, col []string, om ...orm.Ormer) (err error) @@ -82,6 +81,7 @@ func UpdatePositionById(m *Position, col []string, om ...orm.Ormer) (err error)
82 if err = o.Read(&v); err == nil { 81 if err = o.Read(&v); err == nil {
83 var num int64 82 var num int64
84 m.UpdateAt = time.Now() 83 m.UpdateAt = time.Now()
  84 + col = append(col, "UpdateAt")
85 if num, err = o.Update(m, col...); err == nil { 85 if num, err = o.Update(m, col...); err == nil {
86 fmt.Println("Number of records updated in database:", num) 86 fmt.Println("Number of records updated in database:", num)
87 } 87 }
@@ -102,3 +102,13 @@ func ExistPositiontName(companyid int64, parentId int64, dname string) bool { @@ -102,3 +102,13 @@ func ExistPositiontName(companyid int64, parentId int64, dname string) bool {
102 Exist() 102 Exist()
103 return ok 103 return ok
104 } 104 }
  105 +
  106 +func GetPositionByBusinessId(businessId int64) (v *Position, err error) {
  107 + o := orm.NewOrm()
  108 + v = &Position{}
  109 + err = o.QueryTable(&Position{}).
  110 + Filter("business_position_id", businessId).
  111 + Filter("delete_at", 0).
  112 + One(v)
  113 + return v, err
  114 +}
  1 +package models
  2 +
  3 +import (
  4 + "oppmg/common/log"
  5 + "time"
  6 +
  7 + "github.com/astaxie/beego/orm"
  8 +)
  9 +
  10 +type RankItem struct {
  11 + Id int64 `orm:"column(id);auto"`
  12 + CompanyId int64 `orm:"column(company_id);null" description:"公司编号 company.id"`
  13 + RankTypeId int64 `orm:"column(rank_type_id)" description:"表rank_type.id 榜单类型编号"`
  14 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  15 + UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
  16 + SortNum int `orm:"column(sort_num);null" description:"序号"`
  17 + ItemName string `orm:"column(item_name);size(50);null" description:"评比项名称"`
  18 + ItemKey string `orm:"column(item_key);size(50);null" description:"评比项键值(排行榜排序使用)"`
  19 +}
  20 +
  21 +func (t *RankItem) TableName() string {
  22 + return "rank_item"
  23 +}
  24 +
  25 +func init() {
  26 + orm.RegisterModel(new(RankItem))
  27 +}
  28 +
  29 +// AddRankItem insert a new NewRankItem into database and returns
  30 +// last inserted Id on success.
  31 +func AddRankItem(m []RankItem, om orm.Ormer) (successSum int64, err error) {
  32 + nowTime := time.Now()
  33 + for i := range m {
  34 + m[i].CreateAt = nowTime
  35 + m[i].UpdateAt = nowTime
  36 + }
  37 + successSum, err = om.InsertMulti(10, &m)
  38 + return
  39 +}
  40 +
  41 +// GetRankItemById retrieves NewRankItem by Id. Returns error if
  42 +// Id doesn't exist
  43 +func GetRankItemById(id int64) (v *RankItem, err error) {
  44 + o := orm.NewOrm()
  45 + v = &RankItem{Id: id}
  46 + if err = o.Read(v); err == nil {
  47 + return v, nil
  48 + }
  49 + return nil, err
  50 +}
  51 +
  52 +func GetRankItemByCompanyid(companyid int64, rankTypeId int64) ([]RankItem, error) {
  53 + var (
  54 + data []RankItem
  55 + err error
  56 + )
  57 + o := orm.NewOrm()
  58 + _, err = o.QueryTable(&RankItem{}).
  59 + Filter("company_id", companyid).
  60 + Filter("rank_type_id", rankTypeId).
  61 + All(&data)
  62 + if err == orm.ErrNoRows {
  63 + return data, nil
  64 + }
  65 + return data, err
  66 +}
  67 +
  68 +func DeleteRanKItemByIds(ids []int64, om orm.Ormer) error {
  69 + _, err := om.QueryTable(&RankItem{}).Filter("id__in", ids).Delete()
  70 + return err
  71 +}
  72 +
  73 +// UpdateRankItem updates RankItem by Id and returns error if
  74 +// the record to be updated doesn't exist
  75 +func UpdateRankItemById(m *RankItem, cols []string, om orm.Ormer) (err error) {
  76 + if len(cols) > 0 {
  77 + cols = append(cols, "UpdateAt")
  78 + }
  79 + m.UpdateAt = time.Now()
  80 + var num int64
  81 + if num, err = om.Update(m, cols...); err == nil {
  82 + log.Info("Number of records updated in database:%d", num)
  83 + }
  84 + return
  85 +}
  1 +package models
  2 +
  3 +import (
  4 + "oppmg/common/log"
  5 + "time"
  6 +
  7 + "github.com/astaxie/beego/orm"
  8 +)
  9 +
  10 +type RankPeriod struct {
  11 + Id int64 `orm:"column(id);auto" description:"主键"`
  12 + CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
  13 + SeasonName string `orm:"column(season_name);size(50);null" description:"赛季名称"`
  14 + RankTypeId int64 `orm:"column(rank_type_id);size(50);null" description:"赛季类型id"`
  15 + BeginTime time.Time `orm:"column(begin_time);type(timestamp);null" description:"开始时间"`
  16 + EndTime time.Time `orm:"column(end_time);type(timestamp);null" description:"结束时间"`
  17 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  18 + UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
  19 + Status int8 `orm:"column(status);null" description:"状态 0:未开始 1:开始 2:结束 "`
  20 + RankRangeBack string `orm:"column(rank_range_back)" description:"赛季结束时,备份赛季参与人设置"`
  21 + RankItemBack string `orm:"column(rank_item_back)" description:"赛季结束时,备份赛季评比项设置"`
  22 + IsAuto int `orm:"column(is_auto)" description:"是否是自动创建的赛季【0:不是】【1:是】"`
  23 +}
  24 +
  25 +func (t *RankPeriod) TableName() string {
  26 + return "rank_period"
  27 +}
  28 +
  29 +func init() {
  30 + orm.RegisterModel(new(RankPeriod))
  31 +}
  32 +
  33 +//状态 0:未开始 1:开始 2:结束
  34 +const (
  35 + RANKPERIOD_STATUS_NOT int8 = 0
  36 + RANKPERIOD_STATUS_BEGIN int8 = 1
  37 + RANKPERIOD_STATUS_END int8 = 2
  38 +)
  39 +
  40 +// AddNewRankPeriod insert a new RankPeriod into database and returns
  41 +// last inserted Id on success.
  42 +func AddRankPeriod(m *RankPeriod) (id int64, err error) {
  43 + o := orm.NewOrm()
  44 + m.CreateAt = time.Now()
  45 + m.UpdateAt = time.Now()
  46 + id, err = o.Insert(m)
  47 + return
  48 +}
  49 +
  50 +// GetNewRankPeriodById retrieves RankPeriod by Id. Returns error if
  51 +// Id doesn't exist
  52 +func GetRankPeriodById(id int64) (v *RankPeriod, err error) {
  53 + o := orm.NewOrm()
  54 + v = &RankPeriod{Id: id}
  55 + if err = o.Read(v); err == nil {
  56 + return v, nil
  57 + }
  58 + return nil, err
  59 +}
  60 +
  61 +// UpdateNewRankPeriod updates RankPeriod by Id and returns error if
  62 +// the record to be updated doesn't exist
  63 +func UpdateRankPeriodById(m *RankPeriod, cols []string) (err error) {
  64 + o := orm.NewOrm()
  65 + m.UpdateAt = time.Now()
  66 + if len(cols) > 0 {
  67 + cols = append(cols, "UpdateAt")
  68 + }
  69 + var num int64
  70 + if num, err = o.Update(m, cols...); err == nil {
  71 + log.Info("Number of records updated in database:", num)
  72 + }
  73 +
  74 + return
  75 +}
  1 +package models
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/common/log"
  6 + "time"
  7 +
  8 + "github.com/astaxie/beego/orm"
  9 +)
  10 +
  11 +type RankRange struct {
  12 + Id int64 `orm:"column(id);auto"`
  13 + Name string `orm:"column(name);size(50);null" description:"名称"`
  14 + CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
  15 + RankTypeId int64 `orm:"column(rank_type_id);null" description:""`
  16 + Type int8 `orm:"column(type);null" description:"1:所有员工 2:指定员工 3:所有部门 4:指定部门"`
  17 + Data string `orm:"column(data);size(1000);null" description:"人员范围数据(type:2,4 有值 对于人员数据/部门数据)"`
  18 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  19 + UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
  20 + SortNum int `orm:"column(sort_num)"`
  21 + Status int8 `orm:"column(status)"`
  22 +}
  23 +
  24 +func (t *RankRange) TableName() string {
  25 + return "rank_range"
  26 +}
  27 +
  28 +func init() {
  29 + orm.RegisterModel(new(RankRange))
  30 +}
  31 +
  32 +//1:所有员工 2:指定员工 3:所有部门 4:指定部门
  33 +const (
  34 + RANK_RANGE_TYPE_EMPLAYEEALL int8 = 1
  35 + RANK_RANGE_TYPE_EMPLAYEE int8 = 2
  36 + RANK_RANGE_TYPE_DEPARTMENTALL int8 = 3
  37 + RANK_RANGE_TYPE_DEPARTMENT int8 = 4
  38 +)
  39 +
  40 +// AddRankRange insert a new RankRange into database and returns
  41 +// last inserted Id on success.
  42 +func AddRankRange(m *RankRange, om ...orm.Ormer) (id int64, err error) {
  43 + var o orm.Ormer
  44 + if len(om) > 0 {
  45 + o = om[0]
  46 + } else {
  47 + o = orm.NewOrm()
  48 + }
  49 + m.CreateAt = time.Now()
  50 + m.UpdateAt = time.Now()
  51 + id, err = o.Insert(m)
  52 + return
  53 +}
  54 +
  55 +// GetRankRangeById retrieves RankRange by Id. Returns error if
  56 +// Id doesn't exist
  57 +func GetRankRangeById(id int64) (v *RankRange, err error) {
  58 + o := orm.NewOrm()
  59 + v = &RankRange{Id: id}
  60 + if err = o.Read(v); err == nil {
  61 + return v, nil
  62 + }
  63 + return nil, err
  64 +}
  65 +
  66 +// UpdateRankRangeById updates RankRange by Id and returns error if
  67 +// the record to be updated doesn't exist
  68 +func UpdateRankRangeById(m *RankRange, cols []string, om ...orm.Ormer) (err error) {
  69 + var o orm.Ormer
  70 + if len(om) > 0 {
  71 + o = om[0]
  72 + } else {
  73 + o = orm.NewOrm()
  74 + }
  75 + var num int64
  76 + m.UpdateAt = time.Now()
  77 + if len(cols) > 0 {
  78 + cols = append(cols, "UpdateAt")
  79 + }
  80 + if num, err = o.Update(m, cols...); err == nil {
  81 + log.Info("Number of records updated in database:%d", num)
  82 + }
  83 + return
  84 +}
  85 +
  86 +// DeleteRankRange deletes RankRange by Id and returns error if
  87 +// the record to be deleted doesn't exist
  88 +func DeleteRankRange(id int64) (err error) {
  89 + o := orm.NewOrm()
  90 + v := RankRange{Id: id}
  91 + // ascertain id exists in the database
  92 + if err = o.Read(&v); err == nil {
  93 + var num int64
  94 + if num, err = o.Delete(&RankRange{Id: id}); err == nil {
  95 + fmt.Println("Number of records deleted in database:", num)
  96 + }
  97 + }
  98 + return
  99 +}
  1 +package models
  2 +
  3 +import (
  4 + "github.com/astaxie/beego/orm"
  5 +)
  6 +
  7 +type RankRangeData struct {
  8 + Id int64 `orm:"column(id);auto"`
  9 + RankRangeId int64 `orm:"column(rank_range_id)"`
  10 + RangeType int8 `orm:"column(range_type);" description:"类型"`
  11 + RelationId int64 `orm:"column(relation_id);"`
  12 + RankTypeId int64 `orm:"column(rank_type_id)"`
  13 +}
  14 +
  15 +func (t *RankRangeData) TableName() string {
  16 + return "rank_range_data"
  17 +}
  18 +
  19 +func init() {
  20 + orm.RegisterModel(new(RankRangeData))
  21 +}
  22 +
  23 +// AddRankRangeData insert a new RankRangeData into database and returns
  24 +// last inserted Id on success.
  25 +func AddRankRangeDataMulti(m []RankRangeData, om ...orm.Ormer) (successNums int64, err error) {
  26 + var o orm.Ormer
  27 + if len(om) > 0 {
  28 + o = om[0]
  29 + } else {
  30 + o = orm.NewOrm()
  31 + }
  32 + successNums, err = o.InsertMulti(20, m)
  33 + return
  34 +}
  35 +
  36 +// GetRankRangeDataById retrieves RankRangeData by Id. Returns error if
  37 +// Id doesn't exist
  38 +func GetRankRangeDataById(id int64) (v *RankRangeData, err error) {
  39 + o := orm.NewOrm()
  40 + v = &RankRangeData{Id: id}
  41 + if err = o.Read(v); err == nil {
  42 + return v, nil
  43 + }
  44 + return nil, err
  45 +}
  46 +
  47 +// DeleteRankRangeData deletes RankRangeData by Id and returns error if
  48 +// the record to be deleted doesn't exist
  49 +func DeleteRankRangeData(id []int64, om orm.Ormer) (err error) {
  50 +
  51 + _, err = om.QueryTable(&RankRangeData{}).
  52 + Filter("id__in", id).
  53 + Delete()
  54 + return err
  55 +}
  56 +
  57 +func GetRankRangeDataByRangeId(id int64) ([]RankRangeData, error) {
  58 + var (
  59 + data = make([]RankRangeData, 0)
  60 + err error
  61 + )
  62 + o := orm.NewOrm()
  63 + _, err = o.QueryTable(&RankRangeData{}).
  64 + Filter("rank_range_id", id).
  65 + All(&data)
  66 + if err == orm.ErrNoRows {
  67 + return data, nil
  68 + }
  69 + if err != nil {
  70 + return nil, err
  71 + }
  72 + return data, nil
  73 +}
  1 +package models
  2 +
  3 +import (
  4 + "fmt"
  5 + "time"
  6 +
  7 + "github.com/astaxie/beego/orm"
  8 +)
  9 +
  10 +type RankType struct {
  11 + Id int64 `orm:"column(id);pk"`
  12 + CompanyId int64 `orm:"column(company_id)"`
  13 + Name string `orm:"column(name)"`
  14 + EnableStatus int8 `orm:"column(enable_status)"`
  15 + CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
  16 + UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
  17 + Type int8 `orm:"column(type)"`
  18 + AutoCreate int8 `orm:"column(auto_create)"` //是否自动创建赛季 【0:否】【1:是】
  19 + AutoPeriod int `orm:"column(auto_period)"`
  20 +}
  21 +
  22 +func (t *RankType) TableName() string {
  23 + return "rank_type"
  24 +}
  25 +
  26 +func init() {
  27 + orm.RegisterModel(new(RankType))
  28 +}
  29 +
  30 +//榜单类型
  31 +const (
  32 + RANK_TYPE_SEASON int8 = 1 //季赛榜
  33 + RANK_TYPE_YEAR int8 = 2 //年榜
  34 +)
  35 +
  36 +//榜单状态
  37 +const (
  38 + RANK_STATUS_YES int8 = 2 //启用
  39 + RANK_STATUS_NO int8 = 1 //禁用
  40 +)
  41 +
  42 +// AddRank insert a new Rank into database and returns
  43 +// last inserted Id on success.
  44 +func AddRank(m *RankType) (id int64, err error) {
  45 + o := orm.NewOrm()
  46 + nowTime := time.Now()
  47 + m.CreateAt = nowTime
  48 + m.UpdateAt = nowTime
  49 + id, err = o.Insert(m)
  50 + return
  51 +}
  52 +
  53 +// GetRankById retrieves Rank by Id. Returns error if
  54 +// Id doesn't exist
  55 +func GetRankById(id int64) (v *RankType, err error) {
  56 + o := orm.NewOrm()
  57 + v = &RankType{Id: id}
  58 + if err = o.Read(v); err == nil {
  59 + return v, nil
  60 + }
  61 + return nil, err
  62 +}
  63 +
  64 +// UpdateRank updates Rank by Id and returns error if
  65 +// the record to be updated doesn't exist
  66 +func UpdateRankById(m *RankType, cols []string, om ...orm.Ormer) (err error) {
  67 + var o orm.Ormer
  68 + if len(om) > 0 {
  69 + o = om[0]
  70 + } else {
  71 + o = orm.NewOrm()
  72 + }
  73 + m.UpdateAt = time.Now()
  74 + if len(cols) > 0 {
  75 + cols = append(cols, "UpdateAt")
  76 + }
  77 + var num int64
  78 + if num, err = o.Update(m, cols...); err == nil {
  79 + fmt.Println("Number of records updated in database:", num)
  80 + }
  81 +
  82 + return
  83 +}
@@ -19,6 +19,21 @@ type UserCompany struct { @@ -19,6 +19,21 @@ type UserCompany struct {
19 UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"` 19 UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
20 Enable int8 `orm:"column(enable)"` 20 Enable int8 `orm:"column(enable)"`
21 DeleteAt time.Time `orm:"column(delete_at)"` 21 DeleteAt time.Time `orm:"column(delete_at)"`
  22 + OpenId int64 `orm:"column(open_id)" description:"统一用户中心uid"`
  23 + Sex int8 `orm:"column(sex)" description:"性别:0保密 1男 2女"`
  24 + JobNum string `orm:"column(job_num);size(255)" description:"员工工号"`
  25 + Phone string `orm:"column(phone);size(11)" description:"用户手机,登录手机号"`
  26 + PrivatePhone string `orm:"column(private_phone);size(11)" description:"私人手机"`
  27 + Email string `orm:"column(email);size(255)" description:"邮箱"`
  28 + ExtensionNum string `orm:"column(extension_num);size(255)" description:"分机号"`
  29 + EntryTime time.Time `orm:"column(entry_time);type(date);null" description:"入职时间"`
  30 + Workspace string `orm:"column(workspace);size(255)" description:"工作地点"`
  31 + IsBusiness int8 `orm:"column(is_business)" description:"是否开启业务状态 1是 0否"`
  32 + Avatar string `orm:"column(avatar);size(255)" description:"头像"`
  33 + Remarks string `orm:"column(remarks);size(255)" description:"备注"`
  34 + AdminType int8 `orm:"column(admin_type)" description:"1普通用户 2主管理员"`
  35 + ChargeStatus int8 `orm:"column(charge_status)" description:"是否为当前公司主管 1 是2 否"`
  36 + ExtraText string `orm:"column(extra_text);null" description:"自定义参数数据"`
22 } 37 }
23 38
24 func (t *UserCompany) TableName() string { 39 func (t *UserCompany) TableName() string {
@@ -31,6 +46,20 @@ const ( @@ -31,6 +46,20 @@ const (
31 USERCOMPANY_ENABLE_NO int8 = 2 // 无效 46 USERCOMPANY_ENABLE_NO int8 = 2 // 无效
32 ) 47 )
33 48
  49 +//是否为当前公司主管 1 是2 否
  50 +const (
  51 + USERCOMPANY_CHARGE_YES int8 = 1
  52 + USERCOMPANY_CHARGE_NO int8 = 2
  53 +)
  54 +
  55 +//
  56 +
  57 +// 1普通用户 2主管理员
  58 +const (
  59 + USERCOMPANY_ADMIN_SUBSET int8 = 1
  60 + USERCOMPANY_ADMIN_MAIN int8 = 2
  61 +)
  62 +
34 func (t *UserCompany) IsEnable() bool { 63 func (t *UserCompany) IsEnable() bool {
35 switch t.Enable { 64 switch t.Enable {
36 case USERCOMPANY_ENABLE_YES: 65 case USERCOMPANY_ENABLE_YES:
@@ -62,6 +91,17 @@ func GetUserCompanyById(id int64) (v *UserCompany, err error) { @@ -62,6 +91,17 @@ func GetUserCompanyById(id int64) (v *UserCompany, err error) {
62 return nil, err 91 return nil, err
63 } 92 }
64 93
  94 +func GetUserCompanyByIds(ids []int64) (v []UserCompany, err error) {
  95 + if len(ids) == 0 {
  96 + return nil, nil
  97 + }
  98 + o := orm.NewOrm()
  99 + _, err = o.QueryTable(&UserCompany{}).
  100 + Filter("id__in", ids).
  101 + All(&v)
  102 + return v, err
  103 +}
  104 +
65 // AddUserCompany insert a new UserCompany into database and returns 105 // AddUserCompany insert a new UserCompany into database and returns
66 // last inserted Id on success. 106 // last inserted Id on success.
67 func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) { 107 func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
@@ -148,8 +188,8 @@ func GetUserCompanyReal(ids []int64) ([]UserCompany, error) { @@ -148,8 +188,8 @@ func GetUserCompanyReal(ids []int64) ([]UserCompany, error) {
148 func GetUserCompanyAll(companyId int64) (v []*UserCompany, err error) { 188 func GetUserCompanyAll(companyId int64) (v []*UserCompany, err error) {
149 o := orm.NewOrm() 189 o := orm.NewOrm()
150 sql := `select a.*,b.nick_name from ( 190 sql := `select a.*,b.nick_name from (
151 -select id,user_id from user_company where company_id=? and enable=1  
152 -)a inner join user b on a.user_id = b.id` 191 + select id,user_id from user_company where company_id=? and enable=1
  192 + )a inner join user b on a.user_id = b.id`
153 if _, err = o.Raw(sql, companyId).QueryRows(&v); err == nil { 193 if _, err = o.Raw(sql, companyId).QueryRows(&v); err == nil {
154 return v, nil 194 return v, nil
155 } 195 }
@@ -105,3 +105,14 @@ func ExistUserDepart(departid int64, usercompanyid int64) bool { @@ -105,3 +105,14 @@ func ExistUserDepart(departid int64, usercompanyid int64) bool {
105 Exist() 105 Exist()
106 return ok 106 return ok
107 } 107 }
  108 +
  109 +func GetUserDepartment(departId, usercompanyid int64) (*UserDepartment, error) {
  110 + m := &UserDepartment{}
  111 + o := orm.NewOrm()
  112 + err := o.QueryTable(&UserDepartment{}).
  113 + Filter("department_id", departId).
  114 + Filter("user_company_id", usercompanyid).
  115 + Filter("enable_status", USER_DEPARTMENT_ENABLE_YES).
  116 + One(m)
  117 + return m, err
  118 +}
@@ -8,8 +8,7 @@ import ( @@ -8,8 +8,7 @@ import (
8 ) 8 )
9 9
10 type UserPosition struct { 10 type UserPosition struct {
11 - Id int64 `orm:"column(id)" description:"唯一键值"`  
12 - //UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"` 11 + Id int64 `orm:"column(id)" description:"唯一键值"`
13 PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"` 12 PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"`
14 CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"` 13 CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
15 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"` 14 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
  1 +package protocol
  2 +
  3 +//ProviderData 成果提供者
  4 +type AchievementProvider struct {
  5 + UserDepartmentId int64 `json:"user_department_id" orm:"-"` //前端需要的唯一id标识,使用user_department表的id
  6 + UserCompanyId int64 `json:"user_company_id" orm:"column(user_company_id)"` //用户的id
  7 + NickName string `json:"nick_name" orm:"column(nick_name)"`
  8 + DepartmentId int64 `json:"department_id" orm:"column(department_id)" ` //部门id
  9 + DepartmentName string `json:"department_name" orm:"column(department_name)"`
  10 + UserGraspScore float64 `json:"user_grasp_score" orm:"column(user_grasp_score)"` //把握人得分
  11 +}
  12 +
  13 +//AchievementChance 成果的机会列表
  14 +type AchievementChance struct {
  15 + Id string `json:"id"` //大整数特别处理
  16 + Code string `json:"code"`
  17 +}
  18 +
  19 +type AchievementImage struct {
  20 + Path string `json:"path"`
  21 + W int `json:"-"`
  22 + H int `json:"-"`
  23 +}
  24 +
  25 +//RequestAddAchievement 添加成果
  26 +type RequestAddAchievement struct {
  27 + ChanceData []AchievementChance `json:"chance_data"`
  28 + ChanceTypeId int64 `json:"chance_type_id"` //机会一级分类 chance_type
  29 + AuditTemplateId int64 `json:"audit_template_id"` //机会二级分类
  30 + DepartmentId int64 `json:"department_id"` //把握人的部门
  31 + UserCompanyId int64 `json:"user_company_id"` //把握人的id
  32 + GraspScore float64 `json:"grasp_score"` //把握分
  33 + UserGraspScore float64 `json:"user_grasp_score"` //把握人总得分
  34 + Provider []AchievementProvider `json:"provider"` //机会提供者
  35 + SourceContent string `json:"source_content"` //成果描述文本
  36 + Images []AchievementImage `json:"image"` //图片
  37 +}
  38 +
  39 +//RequestAddAchievement 添加成果
  40 +type RequestEditAchievement struct {
  41 + AchievementId int64 `json:"achievement_id"`
  42 + ChanceData []AchievementChance `json:"chance_data"`
  43 + ChanceTypeId int64 `json:"chance_type_id"` //机会一级分类 chance_type
  44 + AuditTemplateId int64 `json:"audit_template_id"` //机会二级分类
  45 + GraspScore float64 `json:"grasp_score"` //把握分
  46 + UserGraspScore float64 `json:"user_grasp_score"` //把握人总得分
  47 + SourceContent string `json:"source_content"` //成果描述文本
  48 + Provider []AchievementProvider `json:"provider"` //机会提供者
  49 + Images []AchievementImage `json:"image"` //图片
  50 +}
  51 +
  52 +// ResponseRankSeasonList 赛季列表
  53 +type AchievementList struct {
  54 + ResponsePageInfo
  55 + List []AchievementListItem `json:"lists"`
  56 +}
  57 +
  58 +//AchievementListItem 成果列表
  59 +type AchievementListItem struct {
  60 + Id int64 `json:"id"`
  61 + CreateTime string `json:"create_time"`
  62 + TypeA string `json:"type_a"`
  63 + TypeB string `json:"type_b"`
  64 + GraspScore string `json:"grasp_score"`
  65 + Status int `json:"status"`
  66 + UserGrasp string `json:"user_grasp"`
  67 +}
  68 +
  69 +//ResponseAchievementInfo 成果详情
  70 +type ResponseAchievementInfo struct {
  71 + AchievementId int64 `json:"achievement_id"`
  72 + ChanceData []AchievementChance `json:"chance_data"`
  73 + ChanceTypeId int64 `json:"chance_type_id"` //机会一级分类 chance_type
  74 + AuditTemplateId int64 `json:"audit_template_id"` //机会二级分类
  75 + ChanceTypeName string `json:"chance_type_name"` //机会一级分类 chance_type
  76 + AuditTemplateName string `json:"audit_template_name"` //机会二级分类
  77 + DepartmentId int64 `json:"department_id"` //把握人的部门
  78 + DeparmentName string `json:"department_name"`
  79 + UserCompanyId int64 `json:"user_company_id"` //把握人的id
  80 + NickName string `json:"nick_name"`
  81 + UserDepartmentId int64 `json:"user_department_id"` //前端需要的把握人唯一id标识
  82 + GraspScore float64 `json:"grasp_score"` //把握分
  83 + UserGraspScore float64 `json:"user_grasp_score"` //把握人总得分
  84 + Provider []AchievementProvider `json:"provider"` //机会提供者
  85 + SourceContent string `json:"source_content"` //成果描述文本
  86 + Images []AchievementImage `json:"image"` //图片
  87 + CrreateAt string `json:"create_at"`
  88 +}
@@ -271,8 +271,10 @@ type RspAuditList struct { @@ -271,8 +271,10 @@ type RspAuditList struct {
271 } 271 }
272 272
273 type ChanceFlowLog struct { 273 type ChanceFlowLog struct {
  274 + Id int64 `json:"id" orm:"column(id)"`
274 ChanceId string `json:"chance_id" orm:"column(chance_id)"` 275 ChanceId string `json:"chance_id" orm:"column(chance_id)"`
275 CreateAt string `json:"create_at" orm:"column(create_at)"` 276 CreateAt string `json:"create_at" orm:"column(create_at)"`
276 Content string `json:"content" orm:"column(content)"` 277 Content string `json:"content" orm:"column(content)"`
277 NickName string `json:"nick_name" orm:"column(nick_name)"` 278 NickName string `json:"nick_name" orm:"column(nick_name)"`
  279 + Code int `json:"code" orm:"column(code)"`
278 } 280 }
@@ -77,3 +77,37 @@ type ChanceTypeBase struct { @@ -77,3 +77,37 @@ type ChanceTypeBase struct {
77 ChanceTypeId int64 `orm:"column(chance_type_id)" json:"chance_type_id"` 77 ChanceTypeId int64 `orm:"column(chance_type_id)" json:"chance_type_id"`
78 Name string `orm:"column(name)" json:"name"` 78 Name string `orm:"column(name)" json:"name"`
79 } 79 }
  80 +
  81 +type SelectCompanyUserListItem struct {
  82 + Id int64 `json:"id" orm:"column(id)"`
  83 + UserCompanyId int64 `json:"user_company_id" orm:"column(user_company_id)"`
  84 + NickName string `json:"nick_name" orm:"column(nick_name)"`
  85 + DepartmentId int64 `json:"department_id" orm:"column(department_id)"`
  86 + DepartmentName string `json:"department_name" orm:"column(department_name)"`
  87 +}
  88 +
  89 +//下拉选择公司员工
  90 +type SelectCompanyUserList struct {
  91 + ResponsePageInfo
  92 + List []SelectCompanyUserListItem `json:"lists"`
  93 +}
  94 +
  95 +type SelectChanceListItem struct {
  96 + Id string `json:"id" orm:"column(id)"`
  97 + DepartmentId int64 `json:"deparment_id" orm:"column(department_id)"`
  98 + DepartmentName string `json:"department_name" orm:"-"`
  99 + ChanceTypeId int `json:"chance_type_id" orm:"column(chance_type_id)"`
  100 + ChanceTypeName string `json:"chance_type_name" orm:"-"`
  101 + AuditTemplateId int64 `json:"audit_template_id" orm:"column(audit_template_id)"`
  102 + AuditTemplateName string `json:"audit_template_name" orm:"-"`
  103 + UserId int64 `json:"user_id" orm:"column(user_id)"`
  104 + UserName string `json:"user_name" orm:"column(nick_name)"`
  105 + Code string `json:"code" orm:"column(code)"`
  106 + CreateAt string `json:"create_at" orm:"column(create_at)"`
  107 +}
  108 +
  109 +//下拉选择机会
  110 +type SelectChanceList struct {
  111 + ResponsePageInfo
  112 + List []SelectChanceListItem `json:"lists"`
  113 +}
@@ -110,8 +110,8 @@ func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) { @@ -110,8 +110,8 @@ func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
110 if x, ok := eRR.(CustomErrParse); ok { 110 if x, ok := eRR.(CustomErrParse); ok {
111 return x.ParseToMessage() 111 return x.ParseToMessage()
112 } 112 }
113 -  
114 - return NewMessage("1") 113 + msg = NewMessage("1")
  114 + return
115 } 115 }
116 116
117 //BadRequestParam 控制层响应返回 117 //BadRequestParam 控制层响应返回
@@ -36,6 +36,7 @@ var errmessge ErrorMap = map[string]string{ @@ -36,6 +36,7 @@ var errmessge ErrorMap = map[string]string{
36 "10028": "请输入正确的验证码", 36 "10028": "请输入正确的验证码",
37 "10029": "获取验证码失败", 37 "10029": "获取验证码失败",
38 "10080": "无操作权限", 38 "10080": "无操作权限",
  39 + "10111": "获取公司信息失败",
39 40
40 //用户相关 41 //用户相关
41 "10031": "无效角色", 42 "10031": "无效角色",
@@ -106,6 +107,22 @@ var errmessge ErrorMap = map[string]string{ @@ -106,6 +107,22 @@ var errmessge ErrorMap = map[string]string{
106 "12102": "评分规则不符合要求", 107 "12102": "评分规则不符合要求",
107 //权限配置相关 108 //权限配置相关
108 "10091": "至少选择一个特定部门", 109 "10091": "至少选择一个特定部门",
  110 +
  111 + "10101": "赛季周期设置与其他赛季重叠",
  112 + "10102": "参与人类型不一致",
  113 + "10103": "排行榜名称最多5个字符",
  114 + "10104": "赛季名称最多输入20个字符",
  115 + "10105": "赛季开始时间必填",
  116 + "10106": "赛季结束时间必填",
  117 + "10107": "参与范围名称最多输入5个字符",
  118 + "10108": "成果一级分类必填",
  119 + "10109": "成果来源必填",
  120 + "10110": "把握人得分不可大于把握得分",
  121 + "10121": "把握得分必填,0.1-100",
  122 + "10122": "分配的总分不可大于把握分",
  123 + "10123": "排行榜评比项最多4项",
  124 + "10124": "公司未启用该模块",
  125 + "10125": "参与范围名称不能重复",
109 } 126 }
110 127
111 //错误码转换 ,兼容需要 128 //错误码转换 ,兼容需要
  1 +package protocol
  2 +
  3 +//获取公司的榜单类型列表
  4 +type ResponseRankType struct {
  5 + Id int `json:"id" orm:"column(id)"`
  6 + Name string `json:"name" orm:"column(name)"`
  7 + EnableStatus int8 `json:"enable_status" orm:"column(enable_status)"`
  8 + Type int8 `json:"type" orm:"column(type)"`
  9 +}
  10 +
  11 +// ResponseRankSeasonList 赛季列表
  12 +type ResponseRankSeasonList struct {
  13 + ResponsePageInfo
  14 + List []RankSeasonItem `json:"lists"`
  15 +}
  16 +type RankSeasonItem struct {
  17 + Id int64 `json:"id" orm:"column(id)"`
  18 + Name string `json:"name" orm:"column(season_name)"`
  19 + BeginTime string `json:"begin_time" orm:"column(begin_time)"`
  20 + EndTime string `json:"end_time" orm:"column(end_time)"`
  21 + Status int8 `json:"status" orm:"column(status)"`
  22 +}
  23 +
  24 +//RankRangeListItem 赛季参与人列表项
  25 +type RankRangeListItem struct {
  26 + Id int64 `json:"id" orm:"column(id)"`
  27 + Name string `json:"name" orm:"column(name)"`
  28 + RangeType int8 `json:"range_type" orm:"column(type)"`
  29 + Status int8 `json:"status" orm:"column(status)"`
  30 + RangeData string `json:"range_data" orm:"-"`
  31 + SortNum int `json:"sort_num"`
  32 +}
  33 +
  34 +type RankRangeList []RankRangeListItem
  35 +
  36 +func (a RankRangeList) Len() int { return len(a) }
  37 +func (a RankRangeList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  38 +func (a RankRangeList) Less(i, j int) bool {
  39 + return a[i].SortNum < a[j].SortNum
  40 +}
  41 +
  42 +//ResponseRankRangeInfo 赛季参与人详情
  43 +type ResponseRankRangeInfo struct {
  44 + Id int64 `json:"id"`
  45 + Name string `json:"name"`
  46 + RangeType int8 `json:"range_type"`
  47 + Relation []RankRangeRelation `json:"relation"`
  48 +}
  49 +
  50 +type RankRangeRelation struct {
  51 + Id int64 `json:"id"`
  52 + Name string `json:"name"`
  53 +}
  54 +
  55 +//排行榜评比项
  56 +type RankItemInfo struct {
  57 + ItemName string `json:"item_name"`
  58 + ItemKey string `json:"item_key"`
  59 + SortNum int `json:"sort_num"`
  60 +}
  61 +
  62 +type RankItemAll []RankItemInfo
  63 +
  64 +func (a RankItemAll) Len() int { return len(a) }
  65 +func (a RankItemAll) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  66 +func (a RankItemAll) Less(i, j int) bool {
  67 + return a[i].SortNum < a[j].SortNum
  68 +}
@@ -75,6 +75,10 @@ func init() { @@ -75,6 +75,10 @@ func init() {
75 beego.NSRouter("/user_and_department", &controllers.CommonController{}, "post:SelectorUserAndDepart"), 75 beego.NSRouter("/user_and_department", &controllers.CommonController{}, "post:SelectorUserAndDepart"),
76 beego.NSRouter("/default_image", &controllers.CommonController{}, "post:DefaultImage"), 76 beego.NSRouter("/default_image", &controllers.CommonController{}, "post:DefaultImage"),
77 beego.NSRouter("/role/user", &controllers.CommonController{}, "post:SelectorRoleUser"), 77 beego.NSRouter("/role/user", &controllers.CommonController{}, "post:SelectorRoleUser"),
  78 + beego.NSRouter("/chance_type", &controllers.CommonController{}, "post:SelectorChanceType"),
  79 + beego.NSRouter("/user", &controllers.CommonController{}, "post:SelectCompanyUserList"),
  80 + beego.NSRouter("/chance", &controllers.CommonController{}, "post:SelectChanceList"),
  81 + beego.NSRouter("/department/list", &controllers.CompanyController{}, "post:DepartmentList"),
78 ), 82 ),
79 beego.NSNamespace("/template", 83 beego.NSNamespace("/template",
80 beego.NSRouter("/add", &controllers.TemplateController{}, "post:TemplateAdd"), 84 beego.NSRouter("/add", &controllers.TemplateController{}, "post:TemplateAdd"),
@@ -102,13 +106,43 @@ func init() { @@ -102,13 +106,43 @@ func init() {
102 beego.NSRouter("/list/before", &controllers.AuditController{}, "post:AuditListBefore"), 106 beego.NSRouter("/list/before", &controllers.AuditController{}, "post:AuditListBefore"),
103 beego.NSRouter("/info", &controllers.AuditController{}, "post:AuditInfo"), 107 beego.NSRouter("/info", &controllers.AuditController{}, "post:AuditInfo"),
104 beego.NSRouter("/allow_forbid", &controllers.AuditController{}, "post:AllowForbidAudit"), 108 beego.NSRouter("/allow_forbid", &controllers.AuditController{}, "post:AllowForbidAudit"),
  109 + beego.NSRouter("/revise/info", &controllers.AuditController{}, "post:GetChanceReviseLog"),
  110 + ),
  111 + beego.NSNamespace("/rank",
  112 + beego.NSRouter("/type/list", &controllers.RankController{}, "post:GetRankType"),
  113 + beego.NSRouter("/type/edit", &controllers.RankController{}, "post:EditRankType"),
  114 + beego.NSRouter("/type/forbid_allow", &controllers.RankController{}, "post:RankTypeForbidAllow"),
  115 + beego.NSRouter("/type/config_set", &controllers.RankController{}, "post:RankTypeConfigSet"),
  116 + beego.NSRouter("/type/config_show", &controllers.RankController{}, "post:RankTypeConfigShow"),
  117 + beego.NSRouter("/season/add", &controllers.RankController{}, "post:RankSeasonAdd"),
  118 + beego.NSRouter("/season/list", &controllers.RankController{}, "post:RankSeasonList"),
  119 + beego.NSRouter("/season/edit", &controllers.RankController{}, "post:RankSeasonEdit"),
  120 + beego.NSRouter("/range/list", &controllers.RankController{}, "post:RankRangeList"),
  121 + beego.NSRouter("/range/edit", &controllers.RankController{}, "post:RankRangeEdit"),
  122 + beego.NSRouter("/range/add", &controllers.RankController{}, "post:RankRangeAdd"),
  123 + beego.NSRouter("/range/forbid_allow", &controllers.RankController{}, "post:RankRangeForbidAllow"),
  124 + beego.NSRouter("/range/info", &controllers.RankController{}, "post:RankRangeInfo"),
  125 + beego.NSRouter("/range/sort", &controllers.RankController{}, "post:RankRangeSort"),
  126 + beego.NSRouter("/range/move", &controllers.RankController{}, "post:RankRangeMove"),
  127 + beego.NSRouter("/item/list", &controllers.RankController{}, "post:RankItemList"),
  128 + beego.NSRouter("/item/edit", &controllers.RankController{}, "post:RankItemEdit"),
  129 + ),
  130 + beego.NSNamespace("/achievement",
  131 + beego.NSRouter("/list", &controllers.AchievementController{}, "post:AchievementList"),
  132 + beego.NSRouter("/add", &controllers.AchievementController{}, "post:AddAchievement"),
  133 + beego.NSRouter("/edit", &controllers.AchievementController{}, "post:EditAchievement"),
  134 + beego.NSRouter("/info", &controllers.AchievementController{}, "post:AchievementInfo"),
  135 + beego.NSRouter("/delete", &controllers.AchievementController{}, "post:DeleteAchievement"),
  136 + beego.NSRouter("/forbid_allow", &controllers.AchievementController{}, "post:ForbidAllowAchievement"),
  137 + beego.NSRouter("/remain/score", &controllers.AchievementController{}, "post:AchievementScoreRemain"),
105 ), 138 ),
106 ) 139 )
107 140
108 nsAuth := beego.NewNamespace("/auth", 141 nsAuth := beego.NewNamespace("/auth",
109 beego.NSBefore(middleware.AllowOption), 142 beego.NSBefore(middleware.AllowOption),
110 beego.NSBefore(middleware.LogRequestData), 143 beego.NSBefore(middleware.LogRequestData),
111 - beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"), 144 + beego.NSRouter("/login_account", &controllers.AuthController{}, "post:Login"),
  145 + beego.NSRouter("/login", &controllers.AuthController{}, "post:LoginSecretKey"),
112 beego.NSRouter("/startCaptcha", &controllers.AuthController{}, "post:RegisterGeetest"), 146 beego.NSRouter("/startCaptcha", &controllers.AuthController{}, "post:RegisterGeetest"),
113 beego.NSRouter("/verifyCaptcha", &controllers.AuthController{}, "post:ValidateGeetest"), 147 beego.NSRouter("/verifyCaptcha", &controllers.AuthController{}, "post:ValidateGeetest"),
114 beego.NSRouter("/login_sms", &controllers.AuthController{}, "post:LoginSms"), 148 beego.NSRouter("/login_sms", &controllers.AuthController{}, "post:LoginSms"),
@@ -118,9 +152,9 @@ func init() { @@ -118,9 +152,9 @@ func init() {
118 ) 152 )
119 nsUcenter := beego.NewNamespace("/ucenter", 153 nsUcenter := beego.NewNamespace("/ucenter",
120 beego.NSBefore(middleware.LogRequestData), 154 beego.NSBefore(middleware.LogRequestData),
121 - beego.NSRouter("/company", &controllers.CompanyController{}, "post:InitCompany"), 155 + //beego.NSRouter("/company", &controllers.CompanyController{}, "post:InitCompany"),(废弃)
122 beego.NSRouter("/company/info", &controllers.CompanyController{}, "post:GetCompanyForUCenter"), 156 beego.NSRouter("/company/info", &controllers.CompanyController{}, "post:GetCompanyForUCenter"),
123 - beego.NSRouter("/company/edit", &controllers.CompanyController{}, "post:EditCompanyForUCenter"), 157 + //beego.NSRouter("/company/edit", &controllers.CompanyController{}, "post:EditCompanyForUCenter"),(废弃)
124 beego.NSRouter("/user/revoke", &controllers.CompanyController{}, "post:UserRevoke"), 158 beego.NSRouter("/user/revoke", &controllers.CompanyController{}, "post:UserRevoke"),
125 beego.NSRouter("/user/changePhone", &controllers.CompanyController{}, "post:UserChangePhone"), 159 beego.NSRouter("/user/changePhone", &controllers.CompanyController{}, "post:UserChangePhone"),
126 beego.NSRouter("/company/allow_forbid", &controllers.CompanyController{}, "post:AllowForidCompanyForUCenter"), 160 beego.NSRouter("/company/allow_forbid", &controllers.CompanyController{}, "post:AllowForidCompanyForUCenter"),
@@ -129,6 +163,7 @@ func init() { @@ -129,6 +163,7 @@ func init() {
129 beego.AddNamespace(nsV1) 163 beego.AddNamespace(nsV1)
130 beego.AddNamespace(nsAuth) 164 beego.AddNamespace(nsAuth)
131 beego.AddNamespace(nsUcenter) 165 beego.AddNamespace(nsUcenter)
  166 +
132 beego.SetStaticPath("/log", beego.AppConfig.String("log_filename")) 167 beego.SetStaticPath("/log", beego.AppConfig.String("log_filename"))
133 beego.SetStaticPath("/file/opp", beego.AppConfig.String("file_save_path")) 168 beego.SetStaticPath("/file/opp", beego.AppConfig.String("file_save_path"))
134 beego.SetStaticPath("/static", "./static") 169 beego.SetStaticPath("/static", "./static")
1 package routers 1 package routers
2 2
  3 +import (
  4 + "oppmg/controllers"
  5 + "oppmg/middleware"
  6 +
  7 + "github.com/astaxie/beego"
  8 +)
  9 +
3 //从公司管理平台同步数据用 10 //从公司管理平台同步数据用
4 func init() { 11 func init() {
5 - //路由 12 + nsPlatform := beego.NewNamespace("/platform",
  13 + beego.NSBefore(middleware.LogRequestData),
  14 + beego.NSRouter("/action", &controllers.PlatformController{}, "post:UpdateData"),
  15 + beego.NSRouter("/admins_change", &controllers.PlatformController{}, "post:CompanyAdminChance"),
  16 + )
  17 + beego.AddNamespace(nsPlatform)
6 } 18 }
  1 +package routers
  2 +
  3 +import (
  4 + "oppmg/services/crontab"
  5 +
  6 + "github.com/astaxie/beego"
  7 + "github.com/astaxie/beego/context"
  8 +)
  9 +
  10 +func init() {
  11 + testNs := beego.NewNamespace("/test",
  12 + beego.NSCond(func(ctx *context.Context) bool {
  13 + if beego.BConfig.RunMode == "prod" {
  14 + return false
  15 + }
  16 + return true
  17 + }),
  18 + beego.NSGet("/create_rank_peroid",
  19 + func(ctx *context.Context) {
  20 + crontab.AutoCreateRankPeriod()
  21 + }),
  22 + )
  23 + beego.AddNamespace(testNs)
  24 +}
  1 +package achievement
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + "oppmg/common/log"
  7 + "oppmg/models"
  8 + "oppmg/protocol"
  9 + "oppmg/utils"
  10 + "strconv"
  11 + "time"
  12 +
  13 + "github.com/astaxie/beego/orm"
  14 +)
  15 +
  16 +//addAchievementProvider 操作achievement_provider 成果提供人表
  17 +func addAchievementProvider(addData []protocol.AchievementProvider, achievementId int64, om orm.Ormer) error {
  18 + var (
  19 + providerList []models.AchievementProvider
  20 + err error
  21 + )
  22 + nowTime := time.Now()
  23 + for _, v := range addData {
  24 + m := models.AchievementProvider{
  25 + AchievementId: achievementId,
  26 + UserCompanyId: v.UserCompanyId,
  27 + UserGraspScore: v.UserGraspScore,
  28 + DepartmentId: v.DepartmentId,
  29 + CreateAt: nowTime,
  30 + }
  31 + providerList = append(providerList, m)
  32 + }
  33 + _, err = om.InsertMulti(10, providerList)
  34 + return err
  35 +}
  36 +
  37 +//addAchievementChance 操作 achievement_chance 机会来源表
  38 +func addAchievementChance(addData []protocol.AchievementChance, achievementId int64, om orm.Ormer) error {
  39 + var (
  40 + chanceList []models.AchievementChance
  41 + err error
  42 + )
  43 + nowTime := time.Now()
  44 + for _, v := range addData {
  45 + chanceId, _ := strconv.ParseInt(v.Id, 10, 64)
  46 + m := models.AchievementChance{
  47 + AchievementId: achievementId,
  48 + ChanceId: chanceId,
  49 + ChanceCode: v.Code,
  50 + CreateAt: nowTime,
  51 + }
  52 + chanceList = append(chanceList, m)
  53 + }
  54 + _, err = om.InsertMulti(10, chanceList)
  55 + return err
  56 +}
  57 +
  58 +//计算剩余的分数
  59 +func achievementGraspScoreRemain(graspScore, userGraspScore, providerScoreAll float64) float64 {
  60 + return graspScore - userGraspScore - providerScoreAll
  61 +}
  62 +
  63 +//AddAchievement 添加成果
  64 +func AddAchievement(addData *protocol.RequestAddAchievement, companyid int64) error {
  65 + var (
  66 + achievementData *models.Achievement
  67 + err error
  68 + )
  69 + nowTime := time.Now()
  70 + var providerScore float64
  71 + for _, v := range addData.Provider {
  72 + providerScore += v.UserGraspScore
  73 + }
  74 + scoreRemain := achievementGraspScoreRemain(addData.GraspScore, addData.UserGraspScore, providerScore)
  75 + achievementData = &models.Achievement{
  76 + CompanyId: companyid,
  77 + DepartmentId: addData.DepartmentId,
  78 + UserCompanyId: addData.UserCompanyId,
  79 + ChanceTypeId: addData.ChanceTypeId,
  80 + AuditTemplateId: addData.AuditTemplateId,
  81 + SourceContent: addData.SourceContent,
  82 + GraspScore: addData.GraspScore,
  83 + UserGraspScore: addData.UserGraspScore,
  84 + CreateAt: nowTime,
  85 + UpdateAt: nowTime,
  86 + Status: models.ACHIEVEMENT_STATUS_YES,
  87 + GraspScoreRemain: scoreRemain,
  88 + }
  89 + if imgData, err := json.Marshal(addData.Images); err == nil {
  90 + achievementData.Images = string(imgData)
  91 + } else {
  92 + achievementData.Images = "[]"
  93 + }
  94 + o := orm.NewOrm()
  95 + o.Begin()
  96 + //操作achievement 成果表
  97 + achievementId, err := models.AddAchievement(achievementData, o)
  98 + if err != nil {
  99 + log.Error("添加Achievement数据失败:%s", err)
  100 + o.Rollback()
  101 + return protocol.NewErrWithMessage("1")
  102 + }
  103 + //操作 achievement_chance 机会来源表
  104 + err = addAchievementChance(addData.ChanceData, achievementId, o)
  105 + if err != nil {
  106 + log.Error("添加achievement_chance失败:%s", err)
  107 + o.Rollback()
  108 + return protocol.NewErrWithMessage("1")
  109 + }
  110 + //操作achievement_provider 成果提供人表
  111 + if len(addData.Provider) > 0 {
  112 + err = addAchievementProvider(addData.Provider, achievementId, o)
  113 + if err != nil {
  114 + log.Error("添加achievement_provider失败:%s", err)
  115 + o.Rollback()
  116 + return protocol.NewErrWithMessage("1")
  117 + }
  118 + }
  119 + //操作achievement_score福利池数据
  120 +
  121 + err = models.IncreaseAchevementScore(companyid, scoreRemain, o)
  122 + if err != nil {
  123 + o.Rollback()
  124 + log.Error("更新福利池分数achevement_score失败")
  125 + return protocol.NewErrWithMessage("1")
  126 + }
  127 + o.Commit()
  128 + return nil
  129 +}
  130 +
  131 +func EditAchievement(editData *protocol.RequestEditAchievement, companyid int64) error {
  132 + var (
  133 + achievementData *models.Achievement
  134 + err error
  135 + )
  136 + achievementData, err = models.GetAchievementById(editData.AchievementId)
  137 + if err != nil {
  138 + log.Error("获取achievement失败:%s", err)
  139 + return protocol.NewErrWithMessage("1")
  140 + }
  141 + var (
  142 + oldRemain float64
  143 + newRamain float64
  144 + providerScore float64
  145 + )
  146 + oldRemain = achievementData.GraspScoreRemain
  147 + for _, v := range editData.Provider {
  148 + providerScore += v.UserGraspScore
  149 + }
  150 + newRamain = achievementGraspScoreRemain(editData.GraspScore, editData.UserGraspScore, providerScore)
  151 + nowTime := time.Now()
  152 + achievementData.UpdateAt = nowTime
  153 + achievementData.ChanceTypeId = editData.ChanceTypeId
  154 + achievementData.AuditTemplateId = editData.AuditTemplateId
  155 + achievementData.SourceContent = editData.SourceContent
  156 + achievementData.GraspScore = editData.GraspScore
  157 + achievementData.UserGraspScore = editData.UserGraspScore
  158 + achievementData.GraspScoreRemain = newRamain
  159 + if imgData, err := json.Marshal(editData.Images); err == nil {
  160 + achievementData.Images = string(imgData)
  161 + } else {
  162 + achievementData.Images = "[]"
  163 + }
  164 + cols := []string{
  165 + "UpdateAt", "ChanceTypeId", "AuditTemplateId", "SourceContent", "GraspScore",
  166 + "UserGraspScore", "GraspScoreRemain", "Images",
  167 + }
  168 + o := orm.NewOrm()
  169 + o.Begin()
  170 + //更新Achievement 数据
  171 + err = models.UpdateAchievementById(achievementData, cols, o)
  172 + if err != nil {
  173 + o.Rollback()
  174 + log.Info("更新Achievement数据失败:%s", err)
  175 + return protocol.NewErrWithMessage("1")
  176 + }
  177 + //删除achievement_chance旧数据
  178 + _, err = o.QueryTable(&models.AchievementChance{}).
  179 + Filter("achievement_id", editData.AchievementId).
  180 + Delete()
  181 + if err != nil {
  182 + o.Rollback()
  183 + log.Info("删除achievement_chance数据失败:%s", err)
  184 + return protocol.NewErrWithMessage("1")
  185 + }
  186 + err = addAchievementChance(editData.ChanceData, achievementData.Id, o)
  187 + if err != nil {
  188 + log.Error("添加achievement_chance失败:%s", err)
  189 + o.Rollback()
  190 + return protocol.NewErrWithMessage("1")
  191 + }
  192 + //删除提供者分数
  193 + _, err = o.QueryTable(&models.AchievementProvider{}).
  194 + Filter("achievement_id", editData.AchievementId).
  195 + Delete()
  196 + if err != nil {
  197 + o.Rollback()
  198 + log.Info("删除achievement_provider数据失败:%s", err)
  199 + return protocol.NewErrWithMessage("1")
  200 + }
  201 + if len(editData.Provider) > 0 {
  202 + err = addAchievementProvider(editData.Provider, achievementData.Id, o)
  203 + if err != nil {
  204 + log.Error("添加achievement_provider失败:%s", err)
  205 + o.Rollback()
  206 + return protocol.NewErrWithMessage("1")
  207 + }
  208 + }
  209 + err = models.IncreaseAchevementScore(companyid, newRamain-oldRemain, o)
  210 + if err != nil {
  211 + o.Rollback()
  212 + log.Error("更新福利池分数achevement_score失败")
  213 + return protocol.NewErrWithMessage("1")
  214 + }
  215 + o.Commit()
  216 + return nil
  217 +}
  218 +
  219 +func GetAchievementList(pageIndex int, pageSize int, companyId int64, status int) protocol.AchievementList {
  220 + dataSql := `SELECT a.id,a.chance_type_id,a.grasp_score,user_company_id
  221 + ,a.create_at,a.status,a.audit_template_id
  222 + FROM achievement AS a WHERE a.company_id=? `
  223 + countSql := ` SELECT COUNT(*) FROM achievement AS a WHERE a.company_id=? `
  224 + pageStart := (pageIndex - 1) * pageSize
  225 + cond := []interface{}{companyId}
  226 + if status > 0 {
  227 + dataSql += ` AND a.status=? `
  228 + countSql += ` AND a.status=? `
  229 + cond = append(cond, status)
  230 + } else {
  231 + dataSql += ` AND a.status>0 `
  232 + countSql += ` AND a.status>0 `
  233 + }
  234 + dataSql = fmt.Sprintf("%s ORDER BY a.create_at DESC LIMIT %d,%d", dataSql, pageStart, pageSize)
  235 + type SqlData struct {
  236 + Id int64 `orm:"column(id)"`
  237 + ChanceTypeId int `orm:"column(chance_type_id)"`
  238 + GraspScore string `orm:"column(grasp_score)"`
  239 + UserCompanyId int64 `orm:"column(user_company_id)"`
  240 + CreateAt string `orm:"column(create_at)"`
  241 + Status int `orm:"column(status)"`
  242 + AuditTemplateId int64 `orm:"column(audit_template_id)"`
  243 + }
  244 + var (
  245 + sqldata []SqlData
  246 + cnt int
  247 + err error
  248 + )
  249 + rspData := protocol.AchievementList{
  250 + ResponsePageInfo: protocol.ResponsePageInfo{
  251 + TotalPage: 0, CurrentPage: pageIndex,
  252 + },
  253 + List: make([]protocol.AchievementListItem, 0),
  254 + }
  255 + err = utils.ExecuteQueryOne(&cnt, countSql, cond...)
  256 + if err != nil {
  257 + log.Error("SQL EXECUTE ERR:%s", err)
  258 + return rspData
  259 + }
  260 + rspData.TotalPage = cnt
  261 + if cnt == 0 {
  262 + return rspData
  263 + }
  264 + err = utils.ExecuteQueryAll(&sqldata, dataSql, cond...)
  265 + if err != nil {
  266 + log.Error("SQL EXECUTE ERR:%s", err)
  267 + return rspData
  268 + }
  269 + for i := range sqldata {
  270 + m := protocol.AchievementListItem{
  271 + Id: sqldata[i].Id,
  272 + CreateTime: sqldata[i].CreateAt,
  273 + GraspScore: sqldata[i].GraspScore,
  274 + Status: sqldata[i].Status,
  275 + }
  276 + var (
  277 + chanceTypeA *models.ChanceType //一级分类
  278 + chanceTypeB *models.AuditTemplate //二级分类
  279 + usercompany *models.UserCompany
  280 + err error
  281 + )
  282 + chanceTypeA, err = models.GetChanceTypeById(sqldata[i].ChanceTypeId)
  283 + if err == nil {
  284 + m.TypeA = chanceTypeA.Name
  285 + } else {
  286 + log.Error(err.Error())
  287 + }
  288 + chanceTypeB, err = models.GetAuditTemplateById(sqldata[i].AuditTemplateId)
  289 + if err == nil {
  290 + m.TypeB = chanceTypeB.Name
  291 + } else {
  292 + log.Error(err.Error())
  293 + }
  294 + usercompany, err = models.GetUserCompanyById(sqldata[i].UserCompanyId)
  295 + if err == nil {
  296 + usr, err := models.GetUserById(usercompany.UserId)
  297 + if err == nil {
  298 + m.UserGrasp = usr.NickName
  299 + } else {
  300 + log.Error(err.Error())
  301 + }
  302 + } else {
  303 + log.Error(err.Error())
  304 + }
  305 + rspData.List = append(rspData.List, m)
  306 + }
  307 +
  308 + return rspData
  309 +}
  310 +
  311 +func GetAchievementInfo(id int64, companyId int64) *protocol.ResponseAchievementInfo {
  312 + rspData := &protocol.ResponseAchievementInfo{
  313 + Images: make([]protocol.AchievementImage, 0),
  314 + Provider: make([]protocol.AchievementProvider, 0),
  315 + ChanceData: make([]protocol.AchievementChance, 0),
  316 + }
  317 + var (
  318 + achievementData *models.Achievement
  319 + chanceData []models.AchievementChance
  320 + err error
  321 + )
  322 + achievementData, err = models.GetAchievementById(id)
  323 + if err == nil {
  324 + rspData.AchievementId = achievementData.Id
  325 + rspData.AuditTemplateId = achievementData.AuditTemplateId
  326 + rspData.ChanceTypeId = achievementData.ChanceTypeId
  327 + rspData.DepartmentId = achievementData.DepartmentId
  328 + rspData.SourceContent = achievementData.SourceContent
  329 + img := make([]protocol.AchievementImage, 0)
  330 + json.Unmarshal([]byte(achievementData.Images), &img)
  331 + rspData.Images = img
  332 + rspData.GraspScore = achievementData.GraspScore
  333 + rspData.UserGraspScore = achievementData.UserGraspScore
  334 + rspData.UserCompanyId = achievementData.UserCompanyId
  335 + rspData.CrreateAt = achievementData.CreateAt.Format("2006-01-02 15:04:05")
  336 + ud, err := models.GetUserDepartment(rspData.DepartmentId, rspData.UserCompanyId)
  337 + if err == nil {
  338 + rspData.UserDepartmentId = ud.Id
  339 + }
  340 + } else {
  341 + log.Error("获取achievement数据失败:%s", err)
  342 + }
  343 + chanceData, err = models.GetAchievementChanceByAchieve(id)
  344 + if err == nil {
  345 + for _, v := range chanceData {
  346 + m := protocol.AchievementChance{
  347 + Id: fmt.Sprint(v.ChanceId),
  348 + Code: v.ChanceCode,
  349 + }
  350 + rspData.ChanceData = append(rspData.ChanceData, m)
  351 + }
  352 + } else {
  353 + log.Error("获取achievement_chance数据失败:%s", err)
  354 + }
  355 + rspData.Provider = getAchievementProvider(rspData.AchievementId)
  356 + var (
  357 + usercompanyData *models.UserCompany
  358 + departmentData *models.Department
  359 + chaneTypeData *models.ChanceType
  360 + auditTempData *models.AuditTemplate
  361 + )
  362 +
  363 + departmentData, err = models.GetDepartmentById(rspData.DepartmentId)
  364 + if err == nil {
  365 + rspData.DepartmentId = departmentData.Id
  366 + rspData.DeparmentName = departmentData.Name
  367 + }
  368 + usercompanyData, err = models.GetUserCompanyById(rspData.UserCompanyId)
  369 + if err == nil {
  370 + rspData.UserCompanyId = usercompanyData.Id
  371 + rspData.NickName = usercompanyData.NickName
  372 + }
  373 + chaneTypeData, err = models.GetChanceTypeById(int(rspData.ChanceTypeId))
  374 + if err == nil {
  375 + rspData.ChanceTypeId = int64(chaneTypeData.Id)
  376 + rspData.ChanceTypeName = chaneTypeData.Name
  377 + }
  378 + auditTempData, err = models.GetAuditTemplateById(rspData.AuditTemplateId)
  379 + if err == nil {
  380 + rspData.AuditTemplateId = auditTempData.Id
  381 + rspData.AuditTemplateName = auditTempData.Name
  382 + }
  383 + return rspData
  384 +}
  385 +
  386 +func getAchievementProvider(achievementId int64) []protocol.AchievementProvider {
  387 + sql := `SELECT a.achievement_id,a.department_id,a.user_company_id,a.user_grasp_score
  388 + ,b.nick_name,c.name As department_name
  389 + FROM achievement_provider AS a
  390 + LEFT JOIN user_company AS b on a.user_company_id = b.id
  391 + LEFT JOIN department AS c ON a.department_id = c.id
  392 + WHERE achievement_id=? `
  393 + var (
  394 + err error
  395 + sqldata = make([]protocol.AchievementProvider, 0)
  396 + )
  397 + err = utils.ExecuteQueryAll(&sqldata, sql, achievementId)
  398 + if err != nil {
  399 + log.Error("SQL EXECUTE ERR:%s", err)
  400 + }
  401 + for i := range sqldata {
  402 + userDepartment, err := models.GetUserDepartment(sqldata[i].DepartmentId, sqldata[i].UserCompanyId)
  403 + if err == nil {
  404 + sqldata[i].UserDepartmentId = userDepartment.Id
  405 + }
  406 + }
  407 + return sqldata
  408 +}
@@ -98,33 +98,7 @@ func buildSqlForAuditList(usercompanyid int64, companyid int64, userid int64) st @@ -98,33 +98,7 @@ func buildSqlForAuditList(usercompanyid int64, companyid int64, userid int64) st
98 unionsql = sql1 + " UNION " + sql2 98 unionsql = sql1 + " UNION " + sql2
99 return fmt.Sprintf(allsql, unionsql) 99 return fmt.Sprintf(allsql, unionsql)
100 } 100 }
101 - // //获取权限  
102 - // if ok := redisdata.ExistUserPermission(userid); !ok {  
103 - // //尝试重数据库获取  
104 - // log.Debug("从数据库读取权限")  
105 - // permissionMap, err := serverabc.GetUserPermission(usercompanyid, serverabc.M_SYSTEM_OPPORTUNITY)  
106 - // if err != nil {  
107 - // log.Debug("从数据库未获得对应权限 :%s", err)  
108 - // unionsql = sql1 + " UNION " + sql2  
109 - // return fmt.Sprintf(allsql, unionsql)  
110 - // }  
111 - // if v, ok := permissionMap[serverabc.M_SYSTEM_OPPORTUNITY]; !ok {  
112 - // unionsql = sql1 + " UNION " + sql2  
113 - // return fmt.Sprintf(allsql, unionsql)  
114 - // } else {  
115 - // permissionObject = v  
116 - // }  
117 - // } else {  
118 - // //使用缓存  
119 - // log.Debug("从缓存读取权限")  
120 - // permissionObject, err = redisdata.GetUserPermission(userid, serverabc.M_SYSTEM_OPPORTUNITY)  
121 - // if err != nil {  
122 - // log.Debug("从缓存未获得对应权限 :%s", err)  
123 - // unionsql = sql1 + " UNION " + sql2  
124 - // return fmt.Sprintf(allsql, unionsql)  
125 - // }  
126 - // }  
127 - // ------------------------- 101 +
128 var ( 102 var (
129 usrPermission *serverabc.OptionOpportunity 103 usrPermission *serverabc.OptionOpportunity
130 ok bool 104 ok bool
@@ -451,12 +425,17 @@ func getAuditFlowLog(chanceid int64) ([]protocol.ChanceFlowLog, error) { @@ -451,12 +425,17 @@ func getAuditFlowLog(chanceid int64) ([]protocol.ChanceFlowLog, error) {
451 flowLogs = make([]protocol.ChanceFlowLog, 0) 425 flowLogs = make([]protocol.ChanceFlowLog, 0)
452 err error 426 err error
453 ) 427 )
454 - const datasql string = `SELECT a.chance_id,a.content,a.create_at,c.nick_name 428 + const datasql string = `SELECT a.id, a.chance_id,a.content,a.create_at,c.nick_name,a.code
455 FROM audit_flow_log AS a 429 FROM audit_flow_log AS a
456 LEFT JOIN user_company AS b ON a.approve_user_id=b.id 430 LEFT JOIN user_company AS b ON a.approve_user_id=b.id
457 LEFT JOIN user AS c ON b.user_id = c.id 431 LEFT JOIN user AS c ON b.user_id = c.id
458 WHERE chance_id =? ` 432 WHERE chance_id =? `
459 err = utils.ExecuteQueryAll(&flowLogs, datasql, chanceid) 433 err = utils.ExecuteQueryAll(&flowLogs, datasql, chanceid)
  434 + for i := range flowLogs {
  435 + if flowLogs[i].Code == 6 { //系统自动审核通过
  436 + flowLogs[i].NickName = "系统"
  437 + }
  438 + }
460 return flowLogs, err 439 return flowLogs, err
461 } 440 }
462 441
@@ -551,3 +530,50 @@ func GetPermissionInAuditPage(userid int64, companyid int64) serverabc.OptionOpp @@ -551,3 +530,50 @@ func GetPermissionInAuditPage(userid int64, companyid int64) serverabc.OptionOpp
551 } 530 }
552 return option 531 return option
553 } 532 }
  533 +
  534 +type ChanceReviseLogInfo struct {
  535 + UserName string `json:"user_name"`
  536 + UserComapnyId int64 `json:"user_company_id"`
  537 + CreateTime string `json:"create_time"`
  538 + models.ChanceReviseLogData
  539 +}
  540 +
  541 +//GetChanceReviseLog 获取对机会的操作记录,补充机会的详情
  542 +func GetChanceReviseLog(flowLogId int64, chanceId int64, companyId int64) (*ChanceReviseLogInfo, error) {
  543 + var (
  544 + reviseLog *models.ChanceReviseLog
  545 + reviseLogData *models.ChanceReviseLogData
  546 + usercompanyData *models.UserCompany
  547 + chanceData *models.Chance
  548 + err error
  549 + )
  550 + chanceData, err = models.GetChanceById(chanceId)
  551 + if err != nil {
  552 + log.Error("获取机会数据chance失败:%s", err)
  553 + return nil, protocol.NewErrWithMessage("1")
  554 + }
  555 + if chanceData.CompanyId != companyId {
  556 + log.Error("机会的公司不匹配")
  557 + }
  558 + reviseLog, reviseLogData, err = models.GetChanceReviseLogData(flowLogId)
  559 + if err != nil {
  560 + log.Error("获取chance_revise_log失败,err:%s", err)
  561 + return nil, protocol.NewErrWithMessage("1")
  562 + }
  563 + if reviseLog.ChanceId != chanceId {
  564 + log.Error("日志与机会不匹配")
  565 + return nil, protocol.NewErrWithMessage("1")
  566 + }
  567 + rspData := &ChanceReviseLogInfo{
  568 + UserComapnyId: reviseLog.UserCompanyId,
  569 + CreateTime: reviseLog.CreateAt.Format("2006-01-02 15:04:05"),
  570 + ChanceReviseLogData: *reviseLogData,
  571 + }
  572 + usercompanyData, err = models.GetUserCompanyById(reviseLog.UserCompanyId)
  573 + if err != nil {
  574 + log.Error("获取用户数据user_company失败;%s", err)
  575 + } else {
  576 + rspData.UserName = usercompanyData.NickName
  577 + }
  578 + return rspData, nil
  579 +}
@@ -505,6 +505,7 @@ func TemplateDelete(uid, companyId int64, request *protocol.TemplateDeleteReques @@ -505,6 +505,7 @@ func TemplateDelete(uid, companyId int64, request *protocol.TemplateDeleteReques
505 template *models.AuditTemplate 505 template *models.AuditTemplate
506 num int 506 num int
507 sql1 string = `select count(0) from chance where audit_template_id = ? limit 1` 507 sql1 string = `select count(0) from chance where audit_template_id = ? limit 1`
  508 + sql2 string = `select count(0) from achievement where audit_template_id = ? and status in (1,2)`
508 ) 509 )
509 if template, err = models.GetAuditTemplateById(int64(request.TemplateId)); err != nil { 510 if template, err = models.GetAuditTemplateById(int64(request.TemplateId)); err != nil {
510 log.Error(err.Error()) 511 log.Error(err.Error())
@@ -519,6 +520,11 @@ func TemplateDelete(uid, companyId int64, request *protocol.TemplateDeleteReques @@ -519,6 +520,11 @@ func TemplateDelete(uid, companyId int64, request *protocol.TemplateDeleteReques
519 err = protocol.NewErrWithMessage("10062") 520 err = protocol.NewErrWithMessage("10062")
520 return 521 return
521 } 522 }
  523 + //3.判断是否有对应发布的成果
  524 + if err = utils.ExecuteQueryOne(&num, sql2, request.TemplateId); err == nil && num > 0 {
  525 + err = protocol.NewErrWithMessage("10062")
  526 + return
  527 + }
522 528
523 //删除数据 529 //删除数据
524 if err = models.DeleteAuditTemplate(int64(request.TemplateId)); err != nil { 530 if err = models.DeleteAuditTemplate(int64(request.TemplateId)); err != nil {
@@ -643,6 +649,7 @@ func TemplateDeleteCategory(uid, companyId int64, request *protocol.TemplateDele @@ -643,6 +649,7 @@ func TemplateDeleteCategory(uid, companyId int64, request *protocol.TemplateDele
643 num int 649 num int
644 sql1 string = `select count(0) from audit_template where chance_type_id =? limit 1` 650 sql1 string = `select count(0) from audit_template where chance_type_id =? limit 1`
645 sql2 string = `select count(0) from chance where chance_type_id = ? limit 1` 651 sql2 string = `select count(0) from chance where chance_type_id = ? limit 1`
  652 + sql3 string = `select count(0) from achievement where chance_type_id = ? and status in (1,2)`
646 ) 653 )
647 rsp = &protocol.TemplateDeleteCategoryResponse{} 654 rsp = &protocol.TemplateDeleteCategoryResponse{}
648 if chanceType, err = models.GetChanceTypeById(request.ChanceTypeId); err != nil { 655 if chanceType, err = models.GetChanceTypeById(request.ChanceTypeId); err != nil {
@@ -667,6 +674,11 @@ func TemplateDeleteCategory(uid, companyId int64, request *protocol.TemplateDele @@ -667,6 +674,11 @@ func TemplateDeleteCategory(uid, companyId int64, request *protocol.TemplateDele
667 err = protocol.NewErrWithMessage("10062") 674 err = protocol.NewErrWithMessage("10062")
668 return 675 return
669 } 676 }
  677 + //3.判断是否有对应发布的成果
  678 + if err = utils.ExecuteQueryOne(&num, sql3, request.ChanceTypeId); err == nil && num > 0 {
  679 + err = protocol.NewErrWithMessage("10062")
  680 + return
  681 + }
670 682
671 //删除数据 683 //删除数据
672 if err = models.DeleteChanceType(request.ChanceTypeId); err != nil { 684 if err = models.DeleteChanceType(request.ChanceTypeId); err != nil {
@@ -571,3 +571,63 @@ func ValidUserPermission(urlPath string, userid int64, companyid int64) bool { @@ -571,3 +571,63 @@ func ValidUserPermission(urlPath string, userid int64, companyid int64) bool {
571 } 571 }
572 return false 572 return false
573 } 573 }
  574 +
  575 +//LoginAuthBySecretKey 使用秘钥进行登录
  576 +func LoginAuthBySecretKey(secretKey string) (protocol.LoginAuthToken, error) {
  577 + var (
  578 + err error
  579 + logintoken protocol.LoginAuthToken
  580 + usercompanyid int64
  581 + userdata *models.User
  582 + companyData *models.Company
  583 + )
  584 + var uclientReturn *ucenter.ResponseLogin
  585 + uclientReturn, err = ucenter.RequestUCenterLoginBySecret(secretKey)
  586 + if err != nil {
  587 + return logintoken, protocol.ErrWithMessage{
  588 + ErrorCode: protocol.ErrorCode{
  589 + Errno: "-1",
  590 + Errmsg: uclientReturn.Msg,
  591 + },
  592 + }
  593 + }
  594 + userdata, err = models.GetUserByPhone(uclientReturn.Data.Phone)
  595 + if err != nil {
  596 + log.Debug("GetUserByPhone(%d) err:%s", uclientReturn.Data.Phone, err)
  597 + return logintoken, protocol.NewErrWithMessage("10021")
  598 + }
  599 + companyData, err = models.GetCompanyByUCenter(uclientReturn.Data.CompanyId)
  600 + if err != nil {
  601 + log.Error("获取company数据失败:%s", err)
  602 + return logintoken, protocol.NewErrWithMessage("10111")
  603 + }
  604 + if companyData.Enable == models.COMPANY_ENABLE_NO {
  605 + log.Error("公司未启用机会模块")
  606 + return logintoken, protocol.NewErrWithMessage("10124")
  607 + }
  608 + ucompany, err := models.GetUserCompanyBy(userdata.Id, companyData.Id)
  609 + if err != nil {
  610 + log.Error("获取user_company失败;%s", err)
  611 + return logintoken, protocol.NewErrWithMessage("10022")
  612 + }
  613 +
  614 + logintoken, _ = GenerateAuthToken(userdata.Id, companyData.Id, ucompany.Id)
  615 + //更新用户数据
  616 + userdata.Accid = uclientReturn.Data.Accid
  617 + userdata.Icon = uclientReturn.Data.Avatar
  618 + userdata.ImToken = uclientReturn.Data.Imtoken
  619 + userdata.NickName = uclientReturn.Data.NickName
  620 + userdata.CsAccount = uclientReturn.Data.CustomerAccount
  621 + userdata.LastLoginTime = time.Now()
  622 + err = models.UpdateUserById(userdata, []string{"Accid", "Icon", "ImToken", "NickName", "CsAccount", "LastLoginTime"})
  623 + if err != nil {
  624 + log.Error("更新用户user数据失败:%s", err)
  625 + }
  626 + ucompany.NickName = uclientReturn.Data.NickName
  627 + err = models.UpdateUserCompanyById(ucompany, []string{"NickName"})
  628 + if err != nil {
  629 + log.Error("更新用户user_company数据失败:%s", err)
  630 + }
  631 + InitPermission(usercompanyid, userdata.Id)
  632 + return logintoken, err
  633 +}
@@ -182,3 +182,136 @@ func SeleteGetChanceTypeList(companyid int64) []protocol.ChanceTypeBase { @@ -182,3 +182,136 @@ func SeleteGetChanceTypeList(companyid int64) []protocol.ChanceTypeBase {
182 } 182 }
183 return data 183 return data
184 } 184 }
  185 +
  186 +func SelectCompanyUserList(pageIndex int, pageSize int, companyid int64, userName string) protocol.SelectCompanyUserList {
  187 + datasql := `SELECT b.id,a.id as user_company_id,d.nick_name,c.name AS department_name,c.id AS department_id
  188 + FROM user_company AS a
  189 + LEFT JOIN user_department AS b ON a.id = b.user_company_id AND b.enable_status=1
  190 + LEFT JOIN department AS c ON b.department_id = c.id
  191 + LEFT JOIN user AS d ON a.user_id = d.id
  192 + WHERE a.delete_at = 0 AND a.enable=1 AND a.company_id = ? `
  193 + countsql := `SELECT count(*)
  194 + FROM user_company AS a
  195 + LEFT JOIN user_department AS b ON a.id = b.user_company_id AND b.enable_status=1
  196 + LEFT JOIN department AS c ON b.department_id = c.id
  197 + LEFT JOIN user AS d ON a.user_id = d.id
  198 + WHERE a.delete_at = 0 AND a.enable=1 AND a.company_id =? `
  199 + cond := []interface{}{companyid}
  200 + where := ""
  201 + if len(userName) > 0 {
  202 + where += ` And d.nick_name like ? `
  203 + cond = append(cond, "%"+userName+"%")
  204 + }
  205 + datasql += where
  206 + countsql += where
  207 + pageStart := (pageIndex - 1) * pageSize
  208 + datasql += fmt.Sprintf(` limit %d,%d `, pageStart, pageSize)
  209 + var (
  210 + err error
  211 + cnt int
  212 + sqlData = make([]protocol.SelectCompanyUserListItem, 0)
  213 + )
  214 + rspData := protocol.SelectCompanyUserList{
  215 + ResponsePageInfo: protocol.ResponsePageInfo{
  216 + TotalPage: 0, CurrentPage: pageIndex,
  217 + },
  218 + List: make([]protocol.SelectCompanyUserListItem, 0),
  219 + }
  220 + err = utils.ExecuteQueryOne(&cnt, countsql, cond...)
  221 + if err != nil {
  222 + log.Error("SQL EXECUTE ERR:%s", err)
  223 + return rspData
  224 + }
  225 + if cnt == 0 {
  226 + return rspData
  227 + }
  228 + err = utils.ExecuteQueryAll(&sqlData, datasql, cond...)
  229 + if err != nil {
  230 + log.Error("SQL EXECUTE ERR:%s", err)
  231 + return rspData
  232 + }
  233 + rspData.List = sqlData
  234 + rspData.TotalPage = cnt
  235 + return rspData
  236 +}
  237 +
  238 +func SelectChanceList(pageIndex int, pageSize int, companyid int64, searchType int, chanceCode string) protocol.SelectChanceList {
  239 + datasql := ` SELECT a.id ,a.department_id,a.chance_type_id,a.audit_template_id
  240 + ,a.user_id,a.create_at,a.code,c.nick_name
  241 + FROM chance as a
  242 + LEFT JOIN user_company AS b ON a.user_id = b.id
  243 + JOIN user AS c ON b.user_id = c.id
  244 + WHERE a.company_id =? AND a.status=1 AND a.enable_status=1 AND a.review_status=3 `
  245 + countsql := `SELECT count(*)
  246 + FROM chance as a
  247 + LEFT JOIN user_company AS b ON a.user_id = b.id
  248 + JOIN user AS c ON b.user_id = c.id
  249 + WHERE a.company_id =? AND a.status=1 AND a.enable_status=1 AND a.review_status=3 `
  250 + cond := []interface{}{companyid}
  251 + where := ""
  252 + if len(chanceCode) > 0 {
  253 + switch searchType {
  254 + case 1:
  255 + //根据机会编码
  256 + where += ` And a.code like ? `
  257 + cond = append(cond, "%"+chanceCode+"%")
  258 + case 2:
  259 + //根据提交人
  260 + where += ` And c.nick_name like ? `
  261 + cond = append(cond, "%"+chanceCode+"%")
  262 + }
  263 + }
  264 + datasql += where
  265 + countsql += where
  266 + pageStart := (pageIndex - 1) * pageSize
  267 + datasql += fmt.Sprintf(` ORDER BY create_at DESC limit %d,%d `, pageStart, pageSize)
  268 + var (
  269 + err error
  270 + cnt int
  271 + sqldata []protocol.SelectChanceListItem
  272 + )
  273 + rspData := protocol.SelectChanceList{
  274 + ResponsePageInfo: protocol.ResponsePageInfo{
  275 + TotalPage: 0, CurrentPage: pageIndex,
  276 + },
  277 + List: make([]protocol.SelectChanceListItem, 0),
  278 + }
  279 + err = utils.ExecuteQueryOne(&cnt, countsql, cond...)
  280 + if err != nil {
  281 + log.Error("SQL EXECUTE ERR:%s", err)
  282 + return rspData
  283 + }
  284 + if cnt == 0 {
  285 + return rspData
  286 + }
  287 + err = utils.ExecuteQueryAll(&sqldata, datasql, cond...)
  288 + if err != nil {
  289 + log.Error("SQL EXECUTE ERR:%s", err)
  290 + return rspData
  291 + }
  292 +
  293 + for i, v := range sqldata {
  294 + d, err := models.GetDepartmentById(v.DepartmentId)
  295 + if err == nil {
  296 + sqldata[i].DepartmentName = d.Name
  297 + }
  298 + ct, err := models.GetChanceTypeById(v.ChanceTypeId)
  299 + if err == nil {
  300 + sqldata[i].ChanceTypeName = ct.Name
  301 + }
  302 + at, err := models.GetAuditTemplateById(v.AuditTemplateId)
  303 + if err == nil {
  304 + sqldata[i].AuditTemplateName = at.Name
  305 + }
  306 + uc, err := models.GetUserCompanyById(v.UserId)
  307 + if err == nil {
  308 + u, err := models.GetUserById(uc.UserId)
  309 + if err == nil {
  310 + sqldata[i].UserName = u.NickName
  311 + }
  312 + }
  313 + }
  314 + rspData.List = sqldata
  315 + rspData.TotalPage = cnt
  316 + return rspData
  317 +}
@@ -116,6 +116,7 @@ func initCompany(centerCompany protocol.CenterCompanyInfo, admininfo *models.Use @@ -116,6 +116,7 @@ func initCompany(centerCompany protocol.CenterCompanyInfo, admininfo *models.Use
116 } 116 }
117 } else if err == orm.ErrNoRows { 117 } else if err == orm.ErrNoRows {
118 newCompany = &models.Company{ 118 newCompany = &models.Company{
  119 + Id: centerCompany.CompanyId,
119 Name: centerCompany.CompanyName, 120 Name: centerCompany.CompanyName,
120 AdminId: admininfo.Id, 121 AdminId: admininfo.Id,
121 UserCenterId: centerCompany.CompanyId, 122 UserCenterId: centerCompany.CompanyId,
@@ -209,8 +210,11 @@ func initUserCompany(newcompany *models.Company, newuser *models.User, o orm.Orm @@ -209,8 +210,11 @@ func initUserCompany(newcompany *models.Company, newuser *models.User, o orm.Orm
209 } 210 }
210 } else if err == orm.ErrNoRows { 211 } else if err == orm.ErrNoRows {
211 uc = &models.UserCompany{ 212 uc = &models.UserCompany{
212 - UserId: newuser.Id,  
213 - CompanyId: newcompany.Id, 213 + UserId: newuser.Id,
  214 + CompanyId: newcompany.Id,
  215 + OpenId: newuser.UserCenterId,
  216 + Enable: models.USERCOMPANY_ENABLE_YES,
  217 + ChargeStatus: models.USERCOMPANY_CHARGE_YES,
214 } 218 }
215 _, err = models.AddUserCompany(uc, o) 219 _, err = models.AddUserCompany(uc, o)
216 if err != nil { 220 if err != nil {
@@ -388,8 +388,8 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs @@ -388,8 +388,8 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs
388 } 388 }
389 const dataSql string = `SELECT a.user_company_id,b.user_id 389 const dataSql string = `SELECT a.user_company_id,b.user_id
390 FROM user_department AS a 390 FROM user_department AS a
391 - LEFT JOIN user_company AS b ON a.user_company_id = b.id  
392 - WHERE a.department_id=? AND b.delete_at=0 AND a.enable_status = 1 ` 391 + JOIN user_company AS b ON a.user_company_id = b.id
  392 + WHERE a.department_id=? AND b.delete_at=0 AND a.enable_status = 1 AND b.enable = 1 `
393 393
394 err = utils.ExecuteQueryAll(&returnData, dataSql, department.Id) 394 err = utils.ExecuteQueryAll(&returnData, dataSql, department.Id)
395 if err != nil { 395 if err != nil {
  1 +package crontab
  2 +
  3 +import (
  4 + "github.com/astaxie/beego/toolbox"
  5 +)
  6 +
  7 +//定时任务
  8 +
  9 +func Run() {
  10 + //自动创建赛季 每隔一小时执行一次
  11 + taskRankPeriod := toolbox.NewTask("AutoCreateRankPeriod", " 0 1 * * * *", AutoCreateRankPeriod)
  12 + toolbox.AddTask("AutoCreateRankPeriod", taskRankPeriod)
  13 + toolbox.StartTask()
  14 +}
  1 +package crontab
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/common/log"
  6 + "oppmg/models"
  7 + "oppmg/utils"
  8 + "strings"
  9 + "time"
  10 +
  11 + "github.com/astaxie/beego/orm"
  12 +)
  13 +
  14 +//rankTypeAutoPeriod 榜单配置:自动创建赛季
  15 +type RankTypeAutoPeriod struct {
  16 + RankTypeId int64 `orm:"column(rank_type_id)"`
  17 + CompanyId int64 `orm:"column(company_id)"`
  18 + AutoPeriod int64 `orm:"column(auto_period)"`
  19 + CreateTime int64 `orm:"column(create_time)"`
  20 + RankType int8 `orm:"column(rank_type)`
  21 +}
  22 +
  23 +//
  24 +type RankPeriodEndTime struct {
  25 + RankTypeId int64 `orm:"column(rank_type_id)"`
  26 + EndTime time.Time `orm:"column(end_time)"`
  27 +}
  28 +
  29 +func AutoCreateRankPeriod() error {
  30 + log.Info("计划任务:【自动创建赛季】")
  31 + //获取需要执行自动创建的榜单记录
  32 + sql1 := `SELECT a.id AS rank_type_id,a.type AS rank_type,a.auto_period,UNIX_TIMESTAMP(a.create_at) AS create_time
  33 + ,a.company_id
  34 + FROM rank_type AS a
  35 + JOIN company AS b ON a.company_id=b.id AND b.enable=1 AND b.delete_at=0
  36 + WHERE a.auto_create = 1 AND a.auto_period>0
  37 + AND NOT EXISTS(
  38 + SELECT 1 FROM rank_period AS c WHERE a.id=c.rank_type_id AND c.status<2
  39 + )
  40 + AND UNIX_TIMESTAMP(a.create_at)>?
  41 + LIMIT 1000`
  42 +
  43 + //获取自动创建赛季时需要的开始时间
  44 + sql2 := `SELECT a.rank_type_id,MAX(a.end_time) AS end_time
  45 + FROM rank_period AS a
  46 + WHERE a.status = 2 AND a.rank_type_id IN (%s)
  47 + GROUP BY a.rank_type_id `
  48 + var (
  49 + rankTypeCreateAt int64
  50 + err error
  51 + )
  52 + o := orm.NewOrm()
  53 +LOOP0:
  54 + for {
  55 + var (
  56 + rankTypeList []RankTypeAutoPeriod
  57 + )
  58 + log.Info("【自动创建赛季】,获取需要执行自动创建的榜单记录")
  59 + err = utils.ExecuteQueryAll(&rankTypeList, sql1, rankTypeCreateAt)
  60 + if err != nil {
  61 + log.Error("【自动创建赛季】,获取需要执行自动创建的榜单记录失败,err:%s", err)
  62 + break LOOP0
  63 + }
  64 + if len(rankTypeList) == 0 {
  65 + log.Info("【自动创建赛季】,获取需要执行自动创建的榜单记录数0,结束任务")
  66 + break LOOP0
  67 + }
  68 + log.Info("【自动创建赛季】,获取需要执行自动创建的榜单记录数%d", len(rankTypeList))
  69 + var rankTypeIds []string
  70 + for i := range rankTypeList {
  71 + rankTypeIds = append(rankTypeIds, fmt.Sprintf("%d", rankTypeList[i].RankTypeId))
  72 + rankTypeCreateAt = rankTypeList[i].CreateTime
  73 + }
  74 + log.Info("【自动创建赛季】,获取自动创建赛季时需要的开始时间")
  75 + runsql2 := fmt.Sprintf(sql2, strings.Join(rankTypeIds, ","))
  76 + var (
  77 + rankPeriodList []RankPeriodEndTime
  78 + )
  79 + rankPeriodMap := make(map[int64]time.Time)
  80 + err = utils.ExecuteQueryAll(&rankPeriodList, runsql2)
  81 + if err != nil {
  82 + log.Error("【自动创建赛季】,获取自动创建赛季时需要的开始时间失败:%s")
  83 + break LOOP0
  84 + }
  85 + for _, v := range rankPeriodList {
  86 + rankPeriodMap[v.RankTypeId] = v.EndTime
  87 + }
  88 + //开始循环rankTypeList,创建赛季
  89 + var (
  90 + successNum int64
  91 + addRankPeriod []models.RankPeriod
  92 + )
  93 + nowTime := time.Now()
  94 + LOOP1:
  95 + for _, v := range rankTypeList {
  96 + m := models.RankPeriod{
  97 + CompanyId: v.CompanyId,
  98 + RankTypeId: v.RankTypeId,
  99 + CreateAt: nowTime,
  100 + UpdateAt: nowTime,
  101 + Status: models.RANKPERIOD_STATUS_NOT,
  102 + IsAuto: 1,
  103 + }
  104 + if t, ok := rankPeriodMap[v.RankTypeId]; ok {
  105 + s := t.Format("2006-01-02")
  106 + dayTime, err := time.ParseInLocation("2006-01-02", s, time.Local)
  107 + if err != nil {
  108 + log.Error("【自动创建赛季】,格式化rank_period的end_time失败,id=%d,end_time=%d", v.RankTypeId, t)
  109 + continue LOOP1
  110 + }
  111 + begin := dayTime.Unix() + 24*60*60
  112 + end := begin + v.AutoPeriod*24*60*60 - 1
  113 + m.BeginTime = time.Unix(begin, 0).Local()
  114 + m.EndTime = time.Unix(end, 0).Local()
  115 + // m.SeasonName = fmt.Sprintf("自动创建赛季%s", s)
  116 + } else {
  117 + s := nowTime.Format("2006-01-02")
  118 + dayTime, _ := time.ParseInLocation("2006-01-02", s, time.Local)
  119 + begin := dayTime.Unix() + 24*60*60
  120 + end := begin + v.AutoPeriod*24*60*60 - 1
  121 + m.BeginTime = time.Unix(begin, 0).Local()
  122 + m.EndTime = time.Unix(end, 0).Local()
  123 + // m.SeasonName = fmt.Sprintf("自动创建赛季%s", s)
  124 + }
  125 + if v.RankType == models.RANK_TYPE_YEAR {
  126 + //年榜
  127 + m.SeasonName = fmt.Sprintf("%d%s", nowTime.Year(), "年赛季")
  128 + } else if v.RankType == models.RANK_TYPE_SEASON {
  129 + //季榜
  130 + m.SeasonName = fmt.Sprintf("%d%s", nowTime.Month(), "月赛季")
  131 + }
  132 + addRankPeriod = append(addRankPeriod, m)
  133 + }
  134 + successNum, err = o.InsertMulti(100, addRankPeriod)
  135 + if err != nil {
  136 + log.Error("【自动创建赛季】,创建赛季出现错误,添加rank_period数据发生错误:%s", err)
  137 + }
  138 + log.Info("【自动创建赛季】,添加rank_period记录数量:%d", successNum)
  139 + }
  140 + return nil
  141 +}
  1 +package platform
  2 +
  3 +import "errors"
  4 +
  5 +type PlatformAction interface {
  6 + DoAction(string, []byte) error
  7 +}
  8 +
  9 +//从主管理平台接收数据数据并处理数据
  10 +type CommonProtocol struct {
  11 + Module string `json:"module"` //模块
  12 + Action string `json:"action"` //动作
  13 + Data interface{} `json:"data"` //实际的未知数据结构
  14 +}
  15 +
  16 +var actionmap = map[string]PlatformAction{
  17 + "department": ModuleDeparmentData{},
  18 + "position": ModulePositionData{},
  19 + "employee": ModuleEmployee{},
  20 + "company": ModuleCompanytData{},
  21 +}
  22 +
  23 +func NewPlatformAction(module string) (PlatformAction, error) {
  24 + if v, ok := actionmap[module]; ok {
  25 + return v, nil
  26 + }
  27 + return nil, errors.New("module cannot found")
  28 +}
  1 +package platform
  2 +
  3 +import (
  4 + "fmt"
  5 + "oppmg/common/log"
  6 + "oppmg/models"
  7 +
  8 + "github.com/astaxie/beego/orm"
  9 +)
  10 +
  11 +// AdminChance g更换公司主管
  12 +//companyid 总管理后台的公司id
  13 +func AdminChance(companyid int64, phone string) error {
  14 + var (
  15 + companyData *models.Company
  16 + userData *models.User
  17 + err error
  18 + newCharge *models.UserCompany
  19 + oldCharge *models.UserCompany
  20 + )
  21 + companyData, err = models.GetCompanyByUCenter(companyid)
  22 + if err != nil {
  23 + e := fmt.Errorf("获取公司数据失败,总后台company_id:%d", companyid)
  24 + log.Error(err.Error())
  25 + return e
  26 + }
  27 + userData, err = models.GetUserByPhone(phone)
  28 + if err != nil {
  29 + e := fmt.Errorf("获取用户数据失败,phone:%s", phone)
  30 + log.Error(err.Error())
  31 + return e
  32 + }
  33 + newCharge, err = models.GetUserCompanyBy(userData.Id, companyData.Id)
  34 + if err != nil {
  35 + e := fmt.Errorf("获取用户和公司的对应关系数据失败,user_id:%d,company_id:%d", userData.Id, companyData.Id)
  36 + log.Error(e.Error())
  37 + return e
  38 + }
  39 + oldCharge, err = models.GetUserCompanyBy(companyData.AdminId, companyData.Id)
  40 + if err != nil {
  41 + e := fmt.Errorf("获取公司原来的主管对应数据失败,user_id:%d,company_id:%d", companyData.AdminId, companyData.Id)
  42 + log.Error(e.Error())
  43 + return e
  44 + }
  45 + o := orm.NewOrm()
  46 + o.Begin()
  47 + companyData.AdminId = userData.Id
  48 + err = models.UpdateCompanyById(companyData, []string{"AdminId"}, o)
  49 + if err != nil {
  50 + o.Rollback()
  51 + e := fmt.Errorf("更新公司数据失败,err:%s", err)
  52 + log.Error(e.Error())
  53 + return e
  54 + }
  55 + newCharge.ChargeStatus = models.USERCOMPANY_CHARGE_YES
  56 + oldCharge.ChargeStatus = models.USERCOMPANY_CHARGE_NO
  57 + err = models.UpdateUserCompanyById(newCharge, []string{"ChargeStatus"}, o)
  58 + if err != nil {
  59 + o.Rollback()
  60 + e := fmt.Errorf("更新原公司主管理员数据失败,user_company_id=%d,err:%s", oldCharge.Id, err)
  61 + log.Error(e.Error())
  62 + return e
  63 + }
  64 + err = models.UpdateUserCompanyById(oldCharge, []string{"ChargeStatus"}, o)
  65 + if err != nil {
  66 + o.Rollback()
  67 + e := fmt.Errorf("更新新公司主管理员数据失败,user_company_id=%d , err:%s", newCharge.Id, err)
  68 + log.Error(e.Error())
  69 + return e
  70 + }
  71 + o.Commit()
  72 + return nil
  73 +}
  1 +package platform
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "errors"
  6 + "fmt"
  7 + "oppmg/common/log"
  8 + "oppmg/models"
  9 + "oppmg/protocol"
  10 + "oppmg/services/ucenter"
  11 + "oppmg/utils"
  12 + "time"
  13 +
  14 + "github.com/astaxie/beego/orm"
  15 +)
  16 +
  17 +type CompanyBase struct {
  18 + Id int64 `json:"id"` //id
  19 + Name string `json:"name"` //公司名称名称
  20 + AdminCompanyId int64 `json:"admin_company_id"`
  21 + Logo string `json:"logo"`
  22 + Remarks string `json:"remarks"`
  23 +}
  24 +
  25 +// ModuleCompanytData 主管理平台发送过来的数据
  26 +type ModuleCompanytData struct {
  27 + Company CompanyBase `json:"company"`
  28 + User ModuleEmployee `json:"user"`
  29 +}
  30 +
  31 +type CompanyCharge struct {
  32 + Id int64 `json:"id"`
  33 + Charge []int64 `json:"charge"`
  34 +}
  35 +
  36 +var _ PlatformAction = ModuleCompanytData{}
  37 +
  38 +func (m ModuleCompanytData) DoAction(code string, jsondata []byte) error {
  39 + switch code {
  40 + case "add":
  41 + var (
  42 + data ModuleCompanytData
  43 + err error
  44 + )
  45 + err = json.Unmarshal(jsondata, &data)
  46 + if err != nil {
  47 + return fmt.Errorf("数据解析失败:%s", err)
  48 + }
  49 + return AddCompanyData(data)
  50 + case "edit":
  51 + var (
  52 + data ModuleCompanytData
  53 + err error
  54 + )
  55 + err = json.Unmarshal(jsondata, &data)
  56 + if err != nil {
  57 + return fmt.Errorf("数据解析失败:%s", err)
  58 + }
  59 + return UpdateCompanyData(data)
  60 + case "setCompanyCharge":
  61 + var (
  62 + data CompanyCharge
  63 + err error
  64 + )
  65 + err = json.Unmarshal(jsondata, &data)
  66 + if err != nil {
  67 + return fmt.Errorf("数据解析失败:%s", err)
  68 + }
  69 + return SetCompanyCharge(data)
  70 + default:
  71 + return errors.New("action not found")
  72 + }
  73 + // return nil
  74 +}
  75 +
  76 +// SetCompanyCharge 更新公司那一级的部门的管理员
  77 +func SetCompanyCharge(data CompanyCharge) error {
  78 + var (
  79 + err error
  80 + companyData *models.Company
  81 + departmentData *models.Department
  82 + )
  83 + companyData, err = models.GetCompanyByUCenter(data.Id)
  84 + if err != nil {
  85 + log.Error("获取公司数据失败,user_center_id=%d,err:%s", data.Id, err)
  86 + return errors.New("获取公司数据失败")
  87 + }
  88 + departmentData, err = models.GetTopDepartmentByCompany(companyData.Id)
  89 + if err != nil {
  90 + log.Error("获取公司一级部门数据失败,company_id=%d, err:%s", companyData.Id, err)
  91 + return errors.New("获取公司一级部门数据失败")
  92 + }
  93 + // 获取公司管理员
  94 + o := orm.NewOrm()
  95 + o.Begin()
  96 + err = models.ChangeDepartmentCharge(data.Id, departmentData.Id, data.Charge, o)
  97 + if err != nil {
  98 + o.Rollback()
  99 + log.Error("变更公司管理员失败,err:%s", err)
  100 + return errors.New("变更公司管理员失败")
  101 + }
  102 + //更新department数据
  103 + bt, _ := json.Marshal(data.Charge)
  104 + departmentData.Manages = string(bt)
  105 + err = models.UpdateDepartmentById(departmentData, []string{"Manages"}, o)
  106 + if err != nil {
  107 + o.Rollback()
  108 + log.Error("变更公司管理员失败,err:%s", err)
  109 + return errors.New("变更公司管理员失败")
  110 + }
  111 + o.Commit()
  112 + return nil
  113 +}
  114 +
  115 +func UpdateCompanyData(data ModuleCompanytData) error {
  116 + var (
  117 + companyData *models.Company
  118 + err error
  119 + )
  120 + newCompanyData := data.Company
  121 + companyData, err = models.GetCompanyByUCenter(newCompanyData.AdminCompanyId)
  122 + if err == orm.ErrNoRows {
  123 + log.Error("编辑操作,未找到数据,执行添加操作")
  124 + return AddCompanyData(data)
  125 + }
  126 + if err != nil {
  127 + log.Error("获取企业数据失败,user_center_id:%d ,err:%s", newCompanyData.AdminCompanyId, err)
  128 + return errors.New("获取企业数据失败")
  129 + }
  130 + var (
  131 + oldAdminData *models.UserCompany
  132 + )
  133 + oldAdminData, err = models.GetUserCompanyBy(companyData.AdminId, companyData.Id)
  134 + if err != nil {
  135 + log.Error("获取公司主管理员user_company数据失败,company_id=%d,user_id=%d,err:%s", companyData.Id, companyData.AdminId, err)
  136 + return errors.New("获取公司主管理员数据失败")
  137 + }
  138 + o := orm.NewOrm()
  139 + o.Begin()
  140 + if data.User.Id != oldAdminData.Id {
  141 + //更新公司主管理员
  142 + oldAdminData.ChargeStatus = models.USERCOMPANY_CHARGE_NO
  143 + err = models.UpdateUserCompanyById(oldAdminData, []string{"ChargeStatus"}, o)
  144 + if err != nil {
  145 + o.Rollback()
  146 + log.Error("去除旧的主管理员失败:user_company_id=%d,err:%s", oldAdminData.Id, err)
  147 + return errors.New("去除旧的更主管理员失败")
  148 + }
  149 + var newAdminData *models.UserCompany
  150 + newAdminData, err = models.GetUserCompanyById(data.User.Id)
  151 + if err != nil {
  152 + o.Rollback()
  153 + log.Error("获取新的主管理员失败,user_company_id=%d,err:%s", data.User.Id, err)
  154 + return errors.New("获取新的主管理员")
  155 + }
  156 + newAdminData.ChargeStatus = models.USERCOMPANY_CHARGE_YES
  157 + err = models.UpdateUserCompanyById(newAdminData, []string{"ChargeStatus"}, o)
  158 + if err != nil {
  159 + o.Rollback()
  160 + log.Error("变更更主管理员失败:user_company_id=%d,err:%s", newAdminData.Id, err)
  161 + return errors.New("变更主管理员失败")
  162 + }
  163 + companyData.AdminId = newAdminData.UserId
  164 + }
  165 + companyData.Logo = newCompanyData.Logo
  166 + companyData.Name = newCompanyData.Name
  167 + companyData.Remark = newCompanyData.Remarks
  168 + err = models.UpdateCompanyById(companyData, []string{"Logo", "Name", "AdminId", "Remark"}, o)
  169 + if err != nil {
  170 + o.Rollback()
  171 + log.Error("更新公司数据失败:%s", err)
  172 + return errors.New("更新公司数据失败")
  173 + }
  174 + o.Commit()
  175 + return nil
  176 +}
  177 +
  178 +//AddCompanyData 新增公司 初始化公司
  179 +func AddCompanyData(data ModuleCompanytData) error {
  180 + var (
  181 + newDeparment *models.Department
  182 + newRoleGroup *models.Role
  183 + newRole *models.Role
  184 + newUser *models.User
  185 + newCompany *models.Company
  186 + newUserCompany *models.UserCompany
  187 + err error
  188 + )
  189 + log.Info("获取统一户中心的数据")
  190 + ucenterReturn, err := ucenter.RequestUCenterAddUser(data.User.Phone, data.User.Name, "")
  191 + if err != nil {
  192 + log.Error("请求统一用户中心数据失败:%s", err)
  193 + return errors.New("获取统一用户中心数据失败")
  194 + }
  195 + data.User.OpenId = ucenterReturn.Data.Id
  196 + o := orm.NewOrm()
  197 + o.Begin()
  198 + //处理用户数据
  199 + log.Info("添加user表数据")
  200 + newUser, err = AddAdminUser(&data, o)
  201 + if err != nil {
  202 + o.Rollback()
  203 + log.Error("处理公司主管数据失败:%s", err)
  204 + return errors.New("处理公司主管数据失败")
  205 + }
  206 + //处理公司数据
  207 + log.Info("添加company表数据")
  208 + newCompany, err = AddCompanyBase(&data, newUser, o)
  209 + if err != nil {
  210 + o.Rollback()
  211 + log.Error("处理公司数据失败:%s", err)
  212 + return errors.New("处理公司数据失败")
  213 + }
  214 + //处理评分配置数据 初始化
  215 + log.Info("添加sys_config表数据")
  216 + err = iniSysConfig(int(newCompany.Id), o)
  217 + if err != nil {
  218 + o.Rollback()
  219 + log.Error("处理评分配置数据失败:%s", err)
  220 + return errors.New("处理评分配置数据")
  221 + }
  222 + //添加user_company
  223 + log.Info("添加user_copmany表数据")
  224 + newUserCompany, err = AddUserCompanyData(&data, newCompany, newUser, o)
  225 + if err != nil {
  226 + o.Rollback()
  227 + log.Error("处理user_company数据失败:%s", err)
  228 + return errors.New("处理user_company数据失败")
  229 + }
  230 + //添加部门
  231 + log.Info("添加department表数据")
  232 + newDeparment, err = AddFirstDepartment(newCompany, newUserCompany, o)
  233 + if err != nil {
  234 + o.Rollback()
  235 + log.Error("处理部门数据失败:%s", err)
  236 + return errors.New("处理部门数据失败")
  237 + }
  238 + //添加用户部门数据
  239 + log.Info("添加user_department表数据")
  240 + _, err = initUserDedaprtmet(newDeparment, newUserCompany, o)
  241 + if err != nil {
  242 + o.Rollback()
  243 + log.Error("处理user_department数据失败:%s", err)
  244 + return protocol.NewErrWithMessage("1")
  245 + }
  246 + //添加部门主管
  247 + log.Info("添加department_charge表数据")
  248 + err = AddFirstDepartmentCharge(newDeparment, newUserCompany, newCompany, o)
  249 + if err != nil {
  250 + o.Rollback()
  251 + log.Error("处理部门主管数据,err:%s", err)
  252 + return errors.New("处理部门主管数据")
  253 + }
  254 + //添加角色组
  255 + log.Info("添加role表数据")
  256 + newRoleGroup, err = initRoleGroup(newCompany, o)
  257 + if err != nil {
  258 + o.Rollback()
  259 + log.Error("处理角色组数据失败:%s", err)
  260 + return protocol.NewErrWithMessage("1")
  261 + }
  262 + //添加角色
  263 + log.Info("添加role表数据")
  264 + newRole, err = initRole(newCompany, newRoleGroup, o)
  265 + if err != nil {
  266 + o.Rollback()
  267 + log.Error("处理角色数据失败:%s", err)
  268 + return protocol.NewErrWithMessage("1")
  269 + }
  270 + //添加用户的角色
  271 + log.Info("添加user_role表数据")
  272 + _, err = initUserRole(newUserCompany, newRole, o)
  273 + if err != nil {
  274 + o.Rollback()
  275 + log.Error("处理user_role数据失败:%s", err)
  276 + return protocol.NewErrWithMessage("1")
  277 + }
  278 + o.Commit()
  279 + return nil
  280 +}
  281 +
  282 +func AddAdminUser(centerCompany *ModuleCompanytData, o orm.Ormer) (*models.User, error) {
  283 + var (
  284 + err error
  285 + newUser = &models.User{}
  286 + )
  287 + companyAdminData := centerCompany.User
  288 + err = o.QueryTable(&models.User{}).
  289 + Filter("phone", companyAdminData.Phone).
  290 + One(newUser)
  291 + if err == nil {
  292 + return newUser, nil
  293 + }
  294 + //添加用户
  295 + newUser = &models.User{
  296 + Id: companyAdminData.Id,
  297 + Phone: companyAdminData.Phone,
  298 + NickName: companyAdminData.Name,
  299 + UserCenterId: companyAdminData.OpenId,
  300 + }
  301 + _, err = models.AddUser(newUser, o)
  302 + if err != nil {
  303 + log.Error("添加用户数据失败:%s", err)
  304 + return nil, err
  305 + }
  306 +
  307 + return newUser, nil
  308 +}
  309 +
  310 +func AddCompanyBase(centerCompany *ModuleCompanytData, admininfo *models.User, o orm.Ormer) (*models.Company, error) {
  311 + var (
  312 + err error
  313 + )
  314 + companybase := centerCompany.Company
  315 + newCompany := &models.Company{
  316 + Id: companybase.Id,
  317 + Name: companybase.Name,
  318 + AdminId: admininfo.Id,
  319 + UserCenterId: companybase.AdminCompanyId,
  320 + Enable: models.COMPANY_ENABLE_NO,
  321 + Logo: companybase.Logo,
  322 + Remark: companybase.Remarks,
  323 + }
  324 + _, err = models.AddCompany(newCompany, o)
  325 + if err != nil {
  326 + log.Error("添加公司数据失败:%s", err)
  327 + return nil, err
  328 + }
  329 + return newCompany, nil
  330 +}
  331 +
  332 +func AddUserCompanyData(centerCompany *ModuleCompanytData, newcompany *models.Company, newuser *models.User, o orm.Ormer) (*models.UserCompany, error) {
  333 + var (
  334 + err error
  335 + uc = &models.UserCompany{}
  336 + )
  337 + adminUserData := centerCompany.User
  338 + err = o.QueryTable(&models.UserCompany{}).
  339 + Filter("company_id", newcompany.Id).
  340 + Filter("user_id", newuser.Id).
  341 + Filter("delete_at", 0).
  342 + One(uc)
  343 + if err == nil {
  344 + return uc, nil
  345 + }
  346 + uc = &models.UserCompany{
  347 + UserId: newuser.Id,
  348 + CompanyId: newcompany.Id,
  349 + Enable: models.USERCOMPANY_ENABLE_YES,
  350 + ChargeStatus: adminUserData.ChargeStatus,
  351 + Id: adminUserData.Id,
  352 + NickName: adminUserData.Name,
  353 + OpenId: adminUserData.OpenId,
  354 + Sex: adminUserData.Sex,
  355 + JobNum: adminUserData.JobNum,
  356 + Phone: adminUserData.Phone,
  357 + PrivatePhone: adminUserData.PrivatePhone,
  358 + Email: adminUserData.Email,
  359 + ExtensionNum: adminUserData.ExtensionNum,
  360 + Workspace: adminUserData.WorkSpace,
  361 + IsBusiness: adminUserData.IsBusiness,
  362 + Avatar: adminUserData.Avatar,
  363 + Remarks: adminUserData.Remarks,
  364 + AdminType: adminUserData.AdminType,
  365 + ExtraText: adminUserData.ExtraText,
  366 + }
  367 + _, err = models.AddUserCompany(uc, o)
  368 + if err != nil {
  369 + log.Error("添加user_company数据失败:%s", err)
  370 + return nil, err
  371 + }
  372 + return uc, nil
  373 +}
  374 +
  375 +//AddFirstDepartment 创建公司的一级部门
  376 +func AddFirstDepartment(newCompany *models.Company, newusercompany *models.UserCompany, o orm.Ormer) (*models.Department, error) {
  377 + var (
  378 + newDepartment = &models.Department{}
  379 + err error
  380 + )
  381 + err = o.QueryTable(&models.Department{}).
  382 + Filter("company_id", newCompany.Id).
  383 + Filter("is_top", 1).
  384 + One(newDepartment)
  385 + if err == nil {
  386 + return newDepartment, nil
  387 + } else if err == orm.ErrNoRows {
  388 + //添加部门
  389 + newDepartment = &models.Department{
  390 + CompanyId: newCompany.Id,
  391 + Name: newCompany.Name,
  392 + IsTop: 1,
  393 + ParentId: 0,
  394 + Relation: fmt.Sprint(utils.GenerateIDBySonyflake()),
  395 + Id: utils.GenerateID14(),
  396 + }
  397 + _, err = models.AddDepartment(newDepartment, o)
  398 + if err != nil {
  399 + log.Error("添加部门数据失败:%s", err)
  400 + return nil, err
  401 + }
  402 + newDepartment.SetRelation(nil)
  403 + err = models.UpdateDepartmentById(newDepartment, []string{"Relation"}, o)
  404 + if err != nil {
  405 + log.Error("更新部门关系树数据失败:%s", err)
  406 + return nil, err
  407 + }
  408 + } else {
  409 + log.Error("查询部门数据失败:%s", err)
  410 + return nil, err
  411 + }
  412 +
  413 + return newDepartment, nil
  414 +}
  415 +
  416 +func AddFirstDepartmentCharge(newDepartment *models.Department, newUserCompany *models.UserCompany, newCompany *models.Company, o orm.Ormer) error {
  417 + var (
  418 + err error
  419 + )
  420 + departmentCharg := &models.DepartmentCharge{
  421 + CompanyId: newCompany.Id,
  422 + DepartmentId: newDepartment.Id,
  423 + UserCompanyId: newUserCompany.Id,
  424 + }
  425 + _, err = models.AddDepartmentCharge(departmentCharg, o)
  426 + if err != nil {
  427 + log.Error("设置部门主管失败,err:%s", err)
  428 + return err
  429 + }
  430 + newDepartment.SetManages([]int64{newUserCompany.Id})
  431 + err = models.UpdateDepartmentById(newDepartment, []string{"Manages"}, o)
  432 + if err != nil {
  433 + log.Error("设置部门主管失败,err:%s", err)
  434 + return err
  435 + }
  436 + return nil
  437 +}
  438 +
  439 +func UpdateCompany(centerCompany *ModuleCompanytData, admininfo *models.User, o orm.Ormer) (*models.Company, error) {
  440 + var (
  441 + err error
  442 + newCompany = &models.Company{}
  443 + )
  444 + err = o.QueryTable(&models.Company{}).
  445 + Filter("user_center_id", centerCompany.Company.AdminCompanyId).
  446 + One(newCompany)
  447 + if err == nil {
  448 + _, err = o.QueryTable(&models.Company{}).
  449 + Filter("user_center_id", centerCompany.Company.AdminCompanyId).
  450 + Update(orm.Params{
  451 + "name": centerCompany.Company.Name,
  452 + "admin_id": admininfo.Id,
  453 + "delete_at": 0,
  454 + })
  455 + if err != nil {
  456 + log.Error("更新公司数据失败:%s", err)
  457 + return nil, err
  458 + }
  459 + } else {
  460 + log.Error("查询公司数据失败:%s", err)
  461 + return nil, err
  462 + }
  463 + return newCompany, nil
  464 +}
  465 +
  466 +// func initAdminUser(centerCompany *ModuleCompanytData, o orm.Ormer) (*models.User, error) {
  467 +// var (
  468 +// err error
  469 +// newUser = &models.User{}
  470 +// )
  471 +// companyAdminData := centerCompany.User
  472 +// err = o.QueryTable(&models.User{}).
  473 +// Filter("phone", companyAdminData.Phone).
  474 +// Filter("delete_at", 0).
  475 +// One(newUser)
  476 +// if err == nil {
  477 +// // 更新数据
  478 +// _, err = o.QueryTable(&models.User{}).
  479 +// Filter("user_center_id", companyAdminData.OpenId).
  480 +// Filter("delete_at", 0).
  481 +// Update(orm.Params{
  482 +// "nick_name": companyAdminData.Name,
  483 +// "phone": companyAdminData.Phone,
  484 +// "enable_status": models.USER_ENABLE_YES,
  485 +// })
  486 +// if err != nil {
  487 +// log.Error("数据操作失败:%s", err)
  488 +// return nil, err
  489 +// }
  490 +// } else if err == orm.ErrNoRows {
  491 +// var (
  492 +// ucenterUser = &ucenter.ResponseAddUser{}
  493 +// err error
  494 +// )
  495 +// ucenterUser, err = ucenter.RequestUCenterAddUser(companyAdminData.Phone, companyAdminData.Name, "")
  496 +// if err != nil {
  497 +// log.Error("获取统一用户中心数据失败 :%s", err)
  498 +// return nil, err
  499 +// }
  500 +// //添加用户
  501 +// newUser = &models.User{
  502 +// Id: companyAdminData.Id,
  503 +// Phone: companyAdminData.Phone,
  504 +// NickName: companyAdminData.Name,
  505 +// Icon: ucenterUser.Data.Avatar,
  506 +// Accid: ucenterUser.Data.Accid,
  507 +// UserCenterId: ucenterUser.Data.Id,
  508 +// CsAccount: ucenterUser.Data.CustomerAccount,
  509 +// }
  510 +// _, err = models.AddUser(newUser, o)
  511 +// if err != nil {
  512 +// log.Error("添加用户数据失败:%s", err)
  513 +// return nil, err
  514 +// }
  515 +// } else {
  516 +// log.Error("查询用户数据失败:%s", err)
  517 +// return nil, err
  518 +// }
  519 +// return newUser, nil
  520 +// }
  521 +
  522 +// func initUserCompany(newcompany *models.Company, newuser *models.User, o orm.Ormer) (*models.UserCompany, error) {
  523 +// var (
  524 +// err error
  525 +// uc = &models.UserCompany{}
  526 +// )
  527 +// err = o.QueryTable(&models.UserCompany{}).
  528 +// Filter("user_id", newuser.Id).
  529 +// Filter("company_id", newcompany.Id).
  530 +// Filter("delete_at", 0).
  531 +// One(uc)
  532 +// if err == nil {
  533 +// _, err = o.QueryTable(&models.UserCompany{}).
  534 +// Filter("id", uc.Id).
  535 +// Update(orm.Params{
  536 +// "enable": models.USERCOMPANY_ENABLE_YES,
  537 +// })
  538 +// if err != nil {
  539 +// log.Error("更新user_company数据失败:%s", err)
  540 +// return nil, err
  541 +// }
  542 +// } else if err == orm.ErrNoRows {
  543 +// uc = &models.UserCompany{
  544 +// UserId: newuser.Id,
  545 +// CompanyId: newcompany.Id,
  546 +// OpenId: newuser.UserCenterId,
  547 +// Enable: models.USERCOMPANY_ENABLE_YES,
  548 +// ChargeStatus: models.USERCOMPANY_CHARGE_YES,
  549 +// }
  550 +// _, err = models.AddUserCompany(uc, o)
  551 +// if err != nil {
  552 +// log.Error("添加user_company数据失败:%s", err)
  553 +// return nil, err
  554 +// }
  555 +// } else {
  556 +// log.Error("获取user_company数据失败:%s", err)
  557 +// return nil, err
  558 +// }
  559 +// return uc, nil
  560 +// }
  561 +
  562 +// func initDepartment(newCompany *models.Company, newusercompany *models.UserCompany, o orm.Ormer) (*models.Department, error) {
  563 +// var (
  564 +// newDepartment = &models.Department{}
  565 +// err error
  566 +// )
  567 +// err = o.QueryTable(&models.Department{}).
  568 +// Filter("company_id", newCompany.Id).
  569 +// Filter("is_top", 1).
  570 +// One(newDepartment)
  571 +// if err == nil {
  572 +// newDepartment.Name = newCompany.Name
  573 +// err = models.UpdateDepartmentById(newDepartment, []string{"Name"}, o)
  574 +// if err != nil {
  575 +// log.Error("更新部门关系树数据失败:%s", err)
  576 +// return nil, err
  577 +// }
  578 +// return newDepartment, nil
  579 +// } else if err == orm.ErrNoRows {
  580 +// //添加部门
  581 +// newDepartment = &models.Department{
  582 +// CompanyId: newCompany.Id,
  583 +// Name: newCompany.Name,
  584 +// IsTop: 1,
  585 +// ParentId: 0,
  586 +// Relation: fmt.Sprint(utils.GenerateIDBySonyflake()),
  587 +// }
  588 +// newDepartment.SetManages([]int64{newusercompany.Id})
  589 +// _, err = models.AddDepartment(newDepartment, o)
  590 +// if err != nil {
  591 +// log.Error("添加部门数据失败:%s", err)
  592 +// return nil, err
  593 +// }
  594 +// newDepartment.SetRelation(nil)
  595 +// err = models.UpdateDepartmentById(newDepartment, []string{"Relation"}, o)
  596 +// if err != nil {
  597 +// log.Error("更新部门关系树数据失败:%s", err)
  598 +// return nil, err
  599 +// }
  600 +// } else {
  601 +// log.Error("查询部门数据失败:%s", err)
  602 +// return nil, err
  603 +// }
  604 +
  605 +// return newDepartment, nil
  606 +// }
  607 +
  608 +//initUserDedaprtmet 设置用户和部门关系
  609 +func initUserDedaprtmet(newDepartment *models.Department, newUserCompany *models.UserCompany, o orm.Ormer) (*models.UserDepartment, error) {
  610 + var (
  611 + newUserDepartment = &models.UserDepartment{}
  612 + err error
  613 + )
  614 + err = o.QueryTable(&models.UserDepartment{}).
  615 + Filter("department_id", newDepartment.Id).
  616 + Filter("user_company_id", newUserCompany.Id).
  617 + Filter("enable_status", models.USER_DEPARTMENT_ENABLE_YES).
  618 + One(newUserDepartment)
  619 + if err == nil {
  620 + return newUserDepartment, nil
  621 + } else if err == orm.ErrNoRows {
  622 + //添加部门
  623 + newUserDepartment = &models.UserDepartment{
  624 + UserCompanyId: newUserCompany.Id,
  625 + //UserId: newUserCompany.UserId,
  626 + CompanyId: newUserCompany.CompanyId,
  627 + DepartmentId: newDepartment.Id,
  628 + }
  629 + _, err = models.AddUserDepartment(newUserDepartment, o)
  630 + if err != nil {
  631 + log.Error("添加部门数据失败:%s", err)
  632 + return nil, err
  633 + }
  634 + } else {
  635 + log.Error("查询部门数据失败:%s", err)
  636 + return nil, err
  637 + }
  638 +
  639 + return newUserDepartment, nil
  640 +}
  641 +
  642 +//initRoleGroup 设置初始的角色组
  643 +func initRoleGroup(newCompany *models.Company, o orm.Ormer) (*models.Role, error) {
  644 + var (
  645 + newRoleGroup = &models.Role{}
  646 + err error
  647 + )
  648 + err = o.QueryTable(&models.Role{}).
  649 + Filter("delete_at", 0).
  650 + Filter("is_default", models.ROLE_DEFAULR).
  651 + Filter("types", models.ROLETYPES_GROUP).
  652 + Filter("company_id", newCompany.Id).
  653 + One(newRoleGroup)
  654 + if err == nil {
  655 + return newRoleGroup, nil
  656 + } else if err == orm.ErrNoRows {
  657 + //添加部角色组
  658 + newRoleGroup = &models.Role{
  659 + Types: models.ROLETYPES_GROUP,
  660 + CompanyId: newCompany.Id,
  661 + IsDefault: models.ROLE_DEFAULR,
  662 + Name: "管理员",
  663 + }
  664 + _, err = models.AddRole(newRoleGroup, o)
  665 + if err != nil {
  666 + log.Error("添加角色组数据失败:%s", err)
  667 + return nil, err
  668 + }
  669 + } else {
  670 + log.Error("查询角色组数据失败:%s", err)
  671 + return nil, err
  672 + }
  673 +
  674 + return newRoleGroup, nil
  675 +}
  676 +
  677 +//initRole 初始化公司的角色
  678 +func initRole(newCompany *models.Company, newRoleGroup *models.Role, o orm.Ormer) (*models.Role, error) {
  679 + var (
  680 + newRole = &models.Role{}
  681 + err error
  682 + )
  683 + err = o.QueryTable(&models.Role{}).
  684 + Filter("delete_at", 0).
  685 + Filter("is_default", models.ROLE_DEFAULR).
  686 + Filter("types", models.ROLETYPES_ROLE).
  687 + Filter("company_id", newCompany.Id).
  688 + One(newRole)
  689 + if err == nil {
  690 + return newRole, nil
  691 + } else if err == orm.ErrNoRows {
  692 + //添加部门
  693 + newRole = &models.Role{
  694 + Types: models.ROLETYPES_ROLE,
  695 + CompanyId: newCompany.Id,
  696 + IsDefault: models.ROLE_DEFAULR,
  697 + Name: "主管理员",
  698 + Pid: newRoleGroup.Id,
  699 + }
  700 + _, err = models.AddRole(newRole, o)
  701 + if err != nil {
  702 + log.Error("添加角色数据失败:%s", err)
  703 + return nil, err
  704 + }
  705 + } else {
  706 + log.Error("查询角色数据失败:%s", err)
  707 + return nil, err
  708 + }
  709 +
  710 + return newRole, nil
  711 +}
  712 +
  713 +//initUserRole 初始化第一个用户和角色的关系
  714 +func initUserRole(newUserCompany *models.UserCompany, newRole *models.Role, o orm.Ormer) (*models.UserRole, error) {
  715 + var (
  716 + newUserRole = &models.UserRole{}
  717 + err error
  718 + )
  719 + err = o.QueryTable(&models.UserRole{}).
  720 + Filter("enable_status", models.USER_ROLE_ENABLE_YES).
  721 + Filter("user_company_id", newUserCompany.Id).
  722 + Filter("role_id", newRole.Id).
  723 + One(newUserRole)
  724 + if err == nil {
  725 + return newUserRole, nil
  726 + } else if err == orm.ErrNoRows {
  727 + //添加UserRole
  728 + newUserRole = &models.UserRole{
  729 + RoleId: newRole.Id,
  730 + UserCompanyId: newUserCompany.Id,
  731 + CompanyId: newUserCompany.CompanyId,
  732 + }
  733 + _, err = models.AddUserRole(newUserRole, o)
  734 + if err != nil {
  735 + log.Error("添加user_role数据失败:%s", err)
  736 + return nil, err
  737 + }
  738 + } else {
  739 + log.Error("查询user_role数据失败:%s", err)
  740 + return nil, err
  741 + }
  742 +
  743 + return newUserRole, nil
  744 +}
  745 +
  746 +//iniSysConfig 初始化公司的系统配置
  747 +func iniSysConfig(companyid int, o orm.Ormer) error {
  748 + var (
  749 + m *models.SysConfig
  750 + err error
  751 + )
  752 + m, err = models.GetSysConfigByCompanyId(companyid, models.KeyScore)
  753 + if err == nil {
  754 + return nil
  755 + }
  756 + v := protocol.ScoreConfig{
  757 + DiscoveryScore: &protocol.DiscoveryScore{
  758 + BasicFactor: 1,
  759 + ExtraFactor: 1,
  760 + ValueFactor: 1,
  761 + },
  762 + SumScore: &protocol.SumScore{
  763 + DiscoveryFactor: 1,
  764 + CatchFactor: 1,
  765 + },
  766 + BasicScore: &protocol.ScoreRange{
  767 + Max: 10000,
  768 + Min: 0,
  769 + Step: 1,
  770 + },
  771 + ExtraScore: &protocol.ScoreRange{
  772 + Max: 10000,
  773 + Min: 0,
  774 + Step: 1,
  775 + },
  776 + ValueScore: &protocol.ScoreRange{
  777 + Max: 10000,
  778 + Min: 0,
  779 + Step: 1,
  780 + },
  781 + }
  782 + bt, _ := json.Marshal(v)
  783 + m = &models.SysConfig{
  784 + Key: models.KeyScore,
  785 + CompanyId: companyid,
  786 + CreateAt: time.Now(),
  787 + UpdateAt: time.Now(),
  788 + Content: string(bt),
  789 + }
  790 + _, err = models.AddSysConfig(m, o)
  791 + return err
  792 +}
  1 +package platform
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "errors"
  6 + "fmt"
  7 + "oppmg/common/log"
  8 + "oppmg/models"
  9 + "oppmg/utils"
  10 + "sort"
  11 + "strings"
  12 + "time"
  13 +
  14 + "github.com/astaxie/beego/orm"
  15 +)
  16 +
  17 +// ModuleDeparmentData 主管理平台发送过来的数据
  18 +type ModuleDeparmentData struct {
  19 + Id int64 `json:"id"` //id
  20 + Name string `json:"name"` //部门名称
  21 + ParentId int64 `json:"parent_id"` //父级id
  22 + CompanyId int64 `json:"company_id"`
  23 + Path string `json:"path"`
  24 + Level int `json:"level"`
  25 + Charge []int64 `json:"charge"` //部门主管
  26 +}
  27 +
  28 +type SortDepartmentByLevel []ModuleDeparmentData
  29 +
  30 +func (a SortDepartmentByLevel) Len() int { return len(a) }
  31 +func (a SortDepartmentByLevel) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  32 +func (a SortDepartmentByLevel) Less(i, j int) bool { return a[i].Level < a[j].Level }
  33 +
  34 +var _ PlatformAction = ModuleDeparmentData{}
  35 +
  36 +//DoAction PlatformAction 的接口实现
  37 +func (m ModuleDeparmentData) DoAction(code string, jsondata []byte) error {
  38 + switch code {
  39 + case "edit":
  40 + var (
  41 + data ModuleDeparmentData
  42 + err error
  43 + )
  44 + err = json.Unmarshal(jsondata, &data)
  45 + if err != nil {
  46 + return fmt.Errorf("数据解析失败:%s", err)
  47 + }
  48 + return UpdateDepartmentData(data)
  49 + case "add":
  50 + var (
  51 + data ModuleDeparmentData
  52 + err error
  53 + )
  54 + err = json.Unmarshal(jsondata, &data)
  55 + if err != nil {
  56 + return fmt.Errorf("数据解析失败:%s", err)
  57 + }
  58 + datas := []ModuleDeparmentData{data}
  59 + return AddDepartmentData(datas)
  60 + case "batchDelete":
  61 + var (
  62 + err error
  63 + )
  64 + ids := struct {
  65 + Ids []int64 `json:"ids"`
  66 + }{}
  67 + err = json.Unmarshal(jsondata, &ids)
  68 + if err != nil {
  69 + return fmt.Errorf("数据解析失败:%s", err)
  70 + }
  71 + if len(ids.Ids) == 0 {
  72 + return fmt.Errorf("参数错误")
  73 + }
  74 + return DeleteDepartmentData(ids.Ids)
  75 + case "import":
  76 + var (
  77 + data []ModuleDeparmentData
  78 + err error
  79 + )
  80 + err = json.Unmarshal(jsondata, &data)
  81 + if err != nil {
  82 + return fmt.Errorf("数据解析失败:%s", err)
  83 + }
  84 + return AddDepartmentData(data)
  85 + default:
  86 + return errors.New("action not found")
  87 + }
  88 + // return nil
  89 +}
  90 +
  91 +//同步 部门数据
  92 +//UpdateDepartmentData ....
  93 +func UpdateDepartmentData(data ModuleDeparmentData) error {
  94 + var (
  95 + departmentData *models.Department
  96 + err error
  97 + )
  98 +
  99 + departmentData, err = models.GetDepartmentById(data.Id)
  100 + if err == orm.ErrNoRows {
  101 + log.Error("编辑操作,未找到数据,执行添加操作")
  102 + return AddDepartmentData([]ModuleDeparmentData{data})
  103 + }
  104 + if err != nil {
  105 + e := fmt.Errorf("获取部门数据失败,err:%s", err)
  106 + log.Error(e.Error())
  107 + return errors.New("获取部门数据失败")
  108 + }
  109 + departmentData.Name = data.Name
  110 + o := orm.NewOrm()
  111 + o.Begin()
  112 + err = models.UpdateDepartmentById(departmentData, []string{"Name"}, o)
  113 + if err != nil {
  114 + o.Rollback()
  115 + e := fmt.Errorf("更新部门数据失败,err:%s", err)
  116 + log.Error(e.Error())
  117 + return errors.New("更新部门数据失败")
  118 + }
  119 + //更新部门管理员
  120 + err = models.ChangeDepartmentCharge(data.Id, departmentData.Id, data.Charge, o)
  121 + if err != nil {
  122 + o.Rollback()
  123 + log.Error("变更公司管理员失败,err:%s", err)
  124 + return errors.New("变更公司管理员失败")
  125 + }
  126 + o.Commit()
  127 + var (
  128 + newParentDepart *models.Department
  129 + )
  130 + if data.ParentId == 0 {
  131 + newParentDepart, err = models.GetTopDepartmentByCompany(departmentData.CompanyId)
  132 + if err != nil {
  133 + log.Error("获取公司一级部门数据失败:company_id=%d,err:%s", departmentData.CompanyId, err)
  134 + return errors.New("获取公司一级部门数据失败")
  135 + }
  136 + } else {
  137 + newParentDepart, err = models.GetDepartmentByBusinessId(data.ParentId)
  138 + if err != nil {
  139 + log.Error("获取父级数据失败,business_admin_id=%d,err:%s", data.ParentId, err)
  140 + }
  141 + }
  142 +
  143 + if departmentData.ParentId != newParentDepart.Id {
  144 + //更新父级
  145 + err = departmentRelationUpdate(*departmentData, *newParentDepart)
  146 + if err != nil {
  147 + return err
  148 + }
  149 + }
  150 +
  151 + return nil
  152 +}
  153 +
  154 +//positionRelationUpdate 处理职位上级发生变化的情况
  155 +func departmentRelationUpdate(departmentUpdate models.Department, newparent models.Department) error {
  156 + const (
  157 + //获取某个职位的下级职位 锁数据 select ... for update
  158 + dataSql0 string = `SELECT id,relation FROM department WHERE relation LIKE ? AND delete_at = 0 FOR UPDATE`
  159 + //更新关系树
  160 + //dataSql2 string = `update department set relation=? where id=?`
  161 + //更新departUpdate的parent_id
  162 + //dataSql3 string = `update department set parent_id=? where id=?`
  163 + )
  164 + var (
  165 + departmentSubset []*models.Department //子级部门
  166 + err error
  167 + oldRelation string = departmentUpdate.Relation
  168 + relationLike string = oldRelation + "%"
  169 + newRelation string
  170 + )
  171 + if newparent.Id == 0 {
  172 + //修改节点为顶层节点的情况
  173 + newRelation = fmt.Sprintf(",%d,", departmentUpdate.Id)
  174 + } else {
  175 + newRelation = fmt.Sprintf("%s%d,", newparent.Relation, departmentUpdate.Id)
  176 + }
  177 + o := orm.NewOrm()
  178 + o.Begin()
  179 + //获取部门及子级部门的relation和id
  180 + err = utils.ExecuteQueryAllWithOrmer(o, &departmentSubset, dataSql0, relationLike)
  181 + if err != nil {
  182 + e := fmt.Errorf("EXECUTE SQL err:%s", err)
  183 + log.Error(e.Error())
  184 + return errors.New("获取部门及子级部门失败")
  185 + }
  186 + for i := range departmentSubset {
  187 + if departmentSubset[i].Id == departmentUpdate.Id {
  188 + departmentSubset[i].ParentId = newparent.Id
  189 + }
  190 + //重建关系树
  191 + s := strings.TrimLeft(departmentSubset[i].Relation, oldRelation)
  192 + departmentSubset[i].Relation = fmt.Sprintf("%s%s", newRelation, s)
  193 + departmentSubset[i].Level = setDepartmentLevel(departmentSubset[i].Relation)
  194 + }
  195 +
  196 + //修改部门及子级部门的relation
  197 + for i := range departmentSubset {
  198 + err = models.UpdateDepartmentById(departmentSubset[i], []string{"ParentId", "Relation", "Level"}, o)
  199 + if err != nil {
  200 + log.Error("更新position发生错误,bussiness_admin_id=%d,id=%d,err:%s", departmentSubset[i].BusinessDepartmentId, departmentSubset[i].Id, err)
  201 + o.Rollback()
  202 + return fmt.Errorf("更新position发生错误,bussiness_admin_id=%d", departmentSubset[i].BusinessDepartmentId)
  203 + }
  204 + }
  205 + o.Commit()
  206 + return nil
  207 +}
  208 +
  209 +func setDepartmentLevel(relation string) int {
  210 + s := strings.Split(relation, ",")
  211 + return len(s) - 3
  212 +}
  213 +
  214 +//AddDepartmentData ...
  215 +func AddDepartmentData(data []ModuleDeparmentData) error {
  216 + if len(data) == 0 {
  217 + return nil
  218 + }
  219 + sort.Sort(SortDepartmentByLevel(data))
  220 + var (
  221 + err error
  222 + companyData *models.Company
  223 + topDepartment *models.Department
  224 + )
  225 + companyData, err = models.GetCompanyByUCenter(data[0].CompanyId)
  226 + if err != nil {
  227 + log.Error("获取公司数据失败,user_center_id=%d,err:%s", data[0].CompanyId, err)
  228 + return errors.New("获取公司数据失败")
  229 + }
  230 + topDepartment, err = models.GetTopDepartmentByCompany(companyData.Id)
  231 + if err != nil {
  232 + log.Error("获取公司一级部门数据失败;company_id=%d,err:%s", companyData.Id, err)
  233 + return errors.New("获取公司一级部门数据失败")
  234 + }
  235 + o := orm.NewOrm()
  236 + o.Begin()
  237 + for _, v := range data {
  238 + departmentData := &models.Department{
  239 + Id: v.Id,
  240 + CompanyId: companyData.Id,
  241 + Name: v.Name,
  242 + Manages: "[]",
  243 + BusinessDepartmentId: v.Id,
  244 + DeleteAt: time.Unix(0, 0),
  245 + CreateAt: time.Now(),
  246 + Level: v.Level,
  247 + }
  248 + if v.ParentId > 0 {
  249 + parentDepart := &models.Department{}
  250 + err = o.QueryTable(&models.Department{}).
  251 + Filter("business_department_id", v.ParentId).
  252 + Filter("delete_at", 0).
  253 + One(parentDepart)
  254 + if err != nil {
  255 + log.Error("获取父级职位数据失败,business_admin_id=%d,err:%s", v.ParentId, err)
  256 + return errors.New("获取父级职位数据失败")
  257 + }
  258 + departmentData.ParentId = parentDepart.Id
  259 + departmentData.SetRelation(parentDepart)
  260 + }
  261 + if v.ParentId == 0 {
  262 + departmentData.ParentId = topDepartment.Id
  263 + departmentData.SetRelation(topDepartment)
  264 + }
  265 +
  266 + // departmentData.Level = setDepartmentLevel(departmentData.Relation)
  267 + _, err = models.AddDepartment(departmentData, o)
  268 + if err != nil {
  269 + e := fmt.Errorf("存储部门数据失败,err:%s", err)
  270 + o.Rollback()
  271 + log.Error(e.Error())
  272 + return errors.New("存储部门数据失败")
  273 + }
  274 + }
  275 + o.Commit()
  276 + return nil
  277 +}
  278 +
  279 +//DeleteDepartmentData ...
  280 +func DeleteDepartmentData(ids []int64) error {
  281 + o := orm.NewOrm()
  282 + _, err := o.QueryTable(&models.Department{}).
  283 + Filter("business_department_id__in", ids).
  284 + Update(orm.Params{
  285 + "delete_at": time.Now().Format("2006-01-02 15:04:05"),
  286 + })
  287 + if err != nil {
  288 + log.Error("更新position数据失败,err:%s", err)
  289 + return errors.New("删除职位数据失败")
  290 + }
  291 + return nil
  292 +}