Commit e023aa90 by chenxianqi

Project progress follow-up

parent f68f5df4
Showing with 1674 additions and 1448 deletions
version = "v2.0"
appname = kefu_server appname = kefu_server
runmode = "dev" runmode = "dev"
httpport = 8080 httpport = 8080
......
...@@ -24,9 +24,8 @@ type AdminController struct { ...@@ -24,9 +24,8 @@ type AdminController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *AdminController) Prepare() { func (c *AdminController) Prepare() {
// init AdminRepository // AdminRepository instance
c.AdminRepository = new(services.AdminRepository) c.AdminRepository = services.GetAdminRepositoryInstance()
c.AdminRepository.Init(new(models.Admin))
} }
...@@ -38,13 +37,12 @@ func (c *AdminController) GetMeInfo() { ...@@ -38,13 +37,12 @@ func (c *AdminController) GetMeInfo() {
// GetAuthInfo // GetAuthInfo
auth := c.GetAuthInfo() auth := c.GetAuthInfo()
admin := c.AdminRepository.GetAdmin(auth.UID) admin := c.AdminRepository.GetAdmin(auth.UID)
if admin == nil { 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 // Get admin
...@@ -52,10 +50,9 @@ func (c *AdminController) Get() { ...@@ -52,10 +50,9 @@ func (c *AdminController) Get() {
// GetAuthInfo // GetAuthInfo
auth := c.GetAuthInfo() auth := c.GetAuthInfo()
admin := c.AdminRepository.GetAdmin(auth.UID) admin := c.AdminRepository.GetAdmin(auth.UID)
if admin == nil { if admin == nil {
c.JSON(configs.ResponseFail, "查询失败,用户不存在!", nil) c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
} }
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
...@@ -65,11 +62,11 @@ func (c *AdminController) Get() { ...@@ -65,11 +62,11 @@ func (c *AdminController) Get() {
retrunAdmin := c.AdminRepository.GetAdmin(id) retrunAdmin := c.AdminRepository.GetAdmin(id)
if retrunAdmin == nil { if retrunAdmin == nil {
c.JSON(configs.ResponseFail, "查询失败,用户不存在!", nil) c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
} }
retrunAdmin.Password = "******" retrunAdmin.Password = "******"
c.JSON(configs.ResponseSucess, "查询成功!", &retrunAdmin) c.JSON(configs.ResponseSucess, "success", &retrunAdmin)
} }
// Put update admin // Put update admin
...@@ -80,10 +77,9 @@ func (c *AdminController) Put() { ...@@ -80,10 +77,9 @@ func (c *AdminController) Put() {
// get request // get request
admin := models.Admin{} admin := models.Admin{}
admin.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &admin); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &admin); err != nil {
logs.Warn("Put update admin error------------", err) logs.Warn("Put update admin error------------", err)
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// admin exist // admin exist
...@@ -114,10 +110,10 @@ func (c *AdminController) Put() { ...@@ -114,10 +110,10 @@ func (c *AdminController) Put() {
} }
// update // update
if _, err := c.AdminRepository.UpdateParams(admin.ID, orm.Params{ if _, err := c.AdminRepository.Update(admin.ID, orm.Params{
"Phone": admin.Phone, "Phone": admin.Phone,
"NickName": admin.NickName, "NickName": admin.NickName,
"UpdateAt": admin.UpdateAt, "UpdateAt": time.Now().Unix(),
"Avatar": admin.Avatar, "Avatar": admin.Avatar,
"AutoReply": admin.AutoReply, "AutoReply": admin.AutoReply,
}); err != nil { }); err != nil {
...@@ -146,7 +142,7 @@ func (c *AdminController) Post() { ...@@ -146,7 +142,7 @@ func (c *AdminController) Post() {
var newAdmin models.Admin var newAdmin models.Admin
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &newAdmin); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &newAdmin); err != nil {
logs.Info("Post add new admin error------------", err) logs.Info("Post add new admin error------------", err)
c.JSON(configs.ResponseFail, "参数错误!", nil) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
} }
// validation // validation
...@@ -217,18 +213,18 @@ func (c *AdminController) Delete() { ...@@ -217,18 +213,18 @@ func (c *AdminController) Delete() {
func (c *AdminController) List() { func (c *AdminController) List() {
// request body // request body
var paginationData services.AdminPaginationData var paginationDto services.AdminPaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
data, err := c.AdminRepository.GetAdmins(&paginationData) data, err := c.AdminRepository.GetAdmins(&paginationDto)
if err != nil { 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 // UpdatePassword update password
...@@ -236,7 +232,7 @@ func (c *AdminController) UpdatePassword() { ...@@ -236,7 +232,7 @@ func (c *AdminController) UpdatePassword() {
request := services.UpdatePasswordRequest{} request := services.UpdatePasswordRequest{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// GetAuthInfo // GetAuthInfo
...@@ -245,7 +241,7 @@ func (c *AdminController) UpdatePassword() { ...@@ -245,7 +241,7 @@ func (c *AdminController) UpdatePassword() {
// oldAdmin // oldAdmin
oldAdmin := c.AdminRepository.GetAdmin(auth.UID) oldAdmin := c.AdminRepository.GetAdmin(auth.UID)
if oldAdmin == nil { if oldAdmin == nil {
c.JSON(configs.ResponseFail, "查询失败,暂时无法更新!", nil) c.JSON(configs.ResponseFail, "fail,暂时无法更新!", nil)
} }
// validation // validation
...@@ -290,7 +286,7 @@ func (c *AdminController) UpdatePassword() { ...@@ -290,7 +286,7 @@ func (c *AdminController) UpdatePassword() {
} }
// Update // Update
if _, err := c.AdminRepository.UpdateParams(newAdmin.ID, orm.Params{ if _, err := c.AdminRepository.Update(newAdmin.ID, orm.Params{
"Password": newAdmin.Password, "Password": newAdmin.Password,
"UpdateAt": newAdmin.UpdateAt, "UpdateAt": newAdmin.UpdateAt,
}); err != nil { }); err != nil {
...@@ -315,7 +311,7 @@ func (c *AdminController) ChangeCurrentUser() { ...@@ -315,7 +311,7 @@ func (c *AdminController) ChangeCurrentUser() {
uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// Update // Update
if _, err := c.AdminRepository.UpdateParams(admin.ID, orm.Params{ if _, err := c.AdminRepository.Update(admin.ID, orm.Params{
"CurrentConUser": uid, "CurrentConUser": uid,
}); err != nil { }); err != nil {
logs.Info("ChangeCurrentUser current connect user Warn------------", err) logs.Info("ChangeCurrentUser current connect user Warn------------", err)
...@@ -341,7 +337,7 @@ func (c *AdminController) Online() { ...@@ -341,7 +337,7 @@ func (c *AdminController) Online() {
} }
// Update // Update
if _, err := c.AdminRepository.UpdateParams(admin.ID, orm.Params{ if _, err := c.AdminRepository.Update(admin.ID, orm.Params{
"Online": online, "Online": online,
}); err != nil { }); err != nil {
c.JSON(configs.ResponseFail, "更新在线状态失败!", &err) c.JSON(configs.ResponseFail, "更新在线状态失败!", &err)
......
...@@ -25,17 +25,14 @@ type AuthController struct { ...@@ -25,17 +25,14 @@ type AuthController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *AuthController) Prepare() { func (c *AuthController) Prepare() {
// init AuthTypes // AuthTypes instance
c.AuthTypesRepository = new(services.AuthTypesRepository) c.AuthTypesRepository = services.GetAuthTypesRepositoryInstance()
c.AuthTypesRepository.Init(new(models.AuthTypes))
// init AdminRepository // AdminRepository instance
c.AdminRepository = new(services.AdminRepository) c.AdminRepository = services.GetAdminRepositoryInstance()
c.AdminRepository.Init(new(models.Admin))
// init AuthsRepository // AuthsRepository instance
c.AuthsRepository = new(services.AuthsRepository) c.AuthsRepository = services.GetAuthsRepositoryInstance()
c.AuthsRepository.Init(new(models.Auths))
} }
...@@ -59,7 +56,7 @@ func (c *AuthController) Login() { ...@@ -59,7 +56,7 @@ func (c *AuthController) Login() {
valid := validation.Validation{} valid := validation.Validation{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &request); err != nil {
c.JSON(configs.ResponseFail, "参数错误", nil) c.JSON(configs.ResponseFail, "参数有误,请检查", nil)
} }
// valid // valid
...@@ -97,7 +94,7 @@ func (c *AuthController) Login() { ...@@ -97,7 +94,7 @@ func (c *AuthController) Login() {
} }
// create token // 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) auth := c.AuthsRepository.GetAuthInfoWithTypeAndUID(request.AuthType, queryAdmin.ID)
if auth == nil { if auth == nil {
...@@ -114,7 +111,7 @@ func (c *AuthController) Login() { ...@@ -114,7 +111,7 @@ func (c *AuthController) Login() {
} else { } else {
_, err := c.AuthsRepository.UpdateParams(auth.ID, orm.Params{ _, err := c.AuthsRepository.Update(auth.ID, orm.Params{
"Token": newToken, "Token": newToken,
"UpdateAt": time.Now().Unix(), "UpdateAt": time.Now().Unix(),
}) })
...@@ -137,7 +134,7 @@ func (c *AuthController) Logout() { ...@@ -137,7 +134,7 @@ func (c *AuthController) Logout() {
if count := c.AuthsRepository.GetAdminOnlineCount(auth.UID); count <= 1 { 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, "CurrentConUser": 0,
"Online": 0, "Online": 0,
}); err != nil { }); err != nil {
......
...@@ -30,7 +30,7 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string, ...@@ -30,7 +30,7 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string,
msg = "sorry server error" msg = "sorry server error"
data = nil 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.ServeJSON()
c.StopRun() c.StopRun()
} }
...@@ -38,8 +38,7 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string, ...@@ -38,8 +38,7 @@ func (c *BaseController) JSON(status configs.ResponseStatusType, message string,
// GetAuthInfo get current anth user that AuthInfo // GetAuthInfo get current anth user that AuthInfo
func (c *BaseController) GetAuthInfo() *models.Auths { func (c *BaseController) GetAuthInfo() *models.Auths {
token := c.Ctx.Input.Header("Authorization") token := c.Ctx.Input.Header("Authorization")
var authsRepository = new(services.AuthsRepository) var authsRepository = services.GetAuthsRepositoryInstance()
authsRepository.Init(new(models.Auths))
auth := authsRepository.GetAuthInfo(token) auth := authsRepository.GetAuthInfo(token)
if auth == nil { if auth == nil {
logs.Warn("GetAuthInfo fun error------------登录已失效!") logs.Warn("GetAuthInfo fun error------------登录已失效!")
......
...@@ -20,9 +20,8 @@ type CompanyController struct { ...@@ -20,9 +20,8 @@ type CompanyController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *CompanyController) Prepare() { func (c *CompanyController) Prepare() {
// init CompanyRepository // CompanyRepository instance
c.CompanyRepository = new(services.CompanyRepository) c.CompanyRepository = services.GetCompanyRepositoryInstance()
c.CompanyRepository.Init(new(models.Company))
} }
...@@ -33,9 +32,9 @@ func (c *CompanyController) Finish() {} ...@@ -33,9 +32,9 @@ func (c *CompanyController) Finish() {}
func (c *CompanyController) Get() { func (c *CompanyController) Get() {
company := c.CompanyRepository.GetCompany(1) company := c.CompanyRepository.GetCompany(1)
if company == nil { 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 // Put update conpany info
...@@ -44,7 +43,7 @@ func (c *CompanyController) Put() { ...@@ -44,7 +43,7 @@ func (c *CompanyController) Put() {
company := models.Company{} company := models.Company{}
company.UpdateAt = time.Now().Unix() company.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &company); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &company); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
} }
// validation // validation
...@@ -63,7 +62,7 @@ func (c *CompanyController) Put() { ...@@ -63,7 +62,7 @@ func (c *CompanyController) Put() {
} }
// orm // orm
row, err := c.CompanyRepository.UpdateParams(1, orm.Params{ row, err := c.CompanyRepository.Update(1, orm.Params{
"Title": company.Title, "Title": company.Title,
"Address": company.Address, "Address": company.Address,
"Email": company.Email, "Email": company.Email,
......
...@@ -17,13 +17,11 @@ type ContactController struct { ...@@ -17,13 +17,11 @@ type ContactController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *ContactController) Prepare() { func (c *ContactController) Prepare() {
// init ContactRepository // ContactRepository instance
c.ContactRepository = new(services.ContactRepository) c.ContactRepository = services.GetContactRepositoryInstance()
c.ContactRepository.Init(new(models.Contact))
// init AdminRepository // AdminRepository instance
c.AdminRepository = new(services.AdminRepository) c.AdminRepository = services.GetAdminRepositoryInstance()
c.AdminRepository.Init(new(models.Admin))
} }
...@@ -36,15 +34,15 @@ func (c *ContactController) GetContacts() { ...@@ -36,15 +34,15 @@ func (c *ContactController) GetContacts() {
// GetAuthInfo // GetAuthInfo
auth := c.GetAuthInfo() auth := c.GetAuthInfo()
contactData, err := c.ContactRepository.GetContacts(auth.UID) contactDto, err := c.ContactRepository.GetContacts(auth.UID)
if err != nil { if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err) c.JSON(configs.ResponseFail, "fail", &err)
} }
if len(contactData) == 0 { if len(contactDto) == 0 {
contactData = []models.ContactData{} contactDto = []models.ContactDto{}
} }
c.JSON(configs.ResponseSucess, "查询成功!", &contactData) c.JSON(configs.ResponseSucess, "success", &contactDto)
} }
......
...@@ -3,7 +3,6 @@ package controllers ...@@ -3,7 +3,6 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"kefu_server/configs" "kefu_server/configs"
"kefu_server/models"
"kefu_server/services" "kefu_server/services"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
...@@ -18,9 +17,8 @@ type HomeController struct { ...@@ -18,9 +17,8 @@ type HomeController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *HomeController) Prepare() { func (c *HomeController) Prepare() {
// init StatisticalRepository // StatisticalRepository instance
c.StatisticalRepository = new(services.StatisticalRepository) c.StatisticalRepository = services.GetStatisticalRepositoryInstance()
c.StatisticalRepository.Init(new(models.ServicesStatistical))
} }
...@@ -39,7 +37,7 @@ func (c *HomeController) Statistical() { ...@@ -39,7 +37,7 @@ func (c *HomeController) Statistical() {
// request body // request body
statisticalRequest := StatisticalRequest{} statisticalRequest := StatisticalRequest{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &statisticalRequest); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &statisticalRequest); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// validation // validation
...@@ -57,7 +55,7 @@ func (c *HomeController) Statistical() { ...@@ -57,7 +55,7 @@ func (c *HomeController) Statistical() {
c.JSON(configs.ResponseFail, err.Error(), &err) 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() { ...@@ -67,7 +65,7 @@ func (c *HomeController) TodayActionStatistical() {
// request body // request body
statisticalRequest := StatisticalRequest{} statisticalRequest := StatisticalRequest{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &statisticalRequest); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &statisticalRequest); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// validation // validation
...@@ -85,6 +83,6 @@ func (c *HomeController) TodayActionStatistical() { ...@@ -85,6 +83,6 @@ func (c *HomeController) TodayActionStatistical() {
c.JSON(configs.ResponseFail, err.Error(), &err) 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 { ...@@ -23,13 +23,11 @@ type KnowledgeBaseController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *KnowledgeBaseController) Prepare() { func (c *KnowledgeBaseController) Prepare() {
// init StatisticalRepository // StatisticalRepository instance
c.KnowledgeBaseRepository = new(services.KnowledgeBaseRepository) c.KnowledgeBaseRepository = services.GetKnowledgeBaseRepositoryInstance()
c.KnowledgeBaseRepository.Init(new(models.KnowledgeBase))
// init PlatformRepository // PlatformRepository instance
c.PlatformRepository = new(services.PlatformRepository) c.PlatformRepository = services.GetPlatformRepositoryInstance()
c.PlatformRepository.Init(new(models.Platform))
} }
...@@ -41,16 +39,16 @@ func (c *KnowledgeBaseController) Get() { ...@@ -41,16 +39,16 @@ func (c *KnowledgeBaseController) Get() {
id, err := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, err := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
if err != nil { if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err) c.JSON(configs.ResponseFail, "fail", &err)
} }
knowledgeBase := c.KnowledgeBaseRepository.GetKnowledgeBase(id) knowledgeBase := c.KnowledgeBaseRepository.GetKnowledgeBase(id)
if knowledgeBase == nil { 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 // Post add a knowledge Base
...@@ -60,7 +58,7 @@ func (c *KnowledgeBaseController) Post() { ...@@ -60,7 +58,7 @@ func (c *KnowledgeBaseController) Post() {
var knowledgeBase models.KnowledgeBase var knowledgeBase models.KnowledgeBase
knowledgeBase.CreateAt = time.Now().Unix() knowledgeBase.CreateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &knowledgeBase); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &knowledgeBase); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// validation // validation
...@@ -98,7 +96,7 @@ func (c *KnowledgeBaseController) Put() { ...@@ -98,7 +96,7 @@ func (c *KnowledgeBaseController) Put() {
// request body // request body
var newKnowledgeBase models.KnowledgeBase var newKnowledgeBase models.KnowledgeBase
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &newKnowledgeBase); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &newKnowledgeBase); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// validation // validation
...@@ -130,7 +128,7 @@ func (c *KnowledgeBaseController) Put() { ...@@ -130,7 +128,7 @@ func (c *KnowledgeBaseController) Put() {
} }
// insert // insert
row, err := c.KnowledgeBaseRepository.UpdateParams(newKnowledgeBase.ID, orm.Params{ row, err := c.KnowledgeBaseRepository.Update(newKnowledgeBase.ID, orm.Params{
"Title": newKnowledgeBase.Title, "Title": newKnowledgeBase.Title,
"SubTitle": newKnowledgeBase.SubTitle, "SubTitle": newKnowledgeBase.SubTitle,
"Content": newKnowledgeBase.Content, "Content": newKnowledgeBase.Content,
...@@ -167,16 +165,16 @@ func (c *KnowledgeBaseController) Delete() { ...@@ -167,16 +165,16 @@ func (c *KnowledgeBaseController) Delete() {
func (c *KnowledgeBaseController) List() { func (c *KnowledgeBaseController) List() {
// request body // request body
var paginationData *models.PaginationData var knowledgePaginationDto *models.KnowledgePaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &knowledgePaginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", &err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
} }
// query // query
paginationData, err := c.KnowledgeBaseRepository.GetKnowledgeBases(paginationData) knowledgePaginationDto, err := c.KnowledgeBaseRepository.GetKnowledgeBases(knowledgePaginationDto)
if err != nil { 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 ( ...@@ -4,6 +4,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
"kefu_server/configs" "kefu_server/configs"
...@@ -24,10 +25,8 @@ type MessageController struct { ...@@ -24,10 +25,8 @@ type MessageController struct {
// Prepare More like construction method // Prepare More like construction method
func (c *MessageController) Prepare() { func (c *MessageController) Prepare() {
// init MessageRepository // MessageRepository instance
c.MessageRepository = new(services.MessageRepository) c.MessageRepository = services.GetMessageRepositoryInstance()
c.MessageRepository.Init(new(models.Message))
} }
// Finish Comparison like destructor // Finish Comparison like destructor
...@@ -36,75 +35,66 @@ func (c *MessageController) Finish() {} ...@@ -36,75 +35,66 @@ func (c *MessageController) Finish() {}
// List get messages // List get messages
func (c *MessageController) List() { func (c *MessageController) List() {
messagePaginationData := models.MessagePaginationData{} messagePaginationDto := models.MessagePaginationDto{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &messagePaginationData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &messagePaginationDto); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
} }
// service ID
var serviceID int64
if messagePaginationData.Service == 0 {
// GetAuthInfo // GetAuthInfo
auth := c.GetAuthInfo() auth := c.GetAuthInfo()
serviceID = auth.UID messagePaginationDto.Service = auth.UID
} else {
serviceID = messagePaginationData.Service
}
// Timestamp == 0 // Timestamp == 0
if messagePaginationData.Timestamp == 0 { if messagePaginationDto.Timestamp == 0 {
messagePaginationData.Timestamp = time.Now().Unix() messagePaginationDto.Timestamp = time.Now().Unix()
} }
// validation // validation
valid := validation.Validation{} valid := validation.Validation{}
valid.Required(messagePaginationData.Account, "account").Message("account不能为空!") valid.Required(messagePaginationDto.Account, "account").Message("account不能为空!")
valid.Required(messagePaginationData.PageSize, "page_size").Message("page_size不能为空!") valid.Required(messagePaginationDto.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(messagePaginationData.Timestamp, "timestamp").Message("timestamp不能为空!") valid.Required(messagePaginationDto.Timestamp, "timestamp").Message("timestamp不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
} }
} }
// query message // query messages
returnMessagePaginationData, err := c.MessageRepository.GetMessages(serviceID, messagePaginationData) returnMessagePaginationDto, err := c.MessageRepository.GetAdminMessages(messagePaginationDto)
if err != nil { if err != nil {
c.JSON(configs.ResponseFail, "查询失败!", &err) c.JSON(configs.ResponseFail, "fail", &err)
} }
// push notify update current service contacts list // push notify update current service contacts list
if len(im.Robots) > 0 { 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 // Remove one message
func (c *MessageController) Remove() { func (c *MessageController) Remove() {
// request body // request body
removeRequestData := models.RemoveMessageRequestData{} removeRequestDto := models.RemoveMessageRequestDto{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &removeRequestData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &removeRequestDto); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
} }
// validation // validation
valid := validation.Validation{} valid := validation.Validation{}
valid.Required(removeRequestData.ToAccount, "to_account").Message("to_account不能为空!") valid.Required(removeRequestDto.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(removeRequestData.FromAccount, "from_account").Message("from_account不能为空!") valid.Required(removeRequestDto.FromAccount, "from_account").Message("from_account不能为空!")
valid.Required(removeRequestData.Key, "key").Message("key不能为空!") valid.Required(removeRequestDto.Key, "key").Message("key不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
} }
} }
row, err := c.MessageRepository.Delete(removeRequestData) row, err := c.MessageRepository.Delete(removeRequestDto)
if err != nil || row == 0 { if err != nil || row == 0 {
c.JSON(configs.ResponseFail, "删除失败!", &err) c.JSON(configs.ResponseFail, "删除失败!", &err)
} }
...@@ -117,20 +107,19 @@ func (c *MessageController) Transfer() { ...@@ -117,20 +107,19 @@ func (c *MessageController) Transfer() {
// GetAuthInfo // GetAuthInfo
auth := c.GetAuthInfo() auth := c.GetAuthInfo()
adminRepository := new(services.AdminRepository) adminRepository := services.GetAdminRepositoryInstance()
adminRepository.Init(new(models.Admin))
admin := adminRepository.GetAdmin(auth.UID) admin := adminRepository.GetAdmin(auth.UID)
// request body // request body
var transferRequestData *models.TransferRequestData var transferDto *models.TransferDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &transferRequestData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &transferDto); err != nil {
c.JSON(configs.ResponseFail, "参数错误!", nil) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
} }
// validation // validation
valid := validation.Validation{} valid := validation.Validation{}
valid.Required(transferRequestData.ToAccount, "to_account").Message("to_account不能为空!") valid.Required(transferDto.ToAccount, "to_account").Message("to_account不能为空!")
valid.Required(transferRequestData.UserAccount, "user_account").Message("user不能为空!") valid.Required(transferDto.UserAccount, "user_account").Message("user不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.JSON(configs.ResponseFail, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
...@@ -145,15 +134,16 @@ func (c *MessageController) Transfer() { ...@@ -145,15 +134,16 @@ func (c *MessageController) Transfer() {
NickName string `json:"nickname"` NickName string `json:"nickname"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
} }
toAdmin := adminRepository.GetAdmin(transferRequestData.ToAccount) toAdmin := adminRepository.GetAdmin(transferDto.ToAccount)
if toAdmin == nil { if toAdmin == nil {
c.JSON(configs.ResponseFail, "转接失败,转接客服不存在!", nil) c.JSON(configs.ResponseFail, "转接失败,转接客服不存在!", nil)
} }
toAdminJSON, _ := json.Marshal(adminData{ID: toAdmin.ID, Avatar: toAdmin.Avatar, NickName: toAdmin.NickName}) toAdminJSON, _ := json.Marshal(adminData{ID: toAdmin.ID, Avatar: toAdmin.Avatar, NickName: toAdmin.NickName})
userRepository := new(services.UserRepository) // UserRepository instance
userRepository.Init(new(models.User)) userRepository := services.GetUserRepositoryInstance()
user := userRepository.GetUser(transferRequestData.UserAccount)
user := userRepository.GetUser(transferDto.UserAccount)
if user == nil { if user == nil {
c.JSON(configs.ResponseFail, "转接失败用户ID不存在!", nil) c.JSON(configs.ResponseFail, "转接失败用户ID不存在!", nil)
} }
...@@ -161,9 +151,9 @@ func (c *MessageController) Transfer() { ...@@ -161,9 +151,9 @@ func (c *MessageController) Transfer() {
// message // message
message := models.Message{} message := models.Message{}
message.BizType = "transfer" message.BizType = "transfer"
message.FromAccount = transferRequestData.UserAccount message.FromAccount = transferDto.UserAccount
message.Timestamp = time.Now().Unix() message.Timestamp = time.Now().Unix()
message.TransferAccount = transferRequestData.ToAccount message.TransferAccount = transferDto.ToAccount
// Send to forwarder // Send to forwarder
message.ToAccount = admin.ID message.ToAccount = admin.ID
...@@ -174,27 +164,27 @@ func (c *MessageController) Transfer() { ...@@ -174,27 +164,27 @@ func (c *MessageController) Transfer() {
utils.MessageInto(message, true) utils.MessageInto(message, true)
// Send to forwarded customer service // Send to forwarded customer service
message.ToAccount = transferRequestData.ToAccount message.ToAccount = transferDto.ToAccount
message.Payload = admin.NickName + "将" + user.NickName + "转接给您" message.Payload = admin.NickName + "将" + user.NickName + "转接给您"
messageJSONTwo, _ := json.Marshal(message) messageJSONTwo, _ := json.Marshal(message)
messageStringTwo := base64.StdEncoding.EncodeToString([]byte(messageJSONTwo)) 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) utils.MessageInto(message, true)
// send to user // send to user
message.FromAccount = robotID message.FromAccount = robotID
message.ToAccount = transferRequestData.UserAccount message.ToAccount = transferDto.UserAccount
message.Delete = 1 message.Delete = 1
message.Payload = string(toAdminJSON) message.Payload = string(toAdminJSON)
messageJSONThree, _ := json.Marshal(message) messageJSONThree, _ := json.Marshal(message)
messageString3 := base64.StdEncoding.EncodeToString([]byte(messageJSONThree)) 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) utils.MessageInto(message, false)
// Transfer to the library for counting service times // 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()} servicesStatistical := models.ServicesStatistical{UserAccount: transferDto.UserAccount, ServiceAccount: transferDto.ToAccount, TransferAccount: admin.ID, Platform: user.Platform, CreateAt: time.Now().Unix()}
statisticalRepository := new(services.StatisticalRepository) // StatisticalRepository instance
statisticalRepository.Init(new(models.ServicesStatistical)) statisticalRepository := services.GetStatisticalRepositoryInstance()
_, err := statisticalRepository.Add(&servicesStatistical) _, err := statisticalRepository.Add(&servicesStatistical)
if err != nil { if err != nil {
} }
...@@ -203,11 +193,14 @@ func (c *MessageController) Transfer() { ...@@ -203,11 +193,14 @@ func (c *MessageController) Transfer() {
tk := time.NewTimer(1 * time.Second) tk := time.NewTimer(1 * time.Second)
select { select {
case <-tk.C: case <-tk.C:
usersID := []int64{admin.ID, transferRequestData.UserAccount} usersID := []int64{admin.ID, transferDto.UserAccount}
contactRepository := new(services.ContactRepository)
contactRepository.Init(new(models.Contact)) // ContactRepository instance
contactRepository := services.GetContactRepositoryInstance()
_, err := contactRepository.UpdateIsSessionEnd(usersID, 1) _, err := contactRepository.UpdateIsSessionEnd(usersID, 1)
if err != nil { if err != nil {
logs.Info(err)
} }
} }
......
...@@ -2,71 +2,66 @@ package controllers ...@@ -2,71 +2,66 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"kefu_server/configs"
"kefu_server/models" "kefu_server/models"
"kefu_server/utils" "kefu_server/services"
"strconv" "strconv"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
// PlatformController struct // PlatformController struct
type 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 // Get get a admin
func (c *PlatformController) Get() { func (c *PlatformController) Get() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
platform := models.Platform{ID: id} platform := c.PlatformRepository.GetPlatform(id)
if err := o.Read(&platform); err != nil { if platform == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err) c.JSON(configs.ResponseFail, "fail", nil)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &platform)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &platform)
} }
// Put update admin // Put update admin
func (c *PlatformController) Put() { func (c *PlatformController) Put() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_auth := models.Auths{Token: token} admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
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)
// is admin ? // is admin root ?
if _admin.Root != 1 { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败,无权限更新", nil) c.JSON(configs.ResponseFail, "更新失败,无权限更新!", nil)
c.ServeJSON()
return
} }
// request body // request body
platform := models.Platform{} platform := models.Platform{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &platform); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &platform); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
// admin exist // platform exist
if err := o.Read(&models.Platform{ID: platform.ID}); err != nil { if p := c.PlatformRepository.GetPlatform(platform.ID); p == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败,数据不存在!", err) c.JSON(configs.ResponseFail, "更新失败,数据不存在!", nil)
c.ServeJSON()
return
} }
// validation // validation
...@@ -80,64 +75,42 @@ func (c *PlatformController) Put() { ...@@ -80,64 +75,42 @@ func (c *PlatformController) Put() {
valid.MaxSize(platform.Alias, 30, "alias").Message("别名不能超过30个字符!") valid.MaxSize(platform.Alias, 30, "alias").Message("别名不能超过30个字符!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
// title exist // title exist
var pt models.Platform if pt := c.PlatformRepository.GetPlatformWithIDAndTitle(platform.ID, platform.Title); pt != nil {
if err := o.Raw("SELECT * FROM platform WHERE id != ? AND title = ?", platform.ID, platform.Title).QueryRow(&pt); err == nil { c.JSON(configs.ResponseFail, "平台名已被使用,请换一个试试", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "平台名已被使用,请换一个试试!", err)
c.ServeJSON()
return
} }
// Alias exist // Alias exist
if err := o.Raw("SELECT * FROM platform WHERE id != ? AND alias = ?", platform.ID, platform.Alias).QueryRow(&pt); err == nil { if pt := c.PlatformRepository.GetPlatformWithIDAndAlias(platform.ID, platform.Alias); pt != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "别名已被使用,请换一个试试!", err) c.JSON(configs.ResponseFail, "别名已被使用,请换一个试试", nil)
c.ServeJSON()
return
} }
_, _ = c.PlatformRepository.Update(platform.ID, orm.Params{
"Title": platform.Title,
"Alias": platform.Alias,
})
if _, err := o.Update(&platform, "Title", "Alias"); err != nil { c.JSON(configs.ResponseSucess, "更新成功!", &platform)
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()
} }
// Post add new admin // Post add new platform
func (c *PlatformController) Post() { func (c *PlatformController) Post() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_auth := models.Auths{Token: token} admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
if err := o.Read(&_auth, "Token"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) if admin.Root != 1 {
c.ServeJSON() c.JSON(configs.ResponseFail, "您没有权限添加平台!", nil)
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
} }
// request body // request body
var platform models.Platform var platform models.Platform
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &platform); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &platform); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
// validation // validation
...@@ -149,86 +122,66 @@ func (c *PlatformController) Post() { ...@@ -149,86 +122,66 @@ func (c *PlatformController) Post() {
valid.MaxSize(platform.Alias, 30, "alias").Message("别名不能超过30个字符!") valid.MaxSize(platform.Alias, 30, "alias").Message("别名不能超过30个字符!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
var pt models.Platform pt := c.PlatformRepository.GetPlatformWithIDAndAlias(platform.ID, platform.Alias)
if err := o.Raw("SELECT * FROM platform WHERE id != ? AND alias = ?", platform.ID, platform.Alias).QueryRow(&pt); err == nil { if pt != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "别名已被使用,请换一个试试!", err) c.JSON(configs.ResponseFail, "别名已被使用,请换一个试试!", nil)
c.ServeJSON()
return
} }
// exist ? and create // exist ? and create
platform.ID = 0 platform.ID = 0
if isExist, _, err := o.ReadOrCreate(&platform, "Title"); err == nil { isExist, _, err := c.PlatformRepository.Add(&platform, "Title")
if isExist {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "添加成功!", nil) if err != nil {
} else { c.JSON(configs.ResponseFail, "添加失败,换个名字试试!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "平台名已被使用,请换一个试试!", nil) }
}
} else { if !isExist {
logs.Error(err) c.JSON(configs.ResponseFail, "平台名已被使用,请换一个试试!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "服务异常", err) }
}
c.ServeJSON() c.JSON(configs.ResponseSucess, "添加成功!", nil)
return
} }
// Delete delete remove admin // Delete delete remove admin
func (c *PlatformController) Delete() { func (c *PlatformController) Delete() {
o := orm.NewOrm() // GetAuthInfo
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) auth := c.GetAuthInfo()
token := c.Ctx.Input.Header("Authorization") admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
_auth := models.Auths{Token: token}
if err := o.Read(&_auth, "Token"); err != nil { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) c.JSON(configs.ResponseFail, "您没有权限添加平台!", 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
} }
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// platform // platform
platform := models.Platform{ID: id} platform := c.PlatformRepository.GetPlatform(id)
// exist // exist
if err := o.Read(&platform); err != nil { if platform == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,平台不存在!", err) c.JSON(configs.ResponseFail, "删除失败,平台不存在!", nil)
c.ServeJSON()
return
} }
if num, err := o.Delete(&platform); err != nil { if _, err := c.PlatformRepository.Delete(id); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "删除失败!", &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 admin all // List get admin all
func (c *PlatformController) List() { func (c *PlatformController) List() {
o := orm.NewOrm() platforms, err := c.PlatformRepository.GetPlatformAll("id")
var platforms []models.Platform
qs := o.QueryTable(new(models.Platform)) if err != nil {
if _, err := qs.OrderBy("id").All(&platforms); err != nil { c.JSON(configs.ResponseFail, "fail", &err)
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &platforms)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &platforms)
} }
...@@ -3,19 +3,17 @@ package controllers ...@@ -3,19 +3,17 @@ package controllers
import ( import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "kefu_server/configs"
"kefu_server/im" "kefu_server/im"
"kefu_server/models" "kefu_server/models"
"kefu_server/services"
"kefu_server/utils" "kefu_server/utils"
"math/rand"
"os" "os"
"path" "path"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
"github.com/qiniu/api.v7/auth/qbox" "github.com/qiniu/api.v7/auth/qbox"
...@@ -24,235 +22,250 @@ import ( ...@@ -24,235 +22,250 @@ import (
// PublicController struct // PublicController struct
type PublicController struct { type PublicController struct {
beego.Controller BaseController
UserRepository *services.UserRepository
MessageRepository *services.MessageRepository
AdminRepository *services.AdminRepository
} }
// Prepare More like construction method
func (c *PublicController) Prepare() {
// UserRepository inttance
c.UserRepository = services.GetUserRepositoryInstance()
// MessageRepository instance
c.MessageRepository = services.GetMessageRepositoryInstance()
// AdminRepository instance
c.AdminRepository = services.GetAdminRepositoryInstance()
}
// Finish Comparison like destructor
func (c *PublicController) Finish() {}
// Register mimc and user // Register mimc and user
func (c *PublicController) Register() { func (c *PublicController) Register() {
// request body // request body
var sessionRequest models.SessionRequest var sessionRequestDto models.SessionRequestDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &sessionRequest); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &sessionRequestDto); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
// type // type
if sessionRequest.Type > 1 || sessionRequest.Type < 0 { if sessionRequestDto.Type > 1 || sessionRequestDto.Type < 0 {
c.Data["json"] = utils.ResponseError(c.Ctx, "type类型错误!", nil) c.JSON(configs.ResponseFail, "type类型错误!", nil)
c.ServeJSON()
return
} }
imToken := new(models.IMToken) imTokenDto := new(models.IMTokenDto)
o := orm.NewOrm()
var user *models.User
var admin *models.Admin
var ( var (
fetchResult string fetchResult string
fetchError error fetchError error
) )
// user // user
var user models.User if sessionRequestDto.Type == 0 {
var admin models.Admin
if sessionRequest.Type == 0 {
// platfrom id exist // platfrom id exist
if count, err := o.QueryTable(new(models.Platform)).Filter("id", sessionRequest.Platform).Count(); count <= 0 || sessionRequest.Platform == 1 { if pt := services.GetPlatformRepositoryInstance().GetPlatform(sessionRequestDto.Platform); pt == nil || sessionRequestDto.Platform == 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "注册失败,该平台ID不存在!", &err) c.JSON(configs.ResponseFail, "注册失败,该平台ID不存在!", nil)
c.ServeJSON()
return
} }
user = models.User{ID: sessionRequest.AccountID, UID: sessionRequest.UID, Platform: sessionRequest.Platform, Address: sessionRequest.Address} // Do business user data expansion here
if sessionRequestDto.UID != 0 {
// “sessionRequestDto.UID”, If there is a mapping relationship with the business platform
// You can update the business profile user information to the customer service database here
// example:
// &myUser := modes.MyUser{}
// o.Raw("SELECT * FROM `members` WHERE id = 100", sessionRequestDto.UID).QueryRow(&myUser)
// & myUser is the data of the business platform user, and finally assigned to models.User
// Read users based on business platform
user = c.UserRepository.GetUserWithUID(sessionRequestDto.UID)
} else {
// Read users using AccountID
user = c.UserRepository.GetUser(sessionRequestDto.AccountID)
}
/// old user /// old user
if err := o.QueryTable(new(models.User)).Filter("id", sessionRequest.AccountID).One(&user); err == nil { if user != nil {
// fetchResult
fetchResult, fetchError = im.GetMiMcToken(strconv.FormatInt(user.ID, 10)) fetchResult, fetchError = im.GetMiMcToken(strconv.FormatInt(user.ID, 10))
if err := json.Unmarshal([]byte(fetchResult), &imToken); err != nil { if err := json.Unmarshal([]byte(fetchResult), &imTokenDto); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "注册失败!", &err) c.JSON(configs.ResponseFail, "注册失败!", &err)
c.ServeJSON()
return
} }
user.Online = 1
user.UID = sessionRequest.UID // update userinfo
user.Address = sessionRequest.Address c.UserRepository.Update(user.ID, orm.Params{
user.Address = sessionRequest.Address "Online": 1,
user.Platform = sessionRequest.Platform "Address": sessionRequestDto.Address,
user.LastActivity = time.Now().Unix() "Platform": sessionRequestDto.Platform,
user.Token = imToken.Data.Token "LastActivity": time.Now().Unix(),
logs.Info("imToken.Data.Token==", imToken.Data.Token) "Token": imTokenDto.Data.Token,
_, _ = o.Update(&user) })
} else { } else {
// create new user // create new user
user = &models.User{}
user.CreateAt = time.Now().Unix() user.CreateAt = time.Now().Unix()
user.ID = 0 user.ID = 0
user.Online = 1 user.Online = 1
user.LastActivity = time.Now().Unix() user.LastActivity = time.Now().Unix()
user.Address = sessionRequest.Address user.Address = sessionRequestDto.Address
if accountID, err := o.Insert(&user); err == nil {
if accountID, err := c.UserRepository.Add(user); err == nil {
fetchResult, fetchError = im.GetMiMcToken(strconv.FormatInt(accountID, 10)) fetchResult, fetchError = im.GetMiMcToken(strconv.FormatInt(accountID, 10))
if err := json.Unmarshal([]byte(fetchResult), &imToken); err != nil { if err := json.Unmarshal([]byte(fetchResult), &imTokenDto); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "注册失败!", &err) c.JSON(configs.ResponseFail, "注册失败!", &err)
c.ServeJSON() }
return
} // update userinfo
user.Token = imToken.Data.Token c.UserRepository.Update(user.ID, orm.Params{
user.NickName = "访客" + strconv.FormatInt(accountID, 10) "Token": imTokenDto.Data.Token,
_, _ = o.Update(&user) "NickName": "访客" + strconv.FormatInt(accountID, 10),
})
} else { } else {
logs.Info(err) c.JSON(configs.ResponseFail, "注册失败!", &err)
c.Data["json"] = utils.ResponseError(c.Ctx, "服务异常,请稍后重试!", err)
c.ServeJSON()
return
} }
} }
} else { } else {
// is service // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
admin = c.AdminRepository.GetAdmin(auth.UID)
// admin
_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}
if err := o.Read(&admin); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "客服不存在!", err)
c.ServeJSON()
return
}
// fetchResult
fetchResult, fetchError = im.GetMiMcToken(strconv.FormatInt(admin.ID, 10)) fetchResult, fetchError = im.GetMiMcToken(strconv.FormatInt(admin.ID, 10))
// imTokenDto
if err := json.Unmarshal([]byte(fetchResult), &imTokenDto); err != nil {
c.JSON(configs.ResponseFail, "注册失败!", &err)
}
} }
// is Error ?
if fetchError != nil { if fetchError != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "注册失败!", &fetchError) c.JSON(configs.ResponseFail, "注册失败!", &fetchError)
c.ServeJSON()
return
}
if err := json.Unmarshal([]byte(fetchResult), &imToken); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "注册失败!", &err)
c.ServeJSON()
return
} }
// response data
type successData struct { type successData struct {
Token interface{} `json:"token"` Token interface{} `json:"token"`
User interface{} `json:"user"` User interface{} `json:"user"`
} }
var resData successData var resData successData
if sessionRequest.Type == 0 { if sessionRequestDto.Type == 0 {
resData = successData{Token: &imToken, User: &user} resData = successData{Token: &imTokenDto, User: &user}
} else { } else {
resData = successData{Token: &imToken, User: &admin} resData = successData{Token: &imTokenDto, User: &admin}
} }
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "获取成功!", &resData)
c.ServeJSON() c.JSON(configs.ResponseSucess, "获取成功!", &resData)
} }
// Read get user read count // Read get user read count
func (c *PublicController) Read() { func (c *PublicController) Read() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
qs := o.QueryTable(new(models.Message)) readCount, err := c.MessageRepository.GetReadCount(id)
var readCount int64 if err == nil {
if _count, err := qs.Filter("to_account", id).Filter("read", 1).Count(); err == nil {
readCount = _count
} else {
readCount = 0 readCount = 0
} }
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &readCount) c.JSON(configs.ResponseSucess, "获取成功!", readCount)
c.ServeJSON()
} }
// Window set user window // Window set user window
func (c *PublicController) Window() { func (c *PublicController) Window() {
o := orm.NewOrm()
type WindowType struct { type WindowType struct {
Window int `json:"window"` Window int `json:"window"`
} }
var wType WindowType var wType WindowType
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &wType); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &wType); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", nil) c.JSON(configs.ResponseFail, "更新失败!", nil)
return
} }
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
user := models.User{ID: id} // get user info
if err := o.Read(&user); err != nil { uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
logs.Info(err) user := c.UserRepository.GetUser(uid)
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", nil)
} else { if user == nil {
user.IsWindow = wType.Window c.JSON(configs.ResponseFail, "更新失败,用户不存在!", nil)
_, _ = o.Update(&user) }
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", nil)
// update
_, err := c.UserRepository.Update(uid, orm.Params{
"IsWindow": wType.Window,
})
if err != nil {
c.JSON(configs.ResponseFail, "更新失败!", nil)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "更新更新成功!", nil)
} }
// CleanRead clean user read // CleanRead clean user read
func (c *PublicController) CleanRead() { func (c *PublicController) CleanRead() {
uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
o := orm.NewOrm() // Can't just clear customer service
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) if admin := c.AdminRepository.GetAdmin(uid); admin != nil {
if _, err := o.Raw("UPDATE `message` SET `read` = 0 WHERE `to_account` = ?", id).Exec(); err != nil { c.JSON(configs.ResponseFail, "清除成功!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "执行失败!", err) }
} else { // clear
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "执行成功!", nil) if _, err := c.MessageRepository.ClearRead(uid); err != nil {
c.JSON(configs.ResponseFail, "清除失败!", &err)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "清除成功!", nil)
} }
// Robot get robot // Robot get robot
func (c *PublicController) Robot() { func (c *PublicController) Robot() {
o := orm.NewOrm()
// request body // request body
platformID, _ := strconv.ParseInt(c.Ctx.Input.Param(":platform"), 10, 64) pid, _ := strconv.ParseInt(c.Ctx.Input.Param(":platform"), 10, 64)
var robots []*models.Robot // get robot
qs := o.QueryTable(new(models.Robot)) robot, err := services.GetRobotRepositoryInstance().GetRobotWithOnline(pid)
_, _ = qs.Filter("platform__in", platformID, 1).Filter("switch", 1).All(&robots) if err != nil {
if len(robots) > 0 { c.JSON(configs.ResponseFail, "fail", &err)
robot := robots[rand.Intn(len(robots))]
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &robot)
} else {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", nil)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &robot)
} }
// RobotInfo get robot info // RobotInfo get robot info
func (c *PublicController) RobotInfo() { func (c *PublicController) RobotInfo() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// request // request
robot := models.Robot{ID: id} robot := services.GetRobotRepositoryInstance().GetRobot(id)
if err := o.Read(&robot); err != nil { if robot == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "获取失败!", err) c.JSON(configs.ResponseFail, "fail,机器人不存在!", nil)
c.ServeJSON()
return
} }
robot.Artificial = strings.Trim(robot.Artificial, "|")
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &robot) c.JSON(configs.ResponseSucess, "success", &robot)
c.ServeJSON()
} }
...@@ -266,31 +279,22 @@ type UploadSecretMode struct { ...@@ -266,31 +279,22 @@ type UploadSecretMode struct {
// UploadSecret update Secret // UploadSecret update Secret
func (c *PublicController) UploadSecret() { func (c *PublicController) UploadSecret() {
o := orm.NewOrm() // system info
system := models.System{ID: 1} system := services.GetSystemRepositoryInstance().GetSystem()
if err := o.Read(&system); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", nil)
c.ServeJSON()
return
}
// System built-in storage // System built-in storage
if system.UploadMode == 1 { if system.UploadMode == 1 {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &UploadSecretMode{ c.JSON(configs.ResponseSucess, "success", &UploadSecretMode{
Mode: system.UploadMode, Mode: system.UploadMode,
Secret: "", Secret: "",
Host: beego.AppConfig.String("static_host"), Host: beego.AppConfig.String("static_host"),
}) })
c.ServeJSON() }
// qiniu // qiniu
} else if system.UploadMode == 2 { if system.UploadMode == 2 {
qiniuSetting := models.QiniuSetting{ID: 1}
if err := o.Read(&qiniuSetting); err != nil { qiniuSetting := services.GetQiniuRepositoryInstance().GetQiniuConfigInfo()
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", nil)
c.ServeJSON()
return
}
putPolicy := storage.PutPolicy{ putPolicy := storage.PutPolicy{
Scope: qiniuSetting.Bucket, Scope: qiniuSetting.Bucket,
} }
...@@ -300,82 +304,56 @@ func (c *PublicController) UploadSecret() { ...@@ -300,82 +304,56 @@ func (c *PublicController) UploadSecret() {
mac := qbox.NewMac(qiniuSetting.AccessKey, qiniuSetting.SecretKey) mac := qbox.NewMac(qiniuSetting.AccessKey, qiniuSetting.SecretKey)
upToken := putPolicy.UploadToken(mac) upToken := putPolicy.UploadToken(mac)
secretModeData := UploadSecretMode{Mode: system.UploadMode, Secret: upToken, Host: qiniuSetting.Host} secretModeData := UploadSecretMode{Mode: system.UploadMode, Secret: upToken, Host: qiniuSetting.Host}
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &secretModeData) c.JSON(configs.ResponseSucess, "success", &secretModeData)
// aliyun OSS
} else if system.UploadMode == 3 {
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", nil)
c.ServeJSON()
} }
c.ServeJSON() c.JSON(configs.ResponseFail, "fail", nil)
} }
// LastActivity change last Activity // LastActivity change last Activity
func (c *PublicController) LastActivity() { func (c *PublicController) LastActivity() {
o := orm.NewOrm() // uid id if exist current request is user, else admin
uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) uid, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// user
if uid > 0 { if uid > 0 {
_, err := c.UserRepository.Update(uid, orm.Params{
user := models.User{ID: uid} "LastActivity": time.Now().Unix(),
user.LastActivity = time.Now().Unix() })
if _, err := o.Update(&user, "LastActivity"); err != nil { if err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "用户不存在!", &err) c.JSON(configs.ResponseFail, "fail,用户不存在!", &err)
c.ServeJSON()
return
}
} else {
// token
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}
if err := o.Read(&admin); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "用户不存在!", nil)
c.ServeJSON()
return
} }
c.JSON(configs.ResponseSucess, "上报成功!", nil)
admin.LastActivity = time.Now().Unix()
if _, err := o.Update(&admin, "LastActivity"); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "用户不存在!", nil)
c.ServeJSON()
return
} }
// admin
// GetAuthInfo
auth := c.GetAuthInfo()
_, err := c.AdminRepository.Update(auth.UID, orm.Params{
"LastActivity": time.Now().Unix(),
})
if err != nil {
c.JSON(configs.ResponseFail, "fail,用户不存在!", &err)
} }
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "上报成功!", nil) c.JSON(configs.ResponseSucess, "上报成功!", nil)
c.ServeJSON()
} }
// GetCompanyInfo get Company info // GetCompanyInfo get Company info
func (c *PublicController) GetCompanyInfo() { func (c *PublicController) GetCompanyInfo() {
o := orm.NewOrm() // system info
system := services.GetSystemRepositoryInstance().GetSystem()
company := models.Company{ID: 1} c.JSON(configs.ResponseSucess, "上报成功!", &system)
if err := o.Read(&company); err != nil {
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &company)
}
c.ServeJSON()
} }
// PushMessage push message // PushMessage push message store
// This Api can be connected to Xiaomi's message callback to determine whether it is an offline message to handle the push
// see https://admin.mimc.chat.xiaomi.net/docs/09-callback.html
// Or the client can manually store messages through the Api
func (c *PublicController) PushMessage() { func (c *PublicController) PushMessage() {
// PushMessage // PushMessage
...@@ -384,39 +362,37 @@ func (c *PublicController) PushMessage() { ...@@ -384,39 +362,37 @@ func (c *PublicController) PushMessage() {
Payload string `json:"payload"` Payload string `json:"payload"`
} }
// get body
var pushMessage PushMessage var pushMessage PushMessage
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &pushMessage); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &pushMessage); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
// 判断是否是单聊消息 // is not Single chat message And kill
if pushMessage.MsgType != "NORMAL_MSG" { if pushMessage.MsgType != "NORMAL_MSG" {
c.ServeJSON() c.JSON(configs.ResponseFail, "sorry this is not Single chat message", nil)
return
} }
// message // push message store
var getMessage models.Message var getMessage models.Message
msgContent, _ := base64.StdEncoding.DecodeString(pushMessage.Payload) msgContent, _ := base64.StdEncoding.DecodeString(pushMessage.Payload)
msgContent, _ = base64.StdEncoding.DecodeString(string(msgContent)) msgContent, _ = base64.StdEncoding.DecodeString(string(msgContent))
json.Unmarshal(msgContent, &getMessage) json.Unmarshal(msgContent, &getMessage)
utils.MessageInto(getMessage, false) utils.MessageInto(getMessage, false)
c.ServeJSON()
c.JSON(configs.ResponseSucess, "push success", nil)
} }
// Upload Upload image // Upload upload image
func (c *PublicController) Upload() { func (c *PublicController) Upload() {
f, h, _ := c.GetFile("file") f, h, er := c.GetFile("file")
fileName := c.GetString("file_name") fileName := c.GetString("file_name")
if er != nil {
c.JSON(configs.ResponseFail, "上传失败,文件不存在!", nil)
}
if fileName == "" { if fileName == "" {
c.Data["json"] = utils.ResponseError(c.Ctx, "上传失败", "file_name不能为空") c.JSON(configs.ResponseFail, "上传失败,file_name不能为空!", nil)
c.ServeJSON()
return
} }
ext := path.Ext(h.Filename) ext := path.Ext(h.Filename)
...@@ -425,123 +401,76 @@ func (c *PublicController) Upload() { ...@@ -425,123 +401,76 @@ func (c *PublicController) Upload() {
".jpg": true, ".jpg": true,
".jpeg": true, ".jpeg": true,
".png": true, ".png": true,
".JPG": true,
".JPEG": true,
".PNG": true,
} }
if _, ok := AllowExtMap[ext]; !ok { if _, ok := AllowExtMap[ext]; !ok {
c.Data["json"] = utils.ResponseError(c.Ctx, "上传失败", "上传文件不合法") c.JSON(configs.ResponseFail, "上传失败,上传文件不合法!", nil)
c.ServeJSON()
return
} }
// create dir // create dir
uploadDir := "static/uploads/images/" uploadDir := "static/uploads/images/" + time.Now().Format("2006-01-02") + "/"
err := os.MkdirAll(uploadDir, 777) err := os.MkdirAll(uploadDir, os.ModePerm)
if err != nil { if err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "上传失败,创建文件夹失败", fmt.Sprintf("%v", err)) c.JSON(configs.ResponseFail, "上传失败,创建文件夹失败!", &err)
c.ServeJSON()
return
} }
fpath := uploadDir + fileName fpath := uploadDir + fileName
defer f.Close() defer f.Close()
err = c.SaveToFile("file", fpath) err = c.SaveToFile("file", fpath)
if err != nil { if err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "上传失败", fmt.Sprintf("%v", err)) c.JSON(configs.ResponseFail, "上传失败!", &err)
c.ServeJSON()
return
} }
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "上传成功", &fileName)
c.ServeJSON()
c.JSON(configs.ResponseSucess, "上传成功!", &fileName)
} }
// GetMessageHistoryList get user messages // GetMessageHistoryList get user messages
func (c *PublicController) GetMessageHistoryList() { func (c *PublicController) GetMessageHistoryList() {
o := orm.NewOrm() messagePaginationDto := models.MessagePaginationDto{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &messagePaginationDto); err != nil {
messagePaginationData := models.MessagePaginationData{} c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &messagePaginationData); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误1!", nil)
c.ServeJSON()
return
} }
token := c.Ctx.Input.Header("token") token := c.Ctx.Input.Header("token")
if token == "" { if token == "" {
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误2!", nil) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.ServeJSON()
return
} }
// validation // validation
valid := validation.Validation{} valid := validation.Validation{}
valid.Required(messagePaginationData.Account, "account").Message("account不能为空!") valid.Required(messagePaginationDto.Account, "account").Message("account不能为空!")
valid.Required(messagePaginationData.PageSize, "page_size").Message("page_size不能为空!") valid.Required(messagePaginationDto.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(messagePaginationData.Timestamp, "timestamp").Message("timestamp不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
// exist user // exist user
user := models.User{ID: messagePaginationData.Account} user := c.UserRepository.GetUser(messagePaginationDto.Account)
if err := o.Read(&user); err != nil { if user == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,用户不存在", err) c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
c.ServeJSON()
return
} }
/// validation TOKEN /// validation TOKEN
if token != user.Token { if token != user.Token {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,用户不存在", nil) c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
c.ServeJSON()
return
} }
// Timestamp == 0 // Timestamp == 0
if messagePaginationData.Timestamp == 0 { if messagePaginationDto.Timestamp == 0 {
messagePaginationData.Timestamp = time.Now().Unix() messagePaginationDto.Timestamp = time.Now().Unix()
}
// join string
var messages []*models.Message
uid := strconv.FormatInt(user.ID, 10)
timestamp := strconv.FormatInt(messagePaginationData.Timestamp, 10)
type MessageCount struct {
Count int64
}
var messageCount MessageCount
o.Raw("SELECT COUNT(*) AS `count` FROM `message` WHERE (`to_account` = ? OR `from_account` = ?) AND `timestamp` < ? AND `delete` = 0", uid, uid, timestamp).QueryRow(&messageCount)
var end = messageCount.Count
start := int(messageCount.Count) - messagePaginationData.PageSize
if start <= 0 {
start = 0
}
if messageCount.Count > 0 {
_, err := 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)
qs := o.QueryTable(new(models.Message))
_, _ = qs.Filter("from_account", uid).Update(orm.Params{"read": 0})
if err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", &err)
c.ServeJSON()
return
} }
o.Raw("SELECT COUNT(*) AS `count` FROM `message` WHERE (`to_account` = ? OR `from_account` = ?) AND `delete` = 0", uid, uid).QueryRow(&messageCount)
messagePaginationData.List = messages // query messages
messagePaginationData.Total = messageCount.Count returnMessagePaginationDto, err := c.MessageRepository.GetAdminMessages(messagePaginationDto)
} else { if err != nil {
messagePaginationData.List = []models.Message{} c.JSON(configs.ResponseFail, "fail", &err)
messagePaginationData.Total = 0
}
for index, msg := range messages {
payload, _ := base64.StdEncoding.DecodeString(msg.Payload)
messages[index].Payload = string(payload)
} }
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &messagePaginationData)
c.ServeJSON() c.JSON(configs.ResponseSucess, "success", &returnMessagePaginationDto)
} }
...@@ -2,79 +2,69 @@ package controllers ...@@ -2,79 +2,69 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"kefu_server/configs"
"kefu_server/models" "kefu_server/models"
"kefu_server/utils" "kefu_server/services"
"time" "time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
// QiniuController struct // QiniuController struct
type 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 // Get get qiniu config info
func (c *QiniuController) Get() { func (c *QiniuController) Get() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_auth := models.Auths{Token: token} admin := c.AdminRepository.GetAdmin(auth.UID)
if err := o.Read(&_auth, "Token"); err != nil { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) c.JSON(configs.ResponseFail, "您没有权限获取配置!", nil)
c.ServeJSON()
return
} }
_admin := models.Admin{ID: _auth.UID}
_ = o.Read(&_admin)
if _admin.Root != 1 { // get qiniu config info
c.Data["json"] = utils.ResponseError(c.Ctx, "您没有权限获取配置!", nil) qiniuSetting := c.QiniuRepository.GetQiniuConfigInfo()
c.ServeJSON() if qiniuSetting == nil {
return c.JSON(configs.ResponseFail, "fail", nil)
} }
qiniuSetting := models.QiniuSetting{ID: 1} // return
if err := o.Read(&qiniuSetting); err != nil { c.JSON(configs.ResponseSucess, "success", &qiniuSetting)
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &qiniuSetting)
}
c.ServeJSON()
} }
// Put update // Put update
func (c *QiniuController) Put() { func (c *QiniuController) Put() {
qiniuSetting := models.QiniuSetting{} qiniuSetting := models.QiniuSetting{}
qiniuSetting.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &qiniuSetting); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &qiniuSetting); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "fail", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
o := orm.NewOrm() // GetAuthInfo
auth := c.GetAuthInfo()
token := c.Ctx.Input.Header("Authorization") admin := c.AdminRepository.GetAdmin(auth.UID)
_auth := models.Auths{Token: token} if admin.Root != 1 {
if err := o.Read(&_auth, "Token"); err != nil { c.JSON(configs.ResponseFail, "您没有权限获取配置!", 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
} }
// validation // validation
...@@ -89,21 +79,20 @@ func (c *QiniuController) Put() { ...@@ -89,21 +79,20 @@ func (c *QiniuController) Put() {
valid.MaxSize(qiniuSetting.Host, 100, "host").Message("host不能超过100字符!") valid.MaxSize(qiniuSetting.Host, 100, "host").Message("host不能超过100字符!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
logs.Error(err) c.JSON(configs.ResponseFail, err.Message, nil)
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
qiniuSetting.ID = 1 // update
qiniuSetting.UpdateAt = time.Now().Unix() if _, err := c.QiniuRepository.Update(orm.Params{
if _, err := o.Update(&qiniuSetting); err != nil { "Bucket": qiniuSetting.Bucket,
logs.Error(err) "AccessKey": qiniuSetting.AccessKey,
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", err) "SecretKey": qiniuSetting.SecretKey,
} else { "Host": qiniuSetting.Host,
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &qiniuSetting) "UpdateAt": time.Now().Unix(),
}); err != nil {
c.JSON(configs.ResponseFail, "更新失败!", &err)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "更新成功!", &qiniuSetting)
} }
...@@ -3,14 +3,13 @@ package controllers ...@@ -3,14 +3,13 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
"kefu_server/configs"
"kefu_server/im" "kefu_server/im"
"kefu_server/models" "kefu_server/models"
"kefu_server/utils" "kefu_server/services"
"strconv" "strconv"
"strings" "strings"
"time" "time"
...@@ -18,109 +17,101 @@ import ( ...@@ -18,109 +17,101 @@ import (
// RobotController struct // RobotController struct
type RobotController struct { type RobotController struct {
beego.Controller BaseController
RobotRepository *services.RobotRepository
AdminRepository *services.AdminRepository
PlatformRepository *services.PlatformRepository
} }
// Prepare More like construction method
func (c *RobotController) Prepare() {
// RobotRepository instance
c.RobotRepository = services.GetRobotRepositoryInstance()
// PlatformRepository instance
c.PlatformRepository = services.GetPlatformRepositoryInstance()
// AdminRepository instance
c.AdminRepository = services.GetAdminRepositoryInstance()
}
// Finish Comparison like destructor
func (c *RobotController) Finish() {}
// Get get robot // Get get robot
func (c *RobotController) Get() { func (c *RobotController) Get() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
robot := models.Robot{ID: id} robot := c.RobotRepository.GetRobot(id)
if err := o.Read(&robot); err != nil { if robot == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "获取失败!", err) c.JSON(configs.ResponseFail, "fail", nil)
c.ServeJSON()
return
} }
robot.Artificial = strings.Trim(robot.Artificial, "|") c.JSON(configs.ResponseSucess, "success", &robot)
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &robot)
c.ServeJSON()
} }
// Delete delete robot // Delete delete robot
func (c *RobotController) Delete() { func (c *RobotController) Delete() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_auth := models.Auths{Token: token} admin := c.AdminRepository.GetAdmin(auth.UID)
if err := o.Read(&_auth, "Token"); err != nil { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) c.JSON(configs.ResponseFail, "您没有权限删除机器人!", 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
} }
// get robot
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
robot := models.Robot{ID: id} robot := c.RobotRepository.GetRobot(id)
// exist // exist
if err := o.Read(&robot); err != nil { if robot == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,机器人不存在!", err) c.JSON(configs.ResponseFail, "删除失败,机器人不存在!", nil)
c.ServeJSON()
return
} }
if robot.System == 1 { if robot.System == 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "不能删除该机器人,系统保留!", nil) c.JSON(configs.ResponseFail, "不能删除该机器人,系统保留!", nil)
c.ServeJSON() }
return
if _, err := c.RobotRepository.Delete(id); err != nil {
c.JSON(configs.ResponseFail, "删除失败!", nil)
} }
if num, err := o.Delete(&robot); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败!", nil)
} else {
// init robots // init robots
im.RobotInit() im.RobotInit()
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "删除成功!", &num) c.JSON(configs.ResponseSucess, "删除成功!", nil)
}
c.ServeJSON()
} }
// Post add robot // Post add robot
func (c *RobotController) Post() { func (c *RobotController) Post() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_auth := models.Auths{Token: token} admin := c.AdminRepository.GetAdmin(auth.UID)
if err := o.Read(&_auth, "Token"); err != nil { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) c.JSON(configs.ResponseFail, "您没有权限添加机器人!", 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
} }
// request body // request body
var robot models.Robot var robot models.Robot
robot.CreateAt = time.Now().Unix() robot.CreateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &robot); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &robot); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", err) }
c.ServeJSON()
return // is exist platform?
if platform := c.PlatformRepository.GetPlatform(robot.Platform); platform == nil {
c.JSON(configs.ResponseFail, "平台参数不存在!", nil)
} }
// exist robot? // exist robot?
oldRobot := models.Robot{NickName: robot.NickName} oldRobot := c.RobotRepository.GetRobotWithNickName(robot.NickName)
if err := o.Read(&oldRobot, "NickName"); err == nil { if oldRobot != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "已存在一个名为"+robot.NickName+"的机器人!", nil) c.JSON(configs.ResponseFail, "已存在一个名为"+robot.NickName+"的机器人!", nil)
c.ServeJSON()
return
} }
// validation // validation
...@@ -133,61 +124,36 @@ func (c *RobotController) Post() { ...@@ -133,61 +124,36 @@ func (c *RobotController) Post() {
valid.Required(robot.Artificial, "artificial").Message("请设置转人工关键字!") valid.Required(robot.Artificial, "artificial").Message("请设置转人工关键字!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
// insert // add
robot.Artificial = strings.Trim(robot.Artificial, "|") id, err := c.RobotRepository.Add(&robot)
if robot.Artificial != "" { if err != nil {
robot.Artificial = "|" + robot.Artificial + "|" c.JSON(configs.ResponseFail, "添加失败!", nil)
} }
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
if robot.KeyWord != "" {
robot.KeyWord = "|" + robot.KeyWord + "|"
}
if id, err := o.Insert(&robot); err == nil {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "添加成功!", &id)
im.RobotInit() im.RobotInit()
} else { c.JSON(configs.ResponseSucess, "添加成功!", id)
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "服务异常!", err)
}
c.ServeJSON()
} }
// Put update robot // Put update robot
func (c *RobotController) Put() { func (c *RobotController) Put() {
o := orm.NewOrm() // GetAuthInfo
auth := c.GetAuthInfo()
token := c.Ctx.Input.Header("Authorization") admin := c.AdminRepository.GetAdmin(auth.UID)
_auth := models.Auths{Token: token} if admin.Root != 1 {
if err := o.Read(&_auth, "Token"); err != nil { c.JSON(configs.ResponseFail, "您没有权限修改机器人!", 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
} }
// RequestBody // RequestBody
var robot models.Robot var robot models.Robot
robot.UpdateAt = time.Now().Unix() robot.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &robot); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &robot); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", err)
c.ServeJSON()
return
} }
// validation // validation
...@@ -201,86 +167,69 @@ func (c *RobotController) Put() { ...@@ -201,86 +167,69 @@ func (c *RobotController) Put() {
valid.Required(robot.Artificial, "artificial").Message("请设置转人工关键字!") valid.Required(robot.Artificial, "artificial").Message("请设置转人工关键字!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
// is change default robot ? // is change default robot ?
if robot.System == 1 && robot.Switch == 0 { if robot.System == 1 && robot.Switch == 0 {
c.Data["json"] = utils.ResponseError(c.Ctx, "不能暂停该机器人!", nil) c.JSON(configs.ResponseFail, "不能暂停该机器人!", nil)
c.ServeJSON()
return
} }
// is change default robot ? // is change default robot ?
if robot.System == 1 && robot.Platform != 1 { if robot.System == 1 && robot.Platform != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "不能修改该机器人平台!", nil) c.JSON(configs.ResponseFail, "不能修改该机器人平台!", nil)
c.ServeJSON()
return
} }
// exist // is exist platform?
oldRobot := models.Robot{ID: robot.ID} if platform := c.PlatformRepository.GetPlatform(robot.Platform); platform == nil {
if err := o.Read(&oldRobot); err != nil { c.JSON(configs.ResponseFail, "平台参数不存在!", nil)
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "机器人"+robot.NickName+"不存在", nil)
c.ServeJSON()
return
} }
// robot name exist // exist robot
oldRobot = models.Robot{NickName: robot.NickName} if rbt := c.RobotRepository.GetRobot(robot.ID); rbt == nil {
if err := o.Read(&oldRobot, "NickName"); err == nil && oldRobot.ID != robot.ID { c.JSON(configs.ResponseFail, "机器人不存在", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "已存在一个名为"+robot.NickName+"的机器人", nil)
c.ServeJSON()
return
} }
// insert // robot name exist
robot.Artificial = strings.Trim(robot.Artificial, "|") oldRobot := c.RobotRepository.GetRobotWithNickName(robot.NickName)
if robot.Artificial != "" { if oldRobot != nil && oldRobot.ID != robot.ID {
robot.Artificial = "|" + robot.Artificial + "|" c.JSON(configs.ResponseFail, "已存在一个名为"+robot.NickName+"的机器人", nil)
} }
robot.KeyWord = strings.Trim(robot.KeyWord, "|")
if robot.KeyWord != "" { // update
robot.KeyWord = "|" + robot.KeyWord + "|" if _, err := c.RobotRepository.Update(robot.ID, orm.Params{
"NickName": robot.NickName,
"Avatar": robot.Avatar,
"Welcome": robot.Welcome,
"Understand": robot.Understand,
"Artificial": robot.Artificial,
"Switch": robot.Switch,
"UpdateAt": robot.UpdateAt,
"KeyWord": robot.KeyWord,
"TimeoutText": robot.TimeoutText,
"NoServices": robot.NoServices,
"LoogTimeWaitText": robot.LoogTimeWaitText,
}); err != nil {
c.JSON(configs.ResponseFail, "修改失败!", nil)
} }
if _, err := o.Update(&robot, "NickName", "Avatar", "Welcome", "Understand", "Artificial", "Switch", "UpdateAt", "KeyWord", "TimeoutText", "NoServices", "LoogTimeWaitText"); err == nil {
robot.Artificial = strings.Trim(robot.Artificial, "|") robot.Artificial = strings.Trim(robot.Artificial, "|")
robot.KeyWord = strings.Trim(robot.KeyWord, "|") robot.KeyWord = strings.Trim(robot.KeyWord, "|")
robot.CreateAt = oldRobot.CreateAt robot.CreateAt = oldRobot.CreateAt
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "修改成功!", &robot)
im.RobotInit() im.RobotInit()
} else { c.JSON(configs.ResponseSucess, "修改成功!", &robot)
logs.Error(err)
c.Data["json"] = utils.ResponseError(c.Ctx, "修改失败!", err)
}
c.ServeJSON()
} }
// List get robot all // List get robot all
func (c *RobotController) List() { func (c *RobotController) List() {
o := orm.NewOrm()
robot := new(models.Robot)
qs := o.QueryTable(robot)
// query // query
var lists []models.Robot robots, err := c.RobotRepository.GetRobots()
if _, err := qs.OrderBy("create_at").All(&lists); err != nil { if err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "fail", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", err)
c.ServeJSON()
return
} }
for index := range lists { c.JSON(configs.ResponseSucess, "success", &robots)
lists[index].Artificial = strings.Trim(lists[index].Artificial, "|")
lists[index].KeyWord = strings.Trim(lists[index].KeyWord, "|")
}
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &lists)
c.ServeJSON()
} }
...@@ -2,95 +2,52 @@ package controllers ...@@ -2,95 +2,52 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"kefu_server/utils" "kefu_server/configs"
"time" "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" "github.com/astaxie/beego/validation"
) )
// ServicesStatisticalController struct // ServicesStatisticalController struct
type ServicesStatisticalController struct { type ServicesStatisticalController struct {
beego.Controller BaseController
StatisticalRepository *services.StatisticalRepository
} }
// ServicesStatisticalPaginationData struct // Prepare More like construction method
type ServicesStatisticalPaginationData struct { func (c *ServicesStatisticalController) Prepare() {
PageSize int `json:"page_size"`
PageOn int `json:"page_on"` // StatisticalRepository instance
Cid int64 `json:"cid"` c.StatisticalRepository = services.GetStatisticalRepositoryInstance()
Date string `json:"date"`
IsDeWeighting bool `json:"is_de_weighting"`
Total int64 `json:"total"`
List interface{} `json:"list"`
} }
// Finish Comparison like destructor
func (c *ServicesStatisticalController) Finish() {}
// List Services Statistical // List Services Statistical
func (c *ServicesStatisticalController) List() { func (c *ServicesStatisticalController) List() {
// request body // request body
var paginationData ServicesStatisticalPaginationData var paginationDto models.ServicesStatisticalPaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &paginationDto); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", err)
c.ServeJSON()
return
} }
// validation // validation
valid := validation.Validation{} valid := validation.Validation{}
valid.Required(paginationData.PageOn, "page_on").Message("page_on不能为空!") valid.Required(paginationDto.PageOn, "page_on").Message("page_on不能为空!")
valid.Required(paginationData.PageSize, "page_size").Message("page_size不能为空!") valid.Required(paginationDto.PageSize, "page_size").Message("page_size不能为空!")
valid.Required(paginationData.Cid, "cid").Message("cid不能为空!") valid.Required(paginationDto.Cid, "cid").Message("cid不能为空!")
valid.Required(paginationData.Date, "date").Message("date不能为空!") valid.Required(paginationDto.Date, "date").Message("date不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
}
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 { // get data
paginationData.List = []string{} data := c.StatisticalRepository.GetCustomerServiceList(paginationDto)
c.Data["json"] = paginationData c.JSON(configs.ResponseSucess, "success", &data)
} else {
paginationData.List = params
c.Data["json"] = paginationData
}
c.ServeJSON()
} }
package controllers package controllers
import ( import (
"encoding/base64"
"encoding/json" "encoding/json"
"kefu_server/configs"
"kefu_server/models" "kefu_server/models"
"kefu_server/utils" "kefu_server/services"
"strconv" "strconv"
"time" "time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
// ShortcutController struct // ShortcutController struct
type 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 // Get get shortcut
func (c *ShortcutController) Get() { 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) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
shortcut := models.Shortcut{ID: id} shortcut := c.ShortcutRepository.GetShortcut(id)
if err := o.Read(&shortcut); err != nil { if shortcut == nil || auth.UID != shortcut.UID {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,内容不存在!", err) c.JSON(configs.ResponseFail, "fail,内容不存在!", nil)
} 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)
}
} }
c.ServeJSON() c.JSON(configs.ResponseSucess, "success", &shortcut)
} }
// Put update shortcut // Put update shortcut
func (c *ShortcutController) Put() { func (c *ShortcutController) Put() {
o := orm.NewOrm() // GetAuthInfo
auth := c.GetAuthInfo()
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)
// request body // request body
shortcut := models.Shortcut{} shortcut := models.Shortcut{}
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shortcut); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shortcut); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
// validation // validation
...@@ -80,54 +60,37 @@ func (c *ShortcutController) Put() { ...@@ -80,54 +60,37 @@ func (c *ShortcutController) Put() {
valid.Required(shortcut.Content, "content").Message("内容不能为空!") valid.Required(shortcut.Content, "content").Message("内容不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
oldShortcut := models.Shortcut{ID: shortcut.ID} // if is my shortcut
_ = o.Read(&oldShortcut) if shortcut.UID != auth.UID {
if oldShortcut.UID != _admin.ID { c.JSON(configs.ResponseFail, "更新失败,内容不存在!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败,内容不存在!", nil)
c.ServeJSON()
return
} }
// update // update
shortcut.Title = base64.StdEncoding.EncodeToString([]byte(shortcut.Title)) _, err := c.ShortcutRepository.Update(shortcut.ID, orm.Params{
shortcut.Content = base64.StdEncoding.EncodeToString([]byte(shortcut.Content)) "UpdateAt": time.Now().Unix(),
if _, err := o.Update(&shortcut, "UpdateAt", "Content", "Title"); err != nil { "Content": shortcut.Content,
logs.Error(err) "Title": shortcut.Title,
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", err) })
} else { if err != nil {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", nil) c.JSON(configs.ResponseFail, "更新失败!", nil)
} }
c.ServeJSON() c.JSON(configs.ResponseSucess, "更新成功!", nil)
} }
// Post add new shortcut // Post add new shortcut
func (c *ShortcutController) Post() { func (c *ShortcutController) Post() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_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)
// request body // request body
var shortcut models.Shortcut var shortcut models.Shortcut
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shortcut); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &shortcut); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", nil)
c.ServeJSON()
return
} }
// validation // validation
...@@ -136,99 +99,42 @@ func (c *ShortcutController) Post() { ...@@ -136,99 +99,42 @@ func (c *ShortcutController) Post() {
valid.Required(shortcut.Content, "content").Message("内容不能为空!") valid.Required(shortcut.Content, "content").Message("内容不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
// exist ? create // exist ? create
shortcut.UID = _admin.ID shortcut.UID = auth.UID
shortcut.CreateAt = time.Now().Unix() isNew, _, err := c.ShortcutRepository.Add(&shortcut, "Title", "Uid")
shortcut.Title = base64.StdEncoding.EncodeToString([]byte(shortcut.Title)) if err != nil {
shortcut.Content = base64.StdEncoding.EncodeToString([]byte(shortcut.Content)) c.JSON(configs.ResponseFail, "添加失败!", nil)
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 { if !isNew {
logs.Error(err) c.JSON(configs.ResponseFail, "已存在相同的内容!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "服务异常!", err)
} }
c.ServeJSON() c.JSON(configs.ResponseSucess, "添加成功!!", nil)
return
} }
// Delete delete remove shortcut // Delete delete remove shortcut
func (c *ShortcutController) Delete() { func (c *ShortcutController) Delete() {
o := orm.NewOrm() // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_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)
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
if row, err := c.ShortcutRepository.Delete(id, auth.UID); err != nil || row == 0 {
shortcut := models.Shortcut{ID: id} c.JSON(configs.ResponseFail, "删除失败!", &err)
// exist
if err := o.Read(&shortcut); err != nil || shortcut.UID != _admin.ID {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,内容不存在!", nil)
c.ServeJSON()
return
}
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 // List get shortcut all
func (c *ShortcutController) List() { func (c *ShortcutController) List() {
o := orm.NewOrm() // GetAuthInfo
shortcut := new(models.Shortcut) auth := c.GetAuthInfo()
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)
// query // query
var lists []models.Shortcut shortcuts := c.ShortcutRepository.GetShortcuts(auth.UID)
if _, err := qs.Filter("uid", _admin.ID).OrderBy("-create_at").All(&lists); err != nil { c.JSON(configs.ResponseSucess, "success", &shortcuts)
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()
} }
...@@ -2,33 +2,40 @@ package controllers ...@@ -2,33 +2,40 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"kefu_server/configs"
"kefu_server/models" "kefu_server/models"
"kefu_server/utils" "kefu_server/services"
"time" "time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
// SystemController struct // SystemController struct
type 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 // Get get info
func (c *SystemController) Get() { func (c *SystemController) Get() {
o := orm.NewOrm() system := c.SystemRepository.GetSystem()
system := models.System{ID: 1} if system == nil {
if err := o.Read(&system); err != nil { c.JSON(configs.ResponseFail, "fail", nil)
logs.Error(err)
c.Data["json"] = &models.Response{Code: 400, Message: "查询失败", Data: err}
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &system)
} }
c.ServeJSON() c.JSON(configs.ResponseSucess, "success", &system)
} }
...@@ -36,38 +43,22 @@ func (c *SystemController) Get() { ...@@ -36,38 +43,22 @@ func (c *SystemController) Get() {
func (c *SystemController) Put() { func (c *SystemController) Put() {
system := models.System{} system := models.System{}
system.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &system); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &system); err != nil {
logs.Error(err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.Data["json"] = &models.Response{Code: 400, Message: "参数错误", Data: nil}
c.ServeJSON()
return
} }
o := orm.NewOrm() // GetAuthInfo
auth := c.GetAuthInfo()
token := c.Ctx.Input.Header("Authorization") admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
_auth := models.Auths{Token: token} // is root ?
if err := o.Read(&_auth, "Token"); err != nil { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) c.JSON(configs.ResponseFail, "您没有权限修改系统设置!", 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
} }
// validation upload mode // validation upload mode
var uploadValues []orm.Params uploadConfig := services.GetUploadsConfigRepositoryInstance().GetUploadsConfig(int64(system.UploadMode))
_, _ = o.Raw("SELECT * FROM uploads_config where id = ?", system.UploadMode).Values(&uploadValues) if uploadConfig == nil {
if len(uploadValues) <= 0 { c.JSON(configs.ResponseFail, "上传模型选项不存在!", nil)
c.Data["json"] = utils.ResponseError(c.Ctx, "上传模型选项不存在!", nil)
c.ServeJSON()
return
} }
// validation request // validation request
...@@ -78,22 +69,20 @@ func (c *SystemController) Put() { ...@@ -78,22 +69,20 @@ func (c *SystemController) Put() {
valid.Required(system.Logo, "logo").Message("系统LOGO不能为空!") valid.Required(system.Logo, "logo").Message("系统LOGO不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
logs.Error(err) c.JSON(configs.ResponseFail, err.Message, nil)
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
system.ID = 1 // update
system.UpdateAt = time.Now().Unix() _, err := c.SystemRepository.Update(orm.Params{
if _, err := o.Update(&system); err != nil { "Title": system.Title,
logs.Error(err) "Logo": system.Logo,
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败", err) "CopyRight": system.CopyRight,
} else { "UploadMode": system.UploadMode,
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &system) "UpdateAt": time.Now().Unix(),
})
if err != nil {
c.JSON(configs.ResponseFail, "更新失败!", &err)
} }
c.ServeJSON() c.JSON(configs.ResponseSucess, "更新成功!", &system)
} }
package controllers package controllers
import ( import (
"kefu_server/models" "kefu_server/configs"
"kefu_server/utils" "kefu_server/services"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
) )
// UploadsConfigController struct // UploadsConfigController struct
type 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() { func (c *UploadsConfigController) Config() {
o := orm.NewOrm() uploadsConfigs := c.UploadsConfigRepository.GetUploadsConfigs()
var configs []models.UploadsConfig c.JSON(configs.ResponseSucess, "success", &uploadsConfigs)
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()
} }
...@@ -2,33 +2,43 @@ package controllers ...@@ -2,33 +2,43 @@ package controllers
import ( import (
"encoding/json" "encoding/json"
"kefu_server/configs"
"kefu_server/models" "kefu_server/models"
"kefu_server/utils" "kefu_server/services"
"strconv" "strconv"
"time" "time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation" "github.com/astaxie/beego/validation"
) )
// UserController struct // UserController struct
type 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 // Get get a user
func (c *UserController) Get() { func (c *UserController) Get() {
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
user := models.User{ID: id} user := c.UserRepository.GetUser(id)
if err := o.Read(&user); err != nil { if user == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败,用户不存在!", err) c.JSON(configs.ResponseFail, "fail,用户不存在!", nil)
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &user)
} }
c.ServeJSON()
c.JSON(configs.ResponseSucess, "success", &user)
} }
...@@ -37,11 +47,8 @@ func (c *UserController) Put() { ...@@ -37,11 +47,8 @@ func (c *UserController) Put() {
// request // request
user := models.User{} user := models.User{}
user.UpdateAt = time.Now().Unix()
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &user); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &user); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误!", err) c.JSON(configs.ResponseFail, "参数有误,请检查!", nil)
c.ServeJSON()
return
} }
// validation // validation
...@@ -53,25 +60,27 @@ func (c *UserController) Put() { ...@@ -53,25 +60,27 @@ func (c *UserController) Put() {
valid.MaxSize(user.Remarks, 150, "remarks").Message("用户备注不能超过150个字符!") valid.MaxSize(user.Remarks, 150, "remarks").Message("用户备注不能超过150个字符!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, nil)
break
} }
c.ServeJSON()
return
} }
// orm // update
o := orm.NewOrm() _, err := c.UserRepository.Update(user.ID, orm.Params{
if _, err := o.Update(&user, "Address", "NickName", "Phone", "Remarks", "UpdateAt", "UpdateAt", "Avatar"); err != nil { "Address": user.Address,
c.Data["json"] = utils.ResponseError(c.Ctx, "更新失败!", nil) "NickName": user.NickName,
} else { "Phone": user.Phone,
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "更新成功!", &user) "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 // 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() { func (c *UserController) Post() {
c.ServeJSON() c.ServeJSON()
} }
...@@ -79,134 +88,68 @@ func (c *UserController) Post() { ...@@ -79,134 +88,68 @@ func (c *UserController) Post() {
// Delete delete remove user // Delete delete remove user
func (c *UserController) Delete() { func (c *UserController) Delete() {
// orm instance // uid
o := orm.NewOrm()
id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64) id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
// is admin ? // GetAuthInfo
token := c.Ctx.Input.Header("Authorization") auth := c.GetAuthInfo()
_auth := models.Auths{Token: token} admin := services.GetAdminRepositoryInstance().GetAdmin(auth.UID)
if err := o.Read(&_auth, "Token"); err != nil { if admin.Root != 1 {
c.Data["json"] = utils.ResponseError(c.Ctx, "登录已失效!", nil) c.JSON(configs.ResponseFail, "您没有权限删除用户!", 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
} }
// user // user
user := models.User{ID: id} user := c.UserRepository.GetUser(id)
// exist // exist
if err := o.Read(&user); err != nil { if user == nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败,用户不存在!", err) c.JSON(configs.ResponseFail, "删除失败,用户不存在!", nil)
c.ServeJSON()
return
} }
if num, err := o.Delete(&user); err != nil { // delete
c.Data["json"] = utils.ResponseError(c.Ctx, "删除失败!", nil) if _, err := c.UserRepository.Delete(id); err != nil {
} else { c.JSON(configs.ResponseFail, "删除失败!", &err)
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "删除成功!", &num)
} }
c.ServeJSON()
}
// UsersPaginationData struct c.JSON(configs.ResponseSucess, "删除成功!", nil)
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"`
} }
// Users get users // Users get users
func (c *UserController) Users() { func (c *UserController) Users() {
// request body // request body
var usersPaginationData UsersPaginationData var usersPaginationDto models.UsersPaginationDto
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &usersPaginationData); err != nil { if err := json.Unmarshal(c.Ctx.Input.RequestBody, &usersPaginationDto); err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "参数错误", err) c.JSON(configs.ResponseFail, "参数有误,请检查!", &err)
c.ServeJSON()
return
} }
// validation // validation
valid := validation.Validation{} valid := validation.Validation{}
valid.Required(usersPaginationData.PageOn, "page_on").Message("page_on不能为空!") valid.Required(usersPaginationDto.PageOn, "page_on").Message("page_on不能为空!")
valid.Required(usersPaginationData.PageSize, "page_size").Message("page_size不能为空!") valid.Required(usersPaginationDto.PageSize, "page_size").Message("page_size不能为空!")
if valid.HasErrors() { if valid.HasErrors() {
for _, err := range valid.Errors { for _, err := range valid.Errors {
c.Data["json"] = utils.ResponseError(c.Ctx, err.Message, nil) c.JSON(configs.ResponseFail, err.Message, &err)
break
}
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)
} }
// 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 // get users
var lists []models.User res, err := c.UserRepository.GetUsers(&usersPaginationDto)
cond3 := cond.AndCond(cond2).OrCond(cond1) if err != nil {
qs = qs.SetCond(cond3) c.JSON(configs.ResponseFail, "fail", &err)
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() c.JSON(configs.ResponseSucess, "success", &res)
usersPaginationData.Total = total
usersPaginationData.List = &lists
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", &usersPaginationData)
c.ServeJSON()
} }
// OnLineCount get all online user count // OnLineCount get all online user count
func (c *UserController) OnLineCount() { func (c *UserController) OnLineCount() {
o := orm.NewOrm() rows, err := c.UserRepository.GetOnlineCount()
if onLineCount, err := o.QueryTable(models.User{}).Filter("online", 1).Count(); err != nil { if err != nil {
c.Data["json"] = utils.ResponseError(c.Ctx, "查询失败!", nil) c.JSON(configs.ResponseFail, "fail", &err)
c.ServeJSON()
} else {
c.Data["json"] = utils.ResponseSuccess(c.Ctx, "查询成功!", onLineCount)
c.ServeJSON()
} }
c.JSON(configs.ResponseSucess, "success", &rows)
} }
...@@ -2,40 +2,23 @@ ...@@ -2,40 +2,23 @@
# ! /bin/sh # ! /bin/sh
CURRENT_PATH=$(readlink -f "$(dirname "$0")")
SERVICE_PATH="/home/kefu_server" SERVICE_PATH="$CURRENT_PATH/kefu_server"
SERVICE_NAME="kefu_server" SERVICE_NAME="kefu_server"
START_CMD="nohup ./$SERVICE_NAME &" START_CMD="nohup ./$SERVICE_NAME &"
LOG_FILE="restart.log" LOG_FILE="restart.log"
cd $SERVICE_PATH cd $SERVICE_PATH
pwd pwd
while true while true
do do
procnum=`ps -ef|grep $SERVICE_NAME|grep -v grep|wc -l` procnum=`ps -ef|grep $SERVICE_NAME|grep -v grep|wc -l`
if [ $procnum -eq 0 ] if [ $procnum -eq 0 ]
then then
echo "start service...................." echo "start service...................."
echo `date +%Y-%m-%d` `date +%H:%M:%S` $SERVICE_NAME >>$LOG_FILE echo `date +%Y-%m-%d` `date +%H:%M:%S` $SERVICE_NAME >>$LOG_FILE
${START_CMD} ${START_CMD}
fi fi
sleep 5 sleep 5
done done
...@@ -14,24 +14,24 @@ import ( ...@@ -14,24 +14,24 @@ import (
// PushNewContacts 推送最新聊天列表给客服 // PushNewContacts 推送最新聊天列表给客服
func PushNewContacts(accountID int64, robot *mimc.MCUser) { func PushNewContacts(accountID int64, robot *mimc.MCUser) {
o := orm.NewOrm() o := orm.NewOrm()
var contactData []models.ContactData var contactDto []models.ContactDto
// 消息体 // 消息体
message := models.Message{} message := models.Message{}
message.BizType = "contacts" message.BizType = "contacts"
robotAccount, _ := strconv.ParseInt(robot.AppAccount(), 10, 64) robotAccount, _ := strconv.ParseInt(robot.AppAccount(), 10, 64)
message.FromAccount = robotAccount message.FromAccount = robotAccount
message.Timestamp = time.Now().Unix() 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 { if rCount == 0 {
contactData = []models.ContactData{} contactDto = []models.ContactDto{}
} }
// base 64转换回来 // base 64转换回来
for index, contact := range contactData { for index, contact := range contactDto {
payload, _ := base64.StdEncoding.DecodeString(contact.LastMessage) payload, _ := base64.StdEncoding.DecodeString(contact.LastMessage)
contactData[index].LastMessage = string(payload) contactDto[index].LastMessage = string(payload)
} }
message.ToAccount = accountID message.ToAccount = accountID
messageContentByte, _ := json.Marshal(contactData) messageContentByte, _ := json.Marshal(contactDto)
message.Payload = string(messageContentByte) message.Payload = string(messageContentByte)
messageJSON, _ := json.Marshal(message) messageJSON, _ := json.Marshal(message)
messageString := base64.StdEncoding.EncodeToString([]byte(messageJSON)) messageString := base64.StdEncoding.EncodeToString([]byte(messageJSON))
......
...@@ -2,12 +2,11 @@ package im ...@@ -2,12 +2,11 @@ package im
import ( import (
"kefu_server/models" "kefu_server/models"
"kefu_server/services"
"strconv" "strconv"
"strings"
"github.com/Xiaomi-mimc/mimc-go-sdk" "github.com/Xiaomi-mimc/mimc-go-sdk"
"github.com/astaxie/beego" "github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
) )
// Robots 工作中的机器人 // Robots 工作中的机器人
...@@ -26,18 +25,12 @@ func CreateRobot(appAccount string) *mimc.MCUser { ...@@ -26,18 +25,12 @@ func CreateRobot(appAccount string) *mimc.MCUser {
// GetRobots get robot all // GetRobots get robot all
func GetRobots() []models.Robot { func GetRobots() []models.Robot {
// orm instance
o := orm.NewOrm()
robot := new(models.Robot)
qs := o.QueryTable(robot)
// 查询 // RobotRepository instance
var lists []models.Robot robotRepository := services.GetRobotRepositoryInstance()
_, _ = qs.OrderBy("-create_at").All(&lists) var robots []models.Robot
for index := range lists { robots, _ = robotRepository.GetRobots()
lists[index].Artificial = strings.Trim(lists[index].Artificial, "|") return robots
}
return lists
} }
// RobotInit 初始化机器人 // 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 package models
// ContactData struct // ContactDto struct
type ContactData struct { type ContactDto struct {
ID int64 `orm:"column(id)" json:"id"` ID int64 `orm:"column(id)" json:"id"`
Cid int64 `json:"cid"` Cid int64 `json:"cid"`
FromAccount int64 `json:"from_account"` 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 package models
// IMToken struct // IMTokenDto struct
type IMToken struct { type IMTokenDto struct {
Code int `json:"code"` Code int `json:"code"`
Message string `json:"message"` Message string `json:"message"`
Data IMTokenData `json:"data"` Data IMTokenDataDto `json:"data"`
} }
// IMTokenData struct // IMTokenDataDto struct
type IMTokenData struct { type IMTokenDataDto struct {
AppID string `json:"appId"` AppID string `json:"appId"`
AppPackage string `json:"appPackage"` AppPackage string `json:"appPackage"`
AppAccount string `json:"appAccount"` AppAccount string `json:"appAccount"`
......
package models package models
// JwtKey struct // JwtKeyDto struct
type JwtKey struct { type JwtKeyDto struct {
ID int64 ID int64
AuthType int64 AuthType int64
UserName string 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 package models
// PaginationData struct // KnowledgePaginationDto struct
type PaginationData struct { type KnowledgePaginationDto struct {
PageSize int `json:"page_size"` PageSize int `json:"page_size"`
PageOn int `json:"page_on"` PageOn int `json:"page_on"`
Keyword string `json:"keyword"` Keyword string `json:"keyword"`
......
package models package models
// MessagePaginationData struct // MessagePaginationDto struct
type MessagePaginationData struct { type MessagePaginationDto struct {
PageSize int `json:"page_size"` PageSize int `json:"page_size"`
Total int64 `json:"total"` Total int64 `json:"total"`
Account int64 `json:"account"` Account int64 `json:"account"`
......
...@@ -2,12 +2,13 @@ package models ...@@ -2,12 +2,13 @@ package models
// Platform struct // Platform struct
type Platform struct { type Platform struct {
ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` ID int64 `orm:"auto;pk;type(bigint);column(id)" json:"id"` // ID
Title string `orm:"unique;type(char);column(title)" json:"title"` Title string `orm:"unique;type(char);column(title)" json:"title"` // 平台名称
Alias string `orm:"unique;type(char);column(alias)" json:"alias"` Alias string `orm:"unique;type(char);column(alias)" json:"alias"` // 平台别名
System int `orm:"default(0);column(system)" json:"system"` 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 (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 (1, 'IOS', 'ios', 1);
//INSERT INTO `kefu_server`.`platform`(`id`, `title`, `alias`, `system`) VALUES (2, '小程序', 'small', 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 package models
// RemoveMessageRequestData struct // RemoveMessageRequestDto struct
type RemoveMessageRequestData struct { type RemoveMessageRequestDto struct {
FromAccount int64 `json:"from_account"` FromAccount int64 `json:"from_account"`
ToAccount int64 `json:"to_account"` ToAccount int64 `json:"to_account"`
Key int64 `json:"key"` Key int64 `json:"key"`
......
...@@ -2,8 +2,8 @@ package models ...@@ -2,8 +2,8 @@ package models
import "kefu_server/configs" import "kefu_server/configs"
// Response struct // ResponseDto struct
type Response struct { type ResponseDto struct {
Code configs.ResponseStatusType `json:"code"` // 错误类型 Code configs.ResponseStatusType `json:"code"` // 错误类型
Message string `json:"message"` // 信息 Message string `json:"message"` // 信息
Data interface{} `json:"data"` // 任意类型 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 package models
// SessionRequest 会话资料 // SessionRequestDto 客户请求注册会话资料
// type 用户类型 0 | 1 0 = 用户 1 = 客服 // type 用户类型 0 | 1 0 = 用户 1 = 客服
// uid 自身业务平台用户ID // uid 自身业务平台用户ID
// account_id 用户客服ID,用户在mimc的唯一ID // account_id 用户客服ID,用户在mimc的唯一ID
// platform 平台 1,2,3,4,5 // platform 平台 1,2,3,4,5
type SessionRequest struct { type SessionRequestDto struct {
Type int `json:"type"` Type int `json:"type"`
UID int64 `orm:"column(uid)" json:"uid"` UID int64 `orm:"column(uid)" json:"uid"`
Platform int64 `json:"platform"` 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 package models
// TransferRequestData struct // TransferDto struct
type TransferRequestData struct { type TransferDto struct {
ToAccount int64 `json:"to_account"` // 转接给谁 ToAccount int64 `json:"to_account"` // 转接给谁
UserAccount int64 `json:"user_account"` // 用户ID 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 ( ...@@ -11,14 +11,14 @@ import (
type AdminRepositoryInterface interface { type AdminRepositoryInterface interface {
GetAdmin(id int64) *models.Admin GetAdmin(id int64) *models.Admin
GetAdminWithUserName(userName string) *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) Add(admin *models.Admin, col1 string) (bool, int64, error)
Delete(id int64) (int64, error) Delete(id int64) (int64, error)
GetAdmins(request *AdminPaginationData) (*AdminPaginationData, error) GetAdmins(request *AdminPaginationDto) (*AdminPaginationDto, error)
} }
// AdminPaginationData a struct // AdminPaginationDto a struct
type AdminPaginationData struct { type AdminPaginationDto struct {
PageSize int `json:"page_size"` PageSize int `json:"page_size"`
PageOn int `json:"page_on"` PageOn int `json:"page_on"`
Keyword string `json:"keyword"` Keyword string `json:"keyword"`
...@@ -39,6 +39,13 @@ type AdminRepository struct { ...@@ -39,6 +39,13 @@ type AdminRepository struct {
BaseRepository BaseRepository
} }
// GetAdminRepositoryInstance get instance
func GetAdminRepositoryInstance() *AdminRepository {
instance := new(AdminRepository)
instance.Init(new(models.Admin))
return instance
}
// GetAdmin get one admin with id // GetAdmin get one admin with id
func (r *AdminRepository) GetAdmin(id int64) *models.Admin { func (r *AdminRepository) GetAdmin(id int64) *models.Admin {
var admin models.Admin var admin models.Admin
...@@ -59,11 +66,11 @@ func (r *AdminRepository) GetAdminWithUserName(userName string) *models.Admin { ...@@ -59,11 +66,11 @@ func (r *AdminRepository) GetAdminWithUserName(userName string) *models.Admin {
return &admin return &admin
} }
// UpdateParams update admin // Update admin
func (r *AdminRepository) UpdateParams(id int64, params orm.Params) (int64, error) { func (r *AdminRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params) index, err := r.q.Filter("id", id).Update(params)
if err != nil { if err != nil {
logs.Warn("UpdateParams update admin------------", err) logs.Warn("Update admin------------", err)
} }
return index, err return index, err
} }
...@@ -87,7 +94,7 @@ func (r *AdminRepository) Delete(id int64) (int64, error) { ...@@ -87,7 +94,7 @@ func (r *AdminRepository) Delete(id int64) (int64, error) {
} }
// GetAdmins get admin list // GetAdmins get admin list
func (r *AdminRepository) GetAdmins(request *AdminPaginationData) (*AdminPaginationData, error) { func (r *AdminRepository) GetAdmins(request *AdminPaginationDto) (*AdminPaginationDto, error) {
var lists []models.Admin var lists []models.Admin
......
...@@ -16,6 +16,13 @@ type AuthTypesRepository struct { ...@@ -16,6 +16,13 @@ type AuthTypesRepository struct {
BaseRepository BaseRepository
} }
// GetAuthTypesRepositoryInstance get instance
func GetAuthTypesRepositoryInstance() *AuthTypesRepository {
instance := new(AuthTypesRepository)
instance.Init(new(models.AuthTypes))
return instance
}
// GetAuthType get a authType // GetAuthType get a authType
func (r *AuthTypesRepository) GetAuthType(id int64) *models.AuthTypes { func (r *AuthTypesRepository) GetAuthType(id int64) *models.AuthTypes {
var authType models.AuthTypes var authType models.AuthTypes
......
...@@ -14,7 +14,7 @@ type AuthsRepositoryInterface interface { ...@@ -14,7 +14,7 @@ type AuthsRepositoryInterface interface {
GetAdminOnlineCount(uid int64) int64 GetAdminOnlineCount(uid int64) int64
Delete(id int64) (int64, error) Delete(id int64) (int64, error)
Add(id *models.Auths) (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 // AuthsRepository struct
...@@ -22,6 +22,13 @@ type AuthsRepository struct { ...@@ -22,6 +22,13 @@ type AuthsRepository struct {
BaseRepository BaseRepository
} }
// GetAuthsRepositoryInstance get instance
func GetAuthsRepositoryInstance() *AuthsRepository {
instance := new(AuthsRepository)
instance.Init(new(models.Auths))
return instance
}
// GetAuthInfo get a auth info // GetAuthInfo get a auth info
func (r *AuthsRepository) GetAuthInfo(token string) *models.Auths { func (r *AuthsRepository) GetAuthInfo(token string) *models.Auths {
var auth models.Auths var auth models.Auths
...@@ -62,11 +69,11 @@ func (r *AuthsRepository) Delete(id int64) (int64, error) { ...@@ -62,11 +69,11 @@ func (r *AuthsRepository) Delete(id int64) (int64, error) {
return row, nil return row, nil
} }
// UpdateParams update admin // Update admin
func (r *AuthsRepository) UpdateParams(id int64, params orm.Params) (int64, error) { func (r *AuthsRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params) index, err := r.q.Filter("id", id).Update(params)
if err != nil { if err != nil {
logs.Warn("UpdateParams update admin------------", err) logs.Warn("Update admin------------", err)
} }
return index, err return index, err
} }
......
...@@ -10,7 +10,7 @@ import ( ...@@ -10,7 +10,7 @@ import (
// CompanyRepositoryInterface interface // CompanyRepositoryInterface interface
type CompanyRepositoryInterface interface { type CompanyRepositoryInterface interface {
GetCompany(id int64) *models.Company GetCompany(id int64) *models.Company
UpdateParams(id int64, params *orm.Params) (int64, error) Update(id int64, params *orm.Params) (int64, error)
} }
// CompanyRepository struct // CompanyRepository struct
...@@ -18,6 +18,13 @@ type CompanyRepository struct { ...@@ -18,6 +18,13 @@ type CompanyRepository struct {
BaseRepository BaseRepository
} }
// GetCompanyRepositoryInstance get instance
func GetCompanyRepositoryInstance() *CompanyRepository {
instance := new(CompanyRepository)
instance.Init(new(models.Company))
return instance
}
// GetCompany get one company // GetCompany get one company
func (r *CompanyRepository) GetCompany(id int64) *models.Company { func (r *CompanyRepository) GetCompany(id int64) *models.Company {
var company models.Company var company models.Company
...@@ -28,11 +35,11 @@ func (r *CompanyRepository) GetCompany(id int64) *models.Company { ...@@ -28,11 +35,11 @@ func (r *CompanyRepository) GetCompany(id int64) *models.Company {
return &company return &company
} }
// UpdateParams update company // Update company
func (r *CompanyRepository) UpdateParams(id int64, params orm.Params) (int64, error) { func (r *CompanyRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params) index, err := r.q.Filter("id", id).Update(params)
if err != nil { if err != nil {
logs.Warn("UpdateParams update company------------", err) logs.Warn("Update company------------", err)
} }
return index, err return index, err
} }
...@@ -11,9 +11,9 @@ import ( ...@@ -11,9 +11,9 @@ import (
// ContactRepositoryInterface interface // ContactRepositoryInterface interface
type ContactRepositoryInterface interface { type ContactRepositoryInterface interface {
GetContact(id int64) *models.Contact GetContact(id int64) *models.Contact
GetContacts(uid int64) ([]models.ContactData, error) GetContacts(uid int64) ([]models.ContactDto, error)
UpdateIsSessionEnd(usersID []int64, isSessionEnd int) (int64, 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) Delete(id int64, uid int64) (int64, error)
DeleteAll(uid int64) (int64, error) DeleteAll(uid int64) (int64, error)
Add(contact *models.Contact) (int64, error) Add(contact *models.Contact) (int64, error)
...@@ -25,6 +25,13 @@ type ContactRepository struct { ...@@ -25,6 +25,13 @@ type ContactRepository struct {
BaseRepository BaseRepository
} }
// GetContactRepositoryInstance get instance
func GetContactRepositoryInstance() *ContactRepository {
instance := new(ContactRepository)
instance.Init(new(models.Contact))
return instance
}
// Add add a Contact // Add add a Contact
func (r *ContactRepository) Add(contact *models.Contact) (int64, error) { func (r *ContactRepository) Add(contact *models.Contact) (int64, error) {
row, err := r.o.Insert(&contact) row, err := r.o.Insert(&contact)
...@@ -66,19 +73,19 @@ func (r *ContactRepository) UpdateIsSessionEnd(usersID []int64, isSessionEnd int ...@@ -66,19 +73,19 @@ func (r *ContactRepository) UpdateIsSessionEnd(usersID []int64, isSessionEnd int
} }
// GetContacts get Contacts // GetContacts get Contacts
func (r *ContactRepository) GetContacts(uid int64) ([]models.ContactData, error) { func (r *ContactRepository) GetContacts(uid int64) ([]models.ContactDto, error) {
var contactData []models.ContactData 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(&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(&contactDto)
if err != nil { if err != nil {
logs.Warn("GetContacts get Contacts------------", err) logs.Warn("GetContacts get Contacts------------", err)
return nil, err return nil, err
} }
// content base 64 decode // content base 64 decode
for index, contact := range contactData { for index, contact := range contactDto {
payload, _ := base64.StdEncoding.DecodeString(contact.LastMessage) 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 // Delete delete a Contact
...@@ -103,11 +110,11 @@ func (r *ContactRepository) DeleteAll(uid int64) (int64, error) { ...@@ -103,11 +110,11 @@ func (r *ContactRepository) DeleteAll(uid int64) (int64, error) {
} }
// UpdateParams update contact // Update contact
func (r *ContactRepository) UpdateParams(id int64, params orm.Params) (int64, error) { func (r *ContactRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params) index, err := r.q.Filter("id", id).Update(params)
if err != nil { if err != nil {
logs.Warn("UpdateParams update contact------------", err) logs.Warn("Update contact------------", err)
} }
return index, err return index, err
} }
...@@ -11,10 +11,10 @@ import ( ...@@ -11,10 +11,10 @@ import (
// KnowledgeBaseRepositoryInterface interface // KnowledgeBaseRepositoryInterface interface
type KnowledgeBaseRepositoryInterface interface { type KnowledgeBaseRepositoryInterface interface {
GetKnowledgeBase(id int64) *models.KnowledgeBase GetKnowledgeBase(id int64) *models.KnowledgeBase
GetKnowledgeBases(request models.PaginationData) (*models.PaginationData, error) GetKnowledgeBases(request models.KnowledgePaginationDto) (*models.KnowledgePaginationDto, error)
GetKnowledgeBaseWithTitle(title string) *models.KnowledgeBase GetKnowledgeBaseWithTitle(title string) *models.KnowledgeBase
Add(knowledgeBase *models.KnowledgeBase, col1 string) (bool, int64, error) 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) Delete(id int64) (int64, error)
} }
...@@ -23,6 +23,13 @@ type KnowledgeBaseRepository struct { ...@@ -23,6 +23,13 @@ type KnowledgeBaseRepository struct {
BaseRepository BaseRepository
} }
// GetKnowledgeBaseRepositoryInstance get instance
func GetKnowledgeBaseRepositoryInstance() *KnowledgeBaseRepository {
instance := new(KnowledgeBaseRepository)
instance.Init(new(models.KnowledgeBase))
return instance
}
// Add create a knowledgeBase // Add create a knowledgeBase
func (r *KnowledgeBaseRepository) Add(knowledgeBase *models.KnowledgeBase, col1 string) (bool, int64, error) { func (r *KnowledgeBaseRepository) Add(knowledgeBase *models.KnowledgeBase, col1 string) (bool, int64, error) {
knowledgeBase.SubTitle = strings.Trim(knowledgeBase.SubTitle, "|") knowledgeBase.SubTitle = strings.Trim(knowledgeBase.SubTitle, "|")
...@@ -36,11 +43,11 @@ func (r *KnowledgeBaseRepository) Add(knowledgeBase *models.KnowledgeBase, col1 ...@@ -36,11 +43,11 @@ func (r *KnowledgeBaseRepository) Add(knowledgeBase *models.KnowledgeBase, col1
return _bool, index, err return _bool, index, err
} }
// UpdateParams update knowledgeBase // Update knowledgeBase
func (r *KnowledgeBaseRepository) UpdateParams(id int64, params orm.Params) (int64, error) { func (r *KnowledgeBaseRepository) Update(id int64, params orm.Params) (int64, error) {
index, err := r.q.Filter("id", id).Update(params) index, err := r.q.Filter("id", id).Update(params)
if err != nil { if err != nil {
logs.Warn("UpdateParams update knowledgeBase------------", index, err) logs.Warn("Update knowledgeBase------------", index, err)
} }
return index, err return index, err
} }
...@@ -57,7 +64,7 @@ func (r *KnowledgeBaseRepository) GetKnowledgeBase(id int64) *models.KnowledgeBa ...@@ -57,7 +64,7 @@ func (r *KnowledgeBaseRepository) GetKnowledgeBase(id int64) *models.KnowledgeBa
} }
// GetKnowledgeBases get one KnowledgeBases // 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 { if request.PageSize < MinPageSize {
request.PageSize = MinPageSize request.PageSize = MinPageSize
......
...@@ -3,6 +3,7 @@ package services ...@@ -3,6 +3,7 @@ package services
import ( import (
"encoding/base64" "encoding/base64"
"kefu_server/models" "kefu_server/models"
"strconv"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
...@@ -10,9 +11,12 @@ import ( ...@@ -10,9 +11,12 @@ import (
// MessageRepositoryInterface interface // MessageRepositoryInterface interface
type MessageRepositoryInterface interface { type MessageRepositoryInterface interface {
GetMessages(serviceID int64, messagePaginationData models.MessagePaginationData) (*models.MessagePaginationData, error) GetAdminMessages(messagePaginationDto models.MessagePaginationDto) (*models.MessagePaginationDto, error)
Delete(removeRequestData models.RemoveMessageRequestData) (int64, error) GetUserMessages(messagePaginationDto models.MessagePaginationDto) (*models.MessagePaginationDto, error)
Delete(removeRequestDto models.RemoveMessageRequestDto) (int64, error)
Add(message *models.Message) (int64, error) Add(message *models.Message) (int64, error)
GetReadCount(uid int64) (int64, error)
ClearRead(uid int64) (int64, error)
} }
// MessageRepository struct // MessageRepository struct
...@@ -20,6 +24,13 @@ type MessageRepository struct { ...@@ -20,6 +24,13 @@ type MessageRepository struct {
BaseRepository BaseRepository
} }
// GetMessageRepositoryInstance get instance
func GetMessageRepositoryInstance() *MessageRepository {
instance := new(MessageRepository)
instance.Init(new(models.Message))
return instance
}
// Add add a message // Add add a message
func (r *MessageRepository) Add(message *models.Message) (int64, error) { func (r *MessageRepository) Add(message *models.Message) (int64, error) {
row, err := r.o.Insert(&message) row, err := r.o.Insert(&message)
...@@ -29,25 +40,91 @@ func (r *MessageRepository) Add(message *models.Message) (int64, error) { ...@@ -29,25 +40,91 @@ func (r *MessageRepository) Add(message *models.Message) (int64, error) {
return row, err 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 // Delete delete a message
func (r *MessageRepository) Delete(removeRequestData models.RemoveMessageRequestData) (int64, error) { 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` = ?", removeRequestData.FromAccount, removeRequestData.ToAccount, removeRequestData.Key).Exec() 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() row, _ := res.RowsAffected()
if err != nil { if err != nil {
logs.Warn("Delete delete a message------------", err)
return 0, err return 0, err
} }
return row, nil return row, nil
} }
// GetMessages get one service message list // GetUserMessages get user messages
func (r *MessageRepository) GetMessages(serviceID int64, messagePaginationData models.MessagePaginationData) (*models.MessagePaginationData, error) { 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 err error
var msgCount int64 var msgCount int64
var messages []*models.Message var messages []*models.Message
// join string // join string
accounts := []int64{messagePaginationData.Account, serviceID} accounts := []int64{messagePaginationDto.Account, messagePaginationDto.Service}
inExp := "?,?" inExp := "?,?"
// get all robot // get all robot
...@@ -62,39 +139,39 @@ func (r *MessageRepository) GetMessages(serviceID int64, messagePaginationData m ...@@ -62,39 +139,39 @@ func (r *MessageRepository) GetMessages(serviceID int64, messagePaginationData m
inExp = inExp + ",?" 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 { if err != nil {
logs.Warn("GetMessages get one service message list1------------", err) logs.Warn("GetMessages get one service message list1------------", err)
} }
// Paging // Paging
end := msgCount end := msgCount
start := int(msgCount) - messagePaginationData.PageSize start := int(msgCount) - messagePaginationDto.PageSize
if start <= 0 { if start <= 0 {
start = 0 start = 0
} }
if msgCount > 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 { if err != nil {
logs.Warn("GetMessages get one service message list2------------", err) logs.Warn("GetMessages get one service message list2------------", err)
return nil, 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 { if err != nil {
logs.Warn("GetMessages get one service message list3------------", err) logs.Warn("GetMessages get one service message list3------------", err)
return nil, err return nil, err
} }
total, _ := r.q.Filter("to_account__in", accounts).Filter("from_account__in", accounts).Filter("delete", 0).Count() total, _ := r.q.Filter("to_account__in", accounts).Filter("from_account__in", accounts).Filter("delete", 0).Count()
messagePaginationData.List = messages messagePaginationDto.List = messages
messagePaginationData.Total = total messagePaginationDto.Total = total
} else { } else {
messagePaginationData.List = []models.Message{} messagePaginationDto.List = []models.Message{}
messagePaginationData.Total = 0 messagePaginationDto.Total = 0
} }
for index, msg := range messages { for index, msg := range messages {
payload, _ := base64.StdEncoding.DecodeString(msg.Payload) payload, _ := base64.StdEncoding.DecodeString(msg.Payload)
messages[index].Payload = string(payload) messages[index].Payload = string(payload)
} }
return &messagePaginationData, nil return &messagePaginationDto, nil
} }
...@@ -4,12 +4,18 @@ import ( ...@@ -4,12 +4,18 @@ import (
"kefu_server/models" "kefu_server/models"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
) )
// PlatformRepositoryInterface interface // PlatformRepositoryInterface interface
type PlatformRepositoryInterface interface { type PlatformRepositoryInterface interface {
GetPlatform(id int64) *models.Platform GetPlatform(id int64) *models.Platform
GetPlatformAll(orderByKey string) ([]models.Platform, error)
Add(platform *models.Platform, col1 string) (bool, int64, 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 //PlatformRepository struct
...@@ -17,9 +23,16 @@ type PlatformRepository struct { ...@@ -17,9 +23,16 @@ type PlatformRepository struct {
BaseRepository BaseRepository
} }
// GetPlatformRepositoryInstance get instance
func GetPlatformRepositoryInstance() *PlatformRepository {
instance := new(PlatformRepository)
instance.Init(new(models.Platform))
return instance
}
// Add create a Platform // Add create a Platform
func (r *PlatformRepository) Add(platform *models.Platform, col1 string) (bool, int64, error) { 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 { if err != nil {
logs.Warn("Add create a Platform------------", err) logs.Warn("Add create a Platform------------", err)
} }
...@@ -30,8 +43,58 @@ func (r *PlatformRepository) Add(platform *models.Platform, col1 string) (bool, ...@@ -30,8 +43,58 @@ func (r *PlatformRepository) Add(platform *models.Platform, col1 string) (bool,
func (r *PlatformRepository) GetPlatform(id int64) *models.Platform { func (r *PlatformRepository) GetPlatform(id int64) *models.Platform {
var platform models.Platform var platform models.Platform
if err := r.q.Filter("id", id).One(&platform); err != nil { 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 nil
} }
return &platform 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 package services
import ( import (
"errors"
"kefu_server/models" "kefu_server/models"
"math/rand"
"strings" "strings"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
) )
// RobotRepositoryInterface interface // RobotRepositoryInterface interface
type RobotRepositoryInterface interface { type RobotRepositoryInterface interface {
GetRobot(id int64) *models.Robot GetRobot(id int64) *models.Robot
GetRobotWithNickName(nickName string) *models.Robot
GetRobotWithOnline(id int64) (*models.Robot, error)
GetRobots() ([]models.Robot, error) GetRobots() ([]models.Robot, error)
GetRobotWithInIds(ids ...int64) ([]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 // RobotRepository struct
...@@ -19,6 +27,49 @@ type RobotRepository struct { ...@@ -19,6 +27,49 @@ type RobotRepository struct {
BaseRepository 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 // GetRobots get Robots
func (r *RobotRepository) GetRobots() ([]models.Robot, error) { func (r *RobotRepository) GetRobots() ([]models.Robot, error) {
var robots []models.Robot var robots []models.Robot
...@@ -28,6 +79,7 @@ func (r *RobotRepository) GetRobots() ([]models.Robot, error) { ...@@ -28,6 +79,7 @@ func (r *RobotRepository) GetRobots() ([]models.Robot, error) {
} }
for index := range robots { for index := range robots {
robots[index].Artificial = strings.Trim(robots[index].Artificial, "|") robots[index].Artificial = strings.Trim(robots[index].Artificial, "|")
robots[index].KeyWord = strings.Trim(robots[index].KeyWord, "|")
} }
return robots, nil return robots, nil
} }
...@@ -39,9 +91,39 @@ func (r *RobotRepository) GetRobot(id int64) *models.Robot { ...@@ -39,9 +91,39 @@ func (r *RobotRepository) GetRobot(id int64) *models.Robot {
logs.Warn("GetRobot get one Robot------------", err) logs.Warn("GetRobot get one Robot------------", err)
return nil 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 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 // GetRobotWithInIds get one Robot with in() ids
func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error) { func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error) {
var robots []models.Robot var robots []models.Robot
...@@ -51,3 +133,15 @@ func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error ...@@ -51,3 +133,15 @@ func (r *RobotRepository) GetRobotWithInIds(ids ...int64) ([]models.Robot, error
} }
return robots, err 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 { ...@@ -15,6 +15,7 @@ type StatisticalRepositoryInterface interface {
Add(servicesStatistical *models.ServicesStatistical) (int64, error) Add(servicesStatistical *models.ServicesStatistical) (int64, error)
GetStatisticals(startDate string, endDate string) (map[string]interface{}, error) GetStatisticals(startDate string, endDate string) (map[string]interface{}, error)
GetTodayActionStatistical(startDate string, endDate string) ([]orm.Params, error) GetTodayActionStatistical(startDate string, endDate string) ([]orm.Params, error)
GetCustomerServiceList(request models.ServicesStatisticalPaginationDto) models.ServicesStatisticalPaginationDto
} }
// StatisticalRepository struct // StatisticalRepository struct
...@@ -22,6 +23,57 @@ type StatisticalRepository struct { ...@@ -22,6 +23,57 @@ type StatisticalRepository struct {
BaseRepository 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 // Add add statistical
func (r *StatisticalRepository) Add(servicesStatistical *models.ServicesStatistical) (int64, error) { func (r *StatisticalRepository) Add(servicesStatistical *models.ServicesStatistical) (int64, error) {
id, err := r.o.Insert(&servicesStatistical) id, err := r.o.Insert(&servicesStatistical)
......
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 ...@@ -2,13 +2,21 @@ package services
import ( import (
"kefu_server/models" "kefu_server/models"
"time"
"github.com/astaxie/beego/logs" "github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
) )
// UserRepositoryInterface interface // UserRepositoryInterface interface
type UserRepositoryInterface interface { type UserRepositoryInterface interface {
Add(admin *models.User) (int64, error)
GetUser(id int64) *models.User 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 // UserRepository struct
...@@ -16,6 +24,22 @@ type UserRepository struct { ...@@ -16,6 +24,22 @@ type UserRepository struct {
BaseRepository 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 // GetUser get one User
func (r *UserRepository) GetUser(id int64) *models.User { func (r *UserRepository) GetUser(id int64) *models.User {
var user models.User var user models.User
...@@ -25,3 +49,80 @@ func (r *UserRepository) GetUser(id int64) *models.User { ...@@ -25,3 +49,80 @@ func (r *UserRepository) GetUser(id int64) *models.User {
} }
return &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 package utils
// InExistInSlice 检查内容是否在slice中存在 // InExistInSlice Check if content exists in slice
func InExistInSlice(input string, slice []string) bool { func InExistInSlice(input string, slice []string) bool {
for _, v := range slice { for _, v := range slice {
if v == input { if v == input {
......
...@@ -18,14 +18,13 @@ func MessageInto(message models.Message, isKF bool) { ...@@ -18,14 +18,13 @@ func MessageInto(message models.Message, isKF bool) {
return return
} }
// init MessageRepository // MessageRepository instance
messageRepository := new(services.MessageRepository) messageRepository := services.GetMessageRepositoryInstance()
messageRepository.Init(new(models.Message))
// 判断是否是撤回消息(软删除) // 判断是否是撤回消息(软删除)
if message.BizType == "cancel" { if message.BizType == "cancel" {
key, _ := strconv.ParseInt(message.Payload, 10, 64) 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 // message create time
...@@ -38,9 +37,10 @@ func MessageInto(message models.Message, isKF bool) { ...@@ -38,9 +37,10 @@ func MessageInto(message models.Message, isKF bool) {
if !(message.BizType == "handshake") { if !(message.BizType == "handshake") {
if !isKF { if !isKF {
// init UserRepository
userRepository := new(services.UserRepository) // UserRepository instance
userRepository.Init(new(models.User)) userRepository := services.GetUserRepositoryInstance()
// 默认已读消息 // 默认已读消息
message.Read = 0 message.Read = 0
user := userRepository.GetUser(message.ToAccount) user := userRepository.GetUser(message.ToAccount)
...@@ -62,18 +62,16 @@ func MessageInto(message models.Message, isKF bool) { ...@@ -62,18 +62,16 @@ func MessageInto(message models.Message, isKF bool) {
} }
// init RobotRepository // RobotRepository instance
robotRepository := new(services.RobotRepository) robotRepository := services.GetRobotRepositoryInstance()
robotRepository.Init(new(models.Robot))
// 判断是否机器人对话(不处理聊天列表) // 判断是否机器人对话(不处理聊天列表)
if rbts, _ := robotRepository.GetRobotWithInIds(message.ToAccount, message.FromAccount); len(rbts) > 0 { if rbts, _ := robotRepository.GetRobotWithInIds(message.ToAccount, message.FromAccount); len(rbts) > 0 {
return return
} }
// init ContactRepository // ContactRepository instance
contactRepository := new(services.ContactRepository) contactRepository := services.GetContactRepositoryInstance()
contactRepository.Init(new(models.Contact))
// 处理客服聊天列表 // 处理客服聊天列表
if contact, err := contactRepository.GetContactWithIds(message.ToAccount, message.FromAccount); err != nil { if contact, err := contactRepository.GetContactWithIds(message.ToAccount, message.FromAccount); err != nil {
...@@ -88,7 +86,7 @@ func MessageInto(message models.Message, isKF bool) { ...@@ -88,7 +86,7 @@ func MessageInto(message models.Message, isKF bool) {
if message.BizType == "end" || message.BizType == "timeout" { if message.BizType == "end" || message.BizType == "timeout" {
isSessionEnd = 1 isSessionEnd = 1
} }
_, _ = contactRepository.UpdateParams(contact.ID, orm.Params{ _, _ = contactRepository.Update(contact.ID, orm.Params{
"LastMessageType": message.BizType, "LastMessageType": message.BizType,
"CreateAt": time.Now().Unix(), "CreateAt": time.Now().Unix(),
"LastMessage": message.Payload, "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 ( ...@@ -10,21 +10,21 @@ import (
) )
// KEY ... // KEY ...
// DEFAULT_EXPIRE_SECONDS ... // DEFAULTEXPIRESECONDS ...
const ( const (
KEY string = "JWT-ARY-STARK" KEY string = "JWT-ARY-STARK"
DEFAULT_EXPIRE_SECONDS int = 259200 DEFAULTEXPIRESECONDS int = 259200
) )
// MyCustomClaims JWT -- json web token // MyCustomClaims JWT -- json web token
// HEADER PAYLOAD SIGNATURE // HEADER PAYLOAD SIGNATURE
// This struct is the PAYLOAD // This struct is the PAYLOAD
type MyCustomClaims struct { type MyCustomClaims struct {
models.JwtKey models.JwtKeyDto
jwt.StandardClaims jwt.StandardClaims
} }
// RefreshToken 刷新token // RefreshToken Refresh token
func RefreshToken(tokenString string) (string, error) { func RefreshToken(tokenString string) (string, error) {
// first get previous token // first get previous token
token, err := jwt.ParseWithClaims( token, err := jwt.ParseWithClaims(
...@@ -37,12 +37,12 @@ func RefreshToken(tokenString string) (string, error) { ...@@ -37,12 +37,12 @@ func RefreshToken(tokenString string) (string, error) {
return "", err return "", err
} }
mySigningKey := []byte(KEY) 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{ newClaims := MyCustomClaims{
claims.JwtKey, claims.JwtKeyDto,
jwt.StandardClaims{ jwt.StandardClaims{
ExpiresAt: expireAt, ExpiresAt: expireAt,
Issuer: claims.JwtKey.UserName, Issuer: claims.JwtKeyDto.UserName,
IssuedAt: time.Now().Unix(), IssuedAt: time.Now().Unix(),
}, },
} }
...@@ -89,21 +89,21 @@ func DecodeToken(token string) (map[string]interface{}, error) { ...@@ -89,21 +89,21 @@ func DecodeToken(token string) (map[string]interface{}, error) {
} }
// GenerateToken 生成token // GenerateToken 生成token
func GenerateToken(jwtKey models.JwtKey) (tokenString string) { func GenerateToken(jwtKeyDto models.JwtKeyDto) (tokenString string) {
var expiredSeconds int var expiredSeconds int
expiredSeconds = 259200 expiredSeconds = 259200
if expiredSeconds == 0 { if expiredSeconds == 0 {
expiredSeconds = DEFAULT_EXPIRE_SECONDS expiredSeconds = DEFAULTEXPIRESECONDS
} }
// Create the Claims // Create the Claims
mySigningKey := []byte(KEY) mySigningKey := []byte(KEY)
expireAt := time.Now().Add(time.Second * time.Duration(expiredSeconds)).Unix() expireAt := time.Now().Add(time.Second * time.Duration(expiredSeconds)).Unix()
// pass parameter to this func or not // pass parameter to this func or not
claims := MyCustomClaims{ claims := MyCustomClaims{
jwtKey, jwtKeyDto,
jwt.StandardClaims{ jwt.StandardClaims{
ExpiresAt: expireAt, ExpiresAt: expireAt,
Issuer: jwtKey.UserName, Issuer: jwtKeyDto.UserName,
IssuedAt: time.Now().Unix(), 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