作者 yangfu

Merge remote-tracking branch 'origin/test'

FROM 192.168.0.243:5000/mmm/mmm-oppmg:20200110 as builder
FROM 192.168.0.243:5000/mmm/mmmopp:20200226 as builder
#FROM golang:1.13 as builder
ENV GOPROXY https://goproxy.cn
ENV GO111MODULE on
ENV GOPATH /go
RUN git clone http://gitlab.fjmaimaimai.com/mmm-go/gocomm.git /go/src/gocomm \
&& cd /go/src/gocomm \
#RUN git clone http://gitlab.fjmaimaimai.com/mmm-go/gocomm.git /go/src/gocomm \
RUN cd /go/src/gocomm \
&& git pull
WORKDIR /go/src/opp
... ...
[dev]
#数据库相关
mysql_user = "${MYSQL_USER||root}"
mysql_password = "${MYSQL_PASSWORD||sutianxia2015}"
mysql_host = "${MYSQL_HOST||115.29.205.99}"
mysql_password = "${MYSQL_PASSWORD||sutianxia2018}"
mysql_host = "${MYSQL_HOST||101.37.68.23}"
mysql_port = "${MYSQL_PORT||3306}"
mysql_db_name = "${MYSQL_DB_NAME||opportunity}"
mysql_db_name = "${MYSQL_DB_NAME||opportunity_dev}"
#日志
log_level = "${LOG_LEVEL||debug}"
... ...
... ... @@ -126,3 +126,8 @@ func Test_RedisLock(t *testing.T) {
//}()
//time.Sleep(11*time.Second)
}
func TestSlice(t *testing.T) {
var array = []int{1, 2, 3, 4, 5}
t.Log(array[0:4])
}
... ...
package v1
import (
"encoding/json"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/controllers"
"opp/protocol"
"opp/services/chance"
)
//成果
type AchievementController struct {
controllers.BaseController
}
//AchievementPool 成果池
// @router /achievementPool [post]
func (this *AchievementController) AchievementPool() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.AchievementPoolRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
request.IncludeSubDepartment = false
msg = protocol.NewReturnResponse(chance.AchievementPool(header, request))
}
//MyGrasp 我把握的
// @router /myGrasp [post]
func (this *AchievementController) MyGrasp() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.MyGraspRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(chance.MyGrasp(header, request))
}
//AchievementDetail 成果详情
// @router /achievementDetail [post]
func (this *AchievementController) AchievementDetail() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.AchievementDetailRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(chance.AchievementDetail(header, request))
}
//MyGraspStatistic 我把握的统计(按一级分类类型)
// @router /myGraspStatistic [post]
func (this *AchievementController) MyGraspStatistic() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.MyGraspStatisticRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(chance.MyGraspStatistic(header, request))
}
... ...
... ... @@ -611,6 +611,28 @@ func (this *ChanceController) ChancePool() {
msg = m
return
}
request.IncludeSubDepartment = false
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(chance.ChancePool(header, request))
}
//ChanceReviseDetail 机会补充详情
//@router /chanceReviseDetail [post]
func (this *ChanceController) ChanceReviseDetail() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.ChanceReviseDetailRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(chance.ChanceReviseDetail(header, request))
}
... ...
... ... @@ -33,3 +33,45 @@ func (this *DepartmentController) Departments() {
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(department.Departments(header, request))
}
//DepartmentStatistics 多部门统计
//@router /statistics [post]
func (this *DepartmentController) DepartmentStatistics() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.DepartmentStatisticsRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(department.Statistics(header, request))
}
//DepartmentStatistic 单部门统计
//@router /statistic [post]
func (this *DepartmentController) DepartmentStatistic() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.DepartmentStatisticRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(department.DepartmentStatistic(header, request))
}
... ...
... ... @@ -242,3 +242,24 @@ func (this *MessageController) MsgChanceThumbUp() {
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(message.MsgChanceThumbUp(header, request))
}
//MsgChanceRevise 消息中心-机会补充
//@router /msgChanceRevise [post]
func (this *MessageController) MsgChanceRevise() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.MsgChanceReviseRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(message.MsgChanceRevise(header, request))
}
... ...
package v1
import (
"encoding/json"
"opp/controllers"
"opp/protocol"
"opp/services/rank"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
)
type RankController struct {
controllers.BaseController
}
//GetRankList 排行榜
// @router /getRankList [post]
func (this *RankController) GetRankList() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetRankListRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(rank.GetRankList(header, request))
}
//GetRankType 获取榜单类型列表 (年榜/赛季榜)
// @router /getRankTypes [post]
func (this *RankController) GetRankType() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetRankTypeRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(rank.GetRankType(header, request))
}
//GetRankRange 获取榜单竞争范围列表
//@router /getRankRanges [post]
func (this *RankController) GetRankRange() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetRankRangeRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(rank.GetRankRange(header, request))
}
//GetRankPeriods 获取排行榜周期列表
//@router /getRankPeriods [post]
func (this *RankController) GetRankPeriods() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetRankPeriodsRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(rank.GetRankPeriods(header, request))
}
//ComputeRankScore 手动计算排行榜
//@router /computeRankScore [post]
func (this *RankController) ComputeRankScore() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.ComputeRankScoreRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(rank.ComputeRankScore(header, request))
}
//GetRankSortItems 获取排行榜评比项
//@router /getRankSortItems [post]
func (this *RankController) GetRankSortItems() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetRankSortItemsRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(rank.GetRankSortItems(header, request))
}
... ...
... ... @@ -6,6 +6,7 @@ require (
github.com/aliyun/alibaba-cloud-sdk-go v1.60.348
github.com/astaxie/beego v1.10.0
github.com/disintegration/imaging v1.6.2
github.com/gin-gonic/gin v1.4.0
github.com/go-sql-driver/mysql v1.4.1
github.com/gomodule/redigo v1.7.0
github.com/gorilla/websocket v1.4.1
... ...
... ... @@ -15,3 +15,9 @@ func Decimal(value float64) float64 {
value, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", value), 64)
return value
}
func DecimalToNumber(value float64) float64 {
value = decimal(value)
value, _ = strconv.ParseFloat(fmt.Sprintf("%.f", value), 64)
return value
}
... ...
... ... @@ -8,4 +8,10 @@ func TestDecimal(t *testing.T) {
t.Log(Decimal(1.7555555))
t.Log(Decimal(1.3555555))
t.Log(Decimal(1.3000001))
t.Log(DecimalToNumber(1.0))
t.Log(DecimalToNumber(1.4))
t.Log(DecimalToNumber(1.5))
t.Log(DecimalToNumber(1.6))
t.Log(DecimalToNumber(99.0))
}
... ...
package utils
import (
"bytes"
"errors"
"fmt"
"github.com/astaxie/beego/orm"
... ... @@ -130,7 +131,6 @@ func PrintLogSql(sql string, param ...interface{}) {
//ExecuteQueryOne 执行原生sql查询单条记录;结果用结构体接收
func ExecuteQueryOne(result interface{}, sqlstr string, param ...interface{}) error {
//PrintLogSql(sqlstr, param...)
var err error
o := orm.NewOrm()
err = ExecuteQueryOneWithOrmer(o, result, sqlstr, param)
... ... @@ -183,3 +183,62 @@ func ExecuteSQLWithOrmer(o orm.Ormer, sqlstr string, param ...interface{}) error
log.Debug(fmt.Sprintf("RowsAffected:%d", num))
return nil
}
type SqlExcutor struct {
table string
wherestr []string
orderstr []string
islimit bool
offset int
pagenum int
}
func NewSqlExutor() *SqlExcutor {
return &SqlExcutor{}
}
func (s *SqlExcutor) Table(str string) *SqlExcutor {
s.table = str
return s
}
func (s *SqlExcutor) Where(condition ...string) *SqlExcutor {
if len(condition) <= 0 {
return s
}
s.wherestr = append(s.wherestr, condition...)
return s
}
func (s *SqlExcutor) Order(condition ...string) *SqlExcutor {
if len(condition) <= 0 {
return s
}
s.orderstr = append(s.orderstr, condition...)
return s
}
func (s *SqlExcutor) Limit(page, pagenum int) *SqlExcutor {
offset := 0
if page > 0 {
offset = (page - 1) * pagenum
}
s.islimit = true
s.offset = offset
s.pagenum = pagenum
return s
}
func (s *SqlExcutor) WhereString() string {
sql := bytes.NewBufferString("")
if len(s.wherestr) > 0 {
sql.WriteString(" where ")
for i := range s.wherestr {
if i != 0 {
sql.WriteString(" AND ")
}
sql.WriteString(s.wherestr[i])
}
}
return sql.String()
}
... ...
... ... @@ -10,6 +10,7 @@ import (
"reflect"
"strconv"
"strings"
"time"
)
// 此函数将指定的结构体成员值更新到结构体中
... ... @@ -121,3 +122,32 @@ func ValidVersion(current, compare string) bool {
}
return false
}
// 统计某函数执行时间
// 使用方式
// defer utils.Profiling("test")()
func Profiling(msg string) func() {
start := time.Now()
return func() {
log.Info(fmt.Sprintf("%s[%s]:%s", msg, "use", time.Since(start)))
}
}
//合并字典
func MergeMap(to map[string]interface{}, from map[string]interface{}) {
for k, v := range from {
to[k] = v
}
}
func GetPageInfo(pageIndex, pageSize int) (offset, size int) {
if pageSize == 0 {
pageSize = 20
}
if pageIndex == 0 {
pageIndex = 1
}
offset = (pageIndex - 1) * pageSize
size = pageSize
return
}
... ...
package utils
import (
"encoding/json"
"fmt"
"testing"
)
... ... @@ -50,3 +51,23 @@ func TestValidVersion(t *testing.T) {
}
}
}
func TestMergeMap(t *testing.T) {
to := map[string]interface{}{"1": 1, "2": 2}
from := map[string]interface{}{"3": 3, "4": 4}
t.Log("merge 前:", to)
MergeMap(to, from)
t.Log("merge 后:", to)
}
func TestIntUnmarsh(t *testing.T) {
jsonString := `{"id":8242051651122944}`
type param struct {
Id int `json:"id"`
}
var p param
json.Unmarshal([]byte(jsonString), &p)
t.Log(p)
jsonByte, _ := json.Marshal(p)
t.Log(string(jsonByte))
}
... ...
... ... @@ -13,6 +13,7 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/websocket"
"opp/internal/utils"
_ "opp/routers"
"opp/services/contrab"
"os"
"strings"
"time"
... ... @@ -91,6 +92,8 @@ func main() {
//beego.BConfig.Listen.HTTPSPort = 8089
//beego.BConfig.Listen.HTTPSCertFile = "conf/server.crt"
//beego.BConfig.Listen.HTTPSKeyFile = "conf/server.key"
contrab.Run()
beego.Run()
}
... ...
package models
import (
"fmt"
"opp/internal/utils"
"time"
"github.com/astaxie/beego/orm"
)
type Achievement struct {
Id int64 `orm:"column(id);pk" description:"id 主键"`
CompanyId int64 `orm:"column(company_id);null" description:"公司编号 表company.id"`
UserCompanyId int64 `orm:"column(user_company_id)" description:"把握人 表user_company.id id"`
ChanceTypeId int `orm:"column(chance_type_id);null" description:"表chance_type.id 机会类型 "`
AuditTemplateId int `orm:"column(audit_template_id);null" description:"表audit_template.id 所属审批模板编号"`
SourceContent string `orm:"column(source_content);null" description:"成果详情文本"`
GraspScore float64 `orm:"column(grasp_score);digits(4);decimals(1)" description:"把握分"`
UserGraspScore float64 `orm:"column(user_grasp_score);digits(4);decimals(1)" description:"把握人得分"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
ViewTotal int `orm:"column(view_total);null" description:"查看总数"`
CommentTotal int `orm:"column(comment_total);null" description:"评论总数"`
ZanTotal int `orm:"column(zan_total);null" description:"点赞总数"`
Status int8 `orm:"column(status);null" description:"机会状态 1:开启 2:关闭 0:删除"`
}
func (t *Achievement) TableName() string {
return "achievement"
}
func init() {
orm.RegisterModel(new(Achievement))
}
// GetAchievementById retrieves Achievement by Id. Returns error if
// Id doesn't exist
func GetAchievementById(id int64) (v *Achievement, err error) {
o := orm.NewOrm()
v = &Achievement{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateAchievement updates Achievement by Id and returns error if
// the record to be updated doesn't exist
func UpdateAchievementById(m *Achievement) (err error) {
o := orm.NewOrm()
v := Achievement{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
//成果列表
//@uid 成果把握人
//@cid 公司编号
//@lastId 最后编号
//@chanceTypeId 机会一级分类编号
//@departmentId 部门编号
func GetAchievementAll(uid, cid int64, chanceTypeId int, lastId int64, departmentId []int, pageSize int, v interface{}) (total int, err error) {
var filter = utils.NewSqlExutor()
filter.Where(fmt.Sprintf("company_id=%v", cid))
filter.Where("status=1")
if lastId > 0 {
filter.Where(fmt.Sprintf("id<%v", lastId))
}
if chanceTypeId > 0 {
filter.Where(fmt.Sprintf("chance_type_id =%v", chanceTypeId))
}
if len(departmentId) > 0 {
filter.Where(fmt.Sprintf("department_id in (%v)", utils.JoinInts(departmentId, ",")))
}
if uid > 0 {
filter.Where(fmt.Sprintf("user_company_id =%v", uid))
}
sql := fmt.Sprintf(`
select id,user_company_id,create_at,source_content,audit_template_id,chance_type_id,grasp_score,user_grasp_score,comment_total,zan_total,view_total,images from achievement
%v
order by create_at desc
limit %v
`, filter.WhereString(), pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from achievement
%v
`, filter.WhereString())
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
if v != nil {
if err = utils.ExecuteQueryAll(v, sql); err != nil {
return
}
}
return
}
//成果详情
func GetCommAchievementItemOrmId(id int64, v interface{}) (err error) {
o := orm.NewOrm()
sql := "select * from achievement where id=?"
if _, err = o.Raw(sql, id).QueryRows(v); err == nil {
return nil
}
return err
}
//获取成果统计
func GetAchievementStatisticByChanceType(uid int64, v interface{}) (err error) {
o := orm.NewOrm()
sql := `select a.*,b.name from (
select chance_type_id,count(0) total from achievement where user_company_id =?
group by chance_type_id
)a inner join chance_type b on a.chance_type_id = b.id
order by sort_num`
if _, err = o.Raw(sql, uid).QueryRows(v); err == nil {
return nil
}
return err
}
... ...
package models
import (
"time"
"github.com/astaxie/beego/orm"
)
type AchievementChance struct {
Id int64 `orm:"column(id);pk"`
AchievementId int64 `orm:"column(achievement_id);null" description:"成果编号 表achievement.id"`
ChanceId int64 `orm:"column(chance_id);null" description:"机会编号 表chance.id"`
ChanceCode string `orm:"column(chance_code);size(255);null" description:"机会编号 表chance.code"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
}
func (t *AchievementChance) TableName() string {
return "achievement_chance"
}
func init() {
orm.RegisterModel(new(AchievementChance))
}
// GetAchievementChanceById retrieves AchievementChance by Id. Returns error if
// Id doesn't exist
func GetAchievementChanceById(id int64) (v *AchievementChance, err error) {
o := orm.NewOrm()
v = &AchievementChance{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
//查询成果提供者列表
func GetAchievementChances(achievementId int64, v interface{}) (err error) {
o := orm.NewOrm()
sql := `select a.*,b.images,speechs,videos
from (
select chance_id,b.user_id chance_user_id,approve_time create_at,source_content,enable_status,review_status,audit_template_id,chance_type_id,comment_total,zan_total,view_total,publish_status,status
from achievement_chance a inner join chance b on a.chance_id=b.id where achievement_id=? and b.review_status=3
) a left JOIN chance_data b on a.chance_id =b.chance_id
order by a.create_at desc
`
if _, err = o.Raw(sql, achievementId).QueryRows(v); err == nil {
return nil
}
return err
}
... ...
package models
import (
"time"
"github.com/astaxie/beego/orm"
)
type AchievementProvider struct {
Id int64 `orm:"column(id);pk" description:"主键id"`
AchievementId int64 `orm:"column(achievement_id);null" description:"表achievement.id"`
UserCompanyId int64 `orm:"column(user_company_id);null" description:"user_company.id"`
UserGraspScore float64 `orm:"column(user_grasp_score);null;digits(4);decimals(1)" description:"把握人得分"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
}
func (t *AchievementProvider) TableName() string {
return "achievement_provider"
}
func init() {
orm.RegisterModel(new(AchievementProvider))
}
// GetAchievementProviderById retrieves AchievementProvider by Id. Returns error if
// Id doesn't exist
func GetAchievementProviderById(id int64) (v *AchievementProvider, err error) {
o := orm.NewOrm()
v = &AchievementProvider{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
//查询成果提供者列表
func GetAchievementProviders(achievementId int64) (v []*AchievementProvider, err error) {
o := orm.NewOrm()
sql := "select * from achievement_provider where achievement_id=?"
if _, err = o.Raw(sql, achievementId).QueryRows(&v); err == nil {
return v, nil
}
return nil, err
}
... ...
... ... @@ -264,23 +264,23 @@ where user_id =?`
}
//type4 查看所有机会
func GetChancePoolAll(uid, cid int64, chanceTypeId int, lastId int64, pageSize int, v interface{}) (total int, err error) {
sql := `select a.*,b.images,speechs,videos
func GetChancePoolAll(uid, cid int64, chanceTypeId int, dIds []int, lastId int64, pageSize int, v interface{}) (total int, err error) {
var filterDepartment string = getFilterSqlByDIds(dIds)
sql := fmt.Sprintf(`select a.*,b.images,speechs,videos
from (
select id,user_id,approve_time create_at,source_content,review_status,audit_template_id,chance_type_id,comment_total,zan_total,view_total from chance
where company_id=? and review_status=3 and (?=0 or chance_type_id =?) and (?=0 or unix_timestamp(approve_time)<?) and enable_status=1 and status=1
where company_id=? and review_status=3 and (?=0 or chance_type_id =?) and (?=0 or unix_timestamp(approve_time)<?) and enable_status=1 and status=1 %v
) a left JOIN chance_data b on a.id =b.chance_id
order by create_at desc
limit ?
`
`, filterDepartment)
//if public==protocol.pu
sqlCount := fmt.Sprintf(`select count(0) from (
select id from chance
where company_id=? and review_status=3 and (%v=0 or chance_type_id =%v) and enable_status=1 and status=1
) a left JOIN chance_data b on a.id =b.chance_id`, chanceTypeId, chanceTypeId)
where company_id=? and review_status=3 and (%v=0 or chance_type_id =%v) and enable_status=1 and status=1 %v
) a left JOIN chance_data b on a.id =b.chance_id`, chanceTypeId, chanceTypeId, filterDepartment)
if err = utils.ExecuteQueryOne(&total, sqlCount, cid); err != nil {
return
}
... ... @@ -293,8 +293,8 @@ where company_id=? and review_status=3 and (%v=0 or chance_type_id =%v) and ena
}
//type3 特定部门机会
func GetChancePoolSpecialDepartment(uid, cid int64, chanceTypeId int, lastId int64, pageSize int, v interface{}, departmentIds []int64) (total int, err error) {
func GetChancePoolSpecialDepartment(uid, cid int64, chanceTypeId int, dIds []int, lastId int64, pageSize int, v interface{}, departmentIds []int64) (total int, err error) {
var filterDepartment string = getFilterSqlByDIds(dIds)
sql := fmt.Sprintf(`
select a.*,b.images,speechs,videos from (
select * from (
... ... @@ -318,11 +318,11 @@ select * from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1 %v
) a left JOIN chance_data b on a.id =b.chance_id
order by create_at desc
limit %v
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, pageSize)
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, filterDepartment, pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from (
... ... @@ -346,8 +346,8 @@ select count(0) from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId)
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1 %v
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, filterDepartment)
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
... ... @@ -360,8 +360,8 @@ select count(0) from (
}
//type32 特定部门机会 - 多角色时包含levl2 部门公开
func GetChancePoolDepartment(uid, cid int64, chanceTypeId int, lastId int64, pageSize int, v interface{}, departmentIds []int64, userDepartmetIds []int64) (total int, err error) {
func GetChancePoolDepartment(uid, cid int64, chanceTypeId int, dIds []int, lastId int64, pageSize int, v interface{}, departmentIds []int64, userDepartmetIds []int64) (total int, err error) {
var filterDepartment string = getFilterSqlByDIds(dIds)
sql := fmt.Sprintf(`
select a.*,b.images,speechs,videos from (
select * from (
... ... @@ -393,11 +393,11 @@ select * from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1 %v
) a left JOIN chance_data b on a.id =b.chance_id
order by create_at desc
limit %v
`, utils.JoinInt64s(userDepartmetIds, ","), cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, pageSize)
`, utils.JoinInt64s(userDepartmetIds, ","), cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, filterDepartment, pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from (
... ... @@ -429,8 +429,8 @@ select count(0) from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1
`, utils.JoinInt64s(userDepartmetIds, ","), cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId)
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1 %v
`, utils.JoinInt64s(userDepartmetIds, ","), cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, filterDepartment)
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
... ... @@ -443,7 +443,8 @@ select count(0) from (
}
//type2 对我所在部门公开的机会 公司公开的机会
func GetChancePoolPublicCompany(uid, cid int64, chanceTypeId int, lastId int64, pageSize int, v interface{}, departmentIds []int64) (total int, err error) {
func GetChancePoolPublicCompany(uid, cid int64, chanceTypeId int, dIds []int, lastId int64, pageSize int, v interface{}, departmentIds []int64) (total int, err error) {
var filterDepartment string = getFilterSqlByDIds(dIds)
sql := fmt.Sprintf(`
select a.*,b.images,speechs,videos from (
select * from (
... ... @@ -470,11 +471,11 @@ select * from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1 %v
) a left JOIN chance_data b on a.id =b.chance_id
order by create_at desc
limit %v
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, pageSize)
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, filterDepartment, pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from (
... ... @@ -501,8 +502,8 @@ select count(0) from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId)
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1 %v
`, cid, utils.JoinInt64s(departmentIds, ","), uid, uid, chanceTypeId, chanceTypeId, filterDepartment)
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
... ... @@ -513,9 +514,16 @@ select count(0) from (
}
return
}
func getFilterSqlByDIds(dIds []int) string {
if len(dIds) == 0 {
return ""
}
return fmt.Sprintf(" and department_id in(%v) ", utils.JoinInts(dIds, ","))
}
//type1 禁止查看所有机会
func GetChancePoolMyself(uid, cid int64, chanceTypeId int, lastId int64, pageSize int, v interface{}) (total int, err error) {
func GetChancePoolMyself(uid, cid int64, chanceTypeId int, dIds []int, lastId int64, pageSize int, v interface{}) (total int, err error) {
var filterDepartment string = getFilterSqlByDIds(dIds)
sql := fmt.Sprintf(`
select a.*,b.images,speechs,videos from (
select * from (
... ... @@ -529,11 +537,11 @@ select * from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1
) a where review_status=3 and (0=%v or chance_type_id =%v) and (0=%v or unix_timestamp(create_at)<%v) and a.enable_status=1 and status=1 %v
) a left JOIN chance_data b on a.id =b.chance_id
order by create_at desc
limit %v
`, uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, pageSize)
`, uid, uid, chanceTypeId, chanceTypeId, lastId, lastId, filterDepartment, pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from (
... ... @@ -547,8 +555,8 @@ select count(0) from (
select DISTINCT chance_id from audit_flow_process where uid =%v
) a inner join chance b on a.chance_id = b.id
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1
`, uid, uid, chanceTypeId, chanceTypeId)
) a where review_status=3 and (0=%v or chance_type_id =%v) and a.enable_status=1 and status=1 %v
`, uid, uid, chanceTypeId, chanceTypeId, filterDepartment)
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
... ... @@ -648,3 +656,19 @@ func ExitsChanceByAuditUser(chanceId int64, auditUserId int64) (v *Chance, err e
}
return
}
//机会统计-按部门
//@departmentIds 按部门编号查询
func GetChanceStatisticByDepartment(companyId int64, departmentIds []int, reviewStatus int) (v int, err error) {
sql := fmt.Sprintf(`select count(0) from chance where company_id=%v
and review_status=%v
and status=1
and enable_status=1
and department_id in (%v)`,
companyId, reviewStatus, utils.JoinInts(departmentIds, ","))
o := orm.NewOrm()
if err = o.Raw(sql).QueryRow(&v); err != nil {
return
}
return
}
... ...
package models
import (
"time"
"github.com/astaxie/beego/orm"
)
type ChanceReviseLog struct {
Id int64 `orm:"column(id);pk" description:"id 主键"`
ChanceId int64 `orm:"column(chance_id)" description:"机会编号"`
UserCompanyId int64 `orm:"column(user_company_id);null" description:"用户编号 编辑机会的人"`
Data string `orm:"column(data);null" description:"机会数据"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
AuditFlowLogId int64 `orm:"column(audit_flow_log_id)" description:"审核流日志表"`
}
func (t *ChanceReviseLog) TableName() string {
return "chance_revise_log"
}
func init() {
orm.RegisterModel(new(ChanceReviseLog))
}
// AddChanceReviseLog insert a new ChanceReviseLog into database and returns
// last inserted Id on success.
func AddChanceReviseLog(m *ChanceReviseLog) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetChanceReviseLogById retrieves ChanceReviseLog by Id. Returns error if
// Id doesn't exist
func GetChanceReviseLogById(id int64) (v *ChanceReviseLog, err error) {
o := orm.NewOrm()
v = &ChanceReviseLog{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
... ...
... ... @@ -16,6 +16,7 @@ type Company struct {
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
UserCenterId int64 `orm:"column(user_center_id)" description:"统一用户中心企业id"`
Enable int8 `orm:"column(enable)" description:"是否有效【1:有效】【2:无效】"`
}
func (t *Company) TableName() string {
... ...
... ... @@ -8,11 +8,11 @@ import (
)
type Department struct {
Id int `orm:"column(id);auto"`
CompanyId int `orm:"column(company_id)" description:"公司id"`
Id int64 `orm:"column(id);auto"`
CompanyId int64 `orm:"column(company_id)" description:"公司id"`
Name string `orm:"column(name);size(30)" description:"部门名称"`
CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
ParentId int `orm:"column(parent_id)" description:"父级id"`
ParentId int64 `orm:"column(parent_id)" description:"父级id"`
Relation string `orm:"column(relation);size(400)" description:"父子级关系树"`
DeleteAt time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
... ... @@ -37,7 +37,7 @@ func AddDepartment(m *Department) (id int64, err error) {
// GetDepartmentById retrieves Department by Id. Returns error if
// Id doesn't exist
func GetDepartmentById(id int) (v *Department, err error) {
func GetDepartmentById(id int64) (v *Department, err error) {
o := orm.NewOrm()
v = &Department{Id: id}
if err = o.Read(v); err == nil {
... ... @@ -63,7 +63,7 @@ func UpdateDepartmentById(m *Department) (err error) {
// DeleteDepartment deletes Department by Id and returns error if
// the record to be deleted doesn't exist
func DeleteDepartment(id int) (err error) {
func DeleteDepartment(id int64) (err error) {
o := orm.NewOrm()
v := Department{Id: id}
// ascertain id exists in the database
... ... @@ -90,3 +90,45 @@ order by parent_id,id`
}
return
}
func GetSubDepartmentIds(companyId int64, relation string) (v []int, err error) {
o := orm.NewOrm()
sql := fmt.Sprintf(`
select id from department where company_id=? and relation like '%v%%' and delete_at =0`, relation)
if _, err = o.Raw(sql, companyId).QueryRows(&v); err == nil {
return
}
return
}
func GetDepartmentIdsByCompanyId(companyId int) (v []int64, err error) {
o := orm.NewOrm()
sql := `
select id
from department
where company_id =? and delete_at =0
order by parent_id,id`
if _, err = o.Raw(sql, companyId).QueryRows(&v); err == nil {
return
}
return
}
//获取用户所有部门
func GetDepartmentByUser(uid int64) (v []*Department, err error) {
o := orm.NewOrm()
sql := `
select id from (
select department_id from user_department where user_company_id=? and enable_status = 1
)a inner join department b on a.department_id = b.id
where b.delete_at =0
order by parent_id,id`
if _, err = o.Raw(sql, uid).QueryRows(&v); err == nil {
if err == orm.ErrNoRows {
err = nil
return
}
return
}
return
}
... ...
package models
import (
"fmt"
"opp/internal/utils"
"time"
"github.com/astaxie/beego/orm"
)
type Rank struct {
Id int64 `orm:"column(id);auto"`
CompanyId int `orm:"column(company_id)" description:"公司编号 表company.id"`
RankTypeId int `orm:"column(rank_type_id)" description:"榜单类型编号"`
RankRangeId int `orm:"column(rank_range_id)" description:"榜单范围编号"`
RankPeriodId int `orm:"column(rank_period_id)" description:"赛季周期编号"`
RelationId int64 `orm:"column(relation_id)" description:"用户编号/部门编号"`
TotalScore float64 `orm:"column(total_score);null;digits(4);decimals(1)" description:"总分"`
DiscoveryScore float64 `orm:"column(discovery_score);null;digits(4);decimals(1)" description:"发现得分"`
GraspScore float64 `orm:"column(grasp_score);null;digits(4);decimals(1)" description:"把握分"`
DiscoveryTotal int `orm:"column(discovery_total);null" description:"发现数量"`
CommentTotal int `orm:"column(comment_total);null" description:"评论数量"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
EnableStatus int8 `orm:"column(enable_status);null" description:"有效状态 0:无效 1:有效 "`
Type int8 `orm:"column(type);null" description:"1:所有员工 2:指定员工 3:所有部门 4:指定部门"`
}
func (t *Rank) TableName() string {
return "rank"
}
func init() {
orm.RegisterModel(new(Rank))
}
// AddRank insert a new Rank into database and returns
// last inserted Id on success.
func AddRank(m *Rank) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetRankById retrieves Rank by Id. Returns error if
// Id doesn't exist
func GetRankById(id int64) (v *Rank, err error) {
o := orm.NewOrm()
v = &Rank{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRank updates Rank by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankById(m *Rank) (err error) {
o := orm.NewOrm()
v := Rank{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
//取用户当前榜单数据
func GetRank(companyId, rankTypeId, rankRangeId, rankPeriodId int, relationId int64) (v *Rank, err error) {
o := orm.NewOrm()
sql := "select * from rank where company_id=? and rank_type_id=? and rank_range_id=? and rank_period_id=? and relation_id=?"
if err = o.Raw(sql, companyId, rankTypeId, rankRangeId, rankPeriodId, relationId).QueryRow(&v); err == nil {
return v, nil
}
return nil, err
}
//排行列表-用户
func GetRanksByUser(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, pageIndex, pageSize int, v interface{}) (total int, err error) {
//var filterDepartment string = getFilterSqlByDIds(dIds)
pageIndex, pageSize = utils.GetPageInfo(pageIndex, pageSize)
sql := fmt.Sprintf(`select (@rowno:=@rowno+1) as ranking,a.*,b.nick_name name from
(
select score,relation_id,user_id from(
select a.%v score,a.relation_id,user_id from rank a inner join user_company c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
) a,(select @rowno:=%v) b
limit %v,%v
)a inner join user b on a.user_id = b.id
`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, pageIndex, pageIndex, pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from rank
where company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v
`, companyId, rankTypeId, rankRangeId, rankPeriodId)
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
if v != nil {
if err = utils.ExecuteQueryAll(v, sql); err != nil {
return
}
}
return
}
//排行榜列表-用户-自己的排名
func GetRanksByUserSelf(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, relationId int64, v interface{}) (err error) {
//var filterDepartment string = getFilterSqlByDIds(dIds)
sql := fmt.Sprintf(`
select a.*,b.nick_name name from
(
select score,relation_id,user_id,(@rowno:=@rowno+1) as ranking from(
select a.%v score,a.relation_id,user_id from rank a inner join user_company c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
) a,(select @rowno:=0 ) b
)a inner join user b on a.user_id = b.id
where relation_id=%v
`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, relationId)
if v != nil {
if err = utils.ExecuteQueryOne(v, sql); err != nil {
if err == orm.ErrNoRows {
err = nil
}
return
}
}
return
}
//排行榜列表-部门
func GetRanksByDepartment(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, pageIndex, pageSize int, v interface{}) (total int, err error) {
//var filterDepartment string = getFilterSqlByDIds(dIds)
pageIndex, pageSize = utils.GetPageInfo(pageIndex, pageSize)
sql := fmt.Sprintf(`
select a.*,(@rowno:=@rowno+1) as ranking from
(
select a.%v score,a.relation_id,c.name
from rank a inner join department c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
)a,(select (@rowno:=%v)) b
limit %v,%v
`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, pageIndex, pageIndex, pageSize)
sqlCount := fmt.Sprintf(`
select count(0) from rank
where company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v
`, companyId, rankTypeId, rankRangeId, rankPeriodId)
if err = utils.ExecuteQueryOne(&total, sqlCount); err != nil {
return
}
if v != nil {
if err = utils.ExecuteQueryAll(v, sql); err != nil {
if err == orm.ErrNoRows {
err = nil
}
return
}
}
return
}
//排行榜列表-部门-用户所属部门排名
func GetRanksByDepartmentSelf(companyId int64, rankTypeId, rankRangeId, rankPeriodId int, key string, relationId int64, v interface{}) (err error) {
sql := fmt.Sprintf(`select * from (
select a.*,(@rowno:=@rowno+1) as ranking from (
select a.%v score,a.relation_id,c.name from rank a inner join department c on a.relation_id=c.id
where a.company_id=%v and rank_type_id=%v and rank_range_id=%v and rank_period_id=%v and a.enable_status=1
order by a.%v desc,c.create_at asc
) a,(select (@rowno:=0)) b
)a
where a.relation_id=%v
`, key, companyId, rankTypeId, rankRangeId, rankPeriodId, key, relationId)
if v != nil {
if err = utils.ExecuteQueryOne(v, sql); err != nil {
if err == orm.ErrNoRows {
err = nil
}
return
}
}
return
}
... ...
package models
import (
"fmt"
"time"
"github.com/astaxie/beego/orm"
)
type RankItem struct {
Id int `orm:"column(id);auto"`
CompanyId int `orm:"column(company_id);null" description:"公司编号 company.id"`
RankTypeId int `orm:"column(rank_type_id)" description:"表rank_type.id 榜单类型编号"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
SortNum int `orm:"column(sort_num);null" description:"序号"`
ItemName string `orm:"column(item_name);size(50);null" description:"评比项名称"`
ItemKey string `orm:"column(item_key);size(50);null" description:"评比项键值(排行榜排序使用)"`
}
func (t *RankItem) TableName() string {
return "rank_item"
}
func init() {
orm.RegisterModel(new(RankItem))
}
// AddRankItem insert a new RankItem into database and returns
// last inserted Id on success.
func AddRankItem(m *RankItem) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetRankItemById retrieves RankItem by Id. Returns error if
// Id doesn't exist
func GetRankItemById(id int) (v *RankItem, err error) {
o := orm.NewOrm()
v = &RankItem{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRankItem updates RankItem by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankItemById(m *RankItem) (err error) {
o := orm.NewOrm()
v := RankItem{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteRankItem deletes RankItem by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankItem(id int) (err error) {
o := orm.NewOrm()
v := RankItem{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&RankItem{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
func GetRankItemKeys(companyId int64, rankTypeId int) (v []string, name []string, err error) {
sql := "select item_key,item_name from rank_item where company_id=? and rank_type_id=? order by sort_num"
o := orm.NewOrm()
if _, err = o.Raw(sql, companyId, rankTypeId).QueryRows(&v, &name); err != nil {
return
}
return
}
func GetRankItems(companyId int64, rankTypeId int, v interface{}) (err error) {
sql := "select item_key,item_name from rank_item where company_id=? and rank_type_id=? order by sort_num"
o := orm.NewOrm()
if _, err = o.Raw(sql, companyId, rankTypeId).QueryRows(v); err != nil {
return
}
return
}
... ...
package models
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
"opp/internal/utils"
"time"
"github.com/astaxie/beego/orm"
)
type RankPeriod struct {
Id int `orm:"column(id);auto" description:"主键"`
CompanyId int `orm:"column(company_id);null" description:"公司编号 表company.id"`
RankTypeId int `orm:"column(rank_type_id)" description:"表rank_type.id 榜单类型编号"`
SeasonName string `orm:"column(season_name);size(50);null" description:"赛季名称"`
BeginTime time.Time `orm:"column(begin_time);type(timestamp);null" description:"开始时间"`
EndTime time.Time `orm:"column(end_time);type(timestamp);null" description:"结束时间"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
Status int8 `orm:"column(status);null" description:"状态 0:未开始 1:开始 2:结束 "`
RankRangeBack string `orm:"column(rank_range_back);null" description:"赛季结束时,备份赛季参与人设置"`
RankItemBack string `orm:"column(rank_item_back);null" description:"赛季结束时,备份赛季评比项设置"`
}
func (t *RankPeriod) TableName() string {
return "rank_period"
}
func init() {
orm.RegisterModel(new(RankPeriod))
}
// AddRankPeriod insert a new RankPeriod into database and returns
// last inserted Id on success.
func AddRankPeriod(m *RankPeriod) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetRankPeriodById retrieves RankPeriod by Id. Returns error if
// Id doesn't exist
func GetRankPeriodById(id int) (v *RankPeriod, err error) {
o := orm.NewOrm()
v = &RankPeriod{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRankPeriod updates RankPeriod by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankPeriodById(m *RankPeriod) (err error) {
o := orm.NewOrm()
v := RankPeriod{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteRankPeriod deletes RankPeriod by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankPeriod(id int) (err error) {
o := orm.NewOrm()
v := RankPeriod{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&RankPeriod{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
//获取进行中的赛季周期 状态 0:未开始 1:开始 2:结束
func GetRankPeriods(companyId int, rankTypeId int, status []int) (v []*RankPeriod, err error) {
sql := mybeego.NewSqlExutor()
sql.Table((&RankPeriod{}).TableName())
if companyId > 0 {
sql.Where(fmt.Sprintf("company_id=%v", companyId))
}
if rankTypeId > 0 {
sql.Where(fmt.Sprintf("rank_type_id=%v", rankTypeId))
}
if len(status) > 0 {
sql.Where(fmt.Sprintf("status in (%v)", utils.JoinInts(status, ",")))
}
sql.Order("end_time desc")
_, err = sql.Querys(&v)
return
}
... ...
package models
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
"time"
"github.com/astaxie/beego/orm"
)
type RankRange struct {
Id int `orm:"column(id);auto"`
CompanyId int `orm:"column(company_id);null" description:"公司编号 表company.id"`
RankTypeId int `orm:"column(rank_type_id)" description:"表rank_type.id 榜单类型编号"`
Name string `orm:"column(name);size(50);null" description:"名称"`
Type int8 `orm:"column(type);null" description:"1:所有员工 2:指定员工 3:所有部门 4:指定部门"`
SortNum int `orm:"column(sort_num);null" description:"序号"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间"`
Status int8 `orm:"column(status);null" description:"【0:显示】【1:隐藏】"`
Data string `orm:"column(data);null"`
}
func (t *RankRange) TableName() string {
return "rank_range"
}
func init() {
orm.RegisterModel(new(RankRange))
}
// AddRankRange insert a new RankRange into database and returns
// last inserted Id on success.
func AddRankRange(m *RankRange) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetRankRangeById retrieves RankRange by Id. Returns error if
// Id doesn't exist
func GetRankRangeById(id int) (v *RankRange, err error) {
o := orm.NewOrm()
v = &RankRange{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRankRange updates RankRange by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankRangeById(m *RankRange) (err error) {
o := orm.NewOrm()
v := RankRange{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteRankRange deletes RankRange by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankRange(id int) (err error) {
o := orm.NewOrm()
v := RankRange{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&RankRange{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
//获取榜单范围数据
func GetRankRanges(companyId int, rankTypeId int) (v []*RankRange, err error) {
sql := mybeego.NewSqlExutor()
sql.Table((&RankRange{}).TableName())
if companyId > 0 {
sql.Where(fmt.Sprintf("company_id=%v", companyId))
}
//if rankTypeId > 0 {
sql.Where(fmt.Sprintf("rank_type_id=%v", rankTypeId))
//}
sql.Order("sort_num")
_, err = sql.Querys(&v)
return
}
... ...
package models
import (
"fmt"
"github.com/astaxie/beego/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
type RankRangeData struct {
Id int `orm:"column(id);auto"`
RankRangeId int `orm:"column(rank_range_id);null"`
RangeType string `orm:"column(range_type);size(255);null" description:"类型"`
RelationId int `orm:"column(relation_id);null"`
}
func (t *RankRangeData) TableName() string {
return "rank_range_data"
}
func init() {
orm.RegisterModel(new(RankRangeData))
}
// AddRankRangeData insert a new RankRangeData into database and returns
// last inserted Id on success.
func AddRankRangeData(m *RankRangeData) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetRankRangeDataById retrieves RankRangeData by Id. Returns error if
// Id doesn't exist
func GetRankRangeDataById(id int) (v *RankRangeData, err error) {
o := orm.NewOrm()
v = &RankRangeData{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRankRangeData updates RankRangeData by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankRangeDataById(m *RankRangeData) (err error) {
o := orm.NewOrm()
v := RankRangeData{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteRankRangeData deletes RankRangeData by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankRangeData(id int) (err error) {
o := orm.NewOrm()
v := RankRangeData{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&RankRangeData{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
//参榜范围列表
func GetRankRangeDataList(rankRangeId int) (v []*RankRangeData, err error) {
sql := mybeego.NewSqlExutor()
sql.Table((&RankRangeData{}).TableName())
if rankRangeId > 0 {
sql.Where(fmt.Sprintf("rank_range_id=%v", rankRangeId))
}
sql.Order("relation_id")
_, err = sql.Querys(&v)
return
}
... ...
package models
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
"time"
"github.com/astaxie/beego/orm"
)
type RankType struct {
Id int `orm:"column(id);auto" json:"id"`
Name string `orm:"column(name);size(50)" description:"榜单名称" json:"name"`
CompanyId int `orm:"column(company_id)" description:"公司编号 company.id" json:"-"`
CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间" json:"-"`
UpdateAt time.Time `orm:"column(update_at);type(timestamp);null" description:"更新时间" json:"-"`
EnableStatus int8 `orm:"column(enable_status);null" description:"是否有效 【1:禁用】【2:启用】" json:"-"`
Type int8 `orm:"column(type);null" description:"榜单类型(1赛季榜、2年榜) json:"type"`
}
func (t *RankType) TableName() string {
return "rank_type"
}
func init() {
orm.RegisterModel(new(RankType))
}
// AddRankType insert a new RankType into database and returns
// last inserted Id on success.
func AddRankType(m *RankType) (id int64, err error) {
o := orm.NewOrm()
id, err = o.Insert(m)
return
}
// GetRankTypeById retrieves RankType by Id. Returns error if
// Id doesn't exist
func GetRankTypeById(id int) (v *RankType, err error) {
o := orm.NewOrm()
v = &RankType{Id: id}
if err = o.Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateRankType updates RankType by Id and returns error if
// the record to be updated doesn't exist
func UpdateRankTypeById(m *RankType) (err error) {
o := orm.NewOrm()
v := RankType{Id: m.Id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Update(m); err == nil {
fmt.Println("Number of records updated in database:", num)
}
}
return
}
// DeleteRankType deletes RankType by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRankType(id int) (err error) {
o := orm.NewOrm()
v := RankType{Id: id}
// ascertain id exists in the database
if err = o.Read(&v); err == nil {
var num int64
if num, err = o.Delete(&RankType{Id: id}); err == nil {
fmt.Println("Number of records deleted in database:", num)
}
}
return
}
//
func GetRankTypes(companyId int64) (v []*RankType, err error) {
sql := mybeego.NewSqlExutor()
sql.Table((&RankType{}).TableName())
if companyId > 0 {
sql.Where(fmt.Sprintf("company_id=%v", companyId))
}
sql.Where(fmt.Sprintf("enable_status=2"))
sql.Order("type")
sql.Limit(0, 2)
_, err = sql.Querys(&v)
return
}
... ...
... ... @@ -109,3 +109,12 @@ func GetUserCompanysFirst(uid int64) (v *UserCompany, err error) {
}
return nil, err
}
func GetUserCompanyIdAll(companyId int) (v []int64, err error) {
o := orm.NewOrm()
sql := "select id from user_company where company_id=? and enable=1" //and enable=1
if _, err = o.Raw(sql, companyId).QueryRows(&v); err == nil {
return v, nil
}
return nil, err
}
... ...
... ... @@ -244,3 +244,26 @@ from user_msg where receive_user_id=? and source_type=1 and msg_type=? and send
}
return
}
func GetChanceReviseMsg(uid, lastId int64, pageSize int, msgType int, v interface{}) (total int, err error) {
sql := `select a.*,b.images,b.speechs,b.videos from (
select a.*,b.source_content,b.enable_status,b.user_id chance_user_id,b.create_at,b.review_status,b.status from (
select id msg_id,message,source_type,source_id,is_read,create_at msg_time,chance_id,receive_user_id,sender_user_id from user_msg
where receive_user_id =? and (?=0 or id<?) and msg_type=?
)a left outer join chance b on a.chance_id = b.id
)a left outer join chance_data b on a.chance_id = b.chance_id
order by msg_id desc
LIMIT ?`
sqlCount := `select count(0)
from user_msg where receive_user_id=? and msg_type=?`
if err = utils.ExecuteQueryOne(&total, sqlCount, uid, msgType); err != nil {
return
}
if v != nil {
if err = utils.ExecuteQueryAll(v, sql, uid, lastId, lastId, msgType, pageSize); err != nil {
return
}
}
return
}
... ...
package protocol
import "time"
const (
Grasper = 1 //把握人
Provider = 2 //提供者
)
//成果项
type AchievementItem struct {
Id int64 `json:"id"`
CreateTime int64 `json:"createTime"`
Provider *BaseUserInfo `json:"provider"`
Content string `json:"content"`
Pictures []Picture `json:"pictures"`
//GraspScore float64 `json:"graspScore"` //把握分
//GraspScorePercent float64 `json:"graspScorePercent"` //把握分百分比
}
type GraspScore struct {
GraspScore float64 `json:"graspScore"` //把握分
GraspScorePercent float64 `json:"graspScorePercent"` //把握分百分比
}
//机会列表 通用项
type AchievementCommonListItem struct {
Achievement AchievementItem `json:"achievement,omitempty"` //成果详情
StatisticData interface{} `json:"statisticData,omitempty"` //统计数据(是否收藏/点赞 浏览数 点赞总数 评论数)ChanceData
//我审核的-通过
Score interface{} `json:"score,omitempty"`
GraspScore interface{} `json:"graspScore,omitempty"` //把握分
//模板
ChanceType interface{} `json:"chanceType,omitempty"` //机会类型
ChanceTemplate interface{} `json:"template,omitempty"` //机会模板
Message interface{} `json:"message,omitempty"` //消息
CommentData interface{} `json:"commentData,omitempty"` //评论
CollectData interface{} `json:"collectData,omitempty"` //收藏数据
ThumbUpData interface{} `json:"thumbUpData,omitempty"` //点赞数据
//我评论的 评论数据
CommentedData interface{} `json:"commentedData,omitempty"`
SourceType int `json:"sourceType,omitempty"` //类型 1:机会 2:评论
Status int `json:"-"` //0:删除 1:开启 2:关闭
}
/*AchievementPool 成果池*/
type AchievementPoolRequest struct {
UserId int64 `json:"userId"`
LastId int64 `json:"lastId"`
PageSize int `json:"pageSize" valid:"Required"`
ChanceTypeId int `json:"chanceTypeId"` //0:所有机会 编号:对应机会类型编号的机会
DepartmentId int `json:"departmentId"`
IncludeSubDepartment bool
}
type AchievementPoolResponse struct {
List []*AchievementCommonListItem `json:"list"`
Total int `json:"total"`
}
//通用 机会orm对象
type CommAchievementItemOrm struct {
AchievementItemOrm
StaticDataOrm
}
type AchievementItemOrm struct {
AchievementId int64 `orm:"column(id)"`
UserId int64 `orm:"column(user_company_id)"`
CreateTime time.Time `orm:"column(create_at)"`
SourceContent string `orm:"column(source_content)"`
Images string `orm:"column(images)"`
GraspScore float64 `orm:"column(grasp_score)"`
UserGraspScore float64 `orm:"column(user_grasp_score)"`
TemplateId int `orm:"column(audit_template_id)"`
ChanceTypeId int `orm:"column(chance_type_id)"`
Status int `orm:"column(status)"`
}
type StaticDataOrm struct {
CommentTotal int `orm:"column(comment_total)"`
ZanTotal int `orm:"column(zan_total)"`
ViewTotal int `orm:"column(view_total)"`
}
//机会池收藏列表项
//type AchievementsOrm struct {
// CommAchievementItemOrm
//}
/*MyGrasp 我把握的*/
type MyGraspRequest struct {
AchievementPoolRequest
}
type MyGraspResponse struct {
AchievementPoolResponse
}
/*AchievementDetail 成果详情*/
type AchievementDetailRequest struct {
Id int64 `json:"id" valid:"Required"`
}
type AchievementDetailResponse struct {
Achievement AchievementItem `json:"achievement,omitempty"` //成果详情
GraspScore interface{} `json:"graspScore,omitempty"` //把握分
StatisticData interface{} `json:"statisticData,omitempty"` //统计数据(是否收藏/点赞 浏览数 点赞总数 评论数
//模板
ChanceType interface{} `json:"chanceType,omitempty"` //机会类型
ChanceTemplate interface{} `json:"template,omitempty"` //机会模板
Status int `json:"-"` //0:删除 1:开启 2:关闭
SourceChance []*CommonListItem `json:"sourceChance"` //机会来源
Participants []UserGraspInfo `json:"participants"` //参与人
}
type UserGraspInfo struct {
Provider *BaseUserInfo `json:"provider"`
GraspScore GraspScore `json:"graspScore"` //把握分
//GraspScorePercent float64 `json:"graspScorePercent"` //把握分百分比
Type int `json:"type"` //1:把握人 2:提供者
}
type SourceChanceItemOrm struct {
CommChanceItemOrm
TemplateId int `orm:"column(audit_template_id)"`
ChanceTypeId int `orm:"column(chance_type_id)"`
}
/*MyGraspStatistic */
type MyGraspStatisticRequest struct {
}
type MyGraspStatisticResponse struct {
GraspStatistic interface{} `json:"list"`
}
... ...
... ... @@ -165,9 +165,11 @@ type MySubmitChanceResponse struct {
/*ChancePool 机会池*/
type ChancePoolRequest struct {
LastId int64 `json:"lastId"`
PageSize int `json:"pageSize" valid:"Required"`
ChanceTypeId int `json:"chanceTypeId"` //0:所有机会 编号:对应机会类型编号的机会
LastId int64 `json:"lastId"`
PageSize int `json:"pageSize" valid:"Required"`
ChanceTypeId int `json:"chanceTypeId"` //0:所有机会 编号:对应机会类型编号的机会
DepartmentId int `json:"departmentId"` //部门编号
IncludeSubDepartment bool
}
type ChancePoolResponse struct {
List []CommonListItem `json:"list"`
... ... @@ -331,6 +333,25 @@ type ChanceCommentItemOrm struct {
SenderUserId int64 `orm:"column(sender_user_id)"`
}
//我的评论
type ChanceReviseItemOrm struct {
CommChanceItemOrm
MsgItemOrm
}
//消息
type MsgItemOrm struct {
MsgId int64 `orm:"column(msg_id)"`
MsgTime time.Time `orm:"column(msg_time)"` //收藏时间
Message string `orm:"column(message)"`
//评论对象类型
SourceType int `orm:"column(source_type)"`
SourceId int64 `orm:"column(source_id)"`
IsRead int64 `orm:"column(is_read)"`
ReceiveUserId int64 `orm:"column(receive_user_id)"`
SenderUserId int64 `orm:"column(sender_user_id)"`
}
//通用 机会orm对象
type CommChanceItemOrm struct {
ChanceId int64 `orm:"column(chance_id)"`
... ... @@ -514,11 +535,11 @@ type CommonListItem struct {
CommentedData interface{} `json:"commentedData,omitempty"`
SourceType int `json:"sourceType,omitempty"` //类型 1:机会 2:评论
ChanceStatus int `json:"chanceStatus"` //0:正常 1.删除 2.关闭
Status int `json:"-"` //1:开启 2:关闭
ReviewStatus int `json:"reviewStatus"` //审核状态
ChanceStatus int `json:"chanceStatus"` //0:正常 1.删除 2.关闭
Status int `json:"-"` //1:开启 2:关闭
ReviewStatus int `json:"reviewStatus,omitempty"` //审核状态
ChanceId int64 `json:"chanceId"` //机会编号
ChanceId int64 `json:"chanceId,omitempty"` //机会编号
}
type MsgCommonListItem struct {
... ... @@ -542,12 +563,17 @@ type MsgCommonListItem struct {
//我评论的 评论数据
CommentedData interface{} `json:"commentedData,omitempty"`
SourceType int `json:"sourceType,omitempty"` //类型 1:机会 2:评论
ChanceStatus int `json:"chanceStatus"` //0:正常 1.删除 2.关闭
ReviewStatus int `json:"reviewStatus"` //审核状态
SourceType int `json:"sourceType,omitempty"` //类型 1:机会 2:评论
SourceId int64 `json:"sourceId,omitempty"` //类型 1:机会 2:评论
ChanceStatus int `json:"chanceStatus"` //0:正常 1.删除 2.关闭
ReviewStatus int `json:"reviewStatus"` //审核状态
IsRead bool `json:"isRead"`
ChanceId int64 `json:"chanceId"` //机会编号
IsRead bool `json:"isRead"`
ChanceId int64 `json:"chanceId"` //机会编号
ChanceReviseLogId int64 `json:"chanceReviseLogId,omitempty"` //机会补充编号
}
type MsgItem struct {
}
type ChanceItem struct {
Id int64 `json:"id"`
... ... @@ -593,3 +619,27 @@ type CommentData struct {
//IsRead bool `json:"isRead"` //是否已读
Provider interface{} `json:"provider,omitempty"`
}
type ChanceReviseLog struct {
Provider *BaseUserInfo `json:"provider,omitempty"`
CreateTime int64 `json:"createTime"`
DiffContents []ReviseContent `json:"reviseContents"`
Speechs []Speech `json:"speechs"`
Pictures []Picture `json:"pictures"`
Videos []Video `json:"videos"`
RemoveAllPhotoVideo bool `json:"removeAllPhotoVideo"` //是否移除所有图片 视频
RemoveAllSpeech bool `json:"removeAllSpeech"` //是否移除所有音频
}
type ReviseContent struct {
Content string `json:"content"`
}
/*ChanceReviseDetail 机会补充详情*/
type ChanceReviseDetailRequest struct {
Id int64 `json:"id"`
}
type ChanceReviseDetailResponse struct {
ChanceReviseData ChanceReviseLog `json:"chanceReviseData"`
ChanceId int64 `json:"chanceId"` //机会编号
}
... ...
package protocol
const (
SourceTypeChance = 1
SourceTypeComment = 2
SourceTypeBulletin = 3
SourceTypeChance = 1 //机会
SourceTypeComment = 2 //机会评论
SourceTypeBulletin = 3 //公告
SourceTypeAchievement = 4 //成果
SourceTypeAchievementComment = 5 //成果评论
SourceTypeChanceReviseLog = 6 //机会变更
)
/*IComment */
... ...
... ... @@ -9,7 +9,7 @@ type GetConfigScoreResponse struct {
type ScoreConfig struct {
DiscoveryScore *DiscoveryScore `json:"discoveryScore"`
SumScore *SumScore `json:"-"` //sumScore
SumScore *SumScore `json:"sumScore"` //sumScore
BasicScore *ScoreRange `json:"basicScore"`
ExtraScore *ScoreRange `json:"extraScore"`
ValueScore *ScoreRange `json:"valueScore"`
... ...
package protocol
import "time"
import (
"time"
)
const (
DepartmentUser = iota //用户所有部门
DepartmentAll //公司所有部门
DepartmentRoot //公司一级部门
)
const (
StatisticApproved = 0 //统计已审核
StatisticApproving = 0 //统计审核中
)
/*Departments */
... ... @@ -16,13 +24,109 @@ type DepartmentsResponse struct {
Departments []*Department `json:"departments,omitempty"`
}
//获取一级部门列表
func (this DepartmentsResponse) GetCompanyDepartment() *Department {
if len(this.Departments) == 0 {
return &Department{}
}
if this.Departments[0].PId != 0 {
return &Department{}
}
return this.Departments[0]
}
//获取一级部门列表
func (this DepartmentsResponse) GetRootDepartments() []*Department {
if len(this.Departments) == 0 {
return []*Department{}
}
if this.Departments[0].PId != 0 {
return []*Department{}
}
return this.Departments[0].Departments
}
//获得部门底下子部门的编号列表(包含本身)
func (this DepartmentsResponse) GetChildDepartmentIds(d *Department, isContainSelf bool) []int {
idList := make([]int, 0)
if isContainSelf {
idList = append(idList, d.DepartmentId)
}
idList = append(idList, walkDeparment(d)...)
return idList
}
//遍历部门
func walkDeparment(d *Department) []int {
idList := make([]int, 0)
for i := range d.Departments {
d := d.Departments[i]
idList = append(idList, d.DepartmentId)
if len(d.Departments) > 0 {
idList = append(idList, walkDeparment(d)...)
}
}
return idList
}
type Department struct {
DepartmentId int `orm:"column(department_id)" json:"id"`
Name string `orm:"column(name)" json:"name"`
PId int `orm:"column(parent_id)" json:"-"`
ManagerString string `orm:"column(managers)" json:"-"`
Relation string `orm:"column(relation)"`
CreateTime time.Time `orm:"column(create_time)"`
Relation string `orm:"column(relation)" json:"-"`
CreateTime time.Time `orm:"column(create_time)" json:"-"`
Managers []int `json:"-"`
Departments []*Department `json:"departments,omitempty"`
}
/*DepartmentStatistics 部门统计*/
type DepartmentStatisticsRequest struct {
//DId int `json:"did"`//部门编号 //查询所有部门 查询特定部门
Type int `json:"type"` //0:已审核 0:待审核
}
type DepartmentStatisticsResponse struct {
Total int `json:"approvedTotal"`
List []*DepartmentStatistics `json:"departmentStatistics"`
}
func (this *DepartmentStatisticsResponse) Len() int { return len(this.List) }
func (this *DepartmentStatisticsResponse) Less(i, j int) bool {
//已审核 按照总数从大到小排序;若相同,按照已通过数量从大到小排序;若还相同,按照成果数量从大到小排序;*/
if this.List[i].ACTotal < this.List[j].ACTotal {
return true
}
if this.List[i].ACTotal == this.List[j].ACTotal && this.List[i].ChanceApprovedTotal < this.List[j].ChanceApprovedTotal {
return true
}
if this.List[i].ACTotal == this.List[j].ACTotal && this.List[i].ChanceApprovedTotal == this.List[j].ChanceApprovedTotal && this.List[i].AchievementTotal < this.List[j].AchievementTotal {
return true
}
if this.List[i].ACTotal == this.List[j].ACTotal && this.List[i].ChanceApprovedTotal == this.List[j].ChanceApprovedTotal && this.List[i].AchievementTotal == this.List[j].AchievementTotal {
if this.List[i].Dep.Id > this.List[j].Dep.Id {
return true
}
}
return false
}
func (this *DepartmentStatisticsResponse) Swap(i, j int) {
this.List[i], this.List[j] = this.List[j], this.List[i]
}
//部门统计项
type DepartmentStatistics struct {
Dep Dep `json:"dep"` //部门
ChanceApprovedTotal int `json:"chanceApprovedTotal"` //已审核的机会
ChanceApprovingTotal int `json:"chanceApprovingTotal"` //待审核的机会
AchievementTotal int `json:"achievementTotal"` //已创建的成果 (显示)
ACTotal int `json:"-"` //机会成果总数 (显示)
}
/*DepartmentStatistic 单部门统计*/
type DepartmentStatisticRequest struct {
DepartmentId int64 `json:"departmentId"`
}
type DepartmentStatisticResponse struct {
DepartmentStatistic DepartmentStatistics `json:"departmentStatistic"`
}
... ...
... ... @@ -37,6 +37,8 @@ const (
MyAuditChanceWait //我审核的机会-待我审批
MyAuditChancePass //我审核的机会-已通过
MyAuditChanceReturn //我审核的机会-已退回
MyAchievements //我的成就
MyGraspAchievement //我把握的成果
)
var MapStaticName map[int64]string
... ... @@ -57,15 +59,16 @@ func init() {
}
var ApproveLog = map[int]string{
1: "提交了机会", //提交人提交机会
2: "删除了机会", //提交人删除机会
3: "退回了机会", //审批人退回机会
4: "通过了机会;基础评分:%v分,附加评分:%v分,价值评分:%v分,公开状态:公司公开", //审批人通过机会(公司公开)
5: "通过了机会;基础评分:%v分,附加评分:%v分,价值评分:%v分,公开状态:%v", //审批人通过机会(部门公开) 测试部、销售部
6: "系统 自动通过了机会;基础评分:%v分,附加评分:%v分,价值评分:%v分,公开状态:公司公开", //审批人通过了机会(系统自动通过)
7: "修改了公开状态:公司公开", //审批通过后修改公开状态(公司公开)
8: "修改了公开状态:%v", //审批通过后修改公开状态(部门公开)
9: "修改了基础评分:“修改后的基础评分%v分,修改后的附加评分%v分,修改后的价值评分%v分“", //审批通过后修改评分
1: "提交了机会", //提交人提交机会
2: "删除了机会", //提交人删除机会
3: "退回了机会", //审批人退回机会
4: "通过了机会;基础评分:%v分,附加评分:%v分,价值评分:%v分,公开状态:公司公开", //审批人通过机会(公司公开)
5: "通过了机会;基础评分:%v分,附加评分:%v分,价值评分:%v分,公开状态:%v", //审批人通过机会(部门公开) 测试部、销售部
6: "系统 自动通过了机会;基础评分:%v分,附加评分:%v分,价值评分:%v分,公开状态:公司公开", //审批人通过了机会(系统自动通过)
7: "修改了公开状态:公司公开", //审批通过后修改公开状态(公司公开)
8: "修改了公开状态:%v", //审批通过后修改公开状态(部门公开)
9: "修改了基础评分:“修改后的基础评分%v分,修改后的附加评分%v分,修改后的价值评分%v分“", //审批通过后修改评分
10: "补充了机会信息", //审批通过后补充机会
}
//用户项
... ...
... ... @@ -65,13 +65,14 @@ var errmessge ErrorMap = map[int]string{
}
const (
MsgTypeBulletin = 1 //公告
MsgTypeCommend = 2 //表彰
MsgTypeInteraction = 4 //互动消息
MsgTypeAudit = 8 //机会审核
MsgTypeAuditBy = 16 //机会被审核消息-我提交的
MsgTypeComment = 32 //评论
MsgTypeThumbUp = 64 //点赞
MsgTypeBulletin = 1 //公告
MsgTypeCommend = 2 //表彰
MsgTypeInteraction = 4 //互动消息
MsgTypeAudit = 8 //机会审核
MsgTypeAuditBy = 16 //机会被审核消息-我提交的
MsgTypeComment = 32 //评论
MsgTypeThumbUp = 64 //点赞
MsgTypeChanceRevise = 128 //补充机会
)
var (
... ... @@ -79,8 +80,9 @@ var (
MessageApproveSuccess = "审核通过您提交的%v机会"
MessageApproveReject = "退回了您提交的%v机会"
MessageZanChance = "点赞了您发布的机会"
MessageZanComment = "点赞了您发布的评论"
MessageZanChance = "点赞了您发布的机会"
MessageZanComment = "点赞了您发布的评论"
MessageChanceRevise = "补充了您发布的%v机会信息"
)
/*MessageCenter */
... ... @@ -258,6 +260,16 @@ type MsgChanceThumbUpResponse struct {
Total int `json:"total"`
}
/*MsgChanceRevise 消息中心-机会补充*/
type MsgChanceReviseRequest struct {
LastId int64 `json:"lastId"`
PageSize int `json:"pageSize" valid:"Required"`
}
type MsgChanceReviseResponse struct {
List []MsgCommonListItem `json:"list"`
Total int `json:"total"`
}
//我的审核机会列表
type MsgChanceApproveItemOrm struct {
ChanceUserId int64 `orm:"column(chance_user_id)"`
... ...
package protocol
const (
RankRangeTypeAllCompanyUser = 1
RankRangeTypeSpecifyUser = 2
RankRangeTypeAllCompanyDepartment = 3
RankRangeTypeAllSpecifyDepartment = 4
)
const (
RankRangeTypeUser = 1
RankRangeTypeDepartment = 2
)
const (
RankPeriodWaiting = iota
RankPeriodBegin
RankPeriodEnd
)
/*GetRankList 排行榜*/
type GetRankListRequest struct {
RankTypeId int `json:"rankTypeId" valid:"Required"` //榜单类型编号(赛季榜、年榜)
RankRangeId int `json:"rankRangeId" valid:"Required"` //排行榜范围编号(员工/部门)
RankPeriodId int `json:"rankPeriodId" valid:"Required"` //排行榜周期范围编号 (开始结束时间)
SortItemKeys []string `json:"sortItemKeys" ` //排行项键值列表 valid:"Required"
PageIndex int `json:"pageIndex" valid:"Required"` //页码(默认0代表第1页)
PageSize int `json:"pageSize" valid:"Required"` //每页数量
}
type GetRankListResponse struct {
//SortItems []string `json:"sortItems"` //评比项
Self []RankItem `json:"self"` //自己或所在部门的排名分数
Lists [][]RankItem `json:"lists"` //排名列表
Total int `json:"total"` //总数
}
type RankItem struct {
Ranking int `json:"ranking" orm:"column(ranking)"` //排名
Name string `json:"name,omitempty" orm:"column(name)"` //名称
Score float64 `json:"score" orm:"column(score)"` //分数
}
/*GetRankType */
type GetRankTypeRequest struct {
}
type GetRankTypeResponse struct {
List []NameItem `json:"rankTypes"`
}
type RankType struct {
Id int `json:"id"`
Name string `json:"name"`
}
/*GetRankRange */
type GetRankRangeRequest struct {
RankTypeId int `json:"rankTypeId"` // valid:"Required"
}
type GetRankRangeResponse struct {
List []RankRange `json:"rankRanges"`
}
type RankRange struct {
Id int `json:"id"`
Type int `json:"type"` //1员工 2:部门
Name string `json:"name"`
}
/*GetRankPeriods 获取榜单竞争范围列表*/
type GetRankPeriodsRequest struct {
RankTypeId int `json:"rankTypeId"`
}
type GetRankPeriodsResponse struct {
List []RankPeriod `json:"rankPeriods"`
}
type RankPeriod struct {
Id int `json:"id"`
SeasonName string `json:"seasonName"`
BeginTime int64 `json:"beginTime"`
EndTime int64 `json:"endTime"`
}
/*ComputeRankScore */
type ComputeRankScoreRequest struct {
RankPeriodId int `json:"rankPeriodId"`
}
type ComputeRankScoreResponse struct {
}
/*GetRankSortItems */
type GetRankSortItemsRequest struct {
RankTypeId int `json:"rankTypeId"`
}
type GetRankSortItemsResponse struct {
RankSortItems []RankSortItem `json:"rankSortItems"`
}
type RankSortItem struct {
ItemName string `json:"name" orm:"column(item_name)"`
ItemKey string `json:"key" orm:"column(item_key)"`
}
... ...
... ... @@ -89,6 +89,7 @@ type Company struct {
type Dep struct {
Id int `json:"id"`
Name string `json:"name"`
Time int64 `json:"-"`
}
//岗位
... ...
... ... @@ -7,6 +7,38 @@ import (
func init() {
beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"],
beego.ControllerComments{
Method: "AchievementDetail",
Router: `/achievementDetail`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"],
beego.ControllerComments{
Method: "AchievementPool",
Router: `/achievementPool`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"],
beego.ControllerComments{
Method: "MyGrasp",
Router: `/myGrasp`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:AchievementController"],
beego.ControllerComments{
Method: "MyGraspStatistic",
Router: `/myGraspStatistic`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:AuthController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:AuthController"],
beego.ControllerComments{
Method: "AccessToken",
... ... @@ -89,6 +121,14 @@ func init() {
beego.GlobalControllerRouter["opp/controllers/v1:ChanceController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:ChanceController"],
beego.ControllerComments{
Method: "ChanceReviseDetail",
Router: `/chanceReviseDetail`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:ChanceController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:ChanceController"],
beego.ControllerComments{
Method: "ChanceType",
Router: `/chanceType`,
AllowHTTPMethods: []string{"post"},
... ... @@ -287,6 +327,22 @@ func init() {
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:DepartmentController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:DepartmentController"],
beego.ControllerComments{
Method: "DepartmentStatistic",
Router: `/statistic`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:DepartmentController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:DepartmentController"],
beego.ControllerComments{
Method: "DepartmentStatistics",
Router: `/statistics`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:FileController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:FileController"],
beego.ControllerComments{
Method: "GetPlayInfo",
... ... @@ -361,6 +417,14 @@ func init() {
beego.GlobalControllerRouter["opp/controllers/v1:MessageController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:MessageController"],
beego.ControllerComments{
Method: "MsgChanceRevise",
Router: `/msgChanceRevise`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:MessageController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:MessageController"],
beego.ControllerComments{
Method: "MsgChanceSubmit",
Router: `/msgChanceSubmit`,
AllowHTTPMethods: []string{"post"},
... ... @@ -391,6 +455,54 @@ func init() {
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:RankController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:RankController"],
beego.ControllerComments{
Method: "ComputeRankScore",
Router: `/computeRankScore`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:RankController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:RankController"],
beego.ControllerComments{
Method: "GetRankList",
Router: `/getRankList`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:RankController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:RankController"],
beego.ControllerComments{
Method: "GetRankPeriods",
Router: `/getRankPeriods`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:RankController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:RankController"],
beego.ControllerComments{
Method: "GetRankRange",
Router: `/getRankRanges`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:RankController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:RankController"],
beego.ControllerComments{
Method: "GetRankSortItems",
Router: `/getRankSortItems`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:RankController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:RankController"],
beego.ControllerComments{
Method: "GetRankType",
Router: `/getRankTypes`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:UcenterController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UcenterController"],
beego.ControllerComments{
Method: "UCenterLogin",
... ...
... ... @@ -24,6 +24,8 @@ func init() {
beego.NSNamespace("department", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.DepartmentController{})),
beego.NSNamespace("config", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.ConfigController{})),
beego.NSNamespace("file", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.FileController{})),
beego.NSNamespace("achievement", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.AchievementController{})),
beego.NSNamespace("rank", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.RankController{})),
)
beego.AddNamespace(nsV1)
... ...
... ... @@ -195,6 +195,21 @@ func GetChanceMarkData(userId, companyId int64, sourceId int64) (flag int, err e
return v.MarkFlag, nil
}
//获取机会标记数据 点赞 / 收藏
func GetMarkData(userId, companyId int64, sourceId int64, sourceType int) (flag int, err error) {
var (
v *models.ChanceFavorite
)
if v, err = models.GetChanceFavorite(userId, companyId, sourceId, sourceType); err != nil {
if err == orm.ErrNoRows {
//log.Error(userId, companyId, sourceId, err)
return 0, nil
}
return
}
return v.MarkFlag, nil
}
//构建统计sql语句
func GetIncrementSql(table string, column string, incre int, id int64) *utils.SqlData {
var sql *bytes.Buffer
... ...
package agg
import (
"fmt"
"github.com/prometheus/common/log"
"opp/models"
)
//检查公司权限
func CheckCompanyPermission(companyId int64) (err error) {
var (
company *models.Company
)
if companyId == 0 {
return nil
}
if company, err = models.GetCompanyById(companyId); err != nil {
log.Error("公司不存在:", companyId, err)
return
}
if company.Enable == 1 {
return nil
}
if company.Enable == 2 {
err = fmt.Errorf("公司:%v 无权限,请联系管理员", company.Name)
}
return
}
... ...
... ... @@ -3,12 +3,14 @@ package agg
import (
"fmt"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/internal/utils"
"opp/models"
"opp/protocol"
)
//机会池
func GetChancePool(uid, cid int64, chanceTypeId int, lastId int64, pageSize int, v interface{}) (total int, err error) {
//@isIncludeSubDeps 是否包含子部门编号
func GetChancePool(uid, cid int64, chanceTypeId int, departmentId int, isIncludeSubDeps bool, lastId int64, pageSize int, v interface{}) (total int, err error) {
var (
check int
checkMap map[int]int
... ... @@ -16,6 +18,7 @@ func GetChancePool(uid, cid int64, chanceTypeId int, lastId int64, pageSize int,
userDIds []int64
user *models.User
chance *models.Chance
dIds []int
)
if user, err = models.GetUserByCompanyId(cid); err != nil {
log.Error(err)
... ... @@ -43,29 +46,32 @@ func GetChancePool(uid, cid int64, chanceTypeId int, lastId int64, pageSize int,
}
lastId = chance.ApproveTime.Unix()
}
if departmentId > 0 {
dIds, _ = GetDepartmentIds(cid, int64(departmentId), isIncludeSubDeps)
}
log.Debug(fmt.Sprintf("user:%v check:%v is_amdin:%v", uid, check, user.Id == uid))
switch check {
case OpportunityCheckLv1:
return models.GetChancePoolMyself(uid, cid, chanceTypeId, lastId, pageSize, v)
return models.GetChancePoolMyself(uid, cid, chanceTypeId, dIds, lastId, pageSize, v)
case OpportunityCheckLv2:
if err = models.GetUserDepartmentIds(uid, cid, &userDIds); err != nil {
log.Error(err)
return
}
return models.GetChancePoolPublicCompany(uid, cid, chanceTypeId, lastId, pageSize, v, userDIds)
return models.GetChancePoolPublicCompany(uid, cid, chanceTypeId, dIds, lastId, pageSize, v, userDIds)
case OpportunityCheckLv3:
if _, ok := checkMap[OpportunityCheckLv2]; ok { //同时存在对部门公开的机会
if err = models.GetUserDepartmentIds(uid, cid, &userDIds); err != nil {
log.Error(err)
return
}
return models.GetChancePoolDepartment(uid, cid, chanceTypeId, lastId, pageSize, v, specialDIds, userDIds)
return models.GetChancePoolDepartment(uid, cid, chanceTypeId, dIds, lastId, pageSize, v, specialDIds, userDIds)
}
return models.GetChancePoolSpecialDepartment(uid, cid, chanceTypeId, lastId, pageSize, v, specialDIds)
return models.GetChancePoolSpecialDepartment(uid, cid, chanceTypeId, dIds, lastId, pageSize, v, specialDIds)
case OpportunityCheckLv4:
return models.GetChancePoolAll(uid, cid, chanceTypeId, lastId, pageSize, v)
return models.GetChancePoolAll(uid, cid, chanceTypeId, dIds, lastId, pageSize, v)
default:
return models.GetChancePoolAll(uid, cid, chanceTypeId, lastId, pageSize, v)
return models.GetChancePoolAll(uid, cid, chanceTypeId, dIds, lastId, pageSize, v)
}
return
}
... ... @@ -101,8 +107,9 @@ func ValidChancePermission(uid, cid int64, items []*protocol.CommonListItem) (er
specialDIds = append(specialDIds, 0)
}
}
log.Debug(fmt.Sprintf("user:%v check:%v is_admin:%v", uid, check, user.Id == uid))
log.Debug(fmt.Sprintf("user:%v check:%v is_admin:%v ", uid, check, user.Id == uid))
for i := range items {
//log.Debug("测试:", items[i].ChanceId, items[i].ChanceStatus)
if items[i].ChanceStatus != 0 {
continue
}
... ... @@ -129,9 +136,6 @@ func ValidChancePermission(uid, cid int64, items []*protocol.CommonListItem) (er
}
switch check {
case OpportunityCheckLv1:
//if chanceUserId == uid {
// continue
//}
if _, e := models.ExitsChanceByAuditUser(chanceId, uid); e == nil {
continue
}
... ... @@ -159,13 +163,10 @@ func ValidChancePermission(uid, cid int64, items []*protocol.CommonListItem) (er
}
items[i].ChanceStatus = protocol.ChanceStatusClose
case OpportunityCheckLv3:
//if chanceUserId == uid {
// continue
//}
if chancePublicStatus == protocol.PublicToCompany {
continue
}
if _, ok := checkMap[OpportunityCheckLv2]; ok { //同时存在对部门公开的机会
if chancePublicStatus == protocol.PublicToCompany {
continue
}
if chancePublicStatus == protocol.PublicToDepartment {
if len(userDIds) == 0 {
if e := models.GetUserDepartmentIds(uid, cid, &userDIds); e != nil {
... ... @@ -193,3 +194,42 @@ func ValidChancePermission(uid, cid int64, items []*protocol.CommonListItem) (er
}
return
}
//设置机会详情
func SetChanceItem(header *protocol.RequestHeader, chance protocol.CommChanceItemOrm) (item protocol.ChanceItem, chanceStatus int) {
var provider *protocol.BaseUserInfo
var err error
if provider, err = GetUserBaseInfo(chance.ChanceUserId, header.CompanyId); err != nil {
chanceStatus = protocol.ChanceStatusDelete
log.Error(err)
return
}
if len(chance.SourceContent) == 0 || chance.ChanceEnableStatus == 0 { //机会删除
chanceStatus = protocol.ChanceStatusDelete
}
if chance.Status == models.ChanceStatusClose { //机会关闭
chanceStatus = protocol.ChanceStatusClose
return
}
item = protocol.ChanceItem{
Id: chance.ChanceId,
Provider: provider,
CreateTime: chance.CreateTime.Unix() * 1000,
PublicStatus: chance.PublishStatus,
}
utils.JsonUnmarshal(chance.SourceContent, &item.FormList)
item.FormList = ClearEmptyForm(item.FormList)
utils.JsonUnmarshal(chance.Images, &item.Pictures)
utils.JsonUnmarshal(chance.Voices, &item.Speechs)
utils.JsonUnmarshal(chance.Videos, &item.Videos)
return item, chanceStatus
}
func SetMsgItem(header *protocol.RequestHeader, msg protocol.MsgItemOrm, commItem *protocol.MsgCommonListItem) {
commItem.MsgId = msg.MsgId
commItem.MsgTime = msg.MsgTime.Unix() * 1000
commItem.IsRead = msg.IsRead == 1
commItem.SourceId = msg.SourceId
commItem.SourceType = msg.SourceType
}
... ...
... ... @@ -278,6 +278,12 @@ func logMsgWithHeaer(header *protocol.RequestHeader, msg *models.UserMsg, name s
//保查审核日志
func SaveApproveLog(orm orm.Ormer, code int, userId int64, chanceId int64, param ...interface{}) (err error) {
_, err = SaveApproveLogResult(orm, code, userId, chanceId, param...)
return
}
//保查审核日志
func SaveApproveLogResult(orm orm.Ormer, code int, userId int64, chanceId int64, param ...interface{}) (id int64, err error) {
var (
message string
ok bool
... ... @@ -287,7 +293,7 @@ func SaveApproveLog(orm orm.Ormer, code int, userId int64, chanceId int64, param
return
}
message = fmt.Sprintf(message, param...)
if _, err = orm.Insert(&models.AuditFlowLog{
if id, err = orm.Insert(&models.AuditFlowLog{
ChanceId: chanceId,
Content: message,
ApproveUserId: userId,
... ...
... ... @@ -45,3 +45,80 @@ func MyApproveEnableStatic(header *protocol.RequestHeader, reviewStatus ...int8)
}
return
}
//我把握的统计
func MyGraspStatic(header *protocol.RequestHeader) (total int, err error) {
var ()
if total, err = models.GetAchievementAll(header.UserId, header.CompanyId, 0, 0, []int{}, 0, nil); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
return
}
//我把握的统计
func AchievementDepartmentStatic(header *protocol.RequestHeader, chanceTypeId int, departmentIds []int) (total int, err error) {
//var (
// departmentIds []int
//)
//if dId>0{
// departmentIds,_=GetDepartmentIds(header.CompanyId,dId)
//}
if total, err = models.GetAchievementAll(0, header.CompanyId, chanceTypeId, 0, departmentIds, 0, nil); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
return
}
//机会待审核统计
func ChanceApprovingStatistic(header *protocol.RequestHeader, departmentIds []int) (total int, err error) {
//var (
// departmentIds []int
//)
//if dId>0{
// departmentIds,_=GetDepartmentIds(header.CompanyId,dId)
//}
//if len(departmentIds)==0{
// return
//}
if total, err = models.GetChanceStatisticByDepartment(header.CompanyId, departmentIds, protocol.ReviewStatusAuditging); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
return
}
//获取部门以及子部门编号
//@isIncludeSubDeps 是否包含子部门
func GetDepartmentIds(companyId int64, dId int64, isIncludeSubDeps bool) (departmentIds []int, err error) {
if dId == 0 {
return []int{}, nil
}
if !isIncludeSubDeps {
return []int{int(dId)}, nil
}
if d, e := models.GetDepartmentById(dId); e != nil {
log.Error(err)
err = e
return
} else {
if departmentIds, err = models.GetSubDepartmentIds(companyId, d.Relation); err != nil {
log.Error(err)
return
}
}
return
}
... ...
... ... @@ -88,8 +88,12 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp
case 10001:
err = protocol.NewErrWithMessage(2002, err) //账号不存在
return
case 10003:
err = protocol.NewErrWithMessage(4140, err) //账号不存在
return
default:
err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)
log.Error("error_no:%v msg:%v", message.Errno, message.Errmsg)
err = protocol.NewErrWithMessage(4140, err)
return
}
... ... @@ -257,6 +261,11 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
if err = models.UpdateUserAuthById(userAuth); err != nil {
return
}
if err = agg.CheckCompanyPermission(userAuth.CurrentCompanyId); err != nil {
log.Error(err)
err = protocol.NewErrWithMessage(4140, err)
return
}
rsp = &protocol.RefreshTokenResponse{
AccessToken: userAuth.AccessToken,
RefreshToken: userAuth.RefreshToken,
... ...
package chance
import (
"github.com/astaxie/beego/orm"
"opp/internal/utils"
"opp/models"
"opp/protocol"
"opp/services/agg"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
)
//成果池
func AchievementPool(header *protocol.RequestHeader, request *protocol.AchievementPoolRequest) (rsp *protocol.AchievementPoolResponse, err error) {
var (
ormItems []protocol.CommAchievementItemOrm
total int
departmentIds []int
)
rsp = &protocol.AchievementPoolResponse{}
rsp.List = make([]*protocol.AchievementCommonListItem, 0)
if request.DepartmentId > 0 && request.IncludeSubDepartment {
if d, e := models.GetDepartmentById(int64(request.DepartmentId)); e != nil {
log.Error(err)
err = e
return
} else {
if departmentIds, err = models.GetSubDepartmentIds(header.CompanyId, d.Relation); err != nil {
log.Error(err)
return
}
}
} else {
if request.DepartmentId > 0 {
departmentIds = []int{request.DepartmentId}
}
}
if total, err = models.GetAchievementAll(request.UserId, header.CompanyId, request.ChanceTypeId, request.LastId, departmentIds, request.PageSize, &ormItems); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
rsp.Total = total
for i := range ormItems {
item := ormItems[i]
rspItem := &protocol.AchievementCommonListItem{
Achievement: GetAchievementItem(header, item),
GraspScore: protocol.GraspScore{
GraspScore: item.UserGraspScore,
GraspScorePercent: utils.DecimalToNumber(item.UserGraspScore),
},
StatisticData: GetStatisticData(header, item.StaticDataOrm, item.AchievementId),
ChanceTemplate: getTemplate(item.TemplateId),
ChanceType: getChanceType(item.ChanceTypeId),
}
rsp.List = append(rsp.List, rspItem)
}
return
}
//获取成果项
func GetAchievementItem(header *protocol.RequestHeader, from protocol.CommAchievementItemOrm) (item protocol.AchievementItem) {
var (
provider *protocol.BaseUserInfo
err error
)
if from.UserId > 0 {
if provider, err = agg.GetUserBaseInfo(from.UserId, header.CompanyId); err != nil {
log.Error(err)
return
} else {
item = protocol.AchievementItem{
Id: from.AchievementId,
Provider: provider,
CreateTime: from.CreateTime.Unix() * 1000,
Content: from.SourceContent,
//GraspScore: from.GraspScore,
//GraspScorePercent: from.GraspScore,
}
jsonUnmarshal(from.Images, &item.Pictures)
}
}
return
}
//获取统计数据
func GetStatisticData(header *protocol.RequestHeader, from protocol.StaticDataOrm, sourceId int64) (chanceData protocol.ChanceData) {
chanceData = protocol.ChanceData{
ThumbsUpTotal: from.ZanTotal,
CommentTotal: from.CommentTotal,
PageViewTotal: from.ViewTotal,
}
chanceData.IsThumbsUp, chanceData.IsCollect, _ = getMarkFlag(header, sourceId, protocol.SourceTypeAchievement)
return
}
//我把握的
func MyGrasp(header *protocol.RequestHeader, request *protocol.MyGraspRequest) (rsp *protocol.MyGraspResponse, err error) {
var (
achievementPool *protocol.AchievementPoolResponse
)
request.UserId = header.UserId
if achievementPool, err = AchievementPool(header, &request.AchievementPoolRequest); err != nil {
log.Error(err)
return
}
rsp = &protocol.MyGraspResponse{}
rsp.AchievementPoolResponse = *achievementPool
return
}
//成果详情
func AchievementDetail(header *protocol.RequestHeader, request *protocol.AchievementDetailRequest) (rsp *protocol.AchievementDetailResponse, err error) {
var (
items []protocol.CommAchievementItemOrm
participants []*models.AchievementProvider
chances []protocol.SourceChanceItemOrm
)
if err = models.GetCommAchievementItemOrmId(request.Id, &items); err != nil {
log.Error(err)
return
}
if len(items) == 0 {
err = protocol.NewErrWithMessage(1)
log.Error("items not empty", request.Id)
return
}
item := items[0]
if item.Status != 1 {
//错误 成果删除或关闭
}
rsp = &protocol.AchievementDetailResponse{}
{
rsp.Achievement = GetAchievementItem(header, item)
rsp.GraspScore = protocol.GraspScore{
GraspScore: item.UserGraspScore,
GraspScorePercent: utils.DecimalToNumber(item.UserGraspScore),
}
rsp.StatisticData = GetStatisticData(header, item.StaticDataOrm, item.AchievementId)
rsp.ChanceTemplate = getTemplate(item.TemplateId)
rsp.ChanceType = getChanceType(item.ChanceTypeId)
}
if participants, err = models.GetAchievementProviders(request.Id); err != nil && err != orm.ErrNoRows {
log.Error(err)
return
}
newParticipant := func(user *protocol.BaseUserInfo, score float64, t int) protocol.UserGraspInfo {
return protocol.UserGraspInfo{
Provider: user,
GraspScore: protocol.GraspScore{
GraspScore: score,
GraspScorePercent: utils.DecimalToNumber(score),
},
Type: t,
}
}
addParticipants := func(item protocol.UserGraspInfo) {
rsp.Participants = append(rsp.Participants, item)
}
addParticipants(newParticipant(rsp.Achievement.Provider, item.UserGraspScore, protocol.Grasper))
for i := range participants {
p := participants[i]
if provider, e := agg.GetUserBaseInfo(p.UserCompanyId, header.CompanyId); e != nil {
log.Error(e)
return
} else {
addParticipants(newParticipant(provider, p.UserGraspScore, protocol.Provider))
}
}
//查看数量
utils.ExecuteSqlByRoll(true, agg.GetIncrementSql((&models.Achievement{}).TableName(), "view_total", 1, request.Id))
if err = models.GetAchievementChances(request.Id, &chances); err != nil {
log.Error(err)
return
}
for i := range chances {
chance := chances[i]
commItem := &protocol.CommonListItem{}
commItem.Chance, commItem.ChanceStatus = agg.SetChanceItem(header, chance.CommChanceItemOrm)
//commItem.ChanceTemplate = getTemplate(chance.TemplateId)
//commItem.ChanceType = getChanceType(chance.ChanceTypeId)
//commItem.Score=protocol.GraspScore{
// GraspScore:chance.,
// GraspScorePercent:chance.GraspScore,
//}
commItem.ChanceId = chance.ChanceId
rsp.SourceChance = append(rsp.SourceChance, commItem)
}
agg.ValidChancePermission(header.UserId, header.CompanyId, rsp.SourceChance)
return
}
//我把握的统计(按一级分类类型)
func MyGraspStatistic(header *protocol.RequestHeader, request *protocol.MyGraspStatisticRequest) (rsp *protocol.MyGraspStatisticResponse, err error) {
type StatisticItemOrm struct {
Id int `json:"id" orm:"column(chance_type_id)"` //类型
Name string `json:"name" orm:"column(name)"` //总数
Total int `json:"total" orm:"column(total)"`
}
var (
items []StatisticItemOrm
)
if err = models.GetAchievementStatisticByChanceType(header.UserId, &items); err != nil {
log.Error(err)
return
}
rsp = &protocol.MyGraspStatisticResponse{}
rsp.GraspStatistic = items
return
}
... ...
... ... @@ -12,6 +12,7 @@ import (
"opp/models"
"opp/protocol"
"opp/services/agg"
"reflect"
"strings"
"time"
)
... ... @@ -576,6 +577,9 @@ func ChanceUpdate(header *protocol.RequestHeader, request *protocol.ChanceUpdate
return
}
auditConfig = &protocol.AuditConfig{NoApprover: template.NoApprover}
CheckChanceDifferent(header, chance, request)
orm := orm.NewOrm()
orm.Begin()
//6.更新文件
... ... @@ -707,6 +711,164 @@ func ChanceUpdate(header *protocol.RequestHeader, request *protocol.ChanceUpdate
return
}
//检查机会更新
func CheckChanceDifferent(header *protocol.RequestHeader, chance *models.Chance, request *protocol.ChanceUpdateRequest) {
var (
isSaveLog bool = false
chanceReviseLog *models.ChanceReviseLog
message string
)
defer func() {
if p := recover(); p != nil {
log.Error(p)
}
}()
if header.UserId == chance.UserId {
return
}
if chance.ReviewStatus != protocol.ReviewStatusPass {
return
}
var modifyLog = protocol.ChanceReviseLog{
RemoveAllPhotoVideo: false,
RemoveAllSpeech: false,
}
checkIsSaveLog := func() {
if !isSaveLog {
isSaveLog = true
}
}
diffFormList := func(source string, dis []*protocol.Form) {
var (
src []*protocol.Form
mapForm map[string]*protocol.Form = make(map[string]*protocol.Form)
reviseContents []protocol.ReviseContent
)
jsonUnmarshal(source, &src)
for i := range src {
mapForm[src[i].Label] = src[i]
}
for i := range dis {
isDiff := false
srcValue := ""
if v, ok := mapForm[dis[i].Label]; ok {
srcValue = v.Value
if dis[i].Value != v.Value {
isDiff = true
}
} else {
isDiff = true
}
if isDiff {
reviseContents = append(reviseContents, protocol.ReviseContent{
Content: fmt.Sprintf("将“%v”由“%v”改为 “%v”", dis[i].Label, srcValue, dis[i].Value)})
checkIsSaveLog()
}
}
modifyLog.DiffContents = reviseContents
}
diffChanceData := func() {
var (
speechs []protocol.Speech
pictures []protocol.Picture
videos []protocol.Video
)
if chanceData, e := models.GetChanceDataByChanceId(chance.Id); e == nil {
jsonUnmarshal(chanceData.Speechs, &speechs)
jsonUnmarshal(chanceData.Images, &pictures)
jsonUnmarshal(chanceData.Videos, &videos)
if !reflect.DeepEqual(request.Videos, videos) || !reflect.DeepEqual(request.Pictures, pictures) {
checkIsSaveLog()
modifyLog.Videos = request.Videos
modifyLog.Pictures = request.Pictures
}
if !reflect.DeepEqual(request.Speechs, speechs) {
checkIsSaveLog()
modifyLog.Speechs = request.Speechs
}
if (len(videos) > 0 && len(request.Videos) == 0) && len(pictures) > 0 && len(request.Pictures) == 0 {
modifyLog.RemoveAllPhotoVideo = true
}
if (len(videos) > 0 && len(request.Videos) == 0) && (len(pictures) == len(request.Pictures) && len(pictures) == 0) {
modifyLog.RemoveAllPhotoVideo = true
}
if (len(videos) == len(request.Videos) && len(videos) == 0) && len(pictures) > 0 && len(request.Pictures) == 0 {
modifyLog.RemoveAllPhotoVideo = true
}
if len(speechs) > 0 && len(request.Speechs) == 0 {
modifyLog.RemoveAllSpeech = true
}
} else {
checkIsSaveLog()
modifyLog.Speechs = request.Speechs
modifyLog.Videos = request.Videos
modifyLog.Speechs = request.Speechs
}
}
diffFormList(chance.SourceContent, request.FormList)
diffChanceData()
checkModifyLog := func() {
if len(modifyLog.Speechs) == 0 {
modifyLog.Speechs = make([]protocol.Speech, 0)
}
if len(modifyLog.Pictures) == 0 {
modifyLog.Pictures = make([]protocol.Picture, 0)
}
if len(modifyLog.Videos) == 0 {
modifyLog.Videos = make([]protocol.Video, 0)
}
if len(modifyLog.DiffContents) == 0 {
modifyLog.DiffContents = make([]protocol.ReviseContent, 0)
}
}
checkModifyLog()
if isSaveLog { //&& changeCount > 0
orm := orm.NewOrm()
orm.Begin()
var logId int64
//发送日志
if id, err := agg.SaveApproveLogResult(orm, 10, header.UserId, chance.Id); err != nil {
log.Error(err)
orm.Rollback()
return
} else {
logId = id
}
//保存修改详情
chanceReviseLog = &models.ChanceReviseLog{
Id: idgen.Next(),
ChanceId: chance.Id,
UserCompanyId: header.UserId,
Data: common.AssertJson(modifyLog),
CreateAt: time.Now(),
AuditFlowLogId: logId,
}
if _, e := orm.Insert(chanceReviseLog); e != nil {
log.Error(e)
orm.Rollback()
return
}
if chanceType, err := models.GetChanceTypeById(chance.ChanceTypeId); err != nil {
log.Error(err)
orm.Rollback()
return
} else {
message = fmt.Sprintf(protocol.MessageChanceRevise, chanceType.Name)
}
//发送修改机会消息
if err := agg.SendMsgWithHeader(header, chance.UserId, "", chanceReviseLog.Id, protocol.SourceTypeChanceReviseLog, message, protocol.MsgTypeChanceRevise, chance.Id); err != nil {
log.Error(err)
orm.Rollback()
return
}
orm.Commit()
}
}
//修改公开状态
func ChanceChangePublish(header *protocol.RequestHeader, request *protocol.ChanceChangePublishRequest) (rsp *protocol.ChanceChangePublishResponse, err error) {
var (
... ... @@ -1174,13 +1336,13 @@ func resolveActionType(t uint) string {
func getDepartmentors(header *protocol.RequestHeader, relatedDeparmentId int64) (ids []int64, err error) {
var (
departments *models.Department
lastDepartmentId int
lastDepartmentId int64
)
//if err = models.GetUserDepartments(header.UserId, header.CompanyId, &departments); err != nil {
// log.Error(header.UserId,header.CompanyId,err)
// return
//}
if departments, err = models.GetDepartmentById(int(relatedDeparmentId)); err != nil {
if departments, err = models.GetDepartmentById(relatedDeparmentId); err != nil {
log.Error(relatedDeparmentId, err)
return
}
... ... @@ -1208,7 +1370,7 @@ func getDepartmentors(header *protocol.RequestHeader, relatedDeparmentId int64)
if departments.ParentId != 0 {
//relatedDeparmentId = int64departments.ParentId
lastDepartmentId = departments.ParentId
if departments, err = models.GetDepartmentById(int(departments.ParentId)); err != nil {
if departments, err = models.GetDepartmentById(departments.ParentId); err != nil {
log.Error(departments.ParentId, err)
err = nil
break
... ... @@ -1247,7 +1409,7 @@ func getRoleUsers(header *protocol.RequestHeader, roleId int) (ids []int64, err
}
//递归寻找上一级部门长
func getParentDepartmentors(pid int) (ids []int64) {
func getParentDepartmentors(pid int64) (ids []int64) {
var (
department *models.Department
err error
... ... @@ -1281,7 +1443,7 @@ func ChanceStatistics(header *protocol.RequestHeader, request *protocol.ChanceSt
rsp = &protocol.ChanceStatisticsResponse{}
for i := range chanceType {
item := chanceType[i]
if total, err = agg.GetChancePool(header.UserId, header.CompanyId, item.Id, 0, 0, nil); err != nil {
if total, err = agg.GetChancePool(header.UserId, header.CompanyId, item.Id, 0, false, 0, 0, nil); err != nil {
log.Error(err)
return
}
... ... @@ -1369,7 +1531,7 @@ func ChancePool(header *protocol.RequestHeader, request *protocol.ChancePoolRequ
provider *protocol.BaseUserInfo
flag int
)
if total, err = agg.GetChancePool(header.UserId, header.CompanyId, request.ChanceTypeId, request.LastId, request.PageSize, &myChances); err != nil {
if total, err = agg.GetChancePool(header.UserId, header.CompanyId, request.ChanceTypeId, request.DepartmentId, request.IncludeSubDepartment, request.LastId, request.PageSize, &myChances); err != nil {
if err == orm.ErrNoRows {
err = nil
return
... ... @@ -1792,6 +1954,18 @@ func getChanceMarkFlag(header *protocol.RequestHeader, chanceId int64) (isThumbs
return
}
//获取机会点赞/收藏状态
func getMarkFlag(header *protocol.RequestHeader, sourceId int64, sourceType int) (isThumbsUp, isCollect bool, err error) {
var flag int
if flag, err = agg.GetMarkData(header.UserId, header.CompanyId, sourceId, sourceType); err != nil {
log.Error(err)
return
}
isThumbsUp = (flag & protocol.MarkFlagZan) == protocol.MarkFlagZan
isCollect = (flag & protocol.MarkFlagCollect) == protocol.MarkFlagCollect
return
}
//获取模板
func getTemplate(templateId int) protocol.NameItem {
if template, e := models.GetAuditTemplateById(int64(templateId)); e == nil {
... ... @@ -2112,3 +2286,25 @@ func Permission(header *protocol.RequestHeader, request *protocol.PermissionRequ
}
return
}
//机会补充详情
func ChanceReviseDetail(header *protocol.RequestHeader, request *protocol.ChanceReviseDetailRequest) (rsp *protocol.ChanceReviseDetailResponse, err error) {
var (
detail *models.ChanceReviseLog
provider *protocol.BaseUserInfo
)
if detail, err = models.GetChanceReviseLogById(request.Id); err != nil {
log.Error(err)
return
}
rsp = &protocol.ChanceReviseDetailResponse{}
if provider, err = agg.GetUserBaseInfo(detail.UserCompanyId, header.CompanyId); err != nil {
log.Error(err)
return
}
json.Unmarshal([]byte(detail.Data), &rsp.ChanceReviseData)
rsp.ChanceReviseData.Provider = provider
rsp.ChanceReviseData.CreateTime = detail.CreateAt.Unix() * 1000
rsp.ChanceId = detail.ChanceId
return
}
... ...
... ... @@ -167,11 +167,11 @@ func Comments(header *protocol.RequestHeader, request *protocol.CommentsRequest)
commentIds = append(commentIds, comment.Id)
rsp.Comments = append(rsp.Comments, item)
}
if len(commentIds) > 0 {
if !utils.ExecuteSqlByRoll(true, agg.GetIncrementSqlBatch("comment", "view_total", 1, commentIds...)) {
//
}
}
//if len(commentIds) > 0 {
// if !utils.ExecuteSqlByRoll(true, agg.GetIncrementSqlBatch("comment", "view_total", 1, commentIds...)) {
// //
// }
//}
return
}
... ... @@ -228,7 +228,7 @@ func CommentDetailsSingle(header *protocol.RequestHeader, request *protocol.Comm
Id: comment.Id,
Provider: baseUserInfo,
Content: comment.Content,
CreateTime: comment.CreateAt.Unix(),
CreateTime: comment.CreateAt.Unix() * 1000,
ViewTotal: comment.ViewTotal,
ZanTotal: comment.ZanTotal,
CommentTotal: comment.CommentTotal,
... ... @@ -237,6 +237,9 @@ func CommentDetailsSingle(header *protocol.RequestHeader, request *protocol.Comm
if exists, _ = models.ExitsChanceFavorite(header.UserId, header.CompanyId, comment.Id, protocol.MarkFlagZan); exists {
rsp.Comment.IsZan = true
}
if !utils.ExecuteSqlByRoll(true, agg.GetIncrementSqlBatch("comment", "view_total", 1, []int64{request.Id}...)) {
//
}
return
}
... ...
package contrab
import "github.com/astaxie/beego/toolbox"
var (
taskComputeRankScore = "0 10 0 * * *" //每0:5分 计算排行榜分数
)
func Run() {
taskRank := toolbox.NewTask("taskComputeRankScore", taskComputeRankScore, ComputeRankScore)
toolbox.AddTask("taskComputeRankScore", taskRank)
toolbox.StartTask()
}
... ...
package contrab
import (
"bytes"
"encoding/json"
"fmt"
"github.com/astaxie/beego/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/identity/idgen"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/internal/utils"
"opp/models"
"opp/protocol"
"reflect"
"sync"
"sync/atomic"
"time"
)
const (
RankGoroutineNum = 1
)
var ComputeRankScoreFlag int32
var rankList = initRankList()
func initRankList() []Rank {
var list []Rank
list = append(list, RankDiscovery{})
list = append(list, RankGrasp{})
list = append(list, RankComment{})
return list
}
type Rank interface {
RankUser(o RankOption) (error, RankResult)
RankDepartment(o RankOption) (error, RankResult)
}
type RankOption struct {
CompanyId int //公司编号
RankTypeId int //榜单类型编号
RankRangeId int //榜单范围编号
RankPeriodId int //赛季周期编号
Type int //Relation类型
RelationId int64 //对象id 用户编号 /部门编号
BeginTime time.Time
EndTime time.Time
Rank *models.Rank //排行榜
}
type RankResult struct{}
//计算排行分
func ComputeRankScore() (err error) {
var (
periods []*models.RankPeriod
)
defer func() {
if p := recover(); p != nil {
log.Error(p)
}
}()
if !atomic.CompareAndSwapInt32(&ComputeRankScoreFlag, 0, 1) {
log.Warn("ComputeRankScore is working", ComputeRankScoreFlag)
return fmt.Errorf("ComputeRankScore is working. try later")
} else {
defer utils.Profiling("【排行榜分数统计】 执行耗时")()
}
defer func() {
atomic.CompareAndSwapInt32(&ComputeRankScoreFlag, 1, 0)
}()
//1.l 查询进行中的赛季
if periods, err = models.GetRankPeriods(0, 0, []int{protocol.RankPeriodBegin}); err != nil {
return
}
//启用多个协程执行
var wg sync.WaitGroup
for i := 0; i < RankGoroutineNum; i++ {
index := i
work := func() {
defer func() {
if p := recover(); p != nil {
log.Error(p)
}
}()
if err = computeRankScore(index, wg, RankGoroutineNum, periods); err != nil {
log.Error(err)
}
}
go work()
}
wg.Wait()
//更新状态
//结束进行中 已到期的榜单
updateRankPeriodStatus(protocol.RankPeriodBegin, protocol.RankPeriodEnd)
//开始等待的榜单
updateRankPeriodStatus(protocol.RankPeriodWaiting, protocol.RankPeriodBegin)
return
}
func updateRankPeriodStatus(fromStatus int, toStatus int) {
var (
sql = `update rank_period set status=?,update_at=NOW() where status=? and UNIX_TIMESTAMP(end_time)<? `
)
if toStatus == protocol.RankPeriodBegin {
sql = `update rank_period set status=?,update_at=NOW() where status=? and ?>UNIX_TIMESTAMP(begin_time) `
}
orm := orm.NewOrm()
if _, err := orm.Raw(sql, toStatus, fromStatus, time.Now().Unix()).Exec(); err != nil {
log.Error(err)
return
}
}
func computeRankScore(index int, wg sync.WaitGroup, gNum int, periods []*models.RankPeriod) (err error) {
var (
rankRanges []*models.RankRange
rankRangeDatas []*models.RankRangeData
)
wg.Add(1)
defer wg.Done()
defer func() {
if p := recover(); p != nil {
log.Error(p)
}
}()
//2.查询对应 rank_type_id 的rank_data
for i := range periods {
period := periods[i]
if (period.Id % gNum) != index {
return
}
if rankRanges, err = models.GetRankRanges(period.CompanyId, period.RankTypeId); err == orm.ErrNoRows {
continue
}
//所有部门
depIdAll, e := models.GetDepartmentIdsByCompanyId(period.CompanyId)
if e != nil {
log.Error(e)
continue
}
//所有用户
userIdAll, e := models.GetUserCompanyIdAll(period.CompanyId)
if e != nil {
log.Error(e)
continue
}
//按类型
//3.查询用户列表/部门列表
logProcessInfo(period)
for j := range rankRanges {
var relationIds []int64
rankRange := rankRanges[j]
if rankRange.Type == protocol.RankRangeTypeAllCompanyUser {
relationIds = userIdAll
} else if rankRange.Type == protocol.RankRangeTypeAllCompanyDepartment {
relationIds = depIdAll
} else {
if rankRangeDatas, err = models.GetRankRangeDataList(rankRange.Id); err == orm.ErrNoRows {
continue
}
}
for k := range rankRangeDatas {
relationIds = append(relationIds, int64(rankRangeDatas[k].RelationId))
}
updateRankByRelationIds(relationIds, period, rankRange)
}
}
//4.调用统计接口列表
//5.汇聚所有的rankResult
//6.查询当前user_rank是否有这条记录,比较记录里面数据是否有变化
//7.更新到表/插入
return nil
}
func logProcessInfo(period *models.RankPeriod) {
log.Debug(fmt.Sprintf("【排行榜统计】 公司:%v 周期编号:%v 赛季名称:%v (榜单类型:%v) ", period.CompanyId, period.Id, period.SeasonName, period.RankTypeId))
}
func logScoreChanceLog(itemName string, old float64, new float64) string {
return fmt.Sprintf(" [%v %v->%v]", itemName, old, new)
}
//更新排行榜按关联id
func updateRankByRelationIds(relationIds []int64, period *models.RankPeriod, rankRange *models.RankRange) {
var option RankOption
for i := range relationIds {
option = RankOption{
CompanyId: period.CompanyId,
RankTypeId: period.RankTypeId,
RankRangeId: rankRange.Id,
RankPeriodId: period.Id,
RelationId: relationIds[i],
Type: int(rankRange.Type),
BeginTime: period.BeginTime,
EndTime: period.EndTime,
}
updateRank(option)
}
updateTotalScore(option)
}
//更新榜单数据
func updateRank(o RankOption) {
var (
rank *models.Rank
e error
isNew = false
rankTmp models.Rank
)
if rank, e = models.GetRank(o.CompanyId, o.RankTypeId, o.RankRangeId, o.RankPeriodId, o.RelationId); e != nil {
isNew = true
rank = &models.Rank{
Id: idgen.Next(),
CompanyId: o.CompanyId,
RankTypeId: o.RankTypeId,
RankRangeId: o.RankRangeId,
RankPeriodId: o.RankPeriodId,
RelationId: o.RelationId,
UpdateAt: time.Now(),
CreateAt: time.Now(),
EnableStatus: protocol.Valid,
Type: int8(o.Type),
}
} else {
rankTmp = *rank
if rank.EnableStatus == protocol.InValid {
rank.EnableStatus = protocol.Valid
}
}
o.Rank = rank
for i := range rankList {
item := rankList[i]
if o.Type == protocol.RankRangeTypeAllCompanyDepartment || o.Type == protocol.RankRangeTypeAllSpecifyDepartment {
item.RankDepartment(o)
continue
}
item.RankUser(o)
}
if isNew {
if _, e = models.AddRank(rank); e != nil {
log.Error(e)
}
log.Debug(fmt.Sprintf("【排行榜统计】 新增加 周期编号:%v 公司:%v 评分者编号:%v (榜单类型:%v 参与类型:%v) ", rank.RankPeriodId, rank.CompanyId, rank.RelationId, rank.RankTypeId, rank.RankRangeId))
} else {
//数据有变化的时候才更新到表
if !reflect.DeepEqual(rankTmp, *rank) {
rank.UpdateAt = time.Now()
if e = models.UpdateRankById(rank); e != nil {
log.Error(e)
}
log.Debug(fmt.Sprintf("【排行榜统计】 更新 周期编号:%v 公司:%v 评分者编号:%v (榜单类型:%v 参与类型:%v) %v", rank.RankPeriodId, rank.CompanyId, rank.RelationId, rank.RankTypeId, rank.RankRangeId,
checkScoreChange(rankTmp, *rank)))
}
}
}
func checkScoreChange(old, new models.Rank) string {
changeLog := bytes.NewBuffer(nil)
if old.TotalScore != new.TotalScore {
changeLog.WriteString(logScoreChanceLog("总分", old.TotalScore, new.TotalScore))
}
if old.DiscoveryScore != new.DiscoveryScore {
changeLog.WriteString(logScoreChanceLog("发现分", old.DiscoveryScore, new.DiscoveryScore))
}
if old.GraspScore != new.GraspScore {
changeLog.WriteString(logScoreChanceLog("把握分", old.GraspScore, new.GraspScore))
}
if old.DiscoveryTotal != new.DiscoveryTotal {
changeLog.WriteString(logScoreChanceLog("发现总数", float64(old.DiscoveryTotal), float64(new.DiscoveryTotal)))
}
if old.CommentTotal != new.CommentTotal {
changeLog.WriteString(logScoreChanceLog("评论总数", float64(old.CommentTotal), float64(new.CommentTotal)))
}
if old.EnableStatus != new.EnableStatus {
changeLog.WriteString(logScoreChanceLog("状态", float64(old.EnableStatus), float64(new.EnableStatus)))
}
return changeLog.String()
}
//更新排行榜总分 //更新总分 系数*发现分 + 系数*把握分
func updateTotalScore(o RankOption) {
var (
config *models.SysConfig
err error
scoreConfig protocol.ScoreConfig
sql = `update rank set total_score=discovery_score*%v + grasp_score*%v where
company_id=%v and rank_type_id=%v and rank_period_id=%v`
)
if config, err = models.GetSysConfigByCompanyId(int(o.CompanyId), models.KeyScore); err != nil {
err = protocol.NewErrWithMessage(5510)
log.Error(err)
return
}
if err = json.Unmarshal([]byte(config.Content), &scoreConfig); err != nil {
//err = protocol.NewErrWithMessage(5510)
log.Error(err)
return
}
if scoreConfig.SumScore == nil {
log.Error(o.CompanyId, config.Content, "未设置总分配置")
return
}
sql = fmt.Sprintf(sql,
scoreConfig.SumScore.DiscoveryFactor,
scoreConfig.SumScore.CatchFactor, o.CompanyId, o.RankTypeId, o.RankPeriodId)
orm := orm.NewOrm()
if _, err := orm.Raw(sql).Exec(); err != nil {
log.Error(err)
return
}
}
//手动单赛季统计
func ComputeRankScoreByPeriod(periodId int) (err error) {
//启用多个协程执行
var (
wg sync.WaitGroup
period *models.RankPeriod
)
if period, err = models.GetRankPeriodById(periodId); err != nil {
log.Error(err)
err = protocol.NewCustomMessage(1, "赛季不存在")
return
}
computeRankScore(0, wg, 1, []*models.RankPeriod{period})
wg.Wait()
return
}
//发现计算规则
type RankDiscovery struct{}
func (rank RankDiscovery) RankUser(o RankOption) (err error, result RankResult) {
var (
sql = `select sum(discovery_score) score,count(0) total from chance where user_id =? and review_status=3 and status=1 and enable_status=1
and UNIX_TIMESTAMP(approve_time)>=? and UNIX_TIMESTAMP(approve_time)<?`
score float64
total int
)
orm := orm.NewOrm()
if err = orm.Raw(sql, o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix()).QueryRow(&score, &total); err != nil {
log.Error(err)
return
}
o.Rank.DiscoveryScore = score
o.Rank.DiscoveryTotal = total
return
}
func (rank RankDiscovery) RankDepartment(o RankOption) (err error, result RankResult) {
var (
sql = `select sum(discovery_score) score,count(0) total from chance where department_id =? and review_status=3 and status=1 and enable_status=1
and UNIX_TIMESTAMP(approve_time)>=? and UNIX_TIMESTAMP(approve_time)<?
`
score float64
total int
)
orm := orm.NewOrm()
if err = orm.Raw(sql, o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix()).QueryRow(&score, &total); err != nil {
log.Error(err)
return
}
o.Rank.DiscoveryScore = score
o.Rank.DiscoveryTotal = total
return
}
//把握分计算规则
type RankGrasp struct{}
func (rank RankGrasp) RankUser(o RankOption) (err error, result RankResult) {
var (
sql = `
select sum(a.user_grasp_score) score from(
select user_grasp_score from achievement where user_company_id=? and status=1 and UNIX_TIMESTAMP(create_at) >=? and UNIX_TIMESTAMP(create_at)<?
UNION ALL
select b.user_grasp_score from (
select user_grasp_score,achievement_id from achievement_provider where user_company_id=? and UNIX_TIMESTAMP(create_at) >=? and UNIX_TIMESTAMP(create_at)<?
)b inner join achievement c on b.achievement_id = c.id and status=1
) a
`
score float64
)
orm := orm.NewOrm()
if err = orm.Raw(sql, o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix(), o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix()).QueryRow(&score); err != nil {
log.Error(err)
return
}
o.Rank.GraspScore = score
return
}
func (rank RankGrasp) RankDepartment(o RankOption) (err error, result RankResult) {
var (
sql = `select sum(a.user_grasp_score) score from(
select user_grasp_score from achievement where department_id=? and status=1 and UNIX_TIMESTAMP(create_at) >=? and UNIX_TIMESTAMP(create_at)<?
UNION ALL
select b.user_grasp_score from (
select user_grasp_score,achievement_id from achievement_provider where department_id=? and UNIX_TIMESTAMP(create_at) >=? and UNIX_TIMESTAMP(create_at)<?
)b inner join achievement c on b.achievement_id = c.id and status=1
) a
`
score float64
)
orm := orm.NewOrm()
if err = orm.Raw(sql, o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix(), o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix()).QueryRow(&score); err != nil {
log.Error(err)
return
}
o.Rank.GraspScore = score
return
}
//评论数计算规则
type RankComment struct{}
func (rank RankComment) RankUser(o RankOption) (err error, result RankResult) {
var (
sql = `select count(0) total from comment where user_id=? and UNIX_TIMESTAMP(create_at) >=? and UNIX_TIMESTAMP(create_at)<?
`
total int
)
orm := orm.NewOrm()
if err = orm.Raw(sql, o.RelationId, o.BeginTime.Unix(), o.EndTime.Unix()).QueryRow(&total); err != nil {
log.Error(err)
return
}
o.Rank.CommentTotal = total
return
}
func (rank RankComment) RankDepartment(o RankOption) (err error, result RankResult) {
var (
sql = `select count(0) total from comment where user_id in (%v) and UNIX_TIMESTAMP(create_at) >=%v and UNIX_TIMESTAMP(create_at)<%v
`
sqlUserDepartment = `select user_company_id from user_department where department_id=? and enable_status=1`
total int
userIds []int
)
orm := orm.NewOrm()
if _, err = orm.Raw(sqlUserDepartment, o.RelationId).QueryRows(&userIds); err != nil {
log.Error(err)
return
}
if len(userIds) == 0 {
return
}
sql = fmt.Sprintf(sql, utils.JoinInts(userIds, ","), o.BeginTime.Unix(), o.EndTime.Unix())
if err = orm.Raw(sql).QueryRow(&total); err != nil {
log.Error(err)
return
}
o.Rank.CommentTotal = total
return
}
... ...
... ... @@ -2,9 +2,12 @@ package department
import (
"encoding/json"
"github.com/astaxie/beego/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/models"
"opp/protocol"
"opp/services/agg"
"sort"
)
func Departments(header *protocol.RequestHeader, request *protocol.DepartmentsRequest) (rsp *protocol.DepartmentsResponse, err error) {
... ... @@ -29,6 +32,17 @@ func Departments(header *protocol.RequestHeader, request *protocol.DepartmentsRe
log.Error(err)
return
}
case protocol.DepartmentRoot:
if departments, err = models.GetDepartmentByCompanyId(header.CompanyId); err != nil {
log.Error(err)
return
}
for i := range departments {
item := departments[i]
walkDepartment(tmpDepartment, item)
}
rsp.Departments = tmpDepartment.Departments
//rsp.Departments = rsp.GetRootDepartment()
default:
break
}
... ... @@ -38,8 +52,9 @@ func Departments(header *protocol.RequestHeader, request *protocol.DepartmentsRe
//遍历部门
func walkDepartment(to *protocol.Department, dfrom *models.Department) (err error) {
var newD *protocol.Department = &protocol.Department{
DepartmentId: dfrom.Id,
DepartmentId: int(dfrom.Id),
Name: dfrom.Name,
CreateTime: dfrom.CreateAt,
Departments: []*protocol.Department{},
}
if len(dfrom.Managers) > 0 {
... ... @@ -48,7 +63,7 @@ func walkDepartment(to *protocol.Department, dfrom *models.Department) (err erro
return
}
}
if to.DepartmentId == dfrom.ParentId {
if to.DepartmentId == int(dfrom.ParentId) {
to.Departments = append(to.Departments, newD)
}
for i := range to.Departments {
... ... @@ -56,3 +71,101 @@ func walkDepartment(to *protocol.Department, dfrom *models.Department) (err erro
}
return nil
}
//多部门统计
func Statistics(header *protocol.RequestHeader, request *protocol.DepartmentStatisticsRequest) (rsp *protocol.DepartmentStatisticsResponse, err error) {
var (
departmentsResponse *protocol.DepartmentsResponse
)
rsp = &protocol.DepartmentStatisticsResponse{}
if departmentsResponse, err = Departments(header, &protocol.DepartmentsRequest{Type: 1}); err != nil && err != orm.ErrNoRows {
log.Error(err)
return
}
//公司部门统计
companyDep := departmentsResponse.GetCompanyDepartment()
if companyDep.DepartmentId > 0 {
var companyDepStatistic *protocol.DepartmentStatisticResponse
if companyDepStatistic, err = DepartmentStatistic(header, &protocol.DepartmentStatisticRequest{DepartmentId: int64(companyDep.DepartmentId)}); err != nil {
log.Error(err)
return
}
rsp.List = append(rsp.List, &companyDepStatistic.DepartmentStatistic)
rsp.Total += companyDepStatistic.DepartmentStatistic.ChanceApprovedTotal + companyDepStatistic.DepartmentStatistic.AchievementTotal
}
departments := departmentsResponse.GetRootDepartments()
iterateDepartments := func(call func(d *protocol.Department) *protocol.DepartmentStatistics) {
for i := range departments {
department := departments[i]
item := call(department)
item.Dep = protocol.Dep{
Id: department.DepartmentId,
Name: department.Name,
Time: department.CreateTime.Unix(),
}
rsp.List = append(rsp.List, item)
rsp.Total += item.ChanceApprovedTotal + item.AchievementTotal
}
}
switch request.Type {
case protocol.StatisticApproved:
callBack := func(d *protocol.Department) *protocol.DepartmentStatistics {
item := &protocol.DepartmentStatistics{}
dIds := departmentsResponse.GetChildDepartmentIds(d, true)
item.AchievementTotal, _ = agg.AchievementDepartmentStatic(header, 0, dIds)
item.ChanceApprovedTotal, _ = agg.GetChancePool(header.UserId, header.CompanyId, 0, d.DepartmentId, true, 0, 0, nil)
item.ACTotal = item.AchievementTotal + item.ChanceApprovedTotal
item.ChanceApprovingTotal, _ = agg.ChanceApprovingStatistic(header, departmentsResponse.GetChildDepartmentIds(d, true))
return item
}
iterateDepartments(callBack)
break
//case protocol.StatisticApproving:
// iterateDepartments(func(d *protocol.Department) *protocol.DepartmentStatistics {
// rsp := &protocol.DepartmentStatistics{}
// dIds := departmentsResponse.GetChildDepartmentIds(d, true)
// rsp.AchievementTotal, _ = agg.AchievementDepartmentStatic(header, 0, dIds)
// rsp.ChanceApprovedTotal, _ = agg.GetChancePool(header.UserId, header.CompanyId, 0, d.DepartmentId, 0, 0, nil)
// rsp.ACTotal = rsp.AchievementTotal + rsp.ChanceApprovedTotal
// rsp.ChanceApprovingTotal, _ = agg.ChanceApprovingStatistic(header, departmentsResponse.GetChildDepartmentIds(d, true))
// return rsp
// })
// break
default:
err = protocol.NewErrWithMessage(2)
return
}
sort.Stable(rsp)
sort.Stable(sort.Reverse(rsp))
return
}
//单部门统计
func DepartmentStatistic(header *protocol.RequestHeader, request *protocol.DepartmentStatisticRequest) (rsp *protocol.DepartmentStatisticResponse, err error) {
var (
dIds []int
deparment *models.Department
)
rsp = &protocol.DepartmentStatisticResponse{}
if deparment, err = models.GetDepartmentById(request.DepartmentId); err != nil {
log.Error(err)
return
}
departmentStatistic := protocol.DepartmentStatistics{}
departmentStatistic.Dep = protocol.Dep{
Id: int(deparment.Id),
Name: deparment.Name,
}
if dIds, err = agg.GetDepartmentIds(header.CompanyId, request.DepartmentId, false); err != nil {
log.Error(err)
return
}
departmentStatistic.AchievementTotal, _ = agg.AchievementDepartmentStatic(header, 0, dIds)
departmentStatistic.ChanceApprovedTotal, _ = agg.GetChancePool(header.UserId, header.CompanyId, 0, int(request.DepartmentId), false, 0, 0, nil)
departmentStatistic.ACTotal = departmentStatistic.AchievementTotal + departmentStatistic.ChanceApprovedTotal
departmentStatistic.ChanceApprovingTotal, _ = agg.ChanceApprovingStatistic(header, dIds)
rsp.DepartmentStatistic = departmentStatistic
return
}
... ...
package department
import (
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"opp/protocol"
"sort"
"testing"
)
func TestGetRootDepartment(t *testing.T) {
sub := []*protocol.Department{
{DepartmentId: 100, Name: "100"},
{DepartmentId: 200, Name: "200"},
}
Departments := []*protocol.Department{
{DepartmentId: 1, Name: "1", Departments: sub},
{DepartmentId: 2, Name: "2"},
{DepartmentId: 3, Name: "3", Departments: []*protocol.Department{{DepartmentId: 31, Name: "3-1", Departments: sub}, {DepartmentId: 32, Name: "3-2"}}},
{DepartmentId: 4, Name: "4", Departments: []*protocol.Department{{DepartmentId: 41, Name: "4-1"}, {DepartmentId: 42, Name: "4-2", Departments: sub}}},
}
var deps protocol.DepartmentsResponse = protocol.DepartmentsResponse{
Departments: []*protocol.Department{
{DepartmentId: 0, Name: "0", Departments: Departments},
},
}
depList := deps.GetRootDepartments()
for i := range depList {
d := depList[i]
t.Log("部门:", d.DepartmentId, deps.GetChildDepartmentIds(d, true))
}
}
//排序
func TestSortDepartmentStastics(t *testing.T) {
s := &protocol.DepartmentStatisticsResponse{
List: []*protocol.DepartmentStatistics{
//{ChanceApprovedTotal: 12, AchievementTotal: 8, ACTotal: 20},
//{ChanceApprovedTotal: 8, AchievementTotal: 12, ACTotal: 20},
//{ChanceApprovedTotal: 20, AchievementTotal: 20, ACTotal: 40},
//{ChanceApprovedTotal: 5, AchievementTotal: 10, ACTotal: 15},
{Dep: protocol.Dep{Id: 3}, ChanceApprovedTotal: 6, AchievementTotal: 10, ACTotal: 16},
{Dep: protocol.Dep{Id: 2}, ChanceApprovedTotal: 7, AchievementTotal: 9, ACTotal: 16},
{Dep: protocol.Dep{Id: 1}, ChanceApprovedTotal: 7, AchievementTotal: 10, ACTotal: 17},
{Dep: protocol.Dep{Id: 0}, ChanceApprovedTotal: 10, AchievementTotal: 10, ACTotal: 20},
{Dep: protocol.Dep{Id: 4}, ChanceApprovedTotal: 6, AchievementTotal: 10, ACTotal: 16},
//{ChanceApprovedTotal: 20, AchievementTotal: 30, ACTotal: 50},
},
//List: []*protocol.DepartmentStatistics{
// {ChanceApprovingTotal: 10},
// {ChanceApprovingTotal: 10},
// {ChanceApprovingTotal: 30},
// {ChanceApprovingTotal: 40},
// {ChanceApprovingTotal: 60},
// {ChanceApprovingTotal: 50},
//},
}
sort.Stable(s)
sort.Stable(sort.Reverse(s))
t.Log(common.AssertJson(s))
}
... ...
... ... @@ -21,6 +21,13 @@ func MessageCenter(header *protocol.RequestHeader, request *protocol.MessageCent
)
rsp = &protocol.MessageCenterResponse{}
rsp.Totals = make([]*protocol.MessageTotal, 0)
//注入公司校验
if err = agg.CheckCompanyPermission(header.CompanyId); err != nil {
log.Error(err)
err = protocol.NewErrWithMessage(4141)
return
}
if request.MsgType&protocol.MsgTypeInteraction > 0 {
if request.MsgType&protocol.MsgTypeThumbUp == 0 {
request.MsgType |= protocol.MsgTypeThumbUp
... ... @@ -31,6 +38,9 @@ func MessageCenter(header *protocol.RequestHeader, request *protocol.MessageCent
if request.MsgType&protocol.MsgTypeAuditBy == 0 {
request.MsgType |= protocol.MsgTypeAuditBy
}
if request.MsgType&protocol.MsgTypeChanceRevise == 0 {
request.MsgType |= protocol.MsgTypeChanceRevise
}
}
err = models.GetUserMsgTotals(header.UserId, header.CompanyId, request.MsgType, &rsp.Totals)
if rsp.Totals == nil || len(rsp.Totals) == 0 {
... ... @@ -51,6 +61,10 @@ func MessageCenter(header *protocol.RequestHeader, request *protocol.MessageCent
interactionCount += item.MsgTotal
continue
}
if item.MsgType == protocol.MsgTypeChanceRevise {
interactionCount += item.MsgTotal
continue
}
if item.MsgType == protocol.MsgTypeBulletin {
var tmpTotal int
models.GetBulletinUserMsgTotals(header.UserId, header.CompanyId, request.MsgType, &tmpTotal)
... ... @@ -586,6 +600,42 @@ func MsgChanceThumbUp(header *protocol.RequestHeader, request *protocol.MsgChanc
return
}
//消息中心-机会补充
func MsgChanceRevise(header *protocol.RequestHeader, request *protocol.MsgChanceReviseRequest) (rsp *protocol.MsgChanceReviseResponse, err error) {
var (
myChances []protocol.ChanceReviseItemOrm
total int
provider *protocol.BaseUserInfo
)
if total, err = models.GetChanceReviseMsg(header.UserId, request.LastId, request.PageSize, protocol.MsgTypeChanceRevise, &myChances); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
rsp = &protocol.MsgChanceReviseResponse{Total: total}
rsp.List = make([]protocol.MsgCommonListItem, 0)
for i := 0; i < len(myChances); i++ {
chance := myChances[i]
commItem := protocol.MsgCommonListItem{}
commItem.Chance, commItem.ChanceStatus = agg.SetChanceItem(header, chance.CommChanceItemOrm)
agg.SetMsgItem(header, chance.MsgItemOrm, &commItem)
if provider, err = agg.GetUserBaseInfo(chance.SenderUserId, header.CompanyId); err != nil {
log.Error(err)
return
}
commItem.Chance.Provider = provider
commItem.ChanceId = chance.ChanceId
commItem.ReviewStatus = chance.ReviewStatus
commItem.Message = chance.Message
rsp.List = append(rsp.List, commItem)
}
return
}
//H5公告详情
func H5Announcement(header *protocol.RequestHeader, request *protocol.AnnouncementRequest) (rsp *protocol.AnnouncementResponse, err error) {
var (
... ...
package rank
import (
"fmt"
"github.com/astaxie/beego/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/models"
"opp/protocol"
"opp/services/contrab"
)
//排行榜
func GetRankList(header *protocol.RequestHeader, request *protocol.GetRankListRequest) (rsp *protocol.GetRankListResponse, err error) {
var (
ranks []protocol.RankItem
selfRank *protocol.RankItem
rankType *models.RankType
rankRange *models.RankRange
rankPeriod *models.RankPeriod
itemKeys []string
//itemNames []string
departments []*models.Department
departmentId int64
hasDepartmentInRank bool = true
currentTotal int
)
rsp = &protocol.GetRankListResponse{
Self: make([]protocol.RankItem, 0),
Lists: make([][]protocol.RankItem, 0),
}
if rankRange, err = models.GetRankRangeById(request.RankRangeId); err != nil {
log.Error(err)
return
}
{
//测试日志
if rankType, err = models.GetRankTypeById(request.RankTypeId); err != nil {
log.Error(err)
return
}
if rankPeriod, err = models.GetRankPeriodById((request.RankPeriodId)); err != nil {
log.Error(err)
return
}
log.Debug(fmt.Sprintf("用户:%v 获取排行榜 :%v %v %v", header.UserId, rankType.Name, rankRange.Name, rankPeriod.SeasonName))
}
itemKeys = request.SortItemKeys
if len(itemKeys) == 0 {
if itemKeys, _, err = models.GetRankItemKeys(header.CompanyId, request.RankTypeId); err != nil && err != orm.ErrNoRows {
log.Error(err)
return
}
}
if len(itemKeys) == 0 {
return
}
//rsp.SortItems = itemNames
if rankRange.Type == protocol.RankRangeTypeAllCompanyDepartment || rankRange.Type == protocol.RankRangeTypeAllSpecifyDepartment {
if departments, err = models.GetDepartmentByUser(header.UserId); err != nil {
log.Error(err)
return
}
if len(departments) == 0 {
hasDepartmentInRank = false
}
}
for i := range itemKeys {
key := itemKeys[i]
if rankRange.Type == protocol.RankRangeTypeAllCompanyDepartment || rankRange.Type == protocol.RankRangeTypeAllSpecifyDepartment {
if rsp.Total, err = models.GetRanksByDepartment(header.CompanyId, request.RankTypeId, request.RankRangeId, request.RankPeriodId, key, request.PageIndex, request.PageSize, &ranks); err != nil && err != orm.ErrNoRows {
log.Error(err)
return
}
if hasDepartmentInRank {
if departmentId > 0 {
if err = models.GetRanksByDepartmentSelf(header.CompanyId, request.RankTypeId, request.RankRangeId, request.RankPeriodId, key, departmentId, &selfRank); err != nil {
log.Error(err)
return
}
} else if hasDepartmentInRank {
for i := range departments {
d := departments[i]
if err = models.GetRanksByDepartmentSelf(header.CompanyId, request.RankTypeId, request.RankRangeId, request.RankPeriodId, key, int64(d.Id), &selfRank); err != nil {
log.Error(err)
return
}
if selfRank != nil {
departmentId = int64(d.Id)
break
}
}
if departmentId == 0 {
hasDepartmentInRank = false
}
}
}
} else if rankRange.Type == protocol.RankRangeTypeAllCompanyUser || rankRange.Type == protocol.RankRangeTypeSpecifyUser {
if rsp.Total, err = models.GetRanksByUser(header.CompanyId, request.RankTypeId, request.RankRangeId, request.RankPeriodId, key, request.PageIndex, request.PageSize, &ranks); err != nil && err != orm.ErrNoRows {
log.Error(err)
return
}
if err = models.GetRanksByUserSelf(header.CompanyId, request.RankTypeId, request.RankRangeId, request.RankPeriodId, key, header.UserId, &selfRank); err != nil {
log.Error(err)
return
}
}
if selfRank != nil {
rsp.Self = append(rsp.Self, *selfRank)
}
if len(ranks) > 0 {
currentTotal = len(ranks)
rsp.Lists = append(rsp.Lists, ranks)
}
}
if len(rsp.Lists) > 0 && len(itemKeys) != len(rsp.Lists) {
log.Error("数据项不匹配", itemKeys, len(rsp.Lists))
err = protocol.NewErrWithMessage(1)
return
}
if len(rsp.Lists) > 0 {
lists := make([][]protocol.RankItem, 0)
for i := 0; i < currentTotal; i++ {
items := make([]protocol.RankItem, 0)
for j := 0; j < len(itemKeys); j++ {
items = append(items, rsp.Lists[j][i])
}
lists = append(lists, items)
}
rsp.Lists = lists
}
return
}
//获取榜单类型列表
func GetRankType(header *protocol.RequestHeader, request *protocol.GetRankTypeRequest) (rsp *protocol.GetRankTypeResponse, err error) {
var (
lists []*models.RankType
)
rsp = &protocol.GetRankTypeResponse{
List: make([]protocol.NameItem, 0),
}
if lists, err = models.GetRankTypes(header.CompanyId); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
for i := range lists {
rsp.List = append(rsp.List, protocol.NameItem{Id: lists[i].Id, Name: lists[i].Name})
}
return
}
//获取榜单范围列表
func GetRankRange(header *protocol.RequestHeader, request *protocol.GetRankRangeRequest) (rsp *protocol.GetRankRangeResponse, err error) {
var (
lists []*models.RankRange
)
rsp = &protocol.GetRankRangeResponse{
List: make([]protocol.RankRange, 0),
}
if request.RankTypeId == 0 {
return
}
if lists, err = models.GetRankRanges(int(header.CompanyId), request.RankTypeId); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
for i := range lists {
if lists[i].Status != 0 { //状态为隐藏的过滤
continue
}
item := protocol.RankRange{
Id: lists[i].Id,
Name: lists[i].Name,
}
if lists[i].Type == protocol.RankRangeTypeAllCompanyDepartment || lists[i].Type == protocol.RankRangeTypeAllSpecifyDepartment {
item.Type = protocol.RankRangeTypeDepartment
} else {
item.Type = protocol.RankRangeTypeUser
}
rsp.List = append(rsp.List, item)
}
return
}
//获取排行榜周期列表
func GetRankPeriods(header *protocol.RequestHeader, request *protocol.GetRankPeriodsRequest) (rsp *protocol.GetRankPeriodsResponse, err error) {
var (
lists []*models.RankPeriod
)
rsp = &protocol.GetRankPeriodsResponse{List: make([]protocol.RankPeriod, 0)}
if request.RankTypeId == 0 {
return
}
if lists, err = models.GetRankPeriods(int(header.CompanyId), request.RankTypeId, []int{protocol.RankPeriodBegin, protocol.RankPeriodEnd}); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
for i := range lists {
item := lists[i]
rsp.List = append(rsp.List, protocol.RankPeriod{
Id: item.Id,
SeasonName: item.SeasonName,
BeginTime: item.BeginTime.Unix() * 1000,
EndTime: item.EndTime.Unix() * 1000,
})
}
return
}
//获取排行榜评比项
func GetRankSortItems(header *protocol.RequestHeader, request *protocol.GetRankSortItemsRequest) (rsp *protocol.GetRankSortItemsResponse, err error) {
var (
sortItems []protocol.RankSortItem
)
rsp = &protocol.GetRankSortItemsResponse{
RankSortItems: make([]protocol.RankSortItem, 0),
}
if request.RankTypeId == 0 {
return
}
if err = models.GetRankItems(header.CompanyId, request.RankTypeId, &sortItems); err != nil {
if err == orm.ErrNoRows {
err = nil
return
}
log.Error(err)
return
}
if len(sortItems) > 0 {
rsp.RankSortItems = sortItems
}
if len(sortItems) > 4 {
rsp.RankSortItems = sortItems[0:4]
return
}
return
}
//手动计算排行榜
func ComputeRankScore(header *protocol.RequestHeader, request *protocol.ComputeRankScoreRequest) (rsp *protocol.ComputeRankScoreResponse, err error) {
var ()
rsp = &protocol.ComputeRankScoreResponse{}
if request.RankPeriodId > 0 {
if err = contrab.ComputeRankScoreByPeriod(request.RankPeriodId); err != nil {
log.Error(err)
err = protocol.NewCustomMessage(1, err.Error())
return
}
err = protocol.NewSuccessWithMessage("排行榜统计成功")
return
}
if err = contrab.ComputeRankScore(); err != nil {
log.Error(err)
err = protocol.NewCustomMessage(1, err.Error())
return
}
err = protocol.NewSuccessWithMessage("排行榜统计成功")
return
}
... ...
... ... @@ -370,70 +370,83 @@ func UserStatistics(header *protocol.RequestHeader, request *protocol.UserStatis
rsp = &protocol.UserStatisticsResponse{}
//buf :=bytes.NewBuffer(nil)
//buf.WriteString(fmt.Sprintf("用户中心-统计信息 user:%v type_total:%v \n",header.UserId,request.TypeTotal))
for flag = 1; flag <= (protocol.MyAuditChanceReturn); flag = flag << 1 {
for flag = 1; flag <= (protocol.MyGraspAchievement); flag = flag << 1 {
total = 0
switch flag {
case protocol.CollectStatic: //收藏
if total, err = models.GetChanceCollect(header.UserId, 0, 0, nil); err != nil {
log.Error(err)
}
break
case protocol.ZanStatic: //点赞
if total, err = models.GetChanceThumbUp(header.UserId, 0, 0, nil); err != nil {
log.Error(err)
}
break
case protocol.CommentStatic: //评论
if total, err = models.GetChanceComment(header.UserId, 0, 0, nil); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChance:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusAuditging, protocol.ReviewStatusReturn, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChanceWait:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusAuditging); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChancePass:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChanceReturn:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusReturn); err != nil {
log.Error(err)
}
break
case protocol.MyAuditChance:
var total1, total2 int
if total1, err = agg.MyApproveStatic(header, protocol.ReviewStatusReturn, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
if total2, err = agg.MyApproveEnableStatic(header, protocol.ReviewStatusAuditging); err != nil {
log.Error(err)
}
total = total1 + total2
break
case protocol.MyAuditChanceWait:
if total, err = agg.MyApproveEnableStatic(header, protocol.ReviewStatusAuditging); err != nil {
log.Error(err)
}
break
case protocol.MyAuditChancePass:
if total, err = agg.MyApproveStatic(header, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
break
case protocol.MyAuditChanceReturn:
if total, err = agg.MyApproveStatic(header, protocol.ReviewStatusReturn); err != nil {
log.Error(err)
if flag&request.TypeTotal > 0 {
switch flag {
case protocol.CollectStatic: //收藏
if total, err = models.GetChanceCollect(header.UserId, 0, 0, nil); err != nil {
log.Error(err)
}
break
case protocol.ZanStatic: //点赞
if total, err = models.GetChanceThumbUp(header.UserId, 0, 0, nil); err != nil {
log.Error(err)
}
break
case protocol.CommentStatic: //评论
if total, err = models.GetChanceComment(header.UserId, 0, 0, nil); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChance:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusAuditging, protocol.ReviewStatusReturn, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChanceWait:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusAuditging); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChancePass:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
break
case protocol.MyCommitChanceReturn:
if total, err = agg.MyChanceStatic(header, protocol.ReviewStatusReturn); err != nil {
log.Error(err)
}
break
case protocol.MyAuditChance:
var total1, total2 int
if total1, err = agg.MyApproveStatic(header, protocol.ReviewStatusReturn, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
if total2, err = agg.MyApproveEnableStatic(header, protocol.ReviewStatusAuditging); err != nil {
log.Error(err)
}
total = total1 + total2
break
case protocol.MyAuditChanceWait:
if total, err = agg.MyApproveEnableStatic(header, protocol.ReviewStatusAuditging); err != nil {
log.Error(err)
}
break
case protocol.MyAuditChancePass:
if total, err = agg.MyApproveStatic(header, protocol.ReviewStatusPass); err != nil {
log.Error(err)
}
break
case protocol.MyAuditChanceReturn:
if total, err = agg.MyApproveStatic(header, protocol.ReviewStatusReturn); err != nil {
log.Error(err)
}
break
case protocol.MyAchievements: //我提交的
if total, err = agg.MyGraspStatic(header); err != nil {
log.Error(err)
}
break
case protocol.MyGraspAchievement: //我把握的成果
if total, err = agg.MyGraspStatic(header); err != nil {
log.Error(err)
}
break
default:
break
}
break
}
if flag&request.TypeTotal > 0 {
rsp.Totals = append(rsp.Totals, protocol.TypeTotalItem{
... ...