Commit e023aa90 by chenxianqi

Project progress follow-up

parent f68f5df4
Showing with 1354 additions and 1006 deletions
version = "v2.0"
appname = kefu_server
runmode = "dev"
httpport = 8080
......
......@@ -24,9 +24,8 @@ type AdminController struct {
// Prepare More like construction method
func (c *AdminController) Prepare() {
// init AdminRepository
c.AdminRepository = new(services.AdminRepository)
c.AdminRepository.Init(new(models.Admin))
// AdminRepository instance
c.AdminRepository = services.GetAdminRepositoryInstance()
}
......@@ -38,13 +37,12 @@ func (c *AdminController) GetMeInfo() {
// GetAuthInfo
auth := c.GetAuthInfo()
admin := c.AdminRepository.GetAdmin(auth.UID)
if admin == nil {
c.JSON(configs.ResponseFail, "查询失败,用户不存在!", nil)
c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
}
c.JSON(configs.ResponseSucess, "查询成功!", &admin)
c.JSON(configs.ResponseSucess, "success", &admin)
}
// Get admin
......@@ -52,10 +50,9 @@ func (c *AdminController) Get() {
// GetAuthInfo
auth := c.GetAuthInfo()
admin := c.AdminRepository.GetAdmin(auth.UID)
if admin == nil {
c.JSON(configs.ResponseFail, "查询失败,用户不存在!", nil)
c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
}
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
......@@ -65,11 +62,11 @@ func (c *AdminController) Get() {
retrunAdmin := c.AdminRepository.GetAdmin(id)
if retrunAdmin == nil {
c.JSON(configs.ResponseFail, "查询失败,用户不存在!", nil)
c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
}
retrunAdmin.Password = "******"
c.JSON(configs.ResponseSucess, "查询成功!", &retrunAdmin)
c.JSON(configs.ResponseSucess, "success", &retrunAdmin)
}
// Put update admin
......@@ -80,10 +77,9 @@ func (c *AdminController) Put() {
// get request
admin := models.Admin{}
admin.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &admin); err != nil {
logs.Warn("Put update admin error------------", err)
c.JSON(configs.ResponseFail, "参数错误!", &err)
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// admin exist
......@@ -114,10 +110,10 @@ func (c *AdminController) Put() {
}
// update
if _, err := c.AdminRepository.UpdateParams(admin.ID, orm.Params{
if _, err := c.AdminRepository.Update(admin.ID, orm.Params{
"Phone": admin.Phone,
"NickName": admin.NickName,
"UpdateAt": admin.UpdateAt,
"UpdateAt": time.Now().Unix(),
"Avatar": admin.Avatar,
"AutoReply": admin.AutoReply,
}); err != nil {
......@@ -146,7 +142,7 @@ func (c *AdminController) Post() {
var newAdmin models.Admin
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &newAdmin); err != nil {
logs.Info("Post add new admin error------------", err)
c.JSON(configs.ResponseFail, "参数错误!", nil)
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
......@@ -217,18 +213,18 @@ func (c *AdminController) Delete() {
func (c *AdminController) List() {
// request body
var paginationData services.AdminPaginationData
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationData); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
var paginationDto services.AdminPaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
data, err := c.AdminRepository.GetAdmins(&paginationData)
data, err := c.AdminRepository.GetAdmins(&paginationDto)
if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err)
c.JSON(configs.ResponseFail, "fail", &err)
}
c.JSON(configs.ResponseSucess, "查询成功!", &data)
c.JSON(configs.ResponseSucess, "success", &data)
}
// UpdatePassword update password
......@@ -236,7 +232,7 @@ func (c *AdminController) UpdatePassword() {
request := services.UpdatePasswordRequest{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// GetAuthInfo
......@@ -245,7 +241,7 @@ func (c *AdminController) UpdatePassword() {
// oldAdmin
oldAdmin := c.AdminRepository.GetAdmin(auth.UID)
if oldAdmin == nil {
c.JSON(configs.ResponseFail, "查询失败,暂时无法更新!", nil)
c.JSON(configs.ResponseFail, "fail,暂时无法更新!", nil)
}
// validation
......@@ -290,7 +286,7 @@ func (c *AdminController) UpdatePassword() {
}
// Update
if _, err := c.AdminRepository.UpdateParams(newAdmin.ID, orm.Params{
if _, err := c.AdminRepository.Update(newAdmin.ID, orm.Params{
"Password": newAdmin.Password,
"UpdateAt": newAdmin.UpdateAt,
}); err != nil {
......@@ -315,7 +311,7 @@ func (c *AdminController) ChangeCurrentUser() {
uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// Update
if _, err := c.AdminRepository.UpdateParams(admin.ID, orm.Params{
if _, err := c.AdminRepository.Update(admin.ID, orm.Params{
"CurrentConUser": uid,
}); err != nil {
logs.Info("ChangeCurrentUser current connect user Warn------------", err)
......@@ -341,7 +337,7 @@ func (c *AdminController) Online() {
}
// Update
if _, err := c.AdminRepository.UpdateParams(admin.ID, orm.Params{
if _, err := c.AdminRepository.Update(admin.ID, orm.Params{
"Online": online,
}); err != nil {
c.JSON(configs.ResponseFail, "更新在线状态失败!", &err)
......
......@@ -25,17 +25,14 @@ type AuthController struct {
// Prepare More like construction method
func (c *AuthController) Prepare() {
// init AuthTypes
c.AuthTypesRepository = new(services.AuthTypesRepository)
c.AuthTypesRepository.Init(new(models.AuthTypes))
// AuthTypes instance
c.AuthTypesRepository = services.GetAuthTypesRepositoryInstance()
// init AdminRepository
c.AdminRepository = new(services.AdminRepository)
c.AdminRepository.Init(new(models.Admin))
// AdminRepository instance
c.AdminRepository = services.GetAdminRepositoryInstance()
// init AuthsRepository
c.AuthsRepository = new(services.AuthsRepository)
c.AuthsRepository.Init(new(models.Auths))
// AuthsRepository instance
c.AuthsRepository = services.GetAuthsRepositoryInstance()
}
......@@ -59,7 +56,7 @@ func (c *AuthController) Login() {
valid := validation.Validation{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil {
c.JSON(configs.ResponseFail, "参数错误", nil)
c.JSON(configs.ResponseFail, "参数有误,请检查", nil)
}
// valid
......@@ -97,7 +94,7 @@ func (c *AuthController) Login() {
}
// create token
newToken := utils.GenerateToken(models.JwtKey{ID: queryAdmin.ID, UserName: queryAdmin.UserName, AuthType: authType.ID})
newToken := utils.GenerateToken(models.JwtKeyDto{ID: queryAdmin.ID, UserName: queryAdmin.UserName, AuthType: authType.ID})
auth := c.AuthsRepository.GetAuthInfoWithTypeAndUID(request.AuthType, queryAdmin.ID)
if auth == nil {
......@@ -114,7 +111,7 @@ func (c *AuthController) Login() {
} else {
_, err := c.AuthsRepository.UpdateParams(auth.ID, orm.Params{
_, err := c.AuthsRepository.Update(auth.ID, orm.Params{
"Token": newToken,
"UpdateAt": time.Now().Unix(),
})
......@@ -137,7 +134,7 @@ func (c *AuthController) Logout() {
if count := c.AuthsRepository.GetAdminOnlineCount(auth.UID); count <= 1 {
if _, err := c.AdminRepository.UpdateParams(auth.UID, orm.Params{
if _, err := c.AdminRepository.Update(auth.UID, orm.Params{
"CurrentConUser": 0,
"Online": 0,
}); err != nil {
......
......@@ -30,7 +30,7 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string,
msg = "sorry server error"
data = nil
}
c.Data["json"] = &models.Response{Code: status, Message: msg, Data: &data}
c.Data["json"] = &models.ResponseDto{Code: status, Message: msg, Data: &data}
c.ServeJSON()
c.StopRun()
}
......@@ -38,8 +38,7 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string,
// GetAuthInfo get current anth user that AuthInfo
func (c *BaseController) GetAuthInfo() *models.Auths {
token := c.Ctx.Input.Header("Authorization")
var authsRepository = new(services.AuthsRepository)
authsRepository.Init(new(models.Auths))
var authsRepository = services.GetAuthsRepositoryInstance()
auth := authsRepository.GetAuthInfo(token)
if auth == nil {
logs.Warn("GetAuthInfo fun error------------登录已失效!")
......
......@@ -20,9 +20,8 @@ type CompanyController struct {
// Prepare More like construction method
func (c *CompanyController) Prepare() {
// init CompanyRepository
c.CompanyRepository = new(services.CompanyRepository)
c.CompanyRepository.Init(new(models.Company))
// CompanyRepository instance
c.CompanyRepository = services.GetCompanyRepositoryInstance()
}
......@@ -33,9 +32,9 @@ func (c *CompanyController) Finish() {}
func (c *CompanyController) Get() {
company := c.CompanyRepository.GetCompany(1)
if company == nil {
c.JSON(configs.ResponseFail, "查询失败!", nil)
c.JSON(configs.ResponseFail, "fail", nil)
}
c.JSON(configs.ResponseSucess, "查询成功!", &company)
c.JSON(configs.ResponseSucess, "success", &company)
}
// Put update conpany info
......@@ -44,7 +43,7 @@ func (c *CompanyController) Put() {
company := models.Company{}
company.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &company); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil)
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
......@@ -63,7 +62,7 @@ func (c *CompanyController) Put() {
}
// orm
row, err := c.CompanyRepository.UpdateParams(1, orm.Params{
row, err := c.CompanyRepository.Update(1, orm.Params{
"Title": company.Title,
"Address": company.Address,
"Email": company.Email,
......
......@@ -17,13 +17,11 @@ type ContactController struct {
// Prepare More like construction method
func (c *ContactController) Prepare() {
// init ContactRepository
c.ContactRepository = new(services.ContactRepository)
c.ContactRepository.Init(new(models.Contact))
// ContactRepository instance
c.ContactRepository = services.GetContactRepositoryInstance()
// init AdminRepository
c.AdminRepository = new(services.AdminRepository)
c.AdminRepository.Init(new(models.Admin))
// AdminRepository instance
c.AdminRepository = services.GetAdminRepositoryInstance()
}
......@@ -36,15 +34,15 @@ func (c *ContactController) GetContacts() {
// GetAuthInfo
auth := c.GetAuthInfo()
contactData, err := c.ContactRepository.GetContacts(auth.UID)
contactDto, err := c.ContactRepository.GetContacts(auth.UID)
if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err)
c.JSON(configs.ResponseFail, "fail", &err)
}
if len(contactData) == 0 {
contactData = []models.ContactData{}
if len(contactDto) == 0 {
contactDto = []models.ContactDto{}
}
c.JSON(configs.ResponseSucess, "查询成功!", &contactData)
c.JSON(configs.ResponseSucess, "success", &contactDto)
}
......
......@@ -3,7 +3,6 @@ package controllers
import (
"encoding/json"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/services"
"github.com/astaxie/beego/validation"
......@@ -18,9 +17,8 @@ type HomeController struct {
// Prepare More like construction method
func (c *HomeController) Prepare() {
// init StatisticalRepository
c.StatisticalRepository = new(services.StatisticalRepository)
c.StatisticalRepository.Init(new(models.ServicesStatistical))
// StatisticalRepository instance
c.StatisticalRepository = services.GetStatisticalRepositoryInstance()
}
......@@ -39,7 +37,7 @@ func (c *HomeController) Statistical() {
// request body
statisticalRequest := StatisticalRequest{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &statisticalRequest); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// validation
......@@ -57,7 +55,7 @@ func (c *HomeController) Statistical() {
c.JSON(configs.ResponseFail, err.Error(), &err)
}
c.JSON(configs.ResponseSucess, "查询成功!", &countsArr)
c.JSON(configs.ResponseSucess, "success", &countsArr)
}
......@@ -67,7 +65,7 @@ func (c *HomeController) TodayActionStatistical() {
// request body
statisticalRequest := StatisticalRequest{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &statisticalRequest); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// validation
......@@ -85,6 +83,6 @@ func (c *HomeController) TodayActionStatistical() {
c.JSON(configs.ResponseFail, err.Error(), &err)
}
c.JSON(configs.ResponseSucess, "查询成功!", &statisticalData)
c.JSON(configs.ResponseSucess, "success", &statisticalData)
}
......@@ -23,13 +23,11 @@ type KnowledgeBaseController struct {
// Prepare More like construction method
func (c *KnowledgeBaseController) Prepare() {
// init StatisticalRepository
c.KnowledgeBaseRepository = new(services.KnowledgeBaseRepository)
c.KnowledgeBaseRepository.Init(new(models.KnowledgeBase))
// StatisticalRepository instance
c.KnowledgeBaseRepository = services.GetKnowledgeBaseRepositoryInstance()
// init PlatformRepository
c.PlatformRepository = new(services.PlatformRepository)
c.PlatformRepository.Init(new(models.Platform))
// PlatformRepository instance
c.PlatformRepository = services.GetPlatformRepositoryInstance()
}
......@@ -41,16 +39,16 @@ func (c *KnowledgeBaseController) Get() {
id, err := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err)
c.JSON(configs.ResponseFail, "fail", &err)
}
knowledgeBase := c.KnowledgeBaseRepository.GetKnowledgeBase(id)
if knowledgeBase == nil {
c.JSON(configs.ResponseFail, "查询失败!", nil)
c.JSON(configs.ResponseFail, "fail", nil)
}
c.JSON(configs.ResponseFail, "查询成功!", &knowledgeBase)
c.JSON(configs.ResponseFail, "success", &knowledgeBase)
}
// Post add a knowledge Base
......@@ -60,7 +58,7 @@ func (c *KnowledgeBaseController) Post() {
var knowledgeBase models.KnowledgeBase
knowledgeBase.CreateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &knowledgeBase); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// validation
......@@ -98,7 +96,7 @@ func (c *KnowledgeBaseController) Put() {
// request body
var newKnowledgeBase models.KnowledgeBase
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &newKnowledgeBase); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// validation
......@@ -130,7 +128,7 @@ func (c *KnowledgeBaseController) Put() {
}
// insert
row, err := c.KnowledgeBaseRepository.UpdateParams(newKnowledgeBase.ID, orm.Params{
row, err := c.KnowledgeBaseRepository.Update(newKnowledgeBase.ID, orm.Params{
"Title": newKnowledgeBase.Title,
"SubTitle": newKnowledgeBase.SubTitle,
"Content": newKnowledgeBase.Content,
......@@ -167,16 +165,16 @@ func (c *KnowledgeBaseController) Delete() {
func (c *KnowledgeBaseController) List() {
// request body
var paginationData *models.PaginationData
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationData); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err)
var knowledgePaginationDto *models.KnowledgePaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &knowledgePaginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// query
paginationData, err := c.KnowledgeBaseRepository.GetKnowledgeBases(paginationData)
knowledgePaginationDto, err := c.KnowledgeBaseRepository.GetKnowledgeBases(knowledgePaginationDto)
if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err)
c.JSON(configs.ResponseFail, "fail", &err)
}
c.JSON(configs.ResponseSucess, "查询成功!", &paginationData)
c.JSON(configs.ResponseSucess, "success", &knowledgePaginationDto)
}
......@@ -4,6 +4,7 @@ import (
"encoding/base64"
"encoding/json"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/validation"
"kefu_server/configs"
......@@ -24,10 +25,8 @@ type MessageController struct {
// Prepare More like construction method
func (c *MessageController) Prepare() {
// init MessageRepository
c.MessageRepository = new(services.MessageRepository)
c.MessageRepository.Init(new(models.Message))
// MessageRepository instance
c.MessageRepository = services.GetMessageRepositoryInstance()
}
// Finish Comparison like destructor
......@@ -36,75 +35,66 @@ func (c *MessageController) Finish() {}
// List get messages
func (c *MessageController) List() {
messagePaginationData := models.MessagePaginationData{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &messagePaginationData); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil)
messagePaginationDto := models.MessagePaginationDto{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &messagePaginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// service ID
var serviceID int64
if messagePaginationData.Service == 0 {
// GetAuthInfo
auth := c.GetAuthInfo()
serviceID = auth.UID
} else {
serviceID = messagePaginationData.Service
}
// GetAuthInfo
auth := c.GetAuthInfo()
messagePaginationDto.Service = auth.UID
// Timestamp == 0
if messagePaginationData.Timestamp == 0 {
messagePaginationData.Timestamp = time.Now().Unix()
if messagePaginationDto.Timestamp == 0 {
messagePaginationDto.Timestamp = time.Now().Unix()
}
// validation
valid := validation.Validation{}
valid.Required(messagePaginationData.Account, "account").Message("account不能为空!")
valid.Required(messagePaginationData.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(messagePaginationData.Timestamp, "timestamp").Message("timestamp不能为空!")
valid.Required(messagePaginationDto.Account, "account").Message("account不能为空!")
valid.Required(messagePaginationDto.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(messagePaginationDto.Timestamp, "timestamp").Message("timestamp不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil)
}
}
// query message
returnMessagePaginationData, err := c.MessageRepository.GetMessages(serviceID, messagePaginationData)
// query messages
returnMessagePaginationDto, err := c.MessageRepository.GetAdminMessages(messagePaginationDto)
if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err)
c.JSON(configs.ResponseFail, "fail", &err)
}
// push notify update current service contacts list
if len(im.Robots) > 0 {
im.PushNewContacts(serviceID, im.Robots[0])
im.PushNewContacts(auth.UID, im.Robots[0])
}
c.JSON(configs.ResponseSucess, "查询成功!", &returnMessagePaginationData)
c.JSON(configs.ResponseSucess, "success", &returnMessagePaginationDto)
}
// Remove one message
func (c *MessageController) Remove() {
// request body
removeRequestData := models.RemoveMessageRequestData{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &removeRequestData); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil)
removeRequestDto := models.RemoveMessageRequestDto{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &removeRequestDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
valid := validation.Validation{}
valid.Required(removeRequestData.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(removeRequestData.FromAccount, "from_account").Message("from_account不能为空!")
valid.Required(removeRequestData.Key, "key").Message("key不能为空!")
valid.Required(removeRequestDto.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(removeRequestDto.FromAccount, "from_account").Message("from_account不能为空!")
valid.Required(removeRequestDto.Key, "key").Message("key不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil)
}
}
row, err := c.MessageRepository.Delete(removeRequestData)
row, err := c.MessageRepository.Delete(removeRequestDto)
if err != nil || row == 0 {
c.JSON(configs.ResponseFail, "删除失败!", &err)
}
......@@ -117,20 +107,19 @@ func (c *MessageController) Transfer() {
// GetAuthInfo
auth := c.GetAuthInfo()
adminRepository := new(services.AdminRepository)
adminRepository.Init(new(models.Admin))
adminRepository := services.GetAdminRepositoryInstance()
admin := adminRepository.GetAdmin(auth.UID)
// request body
var transferRequestData *models.TransferRequestData
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &transferRequestData); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil)
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(transferRequestData.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(transferRequestData.UserAccount, "user_account").Message("user不能为空!")
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)
......@@ -145,15 +134,16 @@ func (c *MessageController) Transfer() {
NickName string `json:"nickname"`
Avatar string `json:"avatar"`
}
toAdmin := adminRepository.GetAdmin(transferRequestData.ToAccount)
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 := new(services.UserRepository)
userRepository.Init(new(models.User))
user := userRepository.GetUser(transferRequestData.UserAccount)
// UserRepository instance
userRepository := services.GetUserRepositoryInstance()
user := userRepository.GetUser(transferDto.UserAccount)
if user == nil {
c.JSON(configs.ResponseFail, "转接失败用户ID不存在!", nil)
}
......@@ -161,9 +151,9 @@ func (c *MessageController) Transfer() {
// message
message := models.Message{}
message.BizType = "transfer"
message.FromAccount = transferRequestData.UserAccount
message.FromAccount = transferDto.UserAccount
message.Timestamp = time.Now().Unix()
message.TransferAccount = transferRequestData.ToAccount
message.TransferAccount = transferDto.ToAccount
// Send to forwarder
message.ToAccount = admin.ID
......@@ -174,27 +164,27 @@ func (c *MessageController) Transfer() {
utils.MessageInto(message, true)
// Send to forwarded customer service
message.ToAccount = transferRequestData.ToAccount
message.ToAccount = transferDto.ToAccount
message.Payload = admin.NickName + "将" + user.NickName + "转接给您"
messageJSONTwo, _ := json.Marshal(message)
messageStringTwo := base64.StdEncoding.EncodeToString([]byte(messageJSONTwo))
robot.SendMessage(strconv.FormatInt(transferRequestData.ToAccount, 10), []byte(messageStringTwo))
robot.SendMessage(strconv.FormatInt(transferDto.ToAccount, 10), []byte(messageStringTwo))
utils.MessageInto(message, true)
// send to user
message.FromAccount = robotID
message.ToAccount = transferRequestData.UserAccount
message.ToAccount = transferDto.UserAccount
message.Delete = 1
message.Payload = string(toAdminJSON)
messageJSONThree, _ := json.Marshal(message)
messageString3 := base64.StdEncoding.EncodeToString([]byte(messageJSONThree))
robot.SendMessage(strconv.FormatInt(transferRequestData.UserAccount, 10), []byte(messageString3))
robot.SendMessage(strconv.FormatInt(transferDto.UserAccount, 10), []byte(messageString3))
utils.MessageInto(message, false)
// Transfer to the library for counting service times
servicesStatistical := models.ServicesStatistical{UserAccount: transferRequestData.UserAccount, ServiceAccount: transferRequestData.ToAccount, TransferAccount: admin.ID, Platform: user.Platform, CreateAt: time.Now().Unix()}
statisticalRepository := new(services.StatisticalRepository)
statisticalRepository.Init(new(models.ServicesStatistical))
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 {
}
......@@ -203,11 +193,14 @@ func (c *MessageController) Transfer() {
tk := time.NewTimer(1 * time.Second)
select {
case <-tk.C:
usersID := []int64{admin.ID, transferRequestData.UserAccount}
contactRepository := new(services.ContactRepository)
contactRepository.Init(new(models.Contact))
usersID := []int64{admin.ID, transferDto.UserAccount}
// ContactRepository instance
contactRepository := services.GetContactRepositoryInstance()
_, err := contactRepository.UpdateIsSessionEnd(usersID, 1)
if err != nil {
logs.Info(err)
}
}
......
......@@ -2,71 +2,66 @@ package controllers
import (
"encoding/json"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/utils"
"kefu_server/services"
"strconv"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
// PlatformController struct
type PlatformController struct {
beego.Controller
BaseController
PlatformRepository *services.PlatformRepository
}
// Prepare More like construction method
func (c *PlatformController) Prepare() {
// PlatformRepository instance
c.PlatformRepository = services.GetPlatformRepositoryInstance()
}
// Finish Comparison like destructor
func (c *PlatformController) Finish() {}
// Get get a admin
func (c *PlatformController) Get() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
platform := models.Platform{ID: id}
if err := o.Read(&platform); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &platform)
platform := c.PlatformRepository.GetPlatform(id)
if platform == nil {
c.JSON(configs.ResponseFail, "fail", nil)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &platform)
}
// Put update admin
func (c *PlatformController) Put() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
// GetAuthInfo
auth := c.GetAuthInfo()
admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
// is admin ?
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败,无权限更新", nil)
c.ServeJSON()
return
// is admin root ?
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "更新失败,无权限更新!", nil)
}
// request body
platform := models.Platform{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &platform); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// admin exist
if err := o.Read(&models.Platform{ID: platform.ID}); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败,数据不存在!", err)
c.ServeJSON()
return
// platform exist
if p := c.PlatformRepository.GetPlatform(platform.ID); p == nil {
c.JSON(configs.ResponseFail, "更新失败,数据不存在!", nil)
}
// validation
......@@ -80,64 +75,42 @@ func (c *PlatformController) Put() {
valid.MaxSize(platform.Alias, 30, "alias").Message("别名不能超过30个字符!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
// title exist
var pt models.Platform
if err := o.Raw("SELECT * FROM platform WHERE id != ? AND title = ?", platform.ID, platform.Title).QueryRow(&pt); err == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "平台名已被使用,请换一个试试!", err)
c.ServeJSON()
return
if pt := c.PlatformRepository.GetPlatformWithIDAndTitle(platform.ID, platform.Title); pt != nil {
c.JSON(configs.ResponseFail, "平台名已被使用,请换一个试试", nil)
}
// Alias exist
if err := o.Raw("SELECT * FROM platform WHERE id != ? AND alias = ?", platform.ID, platform.Alias).QueryRow(&pt); err == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "别名已被使用,请换一个试试!", err)
c.ServeJSON()
return
if pt := c.PlatformRepository.GetPlatformWithIDAndAlias(platform.ID, platform.Alias); pt != nil {
c.JSON(configs.ResponseFail, "别名已被使用,请换一个试试", nil)
}
_, _ = c.PlatformRepository.Update(platform.ID, orm.Params{
"Title": platform.Title,
"Alias": platform.Alias,
})
if _, err := o.Update(&platform, "Title", "Alias"); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", err)
} else {
platform.System = 0
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &platform)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "更新成功!", &platform)
}
// Post add new admin
// Post add new platform
func (c *PlatformController) Post() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限添加平台!", nil)
c.ServeJSON()
return
// GetAuthInfo
auth := c.GetAuthInfo()
admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "您没有权限添加平台!", nil)
}
// request body
var platform models.Platform
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &platform); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
......@@ -149,86 +122,66 @@ func (c *PlatformController) Post() {
valid.MaxSize(platform.Alias, 30, "alias").Message("别名不能超过30个字符!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
var pt models.Platform
if err := o.Raw("SELECT * FROM platform WHERE id != ? AND alias = ?", platform.ID, platform.Alias).QueryRow(&pt); err == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "别名已被使用,请换一个试试!", err)
c.ServeJSON()
return
pt := c.PlatformRepository.GetPlatformWithIDAndAlias(platform.ID, platform.Alias)
if pt != nil {
c.JSON(configs.ResponseFail, "别名已被使用,请换一个试试!", nil)
}
// exist ? and create
platform.ID = 0
if isExist, _, err := o.ReadOrCreate(&platform, "Title"); err == nil {
if isExist {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "添加成功!", nil)
} else {
c.Data["json"] = utils.ResponseError(c.Ctx, "平台名已被使用,请换一个试试!", nil)
}
} else {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "服务异常", err)
isExist, _, err := c.PlatformRepository.Add(&platform, "Title")
if err != nil {
c.JSON(configs.ResponseFail, "添加失败,换个名字试试!", nil)
}
if !isExist {
c.JSON(configs.ResponseFail, "平台名已被使用,请换一个试试!", nil)
}
c.ServeJSON()
return
c.JSON(configs.ResponseSucess, "添加成功!", nil)
}
// Delete delete remove admin
func (c *PlatformController) Delete() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限删除平台!", nil)
c.ServeJSON()
return
// GetAuthInfo
auth := c.GetAuthInfo()
admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "您没有权限添加平台!", nil)
}
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// platform
platform := models.Platform{ID: id}
platform := c.PlatformRepository.GetPlatform(id)
// exist
if err := o.Read(&platform); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,平台不存在!", err)
c.ServeJSON()
return
if platform == nil {
c.JSON(configs.ResponseFail, "删除失败,平台不存在!", nil)
}
if num, err := o.Delete(&platform); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败!", nil)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "删除成功!", num)
if _, err := c.PlatformRepository.Delete(id); err != nil {
c.JSON(configs.ResponseFail, "删除失败!", &err)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "删除成功!", nil)
}
// List get admin all
func (c *PlatformController) List() {
o := orm.NewOrm()
var platforms []models.Platform
qs := o.QueryTable(new(models.Platform))
if _, err := qs.OrderBy("id").All(&platforms); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &platforms)
platforms, err := c.PlatformRepository.GetPlatformAll("id")
if err != nil {
c.JSON(configs.ResponseFail, "fail", &err)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &platforms)
}
......@@ -2,79 +2,69 @@ package controllers
import (
"encoding/json"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/utils"
"kefu_server/services"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
// QiniuController struct
type QiniuController struct {
beego.Controller
BaseController
QiniuRepository *services.QiniuRepository
AdminRepository *services.AdminRepository
}
// Prepare More like construction method
func (c *QiniuController) Prepare() {
// QiniuRepository instance
c.QiniuRepository = services.GetQiniuRepositoryInstance()
// AdminRepository instance
c.AdminRepository = services.GetAdminRepositoryInstance()
}
// Finish Comparison like destructor
func (c *QiniuController) Finish() {}
// Get get qiniu config info
func (c *QiniuController) Get() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
// GetAuthInfo
auth := c.GetAuthInfo()
admin := c.AdminRepository.GetAdmin(auth.UID)
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "您没有权限获取配置!", nil)
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限获取配置!", nil)
c.ServeJSON()
return
// get qiniu config info
qiniuSetting := c.QiniuRepository.GetQiniuConfigInfo()
if qiniuSetting == nil {
c.JSON(configs.ResponseFail, "fail", nil)
}
qiniuSetting := models.QiniuSetting{ID: 1}
if err := o.Read(&qiniuSetting); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &qiniuSetting)
}
c.ServeJSON()
// return
c.JSON(configs.ResponseSucess, "success", &qiniuSetting)
}
// Put update
func (c *QiniuController) Put() {
qiniuSetting := models.QiniuSetting{}
qiniuSetting.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &qiniuSetting); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "fail", nil)
}
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限设置!", nil)
c.ServeJSON()
return
// GetAuthInfo
auth := c.GetAuthInfo()
admin := c.AdminRepository.GetAdmin(auth.UID)
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "您没有权限获取配置!", nil)
}
// validation
......@@ -89,21 +79,20 @@ func (c *QiniuController) Put() {
valid.MaxSize(qiniuSetting.Host, 100, "host").Message("host不能超过100字符!")
if valid.HasErrors() {
for _, err := range valid.Errors {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
qiniuSetting.ID = 1
qiniuSetting.UpdateAt = time.Now().Unix()
if _, err := o.Update(&qiniuSetting); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &qiniuSetting)
// update
if _, err := c.QiniuRepository.Update(orm.Params{
"Bucket": qiniuSetting.Bucket,
"AccessKey": qiniuSetting.AccessKey,
"SecretKey": qiniuSetting.SecretKey,
"Host": qiniuSetting.Host,
"UpdateAt": time.Now().Unix(),
}); err != nil {
c.JSON(configs.ResponseFail, "更新失败!", &err)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "更新成功!", &qiniuSetting)
}
......@@ -2,95 +2,52 @@ package controllers
import (
"encoding/json"
"kefu_server/utils"
"time"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/services"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
// ServicesStatisticalController struct
type ServicesStatisticalController struct {
beego.Controller
BaseController
StatisticalRepository *services.StatisticalRepository
}
// ServicesStatisticalPaginationData struct
type ServicesStatisticalPaginationData struct {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"`
Cid int64 `json:"cid"`
Date string `json:"date"`
IsDeWeighting bool `json:"is_de_weighting"`
Total int64 `json:"total"`
List interface{} `json:"list"`
// Prepare More like construction method
func (c *ServicesStatisticalController) Prepare() {
// StatisticalRepository instance
c.StatisticalRepository = services.GetStatisticalRepositoryInstance()
}
// Finish Comparison like destructor
func (c *ServicesStatisticalController) Finish() {}
// List Services Statistical
func (c *ServicesStatisticalController) List() {
// request body
var paginationData ServicesStatisticalPaginationData
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationData); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", err)
c.ServeJSON()
return
var paginationDto models.ServicesStatisticalPaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// validation
valid := validation.Validation{}
valid.Required(paginationData.PageOn, "page_on").Message("page_on不能为空!")
valid.Required(paginationData.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(paginationData.Cid, "cid").Message("cid不能为空!")
valid.Required(paginationData.Date, "date").Message("date不能为空!")
valid.Required(paginationDto.PageOn, "page_on").Message("page_on不能为空!")
valid.Required(paginationDto.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(paginationDto.Cid, "cid").Message("cid不能为空!")
valid.Required(paginationDto.Date, "date").Message("date不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
o := orm.NewOrm()
layoutDate := "2006-01-02 15:04:05"
loc, _ := time.LoadLocation("Local")
startDateStr := paginationData.Date + " 00:00:00"
endDateStr := paginationData.Date + " 23:59:59"
startDate, _ := time.ParseInLocation(layoutDate, startDateStr, loc)
endDate, _ := time.ParseInLocation(layoutDate, endDateStr, loc)
var params []orm.Params
type TotalModel struct {
Count int64
}
var totalModel TotalModel
// Deduplication
addSQL := " COUNT(*) "
if paginationData.IsDeWeighting {
addSQL = " count(distinct user_account) "
}
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 < ?", paginationData.Cid, startDate.Unix(), endDate.Unix()).QueryRow(&totalModel)
paginationData.Total = totalModel.Count
// Deduplication
addSQL1 := " "
if paginationData.IsDeWeighting {
addSQL1 = " GROUP BY `user_account` "
}
if counter, _ := 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 ?,?", paginationData.Cid, startDate.Unix(), endDate.Unix(), (paginationData.PageOn-1)*paginationData.PageSize, paginationData.PageSize).Values(&params); counter <= 0 {
paginationData.List = []string{}
c.Data["json"] = paginationData
} else {
paginationData.List = params
c.Data["json"] = paginationData
}
// get data
data := c.StatisticalRepository.GetCustomerServiceList(paginationDto)
c.JSON(configs.ResponseSucess, "success", &data)
c.ServeJSON()
}
package controllers
import (
"encoding/base64"
"encoding/json"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/utils"
"kefu_server/services"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
// ShortcutController struct
type ShortcutController struct {
beego.Controller
BaseController
ShortcutRepository *services.ShortcutRepository
}
// Prepare More like construction method
func (c *ShortcutController) Prepare() {
// ShortcutRepository instance
c.ShortcutRepository = services.GetShortcutRepositoryInstance()
}
// Finish Comparison like destructor
func (c *ShortcutController) Finish() {}
// Get get shortcut
func (c *ShortcutController) Get() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
// GetAuthInfo
auth := c.GetAuthInfo()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
shortcut := models.Shortcut{ID: id}
if err := o.Read(&shortcut); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,内容不存在!", err)
} else {
if _admin.ID != shortcut.UID {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,内容不存在!", nil)
} else {
title, _ := base64.StdEncoding.DecodeString(shortcut.Title)
content, _ := base64.StdEncoding.DecodeString(shortcut.Content)
shortcut.Title = string(title)
shortcut.Content = string(content)
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &shortcut)
}
shortcut := c.ShortcutRepository.GetShortcut(id)
if shortcut == nil || auth.UID != shortcut.UID {
c.JSON(configs.ResponseFail, "fail,内容不存在!", nil)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &shortcut)
}
// Put update shortcut
func (c *ShortcutController) Put() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
// GetAuthInfo
auth := c.GetAuthInfo()
// request body
shortcut := models.Shortcut{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shortcut); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
......@@ -80,54 +60,37 @@ func (c *ShortcutController) Put() {
valid.Required(shortcut.Content, "content").Message("内容不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
oldShortcut := models.Shortcut{ID: shortcut.ID}
_ = o.Read(&oldShortcut)
if oldShortcut.UID != _admin.ID {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败,内容不存在!", nil)
c.ServeJSON()
return
// if is my shortcut
if shortcut.UID != auth.UID {
c.JSON(configs.ResponseFail, "更新失败,内容不存在!", nil)
}
// update
shortcut.Title = base64.StdEncoding.EncodeToString([]byte(shortcut.Title))
shortcut.Content = base64.StdEncoding.EncodeToString([]byte(shortcut.Content))
if _, err := o.Update(&shortcut, "UpdateAt", "Content", "Title"); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", nil)
}
c.ServeJSON()
_, err := c.ShortcutRepository.Update(shortcut.ID, orm.Params{
"UpdateAt": time.Now().Unix(),
"Content": shortcut.Content,
"Title": shortcut.Title,
})
if err != nil {
c.JSON(configs.ResponseFail, "更新失败!", nil)
}
c.JSON(configs.ResponseSucess, "更新成功!", nil)
}
// Post add new shortcut
func (c *ShortcutController) Post() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
// GetAuthInfo
auth := c.GetAuthInfo()
// request body
var shortcut models.Shortcut
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shortcut); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
......@@ -136,99 +99,42 @@ func (c *ShortcutController) Post() {
valid.Required(shortcut.Content, "content").Message("内容不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
// exist ? create
shortcut.UID = _admin.ID
shortcut.CreateAt = time.Now().Unix()
shortcut.Title = base64.StdEncoding.EncodeToString([]byte(shortcut.Title))
shortcut.Content = base64.StdEncoding.EncodeToString([]byte(shortcut.Content))
if isExist, createID, err := o.ReadOrCreate(&shortcut, "Title", "Uid"); err == nil {
if isExist {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "添加成功!", &createID)
} else {
c.Data["json"] = utils.ResponseError(c.Ctx, "已存在相同的内容!", nil)
}
} else {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "服务异常!", err)
shortcut.UID = auth.UID
isNew, _, err := c.ShortcutRepository.Add(&shortcut, "Title", "Uid")
if err != nil {
c.JSON(configs.ResponseFail, "添加失败!", nil)
}
c.ServeJSON()
return
if !isNew {
c.JSON(configs.ResponseFail, "已存在相同的内容!", nil)
}
c.JSON(configs.ResponseSucess, "添加成功!!", nil)
}
// Delete delete remove shortcut
func (c *ShortcutController) Delete() {
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
// GetAuthInfo
auth := c.GetAuthInfo()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
shortcut := models.Shortcut{ID: id}
// exist
if err := o.Read(&shortcut); err != nil || shortcut.UID != _admin.ID {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,内容不存在!", nil)
c.ServeJSON()
return
if row, err := c.ShortcutRepository.Delete(id, auth.UID); err != nil || row == 0 {
c.JSON(configs.ResponseFail, "删除失败!", &err)
}
if num, err := o.Delete(&shortcut); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败!", nil)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "删除成功!", &num)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "删除成功!!", nil)
}
// List get shortcut all
func (c *ShortcutController) List() {
o := orm.NewOrm()
shortcut := new(models.Shortcut)
qs := o.QueryTable(shortcut)
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
// GetAuthInfo
auth := c.GetAuthInfo()
// query
var lists []models.Shortcut
if _, err := qs.Filter("uid", _admin.ID).OrderBy("-create_at").All(&lists); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
c.ServeJSON()
return
}
// base 64转换回来
for index, shortcut := range lists {
title, _ := base64.StdEncoding.DecodeString(shortcut.Title)
content, _ := base64.StdEncoding.DecodeString(shortcut.Content)
lists[index].Title = string(title)
lists[index].Content = string(content)
}
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &lists)
c.ServeJSON()
shortcuts := c.ShortcutRepository.GetShortcuts(auth.UID)
c.JSON(configs.ResponseSucess, "success", &shortcuts)
}
......@@ -2,33 +2,40 @@ package controllers
import (
"encoding/json"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/utils"
"kefu_server/services"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
// SystemController struct
type SystemController struct {
beego.Controller
BaseController
SystemRepository *services.SystemRepository
}
// Prepare More like construction method
func (c *SystemController) Prepare() {
// ShortcutRepository instance
c.SystemRepository = services.GetSystemRepositoryInstance()
}
// Finish Comparison like destructor
func (c *SystemController) Finish() {}
// Get get info
func (c *SystemController) Get() {
o := orm.NewOrm()
system := models.System{ID: 1}
if err := o.Read(&system); err != nil {
logs.Error(err)
c.Data["json"] = &models.Response{Code: 400, Message: "查询失败", Data: err}
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &system)
system := c.SystemRepository.GetSystem()
if system == nil {
c.JSON(configs.ResponseFail, "fail", nil)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &system)
}
......@@ -36,38 +43,22 @@ func (c *SystemController) Get() {
func (c *SystemController) Put() {
system := models.System{}
system.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &system); err != nil {
logs.Error(err)
c.Data["json"] = &models.Response{Code: 400, Message: "参数错误", Data: nil}
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
o := orm.NewOrm()
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限修改系统设置!", nil)
c.ServeJSON()
return
// GetAuthInfo
auth := c.GetAuthInfo()
admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
// is root ?
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "您没有权限修改系统设置!", nil)
}
// validation upload mode
var uploadValues []orm.Params
_, _ = o.Raw("SELECT * FROM uploads_config where id = ?", system.UploadMode).Values(&uploadValues)
if len(uploadValues) <= 0 {
c.Data["json"] = utils.ResponseError(c.Ctx, "上传模型选项不存在!", nil)
c.ServeJSON()
return
uploadConfig := services.GetUploadsConfigRepositoryInstance().GetUploadsConfig(int64(system.UploadMode))
if uploadConfig == nil {
c.JSON(configs.ResponseFail, "上传模型选项不存在!", nil)
}
// validation request
......@@ -78,22 +69,20 @@ func (c *SystemController) Put() {
valid.Required(system.Logo, "logo").Message("系统LOGO不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
system.ID = 1
system.UpdateAt = time.Now().Unix()
if _, err := o.Update(&system); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &system)
// update
_, err := c.SystemRepository.Update(orm.Params{
"Title": system.Title,
"Logo": system.Logo,
"CopyRight": system.CopyRight,
"UploadMode": system.UploadMode,
"UpdateAt": time.Now().Unix(),
})
if err != nil {
c.JSON(configs.ResponseFail, "更新失败!", &err)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "更新成功!", &system)
}
package controllers
import (
"kefu_server/models"
"kefu_server/utils"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"kefu_server/configs"
"kefu_server/services"
)
// UploadsConfigController struct
type UploadsConfigController struct {
beego.Controller
BaseController
UploadsConfigRepository *services.UploadsConfigRepository
}
// Prepare More like construction method
func (c *UploadsConfigController) Prepare() {
// UploadsConfigRepository instance
c.UploadsConfigRepository = services.GetUploadsConfigRepositoryInstance()
}
// Config get upload config
// Finish Comparison like destructor
func (c *UploadsConfigController) Finish() {}
// Config get upload config all
func (c *UploadsConfigController) Config() {
o := orm.NewOrm()
var configs []models.UploadsConfig
if _, err := o.QueryTable(new(models.UploadsConfig)).All(&configs); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &configs)
}
c.ServeJSON()
uploadsConfigs := c.UploadsConfigRepository.GetUploadsConfigs()
c.JSON(configs.ResponseSucess, "success", &uploadsConfigs)
}
......@@ -2,33 +2,43 @@ package controllers
import (
"encoding/json"
"kefu_server/configs"
"kefu_server/models"
"kefu_server/utils"
"kefu_server/services"
"strconv"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
)
// UserController struct
type UserController struct {
beego.Controller
BaseController
UserRepository *services.UserRepository
}
// Prepare More like construction method
func (c *UserController) Prepare() {
// UserRepository instance
c.UserRepository = services.GetUserRepositoryInstance()
}
// Finish Comparison like destructor
func (c *UserController) Finish() {}
// Get get a user
func (c *UserController) Get() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
user := models.User{ID: id}
if err := o.Read(&user); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,用户不存在!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &user)
user := c.UserRepository.GetUser(id)
if user == nil {
c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &user)
}
......@@ -37,11 +47,8 @@ func (c *UserController) Put() {
// request
user := models.User{}
user.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &user); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", err)
c.ServeJSON()
return
c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
}
// validation
......@@ -53,25 +60,27 @@ func (c *UserController) Put() {
valid.MaxSize(user.Remarks, 150, "remarks").Message("用户备注不能超过150个字符!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, nil)
}
c.ServeJSON()
return
}
// orm
o := orm.NewOrm()
if _, err := o.Update(&user, "Address", "NickName", "Phone", "Remarks", "UpdateAt", "UpdateAt", "Avatar"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", nil)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &user)
// update
_, err := c.UserRepository.Update(user.ID, orm.Params{
"Address": user.Address,
"NickName": user.NickName,
"Phone": user.Phone,
"Remarks": user.Remarks,
"UpdateAt": time.Now().Unix(),
"Avatar": user.Avatar,
})
if err != nil {
c.JSON(configs.ResponseFail, "更新失败!", &err)
}
c.ServeJSON()
c.JSON(configs.ResponseSucess, "更新成功!", nil)
}
// Post add new user
// 用户创建 请移步(此处暂不提供创建用户逻辑) /v1/im/register
// Create user Please move on (the user creation logic is not provided here /v1/public/register)
func (c *UserController) Post() {
c.ServeJSON()
}
......@@ -79,134 +88,68 @@ func (c *UserController) Post() {
// Delete delete remove user
func (c *UserController) Delete() {
// orm instance
o := orm.NewOrm()
// uid
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// is admin ?
token := c.Ctx.Input.Header("Authorization")
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil)
c.ServeJSON()
return
}
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限删除用户!", nil)
c.ServeJSON()
return
// GetAuthInfo
auth := c.GetAuthInfo()
admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
if admin.Root != 1 {
c.JSON(configs.ResponseFail, "您没有权限删除用户!", nil)
}
// user
user := models.User{ID: id}
user := c.UserRepository.GetUser(id)
// exist
if err := o.Read(&user); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,用户不存在!", err)
c.ServeJSON()
return
if user == nil {
c.JSON(configs.ResponseFail, "删除失败,用户不存在!", nil)
}
if num, err := o.Delete(&user); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败!", nil)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "删除成功!", &num)
// delete
if _, err := c.UserRepository.Delete(id); err != nil {
c.JSON(configs.ResponseFail, "删除失败!", &err)
}
c.ServeJSON()
}
// UsersPaginationData struct
type UsersPaginationData struct {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"`
Keyword string `json:"keyword"`
Total int64 `json:"total"`
Platform int64 `json:"platform"`
DateStart string `json:"date_start"`
DateEnd string `json:"date_end"`
List interface{} `json:"list"`
c.JSON(configs.ResponseSucess, "删除成功!", nil)
}
// Users get users
func (c *UserController) Users() {
// request body
var usersPaginationData UsersPaginationData
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &usersPaginationData); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误", err)
c.ServeJSON()
return
var usersPaginationDto models.UsersPaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &usersPaginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
}
// validation
valid := validation.Validation{}
valid.Required(usersPaginationData.PageOn, "page_on").Message("page_on不能为空!")
valid.Required(usersPaginationData.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(usersPaginationDto.PageOn, "page_on").Message("page_on不能为空!")
valid.Required(usersPaginationDto.PageSize, "page_size").Message("page_size不能为空!")
if valid.HasErrors() {
for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
c.JSON(configs.ResponseFail, err.Message, &err)
}
c.ServeJSON()
return
}
// orm instance
o := orm.NewOrm()
qs := o.QueryTable(new(models.User))
cond := orm.NewCondition()
var cond1 *orm.Condition
var cond2 *orm.Condition
if usersPaginationData.Keyword != "" {
cond1 = cond.Or("nickname__icontains", usersPaginationData.Keyword).Or("phone__icontains", usersPaginationData.Keyword).Or("remarks__icontains", usersPaginationData.Keyword)
}
// exist platfrom id?
if usersPaginationData.Platform != 0 && usersPaginationData.Platform != 1 {
cond2 = cond.And("platform", usersPaginationData.Platform)
// get users
res, err := c.UserRepository.GetUsers(&usersPaginationDto)
if err != nil {
c.JSON(configs.ResponseFail, "fail", &err)
}
// exist platfrom date?
if usersPaginationData.DateStart != "" && usersPaginationData.DateEnd != "" {
layoutDate := "2006-01-02 15:04:05"
loc, _ := time.LoadLocation("Local")
dateStartString := usersPaginationData.DateStart + " 00:00:00"
dateEndString := usersPaginationData.DateEnd + " 23:59:59"
dateStart, _ := time.ParseInLocation(layoutDate, dateStartString, loc)
dateEnd, _ := time.ParseInLocation(layoutDate, dateEndString, loc)
cond2 = cond2.And("create_at__gte", dateStart.Unix()).And("create_at__lte", dateEnd.Unix())
}
// query
var lists []models.User
cond3 := cond.AndCond(cond2).OrCond(cond1)
qs = qs.SetCond(cond3)
qs = qs.OrderBy("-online", "-create_at").Limit(usersPaginationData.PageSize)
if _, err := qs.Offset((usersPaginationData.PageOn - 1) * usersPaginationData.PageSize).All(&lists); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败", err)
c.ServeJSON()
return
}
total, _ := qs.Count()
usersPaginationData.Total = total
usersPaginationData.List = &lists
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &usersPaginationData)
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &res)
}
// OnLineCount get all online user count
func (c *UserController) OnLineCount() {
o := orm.NewOrm()
if onLineCount, err := o.QueryTable(models.User{}).Filter("online", 1).Count(); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", nil)
c.ServeJSON()
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", onLineCount)
c.ServeJSON()
rows, err := c.UserRepository.GetOnlineCount()
if err != nil {
c.JSON(configs.ResponseFail, "fail", &err)
}
c.JSON(configs.ResponseSucess, "success", &rows)
}
......@@ -2,40 +2,23 @@
# ! /bin/sh
SERVICE_PATH="/home/kefu_server"
CURRENT_PATH=$(readlink -f "$(dirname "$0")")
SERVICE_PATH="$CURRENT_PATH/kefu_server"
SERVICE_NAME="kefu_server"
START_CMD="nohup ./$SERVICE_NAME &"
LOG_FILE="restart.log"
cd $SERVICE_PATH
pwd
while true
do
procnum=`ps -ef|grep $SERVICE_NAME|grep -v grep|wc -l`
if [ $procnum -eq 0 ]
then
echo "start service...................."
echo `date +%Y-%m-%d` `date +%H:%M:%S` $SERVICE_NAME >>$LOG_FILE
${START_CMD}
fi
sleep 5
done
......@@ -14,24 +14,24 @@ import (
// PushNewContacts 推送最新聊天列表给客服
func PushNewContacts(accountID int64, robot *mimc.MCUser) {
o := orm.NewOrm()
var contactData []models.ContactData
var contactDto []models.ContactDto
// 消息体
message := models.Message{}
message.BizType = "contacts"
robotAccount, _ := strconv.ParseInt(robot.AppAccount(), 10, 64)
message.FromAccount = robotAccount
message.Timestamp = time.Now().Unix()
rCount, _ := 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", accountID).QueryRows(&contactData)
rCount, _ := 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", accountID).QueryRows(&contactDto)
if rCount == 0 {
contactData = []models.ContactData{}
contactDto = []models.ContactDto{}
}
// base 64转换回来
for index, contact := range contactData {
for index, contact := range contactDto {
payload, _ := base64.StdEncoding.DecodeString(contact.LastMessage)
contactData[index].LastMessage = string(payload)
contactDto[index].LastMessage = string(payload)
}
message.ToAccount = accountID
messageContentByte, _ := json.Marshal(contactData)
messageContentByte, _ := json.Marshal(contactDto)
message.Payload = string(messageContentByte)
messageJSON, _ := json.Marshal(message)
messageString := base64.StdEncoding.EncodeToString([]byte(messageJSON))
......
......@@ -2,12 +2,11 @@ package im
import (
"kefu_server/models"
"kefu_server/services"
"strconv"
"strings"
"github.com/Xiaomi-mimc/mimc-go-sdk"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
)
// Robots 工作中的机器人
......@@ -26,18 +25,12 @@ func CreateRobot(appAccount string) *mimc.MCUser {
// GetRobots get robot all
func GetRobots() []models.Robot {
// orm instance
o := orm.NewOrm()
robot := new(models.Robot)
qs := o.QueryTable(robot)
// 查询
var lists []models.Robot
_, _ = qs.OrderBy("-create_at").All(&lists)
for index := range lists {
lists[index].Artificial = strings.Trim(lists[index].Artificial, "|")
}
return lists
// RobotRepository instance
robotRepository := services.GetRobotRepositoryInstance()
var robots []models.Robot
robots, _ = robotRepository.GetRobots()
return robots
}
// RobotInit 初始化机器人
......
package models
// Company struct
type Company struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // id
Title string `orm:"null;type(char);column(title)" json:"title"` // 公司名称
Logo string `orm:"null;type(char);column(logo)" json:"logo"` // 公司logo
Service string `orm:"null;column(service)" json:"service"` // 在线客服服务时间
Email string `orm:"null;column(email)" json:"email"` // 公司邮箱
Tel string `orm:"null;column(tel)" json:"tel"` // 公司电话
Address string `orm:"null;type(char);column(address)" json:"address"` // 公司地址
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 最后一次更新时间
}
package models
// Company struct
type Company struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // id
Title string `orm:"null;type(char);column(title)" json:"title"` // 公司名称
Logo string `orm:"null;type(char);column(logo)" json:"logo"` // 公司logo
Service string `orm:"null;column(service)" json:"service"` // 在线客服服务时间
Email string `orm:"null;column(email)" json:"email"` // 公司邮箱
Tel string `orm:"null;column(tel)" json:"tel"` // 公司电话
Address string `orm:"null;type(char);column(address)" json:"address"` // 公司地址
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"`
}
package models
// Contact 通讯录
type Contact struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"` // 递增ID
FromAccount int64 `orm:"type(bigint);column(from_account)" json:"from_account"` // 接收者Account
ToAccount int64 `orm:"type(bigint);column(to_account)" json:"to_account"` // 发送者Account
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"` // 最后一条消息内容
Delete int `orm:"default(0);column(delete)" json:"delete"` // 1 已删除 0 未删除
LastMessageType string `orm:"null;type(text);column(last_message_type)" json:"last_message_type"` // 最后一条消息类型
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"` // 创建时间
}
package models
// ContactData struct
type ContactData struct {
// ContactDto struct
type ContactDto struct {
ID int64 `orm:"column(id)" json:"id"`
Cid int64 `json:"cid"`
FromAccount int64 `json:"from_account"`
......
package models
// Contact 通讯录
type Contact struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"`
FromAccount int64 `orm:"type(bigint);column(from_account)" json:"from_account"`
ToAccount int64 `orm:"type(bigint);column(to_account)" json:"to_account"`
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"`
Delete int `orm:"default(0);column(delete)" json:"delete"` // 1 已删除 0 未删除
LastMessageType string `orm:"null;type(text);column(last_message_type)" json:"last_message_type"`
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"`
}
package models
// IMToken struct
type IMToken struct {
Code int `json:"code"`
Message string `json:"message"`
Data IMTokenData `json:"data"`
// IMTokenDto struct
type IMTokenDto struct {
Code int `json:"code"`
Message string `json:"message"`
Data IMTokenDataDto `json:"data"`
}
// IMTokenData struct
type IMTokenData struct {
// IMTokenDataDto struct
type IMTokenDataDto struct {
AppID string `json:"appId"`
AppPackage string `json:"appPackage"`
AppAccount string `json:"appAccount"`
......
package models
// JwtKey struct
type JwtKey struct {
// JwtKeyDto struct
type JwtKeyDto struct {
ID int64
AuthType int64
UserName string
......
package models
// KnowledgeBase struct
type KnowledgeBase struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // 递增ID
UID int64 `orm:"type(bigint);column(uid)" json:"uid"` // 所属发布者者ID
Title string `orm:"unique;type(char);column(title)" json:"title"` // 标题
SubTitle string `orm:"null;type(content);column(sub_title)" json:"sub_title"` // 子标题
Content string `orm:"null;type(text);column(content)" json:"content"` // 内容
Platform int64 `orm:"default(1),type(bigint);column(platform)" json:"platform"` // 0是匹配所有,其它
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 更新时间
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"` // 创建时间
}
package models
// KnowledgeBase struct
type KnowledgeBase struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"`
UID int64 `orm:"type(bigint);column(uid)" json:"uid"`
Title string `orm:"unique;type(char);column(title)" json:"title"`
SubTitle string `orm:"null;type(content);column(sub_title)" json:"sub_title"`
Content string `orm:"null;type(text);column(content)" json:"content"`
Platform int64 `orm:"default(1),type(bigint);column(platform)" json:"platform"` // 0是匹配所有
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"`
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"`
}
package models
// PaginationData struct
type PaginationData struct {
// KnowledgePaginationDto struct
type KnowledgePaginationDto struct {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"`
Keyword string `json:"keyword"`
......
package models
// MessagePaginationData struct
type MessagePaginationData struct {
// MessagePaginationDto struct
type MessagePaginationDto struct {
PageSize int `json:"page_size"`
Total int64 `json:"total"`
Account int64 `json:"account"`
......
......@@ -2,12 +2,13 @@ package models
// Platform struct
type Platform struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"`
Title string `orm:"unique;type(char);column(title)" json:"title"`
Alias string `orm:"unique;type(char);column(alias)" json:"alias"`
System int `orm:"default(0);column(system)" json:"system"`
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // ID
Title string `orm:"unique;type(char);column(title)" json:"title"` // 平台名称
Alias string `orm:"unique;type(char);column(alias)" json:"alias"` // 平台别名
System int `orm:"default(0);column(system)" json:"system"` // 是否是系统设定
}
// System seting
//INSERT INTO `kefu_server`.`platform`(`id`, `title`, `alias`, `system`) VALUES (0, '全平台', 'all', 1);
//INSERT INTO `kefu_server`.`platform`(`id`, `title`, `alias`, `system`) VALUES (1, 'IOS', 'ios', 1);
//INSERT INTO `kefu_server`.`platform`(`id`, `title`, `alias`, `system`) VALUES (2, '小程序', 'small', 1);
......
package models
// QiniuSetting struct
type QiniuSetting struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"` // ID
Bucket string `orm:"type(char);column(bucket)" json:"bucket"` // Bucket
AccessKey string `orm:"unique;type(char);column(access_key)" json:"access_key"` // AccessKey
SecretKey string `orm:"type(char);column(secret_key)" json:"secret_key"`
Host string `orm:"type(char);column(host)" json:"host"` // Host
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 更新时间
}
package models
// QiniuSetting struct
type QiniuSetting struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"`
Bucket string `orm:"type(char);column(bucket)" json:"bucket"`
AccessKey string `orm:"unique;type(char);column(access_key)" json:"access_key"`
SecretKey string `orm:"type(char);column(secret_key)" json:"secret_key"`
Host string `orm:"type(char);column(host)" json:"host"`
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"`
}
package models
// RemoveMessageRequestData struct
type RemoveMessageRequestData struct {
// RemoveMessageRequestDto struct
type RemoveMessageRequestDto struct {
FromAccount int64 `json:"from_account"`
ToAccount int64 `json:"to_account"`
Key int64 `json:"key"`
......
......@@ -2,9 +2,9 @@ package models
import "kefu_server/configs"
// Response struct
type Response struct {
// ResponseDto struct
type ResponseDto struct {
Code configs.ResponseStatusType `json:"code"` // 错误类型
Message string `json:"message"` // 信息
Data interface{} `json:"data"` // 任意类型
Message string `json:"message"` // 信息
Data interface{} `json:"data"` // 任意类型
}
package models
// Robot struct
type Robot struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // 机器人ID
NickName string `orm:"unique;type(char);column(nickname)" json:"nickname"` // 机器人名称
Avatar string `orm:"type(char);column(avatar)" json:"avatar"` // 机器人头像
Welcome string `orm:"column(welcome)" json:"welcome"` // 欢迎语
Understand string `orm:"column(understand)" json:"understand"` // 不明白语句
Artificial string `orm:"column(artificial)" json:"artificial"` // 关键词转人工
KeyWord string `orm:"column(keyword)" json:"keyword"` // 知识库默认匹配词
TimeoutText string `orm:"column(timeout_text)" json:"timeout_text"` // 超时提示语
NoServices string `orm:"column(no_services)" json:"no_services"` // 无人工在线提示语
LoogTimeWaitText string `orm:"column(loog_time_wait_text)" json:"loog_time_wait_text"` // 长时间等待提示
Switch int `orm:"default(0);column(switch)" json:"switch"` // 是否开启
System int `orm:"default(0);column(system)" json:"system"` // 系统内置
Platform int64 `orm:"type(bigint);column(platform)" json:"platform"` // 服务那个平台
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"` // 创建时间
}
package models
// Robot struct
type Robot struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"`
NickName string `orm:"unique;type(char);column(nickname)" json:"nickname"`
Avatar string `orm:"type(char);column(avatar)" json:"avatar"`
Welcome string `orm:"column(welcome)" json:"welcome"` // 欢迎语
Understand string `orm:"column(understand)" json:"understand"` // 不明白语句
Artificial string `orm:"column(artificial)" json:"artificial"` // 关键词转人工
KeyWord string `orm:"column(keyword)" json:"keyword"` // 知识库默认匹配词
TimeoutText string `orm:"column(timeout_text)" json:"timeout_text"` // 超时提示语
NoServices string `orm:"column(no_services)" json:"no_services"` // 无人工在线提示语
LoogTimeWaitText string `orm:"column(loog_time_wait_text)" json:"loog_time_wait_text"` // 长时间等待提示
Switch int `orm:"default(0);column(switch)" json:"switch"` // 是否开启
System int `orm:"default(0);column(system)" json:"system"` // 系统内置
Platform int64 `orm:"type(bigint);column(platform)" json:"platform"` // 服务那个平台
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"`
}
package models
// ServicesStatisticalPaginationDto struct
type ServicesStatisticalPaginationDto struct {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"`
Cid int64 `json:"cid"`
Date string `json:"date"`
IsDeWeighting bool `json:"is_de_weighting"`
Total int64 `json:"total"`
List interface{} `json:"list"`
}
package models
// SessionRequest 会话资料
// SessionRequestDto 客户请求注册会话资料
// type 用户类型 0 | 1 0 = 用户 1 = 客服
// uid 自身业务平台用户ID
// account_id 用户客服ID,用户在mimc的唯一ID
// platform 平台 1,2,3,4,5
type SessionRequest struct {
type SessionRequestDto struct {
Type int `json:"type"`
UID int64 `orm:"column(uid)" json:"uid"`
Platform int64 `json:"platform"`
......
package models
// Shortcut 快捷语
type Shortcut struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"` // ID
UID int64 `orm:"type(bigint);column(uid)" json:"uid"` // 用户ID
Title string `orm:"type(text);null;column(title)" json:"title"` // 标题
Content string `orm:"type(text);null;column(content)" json:"content"` // 内容
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 更新时间
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"` // 创建时间
}
package models
// Shortcut 快捷语
type Shortcut struct {
ID int64 `orm:"auto;pk;column(id)" json:"id"`
UID int64 `orm:"type(bigint);column(uid)" json:"uid"`
Title string `orm:"type(text);null;column(title)" json:"title"`
Content string `orm:"type(text);null;column(content)" json:"content"`
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"`
CreateAt int64 `orm:"type(bigint);column(create_at)" json:"create_at"`
}
package models
// System struct
type System struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // ID
Title string `orm:"type(char);column(title)" json:"title"` // 系统名称
Logo string `orm:"type(char);column(logo)" json:"logo"` // logo
CopyRight string `orm:"column(copy_right)" json:"copy_right"` // 版权
UploadMode int `orm:"column(upload_mode)" json:"upload_mode"` // 1系统内置,2 七牛云,其它的后续可以扩展
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"` // 更新时间
}
package models
// System struct
type System struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // id
Title string `orm:"type(char);column(title)" json:"title"`
Logo string `orm:"type(char);column(logo)" json:"logo"`
CopyRight string `orm:"column(copy_right)" json:"copy_right"`
UploadMode int `orm:"column(upload_mode)" json:"upload_mode"` // 1 七牛 目前只实现七牛,其它的后续可以扩展
UpdateAt int64 `orm:"type(bigint);column(update_at)" json:"update_at"`
}
package models
// TransferRequestData struct
type TransferRequestData struct {
// TransferDto struct
type TransferDto struct {
ToAccount int64 `json:"to_account"` // 转接给谁
UserAccount int64 `json:"user_account"` // 用户ID
}
package models
// UsersPaginationDto struct
type UsersPaginationDto struct {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"`
Keyword string `json:"keyword"`
Total int64 `json:"total"`
Platform int64 `json:"platform"`
DateStart string `json:"date_start"`
DateEnd string `json:"date_end"`
List interface{} `json:"list"`
}
......@@ -11,14 +11,14 @@ import (
type AdminRepositoryInterface interface {
GetAdmin(id int64) *models.Admin
GetAdminWithUserName(userName string) *models.Admin
UpdateParams(id int64, params *orm.Params) (int64, error)
Update(id int64, params *orm.Params) (int64, error)
Add(admin *models.Admin, col1 string) (bool, int64, error)
Delete(id int64) (int64, error)
GetAdmins(request *AdminPaginationData) (*AdminPaginationData, error)
GetAdmins(request *AdminPaginationDto) (*AdminPaginationDto, error)
}
// AdminPaginationData a struct
type AdminPaginationData struct {
// AdminPaginationDto a struct
type AdminPaginationDto struct {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"`
Keyword string `json:"keyword"`
......@@ -39,6 +39,13 @@ type AdminRepository struct {
BaseRepository
}
// GetAdminRepositoryInstance get instance
func GetAdminRepositoryInstance() *AdminRepository {
instance := new(AdminRepository)
instance.Init(new(models.Admin))
return instance
}
// GetAdmin get one admin with id
func (r *AdminRepository) GetAdmin(id int64) *models.Admin {
var admin models.Admin
......@@ -59,11 +66,11 @@ func (r *AdminRepository) GetAdminWithUserName(userName string) *models.Admin {
return &admin
}
// UpdateParams update admin
func (r *AdminRepository) UpdateParams(id int64, params orm.Params) (int64, error) {
// Update admin
func (r *AdminRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("UpdateParams update admin------------", err)
logs.Warn("Update admin------------", err)
}
return index, err
}
......@@ -87,7 +94,7 @@ func (r *AdminRepository) Delete(id int64) (int64, error) {
}
// GetAdmins get admin list
func (r *AdminRepository) GetAdmins(request *AdminPaginationData) (*AdminPaginationData, error) {
func (r *AdminRepository) GetAdmins(request *AdminPaginationDto) (*AdminPaginationDto, error) {
var lists []models.Admin
......
......@@ -16,6 +16,13 @@ type AuthTypesRepository struct {
BaseRepository
}
// GetAuthTypesRepositoryInstance get instance
func GetAuthTypesRepositoryInstance() *AuthTypesRepository {
instance := new(AuthTypesRepository)
instance.Init(new(models.AuthTypes))
return instance
}
// GetAuthType get a authType
func (r *AuthTypesRepository) GetAuthType(id int64) *models.AuthTypes {
var authType models.AuthTypes
......
......@@ -14,7 +14,7 @@ type AuthsRepositoryInterface interface {
GetAdminOnlineCount(uid int64) int64
Delete(id int64) (int64, error)
Add(id *models.Auths) (int64, error)
UpdateParams(id int64, params orm.Params) (int64, error)
Update(id int64, params orm.Params) (int64, error)
}
// AuthsRepository struct
......@@ -22,6 +22,13 @@ type AuthsRepository struct {
BaseRepository
}
// GetAuthsRepositoryInstance get instance
func GetAuthsRepositoryInstance() *AuthsRepository {
instance := new(AuthsRepository)
instance.Init(new(models.Auths))
return instance
}
// GetAuthInfo get a auth info
func (r *AuthsRepository) GetAuthInfo(token string) *models.Auths {
var auth models.Auths
......@@ -62,11 +69,11 @@ func (r *AuthsRepository) Delete(id int64) (int64, error) {
return row, nil
}
// UpdateParams update admin
func (r *AuthsRepository) UpdateParams(id int64, params orm.Params) (int64, error) {
// Update admin
func (r *AuthsRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("UpdateParams update admin------------", err)
logs.Warn("Update admin------------", err)
}
return index, err
}
......
......@@ -4,7 +4,7 @@ import (
"github.com/astaxie/beego/orm"
)
// const val
// const val
var (
MinPageSize = 1
MaxPageSize = 50
......
......@@ -10,7 +10,7 @@ import (
// CompanyRepositoryInterface interface
type CompanyRepositoryInterface interface {
GetCompany(id int64) *models.Company
UpdateParams(id int64, params *orm.Params) (int64, error)
Update(id int64, params *orm.Params) (int64, error)
}
// CompanyRepository struct
......@@ -18,6 +18,13 @@ type CompanyRepository struct {
BaseRepository
}
// GetCompanyRepositoryInstance get instance
func GetCompanyRepositoryInstance() *CompanyRepository {
instance := new(CompanyRepository)
instance.Init(new(models.Company))
return instance
}
// GetCompany get one company
func (r *CompanyRepository) GetCompany(id int64) *models.Company {
var company models.Company
......@@ -28,11 +35,11 @@ func (r *CompanyRepository) GetCompany(id int64) *models.Company {
return &company
}
// UpdateParams update company
func (r *CompanyRepository) UpdateParams(id int64, params orm.Params) (int64, error) {
// Update company
func (r *CompanyRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("UpdateParams update company------------", err)
logs.Warn("Update company------------", err)
}
return index, err
}
......@@ -11,9 +11,9 @@ import (
// ContactRepositoryInterface interface
type ContactRepositoryInterface interface {
GetContact(id int64) *models.Contact
GetContacts(uid int64) ([]models.ContactData, error)
GetContacts(uid int64) ([]models.ContactDto, error)
UpdateIsSessionEnd(usersID []int64, isSessionEnd int) (int64, error)
UpdateParams(id int64, params *orm.Params) (int64, error)
Update(id int64, params *orm.Params) (int64, error)
Delete(id int64, uid int64) (int64, error)
DeleteAll(uid int64) (int64, error)
Add(contact *models.Contact) (int64, error)
......@@ -25,6 +25,13 @@ type ContactRepository struct {
BaseRepository
}
// GetContactRepositoryInstance get instance
func GetContactRepositoryInstance() *ContactRepository {
instance := new(ContactRepository)
instance.Init(new(models.Contact))
return instance
}
// Add add a Contact
func (r *ContactRepository) Add(contact *models.Contact) (int64, error) {
row, err := r.o.Insert(&contact)
......@@ -66,19 +73,19 @@ func (r *ContactRepository) UpdateIsSessionEnd(usersID []int64, isSessionEnd int
}
// GetContacts get Contacts
func (r *ContactRepository) GetContacts(uid int64) ([]models.ContactData, error) {
var contactData []models.ContactData
_, 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(&contactData)
func (r *ContactRepository) GetContacts(uid int64) ([]models.ContactDto, error) {
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)
if err != nil {
logs.Warn("GetContacts get Contacts------------", err)
return nil, err
}
// content base 64 decode
for index, contact := range contactData {
for index, contact := range contactDto {
payload, _ := base64.StdEncoding.DecodeString(contact.LastMessage)
contactData[index].LastMessage = string(payload)
contactDto[index].LastMessage = string(payload)
}
return contactData, nil
return contactDto, nil
}
// Delete delete a Contact
......@@ -103,11 +110,11 @@ func (r *ContactRepository) DeleteAll(uid int64) (int64, error) {
}
// UpdateParams update contact
func (r *ContactRepository) UpdateParams(id int64, params orm.Params) (int64, error) {
// Update contact
func (r *ContactRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("UpdateParams update contact------------", err)
logs.Warn("Update contact------------", err)
}
return index, err
}
......@@ -11,10 +11,10 @@ import (
// KnowledgeBaseRepositoryInterface interface
type KnowledgeBaseRepositoryInterface interface {
GetKnowledgeBase(id int64) *models.KnowledgeBase
GetKnowledgeBases(request models.PaginationData) (*models.PaginationData, error)
GetKnowledgeBases(request models.KnowledgePaginationDto) (*models.KnowledgePaginationDto, error)
GetKnowledgeBaseWithTitle(title string) *models.KnowledgeBase
Add(knowledgeBase *models.KnowledgeBase, col1 string) (bool, int64, error)
UpdateParams(id int64, params *orm.Params) (int64, error)
Update(id int64, params *orm.Params) (int64, error)
Delete(id int64) (int64, error)
}
......@@ -23,6 +23,13 @@ type KnowledgeBaseRepository struct {
BaseRepository
}
// GetKnowledgeBaseRepositoryInstance get instance
func GetKnowledgeBaseRepositoryInstance() *KnowledgeBaseRepository {
instance := new(KnowledgeBaseRepository)
instance.Init(new(models.KnowledgeBase))
return instance
}
// Add create a knowledgeBase
func (r *KnowledgeBaseRepository) Add(knowledgeBase *models.KnowledgeBase, col1 string) (bool, int64, error) {
knowledgeBase.SubTitle = strings.Trim(knowledgeBase.SubTitle, "|")
......@@ -36,11 +43,11 @@ func (r *KnowledgeBaseRepository) Add(knowledgeBase *models.KnowledgeBase, col1
return _bool, index, err
}
// UpdateParams update knowledgeBase
func (r *KnowledgeBaseRepository) UpdateParams(id int64, params orm.Params) (int64, error) {
// Update knowledgeBase
func (r *KnowledgeBaseRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("UpdateParams update knowledgeBase------------", index, err)
logs.Warn("Update knowledgeBase------------", index, err)
}
return index, err
}
......@@ -57,7 +64,7 @@ func (r *KnowledgeBaseRepository) GetKnowledgeBase(id int64) *models.KnowledgeBa
}
// GetKnowledgeBases get one KnowledgeBases
func (r *KnowledgeBaseRepository) GetKnowledgeBases(request *models.PaginationData) (*models.PaginationData, error) {
func (r *KnowledgeBaseRepository) GetKnowledgeBases(request *models.KnowledgePaginationDto) (*models.KnowledgePaginationDto, error) {
if request.PageSize < MinPageSize {
request.PageSize = MinPageSize
......
......@@ -3,6 +3,7 @@ package services
import (
"encoding/base64"
"kefu_server/models"
"strconv"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
......@@ -10,9 +11,12 @@ import (
// MessageRepositoryInterface interface
type MessageRepositoryInterface interface {
GetMessages(serviceID int64, messagePaginationData models.MessagePaginationData) (*models.MessagePaginationData, error)
Delete(removeRequestData models.RemoveMessageRequestData) (int64, error)
GetAdminMessages(messagePaginationDto models.MessagePaginationDto) (*models.MessagePaginationDto, error)
GetUserMessages(messagePaginationDto models.MessagePaginationDto) (*models.MessagePaginationDto, error)
Delete(removeRequestDto models.RemoveMessageRequestDto) (int64, error)
Add(message *models.Message) (int64, error)
GetReadCount(uid int64) (int64, error)
ClearRead(uid int64) (int64, error)
}
// MessageRepository struct
......@@ -20,6 +24,13 @@ type MessageRepository struct {
BaseRepository
}
// GetMessageRepositoryInstance get instance
func GetMessageRepositoryInstance() *MessageRepository {
instance := new(MessageRepository)
instance.Init(new(models.Message))
return instance
}
// Add add a message
func (r *MessageRepository) Add(message *models.Message) (int64, error) {
row, err := r.o.Insert(&message)
......@@ -29,25 +40,91 @@ func (r *MessageRepository) Add(message *models.Message) (int64, error) {
return row, err
}
// ClearRead Clear message read
func (r *MessageRepository) ClearRead(uid int64) (int64, error) {
index, err := r.q.Filter("to_account", uid).Update(orm.Params{
"Read": 0,
})
if err != nil {
logs.Warn("ClearRead Clear message read------------", err)
}
return index, err
}
// GetReadCount message read count
func (r *MessageRepository) GetReadCount(uid int64) (int64, error) {
count, err := r.q.Filter("to_account", uid).Filter("read", 1).Count()
if err != nil {
logs.Warn("Add add a message------------", err)
}
return count, err
}
// Delete delete a message
func (r *MessageRepository) Delete(removeRequestData models.RemoveMessageRequestData) (int64, error) {
res, err := r.o.Raw("UPDATE message SET `delete` = 1 WHERE from_account = ? AND to_account = ? AND `key` = ?", removeRequestData.FromAccount, removeRequestData.ToAccount, removeRequestData.Key).Exec()
func (r *MessageRepository) Delete(removeRequestDto models.RemoveMessageRequestDto) (int64, error) {
res, err := r.o.Raw("UPDATE message SET `delete` = 1 WHERE from_account = ? AND to_account = ? AND `key` = ?", removeRequestDto.FromAccount, removeRequestDto.ToAccount, removeRequestDto.Key).Exec()
row, _ := res.RowsAffected()
if err != nil {
logs.Warn("Delete delete a message------------", err)
return 0, err
}
return row, nil
}
// GetMessages get one service message list
func (r *MessageRepository) GetMessages(serviceID int64, messagePaginationData models.MessagePaginationData) (*models.MessagePaginationData, error) {
// GetUserMessages get user messages
func (r *MessageRepository) GetUserMessages(messagePaginationDto models.MessagePaginationDto) (*models.MessagePaginationDto, error) {
// join string
var messages []*models.Message
uid := strconv.FormatInt(messagePaginationDto.Account, 10)
timestamp := strconv.FormatInt(messagePaginationDto.Timestamp, 10)
type MessageCount struct {
Count int64
}
var messageCount MessageCount
err := r.o.Raw("SELECT COUNT(*) AS `count` FROM `message` WHERE (`to_account` = ? OR `from_account` = ?) AND `timestamp` < ? AND `delete` = 0", uid, uid, timestamp).QueryRow(&messageCount)
if err != nil {
logs.Warn("GetUserMessages get user messages0------------", err)
return nil, err
}
var end = messageCount.Count
start := int(messageCount.Count) - messagePaginationDto.PageSize
if start <= 0 {
start = 0
}
if messageCount.Count > 0 {
_, err := r.o.Raw("SELECT * FROM `message` WHERE (`to_account` = ? OR `from_account` = ?) AND `timestamp` < ? AND `delete` = 0 ORDER BY `timestamp` ASC LIMIT ?,?", uid, uid, timestamp, start, end).QueryRows(&messages)
if err != nil {
logs.Warn("GetUserMessages get user messages1------------", err)
return nil, err
}
_, _ = r.q.Filter("from_account", uid).Update(orm.Params{"read": 0})
if err != nil {
logs.Warn("GetUserMessages get user messages2------------", err)
return nil, err
}
r.o.Raw("SELECT COUNT(*) AS `count` FROM `message` WHERE (`to_account` = ? OR `from_account` = ?) AND `delete` = 0", uid, uid).QueryRow(&messageCount)
messagePaginationDto.List = messages
messagePaginationDto.Total = messageCount.Count
} else {
messagePaginationDto.List = []models.Message{}
messagePaginationDto.Total = 0
}
for index, msg := range messages {
payload, _ := base64.StdEncoding.DecodeString(msg.Payload)
messages[index].Payload = string(payload)
}
return &messagePaginationDto, nil
}
// GetAdminMessages get admin messages
func (r *MessageRepository) GetAdminMessages(messagePaginationDto models.MessagePaginationDto) (*models.MessagePaginationDto, error) {
var err error
var msgCount int64
var messages []*models.Message
// join string
accounts := []int64{messagePaginationData.Account, serviceID}
accounts := []int64{messagePaginationDto.Account, messagePaginationDto.Service}
inExp := "?,?"
// get all robot
......@@ -62,39 +139,39 @@ func (r *MessageRepository) GetMessages(serviceID int64, messagePaginationData m
inExp = inExp + ",?"
}
msgCount, err = r.q.Filter("timestamp__lt", messagePaginationData.Timestamp).Filter("to_account__in", accounts).Filter("from_account__in", accounts).Filter("delete", 0).Count()
msgCount, err = r.q.Filter("timestamp__lt", messagePaginationDto.Timestamp).Filter("to_account__in", accounts).Filter("from_account__in", accounts).Filter("delete", 0).Count()
if err != nil {
logs.Warn("GetMessages get one service message list1------------", err)
}
// Paging
end := msgCount
start := int(msgCount) - messagePaginationData.PageSize
start := int(msgCount) - messagePaginationDto.PageSize
if start <= 0 {
start = 0
}
if msgCount > 0 {
_, err = r.o.Raw("SELECT * FROM `message` WHERE to_account IN ("+inExp+") AND `delete` = 0 AND from_account IN ("+inExp+") AND `timestamp` < ? ORDER BY `timestamp` ASC LIMIT ?,?", accounts, accounts, messagePaginationData.Timestamp, start, end).QueryRows(&messages)
_, err = r.o.Raw("SELECT * FROM `message` WHERE to_account IN ("+inExp+") AND `delete` = 0 AND from_account IN ("+inExp+") AND `timestamp` < ? ORDER BY `timestamp` ASC LIMIT ?,?", accounts, accounts, messagePaginationDto.Timestamp, start, end).QueryRows(&messages)
if err != nil {
logs.Warn("GetMessages get one service message list2------------", err)
return nil, err
}
_, err = r.q.Filter("from_account", messagePaginationData.Account).Update(orm.Params{"read": 0})
_, err = r.q.Filter("from_account", messagePaginationDto.Account).Update(orm.Params{"read": 0})
if err != nil {
logs.Warn("GetMessages get one service message list3------------", err)
return nil, err
}
total, _ := r.q.Filter("to_account__in", accounts).Filter("from_account__in", accounts).Filter("delete", 0).Count()
messagePaginationData.List = messages
messagePaginationData.Total = total
messagePaginationDto.List = messages
messagePaginationDto.Total = total
} else {
messagePaginationData.List = []models.Message{}
messagePaginationData.Total = 0
messagePaginationDto.List = []models.Message{}
messagePaginationDto.Total = 0
}
for index, msg := range messages {
payload, _ := base64.StdEncoding.DecodeString(msg.Payload)
messages[index].Payload = string(payload)
}
return &messagePaginationData, nil
return &messagePaginationDto, nil
}
......@@ -4,12 +4,18 @@ import (
"kefu_server/models"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
// PlatformRepositoryInterface interface
type PlatformRepositoryInterface interface {
GetPlatform(id int64) *models.Platform
GetPlatformAll(orderByKey string) ([]models.Platform, error)
Add(platform *models.Platform, col1 string) (bool, int64, error)
GetPlatformWithIDAndTitle(id int64, title string) *models.Platform
GetPlatformWithIDAndAlias(id int64, alias string) *models.Platform
Update(id int64, params *orm.Params) (int64, error)
Delete(id int64) (int64, error)
}
//PlatformRepository struct
......@@ -17,9 +23,16 @@ type PlatformRepository struct {
BaseRepository
}
// GetPlatformRepositoryInstance get instance
func GetPlatformRepositoryInstance() *PlatformRepository {
instance := new(PlatformRepository)
instance.Init(new(models.Platform))
return instance
}
// Add create a Platform
func (r *PlatformRepository) Add(platform *models.Platform, col1 string) (bool, int64, error) {
_bool, index, err := r.o.ReadOrCreate(&platform, col1)
_bool, index, err := r.o.ReadOrCreate(platform, col1)
if err != nil {
logs.Warn("Add create a Platform------------", err)
}
......@@ -30,8 +43,58 @@ func (r *PlatformRepository) Add(platform *models.Platform, col1 string) (bool,
func (r *PlatformRepository) GetPlatform(id int64) *models.Platform {
var platform models.Platform
if err := r.q.Filter("id", id).One(&platform); err != nil {
logs.Warn("GetPlatform get one platform------------", err)
logs.Warn("GetPlatformWithIDAndTitle get one platform with it and title------------", err)
return nil
}
return &platform
}
// GetPlatformAll get all platform
func (r *PlatformRepository) GetPlatformAll(orderByKey string) ([]models.Platform, error) {
var platforms []models.Platform
if _, err := r.q.OrderBy(orderByKey).All(&platforms); err != nil {
logs.Warn("GetPlatforms get all platform------------", err)
return nil, err
}
return platforms, nil
}
// GetPlatformWithIDAndTitle get one platform with it and title
func (r *PlatformRepository) GetPlatformWithIDAndTitle(id int64, title string) *models.Platform {
var platform models.Platform
err := r.o.Raw("SELECT * FROM platform WHERE id != ? AND title = ?", id, title).QueryRow(&platform)
if err != nil {
logs.Warn("GetPlatformWithIDAndTitle get one platform with it and title------------", err)
return nil
}
return &platform
}
// Update Platform
func (r *PlatformRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("Update Platform------------", err)
}
return index, err
}
// GetPlatformWithIDAndAlias get one platform with it and alias
func (r *PlatformRepository) GetPlatformWithIDAndAlias(id int64, alias string) *models.Platform {
var platform models.Platform
err := r.o.Raw("SELECT * FROM platform WHERE id != ? AND alias = ?", id, alias).QueryRow(&platform)
if err != nil {
logs.Warn("GetPlatformWithIDAndAlias get one platform with it and alias------------", err)
return nil
}
return &platform
}
// Delete delete a platform
func (r *PlatformRepository) Delete(id int64) (int64, error) {
index, err := r.q.Filter("id", id).Delete()
if err != nil {
logs.Warn("Delete delete a platform------------", err)
}
return index, err
}
package services
import (
"kefu_server/models"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
// QiniuRepositoryInterface interface
type QiniuRepositoryInterface interface {
GetQiniu() *models.QiniuSetting
Update(params *orm.Params) (int64, error)
}
// QiniuRepository struct
type QiniuRepository struct {
BaseRepository
}
// GetQiniuRepositoryInstance get instance
func GetQiniuRepositoryInstance() *QiniuRepository {
instance := new(QiniuRepository)
instance.Init(new(models.QiniuSetting))
return instance
}
// GetQiniuConfigInfo get Qiniu Info
func (r *QiniuRepository) GetQiniuConfigInfo() *models.QiniuSetting {
var system models.QiniuSetting
if err := r.q.Filter("id", 1).One(&system); err != nil {
logs.Warn("GetQiniu get Qiniu Info------------", err)
return nil
}
return &system
}
// Update Qiniu Info
func (r *QiniuRepository) Update(params orm.Params) (int64, error) {
index, err := r.q.Filter("id", 1).Update(params)
if err != nil {
logs.Warn("Update Qiniu Info------------", err)
}
return index, err
}
package services
import (
"errors"
"kefu_server/models"
"math/rand"
"strings"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
// RobotRepositoryInterface interface
type RobotRepositoryInterface interface {
GetRobot(id int64) *models.Robot
GetRobotWithNickName(nickName string) *models.Robot
GetRobotWithOnline(id int64) (*models.Robot, error)
GetRobots() ([]models.Robot, error)
GetRobotWithInIds(ids ...int64) ([]models.Robot, error)
Delete(id int64) (int64, error)
Add(robot *models.Robot) (int64, error)
Update(id int64, params *orm.Params) (int64, error)
}
// RobotRepository struct
......@@ -19,6 +27,49 @@ type RobotRepository struct {
BaseRepository
}
// GetRobotRepositoryInstance get instance
func GetRobotRepositoryInstance() *RobotRepository {
instance := new(RobotRepository)
instance.Init(new(models.Robot))
return instance
}
// Add a robot
func (r *RobotRepository) Add(robot *models.Robot) (int64, error) {
robot.Artificial = strings.Trim(robot.Artificial, "|")
if robot.Artificial != "" {
robot.Artificial = "|" + robot.Artificial + "|"
}
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
if robot.KeyWord != "" {
robot.KeyWord = "|" + robot.KeyWord + "|"
}
index, err := r.o.Insert(robot)
if err != nil {
logs.Warn("Add create a robot------------", err)
}
return index, err
}
// Update robot
func (r *RobotRepository) Update(id int64, params orm.Params) (int64, error) {
srtificial := params["Artificial"].(string)
keyWord := params["KeyWord"].(string)
srtificial = strings.Trim(srtificial, "|")
if srtificial != "" {
srtificial = "|" + srtificial + "|"
}
keyWord = strings.Trim(keyWord, "|")
if keyWord != "" {
keyWord = "|" + keyWord + "|"
}
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("Update robot------------", err)
}
return index, err
}
// GetRobots get Robots
func (r *RobotRepository) GetRobots() ([]models.Robot, error) {
var robots []models.Robot
......@@ -28,6 +79,7 @@ func (r *RobotRepository) GetRobots() ([]models.Robot, error) {
}
for index := range robots {
robots[index].Artificial = strings.Trim(robots[index].Artificial, "|")
robots[index].KeyWord = strings.Trim(robots[index].KeyWord, "|")
}
return robots, nil
}
......@@ -39,9 +91,39 @@ func (r *RobotRepository) GetRobot(id int64) *models.Robot {
logs.Warn("GetRobot get one Robot------------", err)
return nil
}
robot.Artificial = strings.Trim(robot.Artificial, "|")
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
return &robot
}
// GetRobotWithNickName get one Robot with nickname
func (r *RobotRepository) GetRobotWithNickName(nickName string) *models.Robot {
var robot models.Robot
if err := r.q.Filter("nickname", nickName).One(&robot); err != nil {
logs.Warn("GetRobotWithNickName get one Robot with nickname------------", err)
return nil
}
robot.Artificial = strings.Trim(robot.Artificial, "|")
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
return &robot
}
// GetRobotWithOnline get one Robot with Online
func (r *RobotRepository) GetRobotWithOnline(id int64) (*models.Robot, error) {
var robots []*models.Robot
if _, err := r.q.Filter("platform__in", id, 1).Filter("switch", 1).All(&robots); err != nil {
logs.Warn("GetRobotWithRandom get one Robot with Random------------", err)
return nil, err
}
var robot *models.Robot
if len(robots) > 0 {
robot = robots[rand.Intn(len(robots))]
}
robot.Artificial = strings.Trim(robot.Artificial, "|")
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
return robot, nil
}
// GetRobotWithInIds get one Robot with in() ids
func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error) {
var robots []models.Robot
......@@ -51,3 +133,15 @@ func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error
}
return robots, err
}
// Delete delete a robot
func (r *RobotRepository) Delete(id int64) (int64, error) {
if id == 1 {
return 0, errors.New("system robot")
}
index, err := r.q.Filter("id", id).Delete()
if err != nil {
logs.Warn("Delete delete a robot------------", err)
}
return index, err
}
......@@ -15,6 +15,7 @@ type StatisticalRepositoryInterface interface {
Add(servicesStatistical *models.ServicesStatistical) (int64, error)
GetStatisticals(startDate string, endDate string) (map[string]interface{}, error)
GetTodayActionStatistical(startDate string, endDate string) ([]orm.Params, error)
GetCustomerServiceList(request models.ServicesStatisticalPaginationDto) models.ServicesStatisticalPaginationDto
}
// StatisticalRepository struct
......@@ -22,6 +23,57 @@ type StatisticalRepository struct {
BaseRepository
}
// GetStatisticalRepositoryInstance get instance
func GetStatisticalRepositoryInstance() *StatisticalRepository {
instance := new(StatisticalRepository)
instance.Init(new(models.ServicesStatistical))
return instance
}
// GetCustomerServiceList get Customer Service List
func (r *StatisticalRepository) GetCustomerServiceList(request models.ServicesStatisticalPaginationDto) models.ServicesStatisticalPaginationDto {
layoutDate := "2006-01-02 15:04:05"
loc, _ := time.LoadLocation("Local")
startDateStr := request.Date + " 00:00:00"
endDateStr := request.Date + " 23:59:59"
startDate, _ := time.ParseInLocation(layoutDate, startDateStr, loc)
endDate, _ := time.ParseInLocation(layoutDate, endDateStr, loc)
var params []orm.Params
type TotalModel struct {
Count int64
}
var totalModel TotalModel
// Deduplication
addSQL := " COUNT(*) "
if request.IsDeWeighting {
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 {
logs.Warn("GetCustomerServiceList get Customer Service List1------------", err)
}
request.Total = totalModel.Count
// Deduplication
addSQL1 := " "
if request.IsDeWeighting {
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 {
logs.Warn("GetCustomerServiceList get Customer Service List2------------", err)
request.List = []string{}
return request
}
request.List = params
return request
}
// Add add statistical
func (r *StatisticalRepository) Add(servicesStatistical *models.ServicesStatistical) (int64, error) {
id, err := r.o.Insert(&servicesStatistical)
......
package services
import (
"encoding/base64"
"kefu_server/models"
"time"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
// ShortcutRepositoryInterface interface
type ShortcutRepositoryInterface interface {
Add(admin *models.Shortcut, col1 string, cols ...string) (bool, int64, error)
GetShortcut(id int64) *models.Shortcut
GetShortcuts(uid int64) []models.Shortcut
Update(id int64, params *orm.Params) (int64, error)
Delete(id int64, uid int64) (int64, error)
}
// ShortcutRepository struct
type ShortcutRepository struct {
BaseRepository
}
// GetShortcutRepositoryInstance get instance
func GetShortcutRepositoryInstance() *ShortcutRepository {
instance := new(ShortcutRepository)
instance.Init(new(models.Shortcut))
return instance
}
// Add create a shortcut
func (r *ShortcutRepository) Add(shortcut *models.Shortcut, col1 string, cols ...string) (bool, int64, error) {
shortcut.Title = base64.StdEncoding.EncodeToString([]byte(shortcut.Title))
shortcut.Content = base64.StdEncoding.EncodeToString([]byte(shortcut.Content))
shortcut.CreateAt = time.Now().Unix()
_bool, id, err := r.o.ReadOrCreate(shortcut, col1, cols...)
if err != nil {
logs.Warn("Add create a shortcut------------", err)
}
return _bool, id, err
}
// GetShortcuts get user shortcut List
func (r *ShortcutRepository) GetShortcuts(uid int64) []models.Shortcut {
var shortcuts []models.Shortcut
if _, err := r.q.Filter("uid", uid).OrderBy("-create_at").All(&shortcuts); err != nil {
logs.Warn("GetShortcuts get user shortcut List------------", err)
return []models.Shortcut{}
}
// base 64转换回来
for index, shortcut := range shortcuts {
title, _ := base64.StdEncoding.DecodeString(shortcut.Title)
content, _ := base64.StdEncoding.DecodeString(shortcut.Content)
shortcuts[index].Title = string(title)
shortcuts[index].Content = string(content)
}
return shortcuts
}
// Delete delete a shortcut
func (r *ShortcutRepository) Delete(id int64, uid int64) (int64, error) {
index, err := r.q.Filter("id", id).Filter("uid", uid).Delete()
if err != nil {
logs.Warn("Delete delete a shortcut------------", err)
}
return index, err
}
// GetShortcut get one Shortcut
func (r *ShortcutRepository) GetShortcut(id int64) *models.Shortcut {
var shortcut models.Shortcut
if err := r.q.Filter("id", id).One(&shortcut); err != nil {
logs.Warn("GetShortcut get one shortcut------------", err)
return nil
}
title, _ := base64.StdEncoding.DecodeString(shortcut.Title)
content, _ := base64.StdEncoding.DecodeString(shortcut.Content)
shortcut.Title = string(title)
shortcut.Content = string(content)
return &shortcut
}
// Update shortcut
func (r *ShortcutRepository) Update(id int64, params orm.Params) (int64, error) {
params["Title"] = base64.StdEncoding.EncodeToString([]byte(params["Title"].(string)))
params["Content"] = base64.StdEncoding.EncodeToString([]byte(params["Content"].(string)))
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("Update shortcut------------", err)
}
return index, err
}
package services
import (
"kefu_server/models"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
// SystemRepositoryInterface interface
type SystemRepositoryInterface interface {
GetSystem() *models.System
Update(params orm.Params) (int64, error)
}
// SystemRepository struct
type SystemRepository struct {
BaseRepository
}
// GetSystemRepositoryInstance get instance
func GetSystemRepositoryInstance() *SystemRepository {
instance := new(SystemRepository)
instance.Init(new(models.System))
return instance
}
// GetSystem get System Info
func (r *SystemRepository) GetSystem() *models.System {
var system models.System
if err := r.q.Filter("id", 1).One(&system); err != nil {
logs.Warn("GetSystem get System Info------------", err)
return nil
}
return &system
}
// Update System
func (r *SystemRepository) Update(params orm.Params) (int64, error) {
index, err := r.q.Filter("id", 1).Update(params)
if err != nil {
logs.Warn("Update System------------", err)
}
return index, err
}
package services
import (
"kefu_server/models"
"github.com/astaxie/beego/logs"
)
// UploadsConfigRepositoryInterface interface
type UploadsConfigRepositoryInterface interface {
GetUploadsConfig(id int64) *models.UploadsConfig
GetUploadsConfigs() []*models.UploadsConfig
}
// UploadsConfigRepository struct
type UploadsConfigRepository struct {
BaseRepository
}
// GetUploadsConfigRepositoryInstance get instance
func GetUploadsConfigRepositoryInstance() *UploadsConfigRepository {
instance := new(UploadsConfigRepository)
instance.Init(new(models.UploadsConfig))
return instance
}
// GetUploadsConfig get one UploadsConfig
func (r *UploadsConfigRepository) GetUploadsConfig(id int64) *models.UploadsConfig {
var config models.UploadsConfig
if err := r.q.Filter("id", id).One(&config); err != nil {
logs.Warn("GetUploadsConfig get one UploadsConfig------------", err)
}
return &config
}
// GetUploadsConfigs get UploadsConfig all
func (r *UploadsConfigRepository) GetUploadsConfigs() []*models.UploadsConfig {
var configs []*models.UploadsConfig
if _, err := r.q.All(&configs); err != nil {
logs.Warn("GetUploadsConfigs get UploadsConfig all------------", err)
}
return configs
}
......@@ -2,13 +2,21 @@ package services
import (
"kefu_server/models"
"time"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
)
// UserRepositoryInterface interface
type UserRepositoryInterface interface {
Add(admin *models.User) (int64, error)
GetUser(id int64) *models.User
GetUsers(usersPaginationDto *models.UsersPaginationDto) (*models.UsersPaginationDto, error)
GetUserWithUID(uid int64) *models.User
Update(id int64, params *orm.Params) (int64, error)
Delete(id int64) (int64, error)
GetOnlineCount() (int64, error)
}
// UserRepository struct
......@@ -16,6 +24,22 @@ type UserRepository struct {
BaseRepository
}
// GetUserRepositoryInstance get instance
func GetUserRepositoryInstance() *UserRepository {
instance := new(UserRepository)
instance.Init(new(models.User))
return instance
}
// Add create a user
func (r *UserRepository) Add(user *models.User) (int64, error) {
id, err := r.o.Insert(user)
if err != nil {
logs.Warn("Add create a user------------", err)
}
return id, err
}
// GetUser get one User
func (r *UserRepository) GetUser(id int64) *models.User {
var user models.User
......@@ -25,3 +49,80 @@ func (r *UserRepository) GetUser(id int64) *models.User {
}
return &user
}
// GetOnlineCount online user count
func (r *UserRepository) GetOnlineCount() (int64, error) {
rows, err := r.q.Filter("online", 1).Count()
if err != nil {
logs.Warn("GetOnlineCount online user count------------", err)
}
return rows, err
}
// GetUsers get Users
func (r *UserRepository) GetUsers(usersPaginationDto *models.UsersPaginationDto) (*models.UsersPaginationDto, error) {
// orm instance
qs := r.q
cond := orm.NewCondition()
var cond1 *orm.Condition
var cond2 *orm.Condition
if usersPaginationDto.Keyword != "" {
cond1 = cond.Or("nickname__icontains", usersPaginationDto.Keyword).Or("phone__icontains", usersPaginationDto.Keyword).Or("remarks__icontains", usersPaginationDto.Keyword)
}
// exist platfrom id?
if usersPaginationDto.Platform != 0 && usersPaginationDto.Platform != 1 {
cond2 = cond.And("platform", usersPaginationDto.Platform)
}
// exist platfrom date?
if usersPaginationDto.DateStart != "" && usersPaginationDto.DateEnd != "" {
layoutDate := "2006-01-02 15:04:05"
loc, _ := time.LoadLocation("Local")
dateStartString := usersPaginationDto.DateStart + " 00:00:00"
dateEndString := usersPaginationDto.DateEnd + " 23:59:59"
dateStart, _ := time.ParseInLocation(layoutDate, dateStartString, loc)
dateEnd, _ := time.ParseInLocation(layoutDate, dateEndString, loc)
cond2 = cond2.And("create_at__gte", dateStart.Unix()).And("create_at__lte", dateEnd.Unix())
}
// query
var lists []models.User
cond3 := cond.AndCond(cond2).OrCond(cond1)
qs = qs.SetCond(cond3)
qs = qs.OrderBy("-online", "-create_at").Limit(usersPaginationDto.PageSize)
if _, err := qs.Offset((usersPaginationDto.PageOn - 1) * usersPaginationDto.PageSize).All(&lists); err != nil {
return nil, err
}
total, _ := qs.Count()
usersPaginationDto.Total = total
usersPaginationDto.List = &lists
return usersPaginationDto, nil
}
// GetUserWithUID get one User with uid
func (r *UserRepository) GetUserWithUID(uid int64) *models.User {
var user models.User
if err := r.q.Filter("uid", uid).One(&user); err != nil {
logs.Warn("GetUserWithUID get one User with uid------------", err)
return nil
}
return &user
}
// Update user
func (r *UserRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params)
if err != nil {
logs.Warn("Update user------------", err)
}
return index, err
}
// Delete user
func (r *UserRepository) Delete(id int64) (int64, error) {
index, err := r.q.Filter("id", id).Delete()
if err != nil {
logs.Warn("Delete user------------", err)
}
return index, err
}
package utils
// InExistInSlice 检查内容是否在slice中存在
// InExistInSlice Check if content exists in slice
func InExistInSlice(input string, slice []string) bool {
for _, v := range slice {
if v == input {
......
......@@ -18,14 +18,13 @@ func MessageInto(message models.Message, isKF bool) {
return
}
// init MessageRepository
messageRepository := new(services.MessageRepository)
messageRepository.Init(new(models.Message))
// MessageRepository instance
messageRepository := services.GetMessageRepositoryInstance()
// 判断是否是撤回消息(软删除)
if message.BizType == "cancel" {
key, _ := strconv.ParseInt(message.Payload, 10, 64)
_, _ = messageRepository.Delete(models.RemoveMessageRequestData{FromAccount: message.FromAccount, ToAccount: message.ToAccount, Key: key})
_, _ = messageRepository.Delete(models.RemoveMessageRequestDto{FromAccount: message.FromAccount, ToAccount: message.ToAccount, Key: key})
}
// message create time
......@@ -38,9 +37,10 @@ func MessageInto(message models.Message, isKF bool) {
if !(message.BizType == "handshake") {
if !isKF {
// init UserRepository
userRepository := new(services.UserRepository)
userRepository.Init(new(models.User))
// UserRepository instance
userRepository := services.GetUserRepositoryInstance()
// 默认已读消息
message.Read = 0
user := userRepository.GetUser(message.ToAccount)
......@@ -62,18 +62,16 @@ func MessageInto(message models.Message, isKF bool) {
}
// init RobotRepository
robotRepository := new(services.RobotRepository)
robotRepository.Init(new(models.Robot))
// RobotRepository instance
robotRepository := services.GetRobotRepositoryInstance()
// 判断是否机器人对话(不处理聊天列表)
if rbts, _ := robotRepository.GetRobotWithInIds(message.ToAccount, message.FromAccount); len(rbts) > 0 {
return
}
// init ContactRepository
contactRepository := new(services.ContactRepository)
contactRepository.Init(new(models.Contact))
// ContactRepository instance
contactRepository := services.GetContactRepositoryInstance()
// 处理客服聊天列表
if contact, err := contactRepository.GetContactWithIds(message.ToAccount, message.FromAccount); err != nil {
......@@ -88,7 +86,7 @@ func MessageInto(message models.Message, isKF bool) {
if message.BizType == "end" || message.BizType == "timeout" {
isSessionEnd = 1
}
_, _ = contactRepository.UpdateParams(contact.ID, orm.Params{
_, _ = contactRepository.Update(contact.ID, orm.Params{
"LastMessageType": message.BizType,
"CreateAt": time.Now().Unix(),
"LastMessage": message.Payload,
......
package utils
import (
"kefu_server/models"
"github.com/astaxie/beego/context"
)
// ResponseError ...
func ResponseError(ctx *context.Context, message string, error interface{}) *models.Response {
ctx.Output.Status = 400
ctx.Output.Header("Access-Control-Max-Age", "2592000")
return &models.Response{Code: 400, Message: message, Data: error}
}
package utils
import (
"kefu_server/models"
"github.com/astaxie/beego/context"
)
// ResponseSuccess ...
func ResponseSuccess(ctx *context.Context, message string, data interface{}) *models.Response {
ctx.Output.Header("Access-Control-Max-Age", "2592000")
return &models.Response{Code: 200, Message: message, Data: data}
}
......@@ -10,21 +10,21 @@ import (
)
// KEY ...
// DEFAULT_EXPIRE_SECONDS ...
// DEFAULTEXPIRESECONDS ...
const (
KEY string = "JWT-ARY-STARK"
DEFAULT_EXPIRE_SECONDS int = 259200
KEY string = "JWT-ARY-STARK"
DEFAULTEXPIRESECONDS int = 259200
)
// MyCustomClaims JWT -- json web token
// HEADER PAYLOAD SIGNATURE
// This struct is the PAYLOAD
type MyCustomClaims struct {
models.JwtKey
models.JwtKeyDto
jwt.StandardClaims
}
// RefreshToken 刷新token
// RefreshToken Refresh token
func RefreshToken(tokenString string) (string, error) {
// first get previous token
token, err := jwt.ParseWithClaims(
......@@ -37,12 +37,12 @@ func RefreshToken(tokenString string) (string, error) {
return "", err
}
mySigningKey := []byte(KEY)
expireAt := time.Now().Add(time.Second * time.Duration(DEFAULT_EXPIRE_SECONDS)).Unix()
expireAt := time.Now().Add(time.Second * time.Duration(DEFAULTEXPIRESECONDS)).Unix()
newClaims := MyCustomClaims{
claims.JwtKey,
claims.JwtKeyDto,
jwt.StandardClaims{
ExpiresAt: expireAt,
Issuer: claims.JwtKey.UserName,
Issuer: claims.JwtKeyDto.UserName,
IssuedAt: time.Now().Unix(),
},
}
......@@ -89,21 +89,21 @@ func DecodeToken(token string) (map[string]interface{}, error) {
}
// GenerateToken 生成token
func GenerateToken(jwtKey models.JwtKey) (tokenString string) {
func GenerateToken(jwtKeyDto models.JwtKeyDto) (tokenString string) {
var expiredSeconds int
expiredSeconds = 259200
if expiredSeconds == 0 {
expiredSeconds = DEFAULT_EXPIRE_SECONDS
expiredSeconds = DEFAULTEXPIRESECONDS
}
// Create the Claims
mySigningKey := []byte(KEY)
expireAt := time.Now().Add(time.Second * time.Duration(expiredSeconds)).Unix()
// pass parameter to this func or not
claims := MyCustomClaims{
jwtKey,
jwtKeyDto,
jwt.StandardClaims{
ExpiresAt: expireAt,
Issuer: jwtKey.UserName,
Issuer: jwtKeyDto.UserName,
IssuedAt: time.Now().Unix(),
},
}
......
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