Commit a46f1cc2 by chenxianqi

UPDATE

parent 699d2a1c
...@@ -8,10 +8,8 @@ import ( ...@@ -8,10 +8,8 @@ import (
"kefu_server/models" "kefu_server/models"
"kefu_server/services" "kefu_server/services"
"kefu_server/utils" "kefu_server/utils"
"strconv"
"time" "time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
...@@ -148,70 +146,3 @@ func (c *AuthController) Logout() { ...@@ -148,70 +146,3 @@ func (c *AuthController) Logout() {
} }
c.JSON(configs.ResponseSucess, "退出成功!", nil) c.JSON(configs.ResponseSucess, "退出成功!", nil)
} }
// RobotFetchTokenRequest struct
type RobotFetchTokenRequest struct {
AppSecret string `json:"app_secret"`
}
// RobotFetchToken admin logout
func (c *AuthController) RobotFetchToken() {
var request RobotFetchTokenRequest
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查", nil)
}
// valid
valid := validation.Validation{}
valid.Required(request.AppSecret, "app_secret").Message("app_secret不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil)
}
}
// current app Secret
_AppID, _ := beego.AppConfig.Int64("mimc_appId")
_AppKey := beego.AppConfig.String("mimc_appKey")
_AppSecret := beego.AppConfig.String("mimc_appSecret")
m51 := md5.New()
m51.Write([]byte(strconv.FormatInt(_AppID, 10) + _AppKey + _AppSecret))
currentAppSecret := hex.EncodeToString(m51.Sum(nil))
// check
if request.AppSecret != currentAppSecret {
c.JSON(configs.ResponseFail, "server error~", nil)
}
// create token
newToken := utils.GenerateToken(models.JwtKeyDto{ID: _AppID, UserName: _AppKey, AuthType: 0})
auth := c.AuthsRepository.GetAuthInfoWithTypeAndUID(0, 0)
if auth == nil {
newAuth := models.Auths{
Token: newToken,
UID: 0,
AuthType: 0,
UpdateAt: time.Now().Unix(),
CreateAt: time.Now().Unix(),
}
if _, err := c.AuthsRepository.Add(&newAuth); err != nil {
c.JSON(configs.ResponseFail, "授权失败!", nil)
}
} else {
_, err := c.AuthsRepository.Update(auth.ID, orm.Params{
"Token": newToken,
"UpdateAt": time.Now().Unix(),
})
if err != nil {
c.JSON(configs.ResponseFail, "授权失败!", nil)
}
}
c.JSON(configs.ResponseSucess, "授权成功!", &newToken)
}
...@@ -30,6 +30,11 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string, ...@@ -30,6 +30,11 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string,
msg = "sorry server error" msg = "sorry server error"
data = nil data = nil
} }
if status == configs.ResponseFail {
c.Ctx.Output.Status = 400
} else if status == configs.ResponseError {
c.Ctx.Output.Status = 500
}
c.Data["json"] = &models.ResponseDto{Code: status, Message: msg, Data: &data} c.Data["json"] = &models.ResponseDto{Code: status, Message: msg, Data: &data}
c.ServeJSON() c.ServeJSON()
c.StopRun() c.StopRun()
......
package controllers package controllers
import ( import (
"encoding/json"
"kefu_server/configs" "kefu_server/configs"
"kefu_server/models" "kefu_server/models"
"kefu_server/services" "kefu_server/services"
"kefu_server/utils"
"strconv" "strconv"
"time"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/validation"
) )
// ContactController struct // ContactController struct
...@@ -78,3 +84,104 @@ func (c *ContactController) DeleteAll() { ...@@ -78,3 +84,104 @@ func (c *ContactController) DeleteAll() {
} }
c.JSON(configs.ResponseSucess, "清空成功!", rows) c.JSON(configs.ResponseSucess, "清空成功!", rows)
} }
// Transfer transfer admin to admin
func (c *ContactController) Transfer() {
// GetAuthInfo
auth := c.GetAuthInfo()
adminRepository := services.GetAdminRepositoryInstance()
admin := adminRepository.GetAdmin(auth.UID)
// request body
var transferDto *models.TransferDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &transferDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
valid := validation.Validation{}
valid.Required(transferDto.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(transferDto.UserAccount, "user_account").Message("user不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil)
}
}
type adminData struct {
ID int64 `orm:"column(id)" json:"id"`
NickName string `json:"nickname"`
Avatar string `json:"avatar"`
}
toAdmin := adminRepository.GetAdmin(transferDto.ToAccount)
if toAdmin == nil {
c.JSON(configs.ResponseFail, "转接失败,转接客服不存在!", nil)
}
toAdminJSON, _ := json.Marshal(adminData{ID: toAdmin.ID, Avatar: toAdmin.Avatar, NickName: toAdmin.NickName})
// UserRepository instance
userRepository := services.GetUserRepositoryInstance()
user := userRepository.GetUser(transferDto.UserAccount)
if user == nil {
c.JSON(configs.ResponseFail, "转接失败用户ID不存在!", nil)
}
// message
message := models.Message{}
message.BizType = "transfer"
message.Platform = user.Platform
message.FromAccount = transferDto.UserAccount
message.Timestamp = time.Now().Unix()
message.TransferAccount = transferDto.ToAccount
// Send to forwarder
message.ToAccount = admin.ID
message.Payload = "您将" + user.NickName + "转接给" + toAdmin.NickName
messageString := utils.InterfaceToString(message)
utils.PushMessage(admin.ID, messageString)
utils.MessageInto(message)
// Send to forwarded customer service
message.ToAccount = transferDto.ToAccount
message.Payload = admin.NickName + "将" + user.NickName + "转接给您"
messageString = utils.InterfaceToString(message)
utils.PushMessage(toAdmin.ID, messageString)
utils.MessageInto(message)
// send to user
message.FromAccount = 1
message.ToAccount = transferDto.UserAccount
message.Delete = 1
message.Payload = string(toAdminJSON)
messageString = utils.InterfaceToString(message)
utils.PushMessage(user.ID, messageString)
utils.MessageInto(message)
// Transfer to the library for counting service times
servicesStatistical := models.ServicesStatistical{UserAccount: transferDto.UserAccount, ServiceAccount: transferDto.ToAccount, TransferAccount: admin.ID, Platform: user.Platform, CreateAt: time.Now().Unix()}
// StatisticalRepository instance
statisticalRepository := services.GetStatisticalRepositoryInstance()
_, _ = statisticalRepository.Add(&servicesStatistical)
// End the repeater's and user's current session
tk := time.NewTimer(1 * time.Second)
select {
case <-tk.C:
usersID := []int64{admin.ID, transferDto.UserAccount}
// ContactRepository instance
contactRepository := services.GetContactRepositoryInstance()
_, err := contactRepository.UpdateIsSessionEnd(usersID, 1)
if err != nil {
logs.Info(err)
}
}
c.JSON(configs.ResponseSucess, "转接成功!", nil)
}
...@@ -9,7 +9,6 @@ import ( ...@@ -9,7 +9,6 @@ import (
"kefu_server/utils" "kefu_server/utils"
"time" "time"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
...@@ -64,10 +63,7 @@ func (c *MessageController) List() { ...@@ -64,10 +63,7 @@ func (c *MessageController) List() {
} }
// push notify update current service contacts list // push notify update current service contacts list
// 待处理888 推送给客服的的聊天列表 utils.PushNewContacts(auth.UID)
// if len(robotlbrary.Robots) > 0 {
// robotlbrary.PushNewContacts(auth.UID, robotlbrary.Robots[0])
// }
c.JSON(configs.ResponseSucess, "success", &returnMessagePaginationDto) c.JSON(configs.ResponseSucess, "success", &returnMessagePaginationDto)
} }
...@@ -99,122 +95,3 @@ func (c *MessageController) Remove() { ...@@ -99,122 +95,3 @@ func (c *MessageController) Remove() {
c.JSON(configs.ResponseSucess, "删除成!", row) c.JSON(configs.ResponseSucess, "删除成!", row)
} }
// Transfer transfer admin to admin
func (c *MessageController) Transfer() {
// GetAuthInfo
auth := c.GetAuthInfo()
adminRepository := services.GetAdminRepositoryInstance()
admin := adminRepository.GetAdmin(auth.UID)
// request body
var transferDto *models.TransferDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &transferDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
valid := validation.Validation{}
valid.Required(transferDto.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(transferDto.UserAccount, "user_account").Message("user不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil)
}
}
type adminData struct {
ID int64 `orm:"column(id)" json:"id"`
NickName string `json:"nickname"`
Avatar string `json:"avatar"`
}
toAdmin := adminRepository.GetAdmin(transferDto.ToAccount)
if toAdmin == nil {
c.JSON(configs.ResponseFail, "转接失败,转接客服不存在!", nil)
}
toAdminJSON, _ := json.Marshal(adminData{ID: toAdmin.ID, Avatar: toAdmin.Avatar, NickName: toAdmin.NickName})
// UserRepository instance
userRepository := services.GetUserRepositoryInstance()
user := userRepository.GetUser(transferDto.UserAccount)
if user == nil {
c.JSON(configs.ResponseFail, "转接失败用户ID不存在!", nil)
}
// get one online robot
// robot, _ := services.GetRobotRepositoryInstance().GetRobotWithRandomOnline()
// 待处理888 记得要使用toAdminJSON
logs.Info(toAdminJSON)
// message
message := models.Message{}
message.BizType = "transfer"
message.FromAccount = transferDto.UserAccount
message.Timestamp = time.Now().Unix()
message.TransferAccount = transferDto.ToAccount
// Send to forwarder
// message.ToAccount = admin.ID
// message.Payload = "您将" + user.NickName + "转接给" + toAdmin.NickName
// messageJSONOne, _ := json.Marshal(message)
// messageStringOne := base64.StdEncoding.EncodeToString([]byte(messageJSONOne))
// 待处理888 发送消息
// robot.SendMessage(strconv.FormatInt(admin.ID, 10), []byte(messageStringOne))
utils.MessageInto(message)
// Send to forwarded customer service
// message.ToAccount = transferDto.ToAccount
// message.Payload = admin.NickName + "将" + user.NickName + "转接给您"
// messageJSONTwo, _ := json.Marshal(message)
// messageStringTwo := base64.StdEncoding.EncodeToString([]byte(messageJSONTwo))
// 待处理888 发送消息
// robot.SendMessage(strconv.FormatInt(transferDto.ToAccount, 10), []byte(messageStringTwo))
utils.MessageInto(message)
// send to user
// message.FromAccount = robot.ID
// message.ToAccount = transferDto.UserAccount
// message.Delete = 1
// message.Payload = string(toAdminJSON)
// messageJSONThree, _ := json.Marshal(message)
// messageString3 := base64.StdEncoding.EncodeToString([]byte(messageJSONThree))
// 待处理888 发送消息
// robot.SendMessage(strconv.FormatInt(transferDto.UserAccount, 10), []byte(messageString3))
utils.MessageInto(message)
// Transfer to the library for counting service times
servicesStatistical := models.ServicesStatistical{UserAccount: transferDto.UserAccount, ServiceAccount: transferDto.ToAccount, TransferAccount: admin.ID, Platform: user.Platform, CreateAt: time.Now().Unix()}
// StatisticalRepository instance
statisticalRepository := services.GetStatisticalRepositoryInstance()
_, err := statisticalRepository.Add(&servicesStatistical)
if err != nil {
}
// End the repeater's and user's current session
tk := time.NewTimer(1 * time.Second)
select {
case <-tk.C:
usersID := []int64{admin.ID, transferDto.UserAccount}
// ContactRepository instance
contactRepository := services.GetContactRepositoryInstance()
_, err := contactRepository.UpdateIsSessionEnd(usersID, 1)
if err != nil {
logs.Info(err)
}
}
c.JSON(configs.ResponseSucess, "转接成功!", nil)
}
...@@ -377,11 +377,11 @@ func (c *PublicController) PushMessage() { ...@@ -377,11 +377,11 @@ func (c *PublicController) PushMessage() {
c.JSON(configs.ResponseFail, "sorry you send message type is not NORMAL_MSG, it is "+pushMessage.MsgType, nil) c.JSON(configs.ResponseFail, "sorry you send message type is not NORMAL_MSG, it is "+pushMessage.MsgType, nil)
} }
// push message store // push message store
var getMessage models.Message var message models.Message
var msgContent []byte var msgContent []byte
msgContent, _ = base64.StdEncoding.DecodeString(pushMessage.Payload) msgContent, _ = base64.StdEncoding.DecodeString(pushMessage.Payload)
utils.StringToInterface(string(msgContent), &getMessage) utils.StringToInterface(string(msgContent), &message)
utils.MessageInto(getMessage) utils.MessageInto(message)
c.JSON(configs.ResponseSucess, "push success", nil) c.JSON(configs.ResponseSucess, "push success", nil)
...@@ -499,7 +499,7 @@ func (c *PublicController) GetMessageHistoryList() { ...@@ -499,7 +499,7 @@ func (c *PublicController) GetMessageHistoryList() {
} }
// query messages // query messages
returnMessagePaginationDto, err := c.MessageRepository.GetAdminMessages(messagePaginationDto) returnMessagePaginationDto, err := c.MessageRepository.GetUserMessages(messagePaginationDto)
if err != nil { if err != nil {
c.JSON(configs.ResponseFail, "fail", &err) c.JSON(configs.ResponseFail, "fail", &err)
} }
......
...@@ -79,9 +79,6 @@ func (c *RobotController) Delete() { ...@@ -79,9 +79,6 @@ func (c *RobotController) Delete() {
c.JSON(configs.ResponseFail, "删除失败!", nil) c.JSON(configs.ResponseFail, "删除失败!", nil)
} }
// init robots
// 待处理888 删除成功后处理重启机器人
// robotlbrary.RobotInit()
c.JSON(configs.ResponseSucess, "删除成功!", nil) c.JSON(configs.ResponseSucess, "删除成功!", nil)
} }
...@@ -134,8 +131,6 @@ func (c *RobotController) Post() { ...@@ -134,8 +131,6 @@ func (c *RobotController) Post() {
c.JSON(configs.ResponseFail, "添加失败!", nil) c.JSON(configs.ResponseFail, "添加失败!", nil)
} }
// 待处理888 处理重启机器人
// robotlbrary.RobotInit()
c.JSON(configs.ResponseSucess, "添加成功!", id) c.JSON(configs.ResponseSucess, "添加成功!", id)
} }
...@@ -218,8 +213,7 @@ func (c *RobotController) Put() { ...@@ -218,8 +213,7 @@ func (c *RobotController) Put() {
robot.Artificial = strings.Trim(robot.Artificial, "|") robot.Artificial = strings.Trim(robot.Artificial, "|")
robot.KeyWord = strings.Trim(robot.KeyWord, "|") robot.KeyWord = strings.Trim(robot.KeyWord, "|")
robot.CreateAt = oldRobot.CreateAt robot.CreateAt = oldRobot.CreateAt
// 待处理888 处理重启机器人
// robotlbrary.RobotInit()
c.JSON(configs.ResponseSucess, "修改成功!", &robot) c.JSON(configs.ResponseSucess, "修改成功!", &robot)
} }
......
syntax = "proto3"; syntax = "proto3";
package grpcs; package grpcs;
// protoc --go_out=plugins=grpc:./ client.proto
service Kefu { service Kefu {
rpc GetOnlineAllRobots (Request) returns (Respones) {} rpc GetOnlineAllRobots (Request) returns (Respones) {}
rpc PushMessage (Request) returns (Respones) {} rpc InsertMessage (Request) returns (Respones) {}
rpc CancelMessage (Request) returns (Respones) {} rpc CancelMessage (Request) returns (Respones) {}
rpc SearchKnowledgeTitles (Request) returns (Respones) {} rpc SearchKnowledgeTitles (Request) returns (Respones) {}
rpc GetOnlineAdmins (Request) returns (Respones) {} rpc GetOnlineAdmins (Request) returns (Respones) {}
rpc InsertStatistical (Request) returns (Respones) {} rpc InsertStatistical (Request) returns (Respones) {}
rpc PushNewContacts (Request) returns (Respones) {} rpc PushNewContacts (Request) returns (Respones) {}
rpc GetKnowledgeBaseWithTitleAndPlatform (Request) returns (Respones) {} rpc GetKnowledgeBaseWithTitleAndPlatform (Request) returns (Respones) {}
}
message StreamRes {
string data = 1;
} }
message StreamReq {
string data = 1;
}
message Respones { message Respones {
string data = 1; string data = 1;
} }
......
...@@ -25,8 +25,8 @@ func (s *kefuServer) GetOnlineAllRobots(ctx context.Context, in *Request) (*Resp ...@@ -25,8 +25,8 @@ func (s *kefuServer) GetOnlineAllRobots(ctx context.Context, in *Request) (*Resp
return &Respones{Data: utils.InterfaceToString(robots)}, nil return &Respones{Data: utils.InterfaceToString(robots)}, nil
} }
// PushMessage // InsertMessage
func (s *kefuServer) PushMessage(ctx context.Context, in *Request) (*Respones, error) { func (s *kefuServer) InsertMessage(ctx context.Context, in *Request) (*Respones, error) {
var message models.Message var message models.Message
msgContent, _ := base64.StdEncoding.DecodeString(in.Data) msgContent, _ := base64.StdEncoding.DecodeString(in.Data)
utils.StringToInterface(string(msgContent), &message) utils.StringToInterface(string(msgContent), &message)
...@@ -74,7 +74,6 @@ func (s *kefuServer) PushNewContacts(ctx context.Context, in *Request) (*Respone ...@@ -74,7 +74,6 @@ func (s *kefuServer) PushNewContacts(ctx context.Context, in *Request) (*Respone
func (s *kefuServer) InsertStatistical(ctx context.Context, in *Request) (*Respones, error) { func (s *kefuServer) InsertStatistical(ctx context.Context, in *Request) (*Respones, error) {
var servicesStatistical models.ServicesStatistical var servicesStatistical models.ServicesStatistical
utils.StringToInterface(in.Data, &servicesStatistical) utils.StringToInterface(in.Data, &servicesStatistical)
statisticalRepository := services.GetStatisticalRepositoryInstance() statisticalRepository := services.GetStatisticalRepositoryInstance()
_, err := statisticalRepository.Add(&servicesStatistical) _, err := statisticalRepository.Add(&servicesStatistical)
if err != nil { if err != nil {
...@@ -106,4 +105,5 @@ func Run() { ...@@ -106,4 +105,5 @@ func Run() {
if err != nil { if err != nil {
logs.Info("failed to serve: ", err) logs.Info("failed to serve: ", err)
} }
} }
...@@ -3,7 +3,6 @@ package main ...@@ -3,7 +3,6 @@ package main
import ( import (
"fmt" "fmt"
"github.com/Xiaomi-mimc/mimc-go-sdk/util/log"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
"github.com/astaxie/beego/toolbox" "github.com/astaxie/beego/toolbox"
...@@ -20,12 +19,10 @@ import ( ...@@ -20,12 +19,10 @@ import (
func initLog() { func initLog() {
if isDev := beego.AppConfig.String("runmode"); isDev == "prod" { if isDev := beego.AppConfig.String("runmode"); isDev == "prod" {
log.SetLogLevel(log.FatalLevel)
_ = logs.SetLogger(logs.AdapterFile, `{"filename":"project.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`) _ = logs.SetLogger(logs.AdapterFile, `{"filename":"project.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`)
fmt.Print("当前环境为生产环境") fmt.Print("当前环境为生产环境")
_ = beego.BeeLogger.DelLogger("console") _ = beego.BeeLogger.DelLogger("console")
} else { } else {
log.SetLogLevel(log.ErrorLevel)
_ = logs.SetLogger(logs.AdapterConsole, `{"filename":"test.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`) _ = logs.SetLogger(logs.AdapterConsole, `{"filename":"test.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`)
fmt.Print("当前环境为测试环境") fmt.Print("当前环境为测试环境")
} }
......
package models package models
// AuthTypes 登录配置模 // AuthTypes 登录配置模
// 目前有一种情况是机器人客户端使用的 0类型
type AuthTypes struct { type AuthTypes struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"` // ID ID int64 `orm:"auto;pk;column(id)" json:"id"` // ID
Title string `orm:"type(char);column(title)" json:"title"` // 标题 Title string `orm:"type(char);column(title)" json:"title"` // 标题
......
package models package models
// Auths 登录授权信息 // Auths 登录授权信息
// 目前有一种情况是机器人客户端使用的 UID=0 进行登录
type Auths struct { type Auths struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"` // 客服(管理员)ID ID int64 `orm:"auto;pk;column(id)" json:"id"` // 客服(管理员)ID
AuthType int64 `orm:"column(auth_type)" json:"auth_type"` // AuthType登录配置模ID AuthType int64 `orm:"column(auth_type)" json:"auth_type"` // AuthType登录配置模ID
......
...@@ -5,6 +5,7 @@ type Contact struct { ...@@ -5,6 +5,7 @@ type Contact struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"` // 递增ID ID int64 `orm:"auto;pk;column(id)" json:"id"` // 递增ID
FromAccount int64 `orm:"type(bigint);column(from_account)" json:"from_account"` // 接收者Account FromAccount int64 `orm:"type(bigint);column(from_account)" json:"from_account"` // 接收者Account
ToAccount int64 `orm:"type(bigint);column(to_account)" json:"to_account"` // 发送者Account ToAccount int64 `orm:"type(bigint);column(to_account)" json:"to_account"` // 发送者Account
LastAccount int64 `orm:"type(bigint);column(last_account)" json:"last_account"` // 最后一条消息者Account
IsSessionEnd int `orm:"default(0),column(is_session_end)" json:"is_session_end"` // 1 已结束对话 0 未结束对话 IsSessionEnd int `orm:"default(0),column(is_session_end)" json:"is_session_end"` // 1 已结束对话 0 未结束对话
LastMessage string `orm:"null;type(text);column(last_message)" json:"last_message"` // 最后一条消息内容 LastMessage string `orm:"null;type(text);column(last_message)" json:"last_message"` // 最后一条消息内容
Delete int `orm:"default(0);column(delete)" json:"delete"` // 1 已删除 0 未删除 Delete int `orm:"default(0);column(delete)" json:"delete"` // 1 已删除 0 未删除
......
...@@ -6,6 +6,7 @@ type ContactDto struct { ...@@ -6,6 +6,7 @@ type ContactDto struct {
Cid int64 `json:"cid"` Cid int64 `json:"cid"`
FromAccount int64 `json:"from_account"` FromAccount int64 `json:"from_account"`
ToAccount int64 `json:"to_account"` ToAccount int64 `json:"to_account"`
LastAccount int64 `json:"last_account"`
LastMessage string `json:"last_message"` LastMessage string `json:"last_message"`
IsSessionEnd int `json:"is_session_end"` IsSessionEnd int `json:"is_session_end"`
LastMessageType string `json:"last_message_type"` LastMessageType string `json:"last_message_type"`
......
...@@ -15,6 +15,7 @@ type Robot struct { ...@@ -15,6 +15,7 @@ type Robot struct {
Switch int `orm:"default(0);column(switch)" json:"switch"` // 是否开启 Switch int `orm:"default(0);column(switch)" json:"switch"` // 是否开启
System int `orm:"default(0);column(system)" json:"system"` // 系统内置 System int `orm:"default(0);column(system)" json:"system"` // 系统内置
Platform int64 `orm:"type(bigint);column(platform)" json:"platform"` // 服务那个平台 Platform int64 `orm:"type(bigint);column(platform)" json:"platform"` // 服务那个平台
Delete int `orm:"default(0);column(delete)" json:"delete"` // 是否已删除 0 false 1 true
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 更新时间 UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 更新时间
CreateAt int64 `orm:"auto_now_add;type(int64);null;column(create_at)" json:"create_at"` // 创建时间 CreateAt int64 `orm:"auto_now_add;type(int64);null;column(create_at)" json:"create_at"` // 创建时间
} }
...@@ -8,6 +8,7 @@ type ServicesStatistical struct { ...@@ -8,6 +8,7 @@ type ServicesStatistical struct {
TransferAccount int64 `orm:"type(bigint);column(transfer_account)" json:"transfer_account"` // 转接者ID TransferAccount int64 `orm:"type(bigint);column(transfer_account)" json:"transfer_account"` // 转接者ID
Platform int64 `orm:"type(bigint);column(platform)" json:"platform"` // 此用户来自哪个平台(即渠道) Platform int64 `orm:"type(bigint);column(platform)" json:"platform"` // 此用户来自哪个平台(即渠道)
NickName string `orm:"type(char);null;column(nickname)" json:"nickname"` // 用户昵称 NickName string `orm:"type(char);null;column(nickname)" json:"nickname"` // 用户昵称
IsReception int `orm:"default(0);null;column(is_reception)" json:"is_reception"` // 客服是否已回复用户 0 未接待处理 1 已接待处理
Satisfaction int `orm:"default(0);column(satisfaction)" json:"satisfaction"` // 满意度1-5 Satisfaction int `orm:"default(0);column(satisfaction)" json:"satisfaction"` // 满意度1-5
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"` // 创建时间 CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"` // 创建时间
} }
...@@ -6,6 +6,7 @@ type ServicesStatisticalPaginationDto struct { ...@@ -6,6 +6,7 @@ type ServicesStatisticalPaginationDto struct {
PageOn int `json:"page_on"` PageOn int `json:"page_on"`
Cid int64 `json:"cid"` Cid int64 `json:"cid"`
Date string `json:"date"` Date string `json:"date"`
IsReception bool `json:"is_reception"`
IsDeWeighting bool `json:"is_de_weighting"` IsDeWeighting bool `json:"is_de_weighting"`
Total int64 `json:"total"` Total int64 `json:"total"`
List interface{} `json:"list"` List interface{} `json:"list"`
......
...@@ -31,7 +31,6 @@ func init() { ...@@ -31,7 +31,6 @@ func init() {
beego.NSNamespace("/auth", beego.NSNamespace("/auth",
beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"), beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"),
beego.NSRouter("/logout", &controllers.AuthController{}, "get:Logout"), beego.NSRouter("/logout", &controllers.AuthController{}, "get:Logout"),
beego.NSRouter("/token", &controllers.AuthController{}, "post:RobotFetchToken"),
), ),
// public // public
...@@ -69,7 +68,6 @@ func init() { ...@@ -69,7 +68,6 @@ func init() {
beego.NSNamespace("/message", beego.NSNamespace("/message",
beego.NSBefore(filters.FilterToken), beego.NSBefore(filters.FilterToken),
beego.NSRouter("/list", &controllers.MessageController{}, "post:List"), beego.NSRouter("/list", &controllers.MessageController{}, "post:List"),
beego.NSRouter("/transfer", &controllers.MessageController{}, "post:Transfer"),
beego.NSRouter("/remove", &controllers.MessageController{}, "post:Remove"), beego.NSRouter("/remove", &controllers.MessageController{}, "post:Remove"),
), ),
...@@ -137,6 +135,7 @@ func init() { ...@@ -137,6 +135,7 @@ func init() {
beego.NSRouter("/?:id", &controllers.ContactController{}), beego.NSRouter("/?:id", &controllers.ContactController{}),
beego.NSRouter("/list", &controllers.ContactController{}, "get:GetContacts"), beego.NSRouter("/list", &controllers.ContactController{}, "get:GetContacts"),
beego.NSRouter("/clear", &controllers.ContactController{}, "delete:DeleteAll"), beego.NSRouter("/clear", &controllers.ContactController{}, "delete:DeleteAll"),
beego.NSRouter("/transfer", &controllers.ContactController{}, "post:Transfer"),
), ),
// platform // platform
......
...@@ -98,7 +98,7 @@ func (r *ContactRepository) UpdateIsSessionEnd(usersID []int64, isSessionEnd int ...@@ -98,7 +98,7 @@ func (r *ContactRepository) UpdateIsSessionEnd(usersID []int64, isSessionEnd int
// GetContacts get Contacts // GetContacts get Contacts
func (r *ContactRepository) GetContacts(uid int64) ([]models.ContactDto, error) { func (r *ContactRepository) GetContacts(uid int64) ([]models.ContactDto, error) {
var contactDto []models.ContactDto var contactDto []models.ContactDto
_, err := r.o.Raw("SELECT c.id AS cid,c.to_account,c.is_session_end, c.last_message,c.last_message_type,c.from_account, c.create_at AS contact_create_at,u.*, IFNULL(m.`count`,0) AS `read` FROM `contact` c LEFT JOIN `user` u ON c.from_account = u.id LEFT JOIN (SELECT to_account,from_account, COUNT(*) as `count` FROM message WHERE `read` = 1 GROUP BY to_account,from_account) m ON m.to_account = c.to_account AND m.from_account = c.from_account WHERE c.to_account = ? AND c.delete = 0 ORDER BY c.create_at DESC", uid).QueryRows(&contactDto) _, err := r.o.Raw("SELECT c.id AS cid,c.to_account,c.last_account,c.is_session_end, c.last_message,c.last_message_type,c.from_account, c.create_at AS contact_create_at,u.*, IFNULL(m.`count`,0) AS `read` FROM `contact` c LEFT JOIN `user` u ON c.from_account = u.id LEFT JOIN (SELECT to_account,from_account, COUNT(*) as `count` FROM message WHERE `read` = 1 GROUP BY to_account,from_account) m ON m.to_account = c.to_account AND m.from_account = c.from_account WHERE c.to_account = ? AND c.delete = 0 ORDER BY c.create_at DESC", uid).QueryRows(&contactDto)
if err != nil { if err != nil {
logs.Warn("GetContacts get Contacts------------", err) logs.Warn("GetContacts get Contacts------------", err)
return []models.ContactDto{}, err return []models.ContactDto{}, err
......
...@@ -129,8 +129,7 @@ func (r *MessageRepository) GetAdminMessages(messagePaginationDto models.Message ...@@ -129,8 +129,7 @@ func (r *MessageRepository) GetAdminMessages(messagePaginationDto models.Message
inExp := "?,?" inExp := "?,?"
// get all robot // get all robot
robotRepository := new(RobotRepository) robotRepository := GetRobotRepositoryInstance()
robotRepository.Init(new(models.Robot))
robots, err := robotRepository.GetRobots() robots, err := robotRepository.GetRobots()
if err != nil { if err != nil {
logs.Warn("GetMessages get one service message list0------------", err) logs.Warn("GetMessages get one service message list0------------", err)
......
...@@ -75,8 +75,8 @@ func (r *RobotRepository) Update(id int64, params orm.Params) (int64, error) { ...@@ -75,8 +75,8 @@ func (r *RobotRepository) Update(id int64, params orm.Params) (int64, error) {
// GetRobots get Robots // GetRobots get Robots
func (r *RobotRepository) GetRobots() ([]models.Robot, error) { func (r *RobotRepository) GetRobots() ([]models.Robot, error) {
var robots []models.Robot var robots []models.Robot
if _, err := r.q.OrderBy("-create_at").All(&robots); err != nil { if _, err := r.q.Filter("delete", 0).OrderBy("-create_at").All(&robots); err != nil {
logs.Warn("GetRobot get one Robot------------", err) logs.Warn("GetRobots get Robots------------", err)
return nil, err return nil, err
} }
for index := range robots { for index := range robots {
...@@ -89,7 +89,7 @@ func (r *RobotRepository) GetRobots() ([]models.Robot, error) { ...@@ -89,7 +89,7 @@ func (r *RobotRepository) GetRobots() ([]models.Robot, error) {
// GetRobot get one Robot // GetRobot get one Robot
func (r *RobotRepository) GetRobot(id int64) *models.Robot { func (r *RobotRepository) GetRobot(id int64) *models.Robot {
var robot models.Robot var robot models.Robot
if err := r.q.Filter("id", id).One(&robot); err != nil { if err := r.q.Filter("delete", 0).Filter("id", id).One(&robot); err != nil {
logs.Warn("GetRobot get one Robot------------", err) logs.Warn("GetRobot get one Robot------------", err)
return nil return nil
} }
...@@ -101,7 +101,7 @@ func (r *RobotRepository) GetRobot(id int64) *models.Robot { ...@@ -101,7 +101,7 @@ func (r *RobotRepository) GetRobot(id int64) *models.Robot {
// GetRobotWithNickName get one Robot with nickname // GetRobotWithNickName get one Robot with nickname
func (r *RobotRepository) GetRobotWithNickName(nickName string) *models.Robot { func (r *RobotRepository) GetRobotWithNickName(nickName string) *models.Robot {
var robot models.Robot var robot models.Robot
if err := r.q.Filter("nickname", nickName).One(&robot); err != nil { if err := r.q.Filter("delete", 0).Filter("nickname", nickName).One(&robot); err != nil {
logs.Warn("GetRobotWithNickName get one Robot with nickname------------", err) logs.Warn("GetRobotWithNickName get one Robot with nickname------------", err)
return nil return nil
} }
...@@ -113,7 +113,7 @@ func (r *RobotRepository) GetRobotWithNickName(nickName string) *models.Robot { ...@@ -113,7 +113,7 @@ func (r *RobotRepository) GetRobotWithNickName(nickName string) *models.Robot {
// GetRobotWithRandomOnline get one Robot with Random Online // GetRobotWithRandomOnline get one Robot with Random Online
func (r *RobotRepository) GetRobotWithRandomOnline() (*models.Robot, error) { func (r *RobotRepository) GetRobotWithRandomOnline() (*models.Robot, error) {
var robot *models.Robot var robot *models.Robot
if err := r.q.Filter("switch", 1).One(&robot); err != nil { if err := r.q.Filter("delete", 0).Filter("switch", 1).One(&robot); err != nil {
logs.Warn("GetRobotWithRandomOnline get one Robot with Random Online------------", err) logs.Warn("GetRobotWithRandomOnline get one Robot with Random Online------------", err)
return nil, err return nil, err
} }
...@@ -125,7 +125,7 @@ func (r *RobotRepository) GetRobotWithRandomOnline() (*models.Robot, error) { ...@@ -125,7 +125,7 @@ func (r *RobotRepository) GetRobotWithRandomOnline() (*models.Robot, error) {
// GetRobotOnlineAll get one Robot with Random Online // GetRobotOnlineAll get one Robot with Random Online
func (r *RobotRepository) GetRobotOnlineAll() ([]*models.Robot, error) { func (r *RobotRepository) GetRobotOnlineAll() ([]*models.Robot, error) {
var robots []*models.Robot var robots []*models.Robot
if _, err := r.q.Filter("switch", 1).All(&robots); err != nil { if _, err := r.q.Filter("delete", 0).Filter("switch", 1).All(&robots); err != nil {
logs.Warn("GetRobotWithRandomOnline get one Robot with Random Online------------", err) logs.Warn("GetRobotWithRandomOnline get one Robot with Random Online------------", err)
return nil, err return nil, err
} }
...@@ -139,7 +139,7 @@ func (r *RobotRepository) GetRobotOnlineAll() ([]*models.Robot, error) { ...@@ -139,7 +139,7 @@ func (r *RobotRepository) GetRobotOnlineAll() ([]*models.Robot, error) {
// GetRobotWithOnline get one Robot with Online // GetRobotWithOnline get one Robot with Online
func (r *RobotRepository) GetRobotWithOnline(platformID int64) (*models.Robot, error) { func (r *RobotRepository) GetRobotWithOnline(platformID int64) (*models.Robot, error) {
var robots []*models.Robot var robots []*models.Robot
if _, err := r.q.Filter("platform__in", platformID, 1).Filter("switch", 1).All(&robots); err != nil { if _, err := r.q.Filter("delete", 0).Filter("platform__in", platformID, 1).Filter("switch", 1).All(&robots); err != nil {
logs.Warn("GetRobotWithRandom get one Robot with Random------------", err) logs.Warn("GetRobotWithRandom get one Robot with Random------------", err)
return nil, err return nil, err
} }
...@@ -155,9 +155,9 @@ func (r *RobotRepository) GetRobotWithOnline(platformID int64) (*models.Robot, e ...@@ -155,9 +155,9 @@ func (r *RobotRepository) GetRobotWithOnline(platformID int64) (*models.Robot, e
// GetRobotWithInIds get one Robot with in() ids // GetRobotWithInIds get one Robot with in() ids
func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error) { func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error) {
var robots []models.Robot var robots []models.Robot
_, err := r.o.Raw("SELECT * FROM robot WHERE id IN(?, ?)", ids).QueryRows(&robots) _, err := r.o.Raw("SELECT * FROM robot WHERE id IN(?, ?) AND `delete` = 0", ids).QueryRows(&robots)
if err != nil { if err != nil {
logs.Warn("GetRobot get one Robot------------", err) logs.Warn("GetRobotWithInIds get one Robot with in() ids", err)
} }
return robots, err return robots, err
} }
...@@ -165,9 +165,9 @@ func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error ...@@ -165,9 +165,9 @@ func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error
// Delete delete a robot // Delete delete a robot
func (r *RobotRepository) Delete(id int64) (int64, error) { func (r *RobotRepository) Delete(id int64) (int64, error) {
if id == 1 { if id == 1 {
return 0, errors.New("system robot") return 0, errors.New("system robot do not delete")
} }
index, err := r.q.Filter("id", id).Delete() index, err := r.q.Filter("id", id).Update(orm.Params{"Delete": 1})
if err != nil { if err != nil {
logs.Warn("Delete delete a robot------------", err) logs.Warn("Delete delete a robot------------", err)
} }
......
...@@ -16,6 +16,7 @@ type StatisticalRepositoryInterface interface { ...@@ -16,6 +16,7 @@ type StatisticalRepositoryInterface interface {
GetStatisticals(startDate string, endDate string) (map[string]interface{}, error) GetStatisticals(startDate string, endDate string) (map[string]interface{}, error)
GetTodayActionStatistical(startDate string, endDate string) ([]orm.Params, error) GetTodayActionStatistical(startDate string, endDate string) ([]orm.Params, error)
GetCustomerServiceList(request models.ServicesStatisticalPaginationDto) models.ServicesStatisticalPaginationDto GetCustomerServiceList(request models.ServicesStatisticalPaginationDto) models.ServicesStatisticalPaginationDto
CheckIsReplyAndSetReply(uid int64, aid int64, platform int64)
} }
// StatisticalRepository struct // StatisticalRepository struct
...@@ -52,7 +53,13 @@ func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesSt ...@@ -52,7 +53,13 @@ func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesSt
addSQL = " count(distinct user_account) " addSQL = " count(distinct user_account) "
} }
if err := r.o.Raw("SELECT "+addSQL+" AS `count` FROM services_statistical AS s INNER JOIN (SELECT * FROM `user`) AS u ON s.user_account = u.id AND s.service_account = ? AND s.create_at > ? AND s.create_at < ?", request.Cid, startDate.Unix(), endDate.Unix()).QueryRow(&totalModel); err != nil { // is not reception?
INReception := "0,1"
if request.IsReception {
INReception = "0"
}
if err := r.o.Raw("SELECT "+addSQL+" AS `count` FROM services_statistical AS s INNER JOIN (SELECT * FROM `user`) AS u ON s.user_account = u.id AND s.service_account = ? AND s.create_at > ? AND s.create_at < ? AND is_reception IN("+INReception+")", request.Cid, startDate.Unix(), endDate.Unix()).QueryRow(&totalModel); err != nil {
logs.Warn("GetCustomerServiceList get Customer Service List1------------", err) logs.Warn("GetCustomerServiceList get Customer Service List1------------", err)
} }
request.Total = totalModel.Count request.Total = totalModel.Count
...@@ -63,7 +70,7 @@ func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesSt ...@@ -63,7 +70,7 @@ func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesSt
addSQL1 = " GROUP BY `user_account` " addSQL1 = " GROUP BY `user_account` "
} }
if counter, err := r.o.Raw("SELECT s.id, s.user_account, s.service_account,s.create_at, s.transfer_account,s.platform,u.nickname FROM services_statistical AS s INNER JOIN (SELECT * FROM `user` ) AS u ON s.user_account = u.id AND s.service_account = ? AND s.create_at > ? AND s.create_at < ? "+addSQL1+" ORDER BY s.create_at DESC LIMIT ?,?", request.Cid, startDate.Unix(), endDate.Unix(), (request.PageOn-1)*request.PageSize, request.PageSize).Values(&params); counter <= 0 { if counter, err := r.o.Raw("SELECT s.id, s.user_account, s.service_account,s.create_at,s.is_reception, s.transfer_account,s.platform,u.nickname FROM services_statistical AS s INNER JOIN (SELECT * FROM `user` ) AS u ON s.user_account = u.id AND s.service_account = ? AND s.create_at > ? AND s.create_at < ? AND is_reception IN("+ INReception +") "+addSQL1+" ORDER BY s.create_at DESC LIMIT ?,?", request.Cid, startDate.Unix(), endDate.Unix(), (request.PageOn-1)*request.PageSize, request.PageSize).Values(&params); counter <= 0 {
logs.Warn("GetCustomerServiceList get Customer Service List2------------", err) logs.Warn("GetCustomerServiceList get Customer Service List2------------", err)
request.List = []string{} request.List = []string{}
return request return request
...@@ -76,7 +83,7 @@ func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesSt ...@@ -76,7 +83,7 @@ func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesSt
// Add add statistical // Add add statistical
func (r *StatisticalRepository) Add(servicesStatistical *models.ServicesStatistical) (int64, error) { func (r *StatisticalRepository) Add(servicesStatistical *models.ServicesStatistical) (int64, error) {
id, err := r.o.Insert(&servicesStatistical) id, err := r.o.Insert(servicesStatistical)
if err != nil { if err != nil {
logs.Warn("Add add statistical------------", err) logs.Warn("Add add statistical------------", err)
} }
...@@ -155,3 +162,21 @@ func (r *StatisticalRepository) GetTodayActionStatistical(startDate string, endD ...@@ -155,3 +162,21 @@ func (r *StatisticalRepository) GetTodayActionStatistical(startDate string, endD
} }
return statisticalData, nil return statisticalData, nil
} }
// CheckIsReplyAndSetReply cehck is reply and set reply
func (r *StatisticalRepository) CheckIsReplyAndSetReply(userAccount int64, serviceAccount int64, userPlatform int64) {
logs.Info(userAccount, serviceAccount, userPlatform)
var servicesStatistical models.ServicesStatistical
maxTime := time.Now().Unix() - 60*10
logs.Info(maxTime)
err := r.q.Filter("user_account", userAccount).Filter("service_account", serviceAccount).Filter("is_reception", 0).Filter("platform", userPlatform).Filter("create_at__gte", maxTime).One(&servicesStatistical)
if err != nil {
logs.Warn("CheckIsReplyAndSetReply cehck is reply and set reply Filter------------", err)
} else {
servicesStatistical.IsReception = 1
_, err := r.o.Update(&servicesStatistical)
if err != nil {
logs.Warn("CheckIsReplyAndSetReply cehck is reply and set reply Update------------", err)
}
}
}
...@@ -44,6 +44,7 @@ func appTask() { ...@@ -44,6 +44,7 @@ func appTask() {
continue continue
} }
_lastBackAdmin := services.GetAdminRepositoryInstance().GetAdmin(contact.LastAccount)
robot := robots[0] robot := robots[0]
// message body // message body
...@@ -52,7 +53,10 @@ func appTask() { ...@@ -52,7 +53,10 @@ func appTask() {
message.Read = 0 message.Read = 0
message.FromAccount = robot.ID message.FromAccount = robot.ID
message.Timestamp = time.Now().Unix() message.Timestamp = time.Now().Unix()
message.Payload = "由于您长时间未回复,本次会话超时了" message.Payload = "您长时间未回复,本次会话超时了"
if _lastBackAdmin == nil {
message.Payload = "客服长时间未回复,会话结束,您可以重新发起人工"
}
message.ToAccount = contact.FromAccount message.ToAccount = contact.FromAccount
var messageString string var messageString string
messageString = utils.InterfaceToString(message) messageString = utils.InterfaceToString(message)
...@@ -61,12 +65,17 @@ func appTask() { ...@@ -61,12 +65,17 @@ func appTask() {
// Send a reminder message to customer service // Send a reminder message to customer service
message.FromAccount = contact.FromAccount message.FromAccount = contact.FromAccount
message.ToAccount = contact.ToAccount message.ToAccount = contact.ToAccount
message.Payload = "用户长时间无应答,会话结束"
if _lastBackAdmin == nil {
message.Read = 1
message.Payload = "您长时间未回复客户,会话结束"
}
messageString = utils.InterfaceToString(message) messageString = utils.InterfaceToString(message)
utils.PushMessage(contact.ToAccount, messageString) utils.PushMessage(contact.ToAccount, messageString)
utils.MessageInto(message) utils.MessageInto(message)
// Message after timeout // Message after timeout
if robot.TimeoutText != "" { if robot.TimeoutText != "" && _lastBackAdmin != nil {
message.FromAccount = robot.ID message.FromAccount = robot.ID
message.ToAccount = contact.FromAccount message.ToAccount = contact.FromAccount
message.BizType = "text" message.BizType = "text"
......
...@@ -36,10 +36,18 @@ func MessageInto(message models.Message) { ...@@ -36,10 +36,18 @@ func MessageInto(message models.Message) {
// 默认已读消息 // 默认已读消息
message.Read = 0 message.Read = 0
user := userRepository.GetUser(message.ToAccount) user := userRepository.GetUser(message.ToAccount)
if user != nil && user.Online == 0 { if user != nil && (user.Online == 0 || user.IsWindow == 0) {
message.Read = 1 message.Read = 1
} }
if user != nil && user.IsWindow == 0 {
// 处理是否已回复
services.GetStatisticalRepositoryInstance().CheckIsReplyAndSetReply(user.ID, message.FromAccount, user.Platform)
} else {
// 接收者是客服
admin := services.GetAdminRepositoryInstance().GetAdmin(message.ToAccount)
if admin != nil && admin.CurrentConUser != message.FromAccount {
message.Read = 1 message.Read = 1
} }
...@@ -71,6 +79,7 @@ func MessageInto(message models.Message) { ...@@ -71,6 +79,7 @@ func MessageInto(message models.Message) {
newContact.FromAccount = message.FromAccount newContact.FromAccount = message.FromAccount
newContact.LastMessageType = message.BizType newContact.LastMessageType = message.BizType
newContact.CreateAt = time.Now().Unix() newContact.CreateAt = time.Now().Unix()
newContact.LastAccount = message.FromAccount
newContact.LastMessage = message.Payload newContact.LastMessage = message.Payload
_, _ = contactRepository.Add(&newContact) _, _ = contactRepository.Add(&newContact)
} else { } else {
...@@ -82,9 +91,16 @@ func MessageInto(message models.Message) { ...@@ -82,9 +91,16 @@ func MessageInto(message models.Message) {
"LastMessageType": message.BizType, "LastMessageType": message.BizType,
"CreateAt": time.Now().Unix(), "CreateAt": time.Now().Unix(),
"LastMessage": message.Payload, "LastMessage": message.Payload,
"LastAccount": message.FromAccount,
"IsSessionEnd": isSessionEnd, "IsSessionEnd": isSessionEnd,
"Delete": 0, "Delete": 0,
}) })
} }
if user != nil {
PushNewContacts(message.FromAccount)
} else {
PushNewContacts(message.ToAccount)
}
} }
package utils package utils
import ( import (
"encoding/base64"
"encoding/json" "encoding/json"
"kefu_server/models" "kefu_server/models"
"kefu_server/services" "kefu_server/services"
...@@ -16,10 +15,6 @@ func PushNewContacts(uid int64) { ...@@ -16,10 +15,6 @@ func PushNewContacts(uid int64) {
message.BizType = "contacts" message.BizType = "contacts"
message.FromAccount = 1 message.FromAccount = 1
message.Timestamp = time.Now().Unix() message.Timestamp = time.Now().Unix()
for index, contact := range contactData {
payload, _ := base64.StdEncoding.DecodeString(contact.LastMessage)
contactData[index].LastMessage = string(payload)
}
message.ToAccount = uid message.ToAccount = uid
messageContentByte, _ := json.Marshal(contactData) messageContentByte, _ := json.Marshal(contactData)
message.Payload = string(messageContentByte) message.Payload = string(messageContentByte)
......
...@@ -5,7 +5,6 @@ import ( ...@@ -5,7 +5,6 @@ import (
"strconv" "strconv"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
) )
// PushMessage send message // PushMessage send message
...@@ -25,7 +24,6 @@ func PushMessage(toAccount int64, msg string) bool { ...@@ -25,7 +24,6 @@ func PushMessage(toAccount int64, msg string) bool {
request["toAccount"] = strconv.FormatInt(toAccount, 10) request["toAccount"] = strconv.FormatInt(toAccount, 10)
request["msg"] = msg request["msg"] = msg
response := HTTPRequest(api, "POST", request, "") response := HTTPRequest(api, "POST", request, "")
logs.Info(response)
if response.Code != 200 { if response.Code != 200 {
fmt.Println(response) fmt.Println(response)
return false return false
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment