作者 yangfu

fix bug

... ... @@ -11,6 +11,8 @@ import (
type RefreshIMCommand struct {
// 手机号码
Phone string `cname:"手机号码" json:"phone" valid:"Required"`
// 刷新标识 0:刷新IM信息,并返回 1:使用旧的im信息
RefreshFlag int `cname:"刷新标识" json:"refreshFlag"`
}
func (refreshIMCommand *RefreshIMCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -9,6 +9,8 @@ import (
)
type UserInfoQuery struct {
// 用户Id 用户唯一标识
UserId int64 `cname:"用户Id 用户唯一标识" json:"userId"`
}
func (userInfoQuery *UserInfoQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -6,6 +6,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/auth/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"strconv"
"time"
)
... ... @@ -286,10 +287,19 @@ func (authService *AuthService) RefreshIM(refreshIMCommand *command.RefreshIMCom
defer func() {
transactionContext.RollbackTransaction()
}()
imService, _ := factory.CreatePgImService(map[string]interface{}{
"transactionContext": transactionContext,
})
userId, _ := strconv.Atoi(refreshIMCommand.Phone)
imInfo, err := imService.InitOrUpdateUserIMInfo(int64(userId), refreshIMCommand.RefreshFlag)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
return imInfo, nil
}
// 用户信息
... ...
... ... @@ -256,6 +256,19 @@ func (companyService *CompanyService) UpdateCompany(updateCompanyCommand *comman
if err := company.Update(tool_funs.SimpleStructToMap(updateCompanyCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
orgRepository, _, _ := factory.FastPgOrg(transactionContext, 0)
if org, err := orgRepository.FindOne(map[string]interface{}{"companyId": updateCompanyCommand.CompanyId, "parentId": 0}); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
} else {
if org.OrgName != company.CompanyInfo.CompanyName {
org.Update(map[string]interface{}{"orgName": company.CompanyInfo.CompanyName})
}
if _, err := orgRepository.Save(org); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
}
if company, err := companyRepository.Save(company); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ...
... ... @@ -78,3 +78,11 @@ func CreatePgRoleAccessMenusService(options map[string]interface{}) (service.PgR
}
return domainService.NewPgRoleAccessMenusService(transactionContext)
}
func CreatePgImService(options map[string]interface{}) (service.PgImService, error) {
var transactionContext *pgTransaction.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pgTransaction.TransactionContext)
}
return domainService.NewPgImService(transactionContext)
}
... ...
... ... @@ -31,6 +31,7 @@ type UserDto struct {
Organization *domain.Org `json:"org,omitempty"`
// 部门
Department *domain.Department `json:"department,omitempty"`
Im *domain.Im `json:"im,omitempty"`
}
type Company struct {
... ... @@ -39,6 +40,8 @@ type Company struct {
// 企业基本信息
domain.CompanyInfo
Status int `json:"status"`
// 系统名称
SystemName string `json:"systemName,omitempty"`
}
func (dto *UserDto) LoadDto(user *domain.User, company *domain.Company) error {
... ... @@ -57,6 +60,7 @@ func (dto *UserDto) LoadDto(user *domain.User, company *domain.Company) error {
CompanyId: company.CompanyId,
CompanyInfo: *company.CompanyInfo,
Status: company.Status,
SystemName: company.CompanyConfig.SystemName,
}
}
if user.UserInfo == nil {
... ...
... ... @@ -22,7 +22,7 @@ type ListUserQuery struct {
// 部门编号
DepartmentId int64 `cname:"部门编号" json:"departmentId,omitempty"`
// 用户基础ID
UserBaseId string `cname:"用户基础ID" json:"userBaseId,omitempty"`
UserBaseId int64 `cname:"用户基础ID" json:"userBaseId,omitempty"`
// 用户姓名
UserName string `cname:"用户姓名" json:"userName,omitempty"`
// 共创公司
... ... @@ -37,6 +37,8 @@ type ListUserQuery struct {
InOrgIds []int64 `cname:"在组织范围内" json:"inOrgIds,omitempty"`
// 实时拉取数据 (获取最新的)
PullRealTime bool `cname:"拉取最新数据" json:"pullRealTime,omitempty"`
// 状态(1:启用 2:禁用 3:注销)
EnableStatus int `cname:"状态(1:启用 2:禁用 3:注销)" json:"enableStatus,omitempty"`
}
func (listUserQuery *ListUserQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -328,7 +328,7 @@ func (userService *UserService) GetUser(getUserQuery *query.GetUserQuery) (inter
user.Company = company.CloneSample()
user.UserInfo = userBase.UserInfo
}
userDto := &dto.UserDto{}
userDto := &dto.UserDto{Im: userBase.Im}
if err := userDto.LoadDto(user, company); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
... ... @@ -448,7 +448,7 @@ func (userService *UserService) ListUser(listUserQuery *query.ListUserQuery) (in
} else {
userRepository = value
}
_, company, _ := factory.FastPgCompany(transactionContext, listUserQuery.CompanyId)
_, company, _ := factory.FastPgCompany(transactionContext, listUserQuery.OperateInfo.GetCompanyId(listUserQuery.CompanyId))
var dtoUsers []*dto.UserDto
queryOptions := utils.ObjectToMap(listUserQuery)
if len(listUserQuery.Phone) > 0 {
... ... @@ -465,6 +465,9 @@ func (userService *UserService) ListUser(listUserQuery *query.ListUserQuery) (in
for i := range users {
user := users[i]
userDto := &dto.UserDto{}
if company == nil && user.CompanyId != 0 {
_, company, _ = factory.FastPgCompany(transactionContext, user.CompanyId)
}
if listUserQuery.PullRealTime {
_, dep, _ := factory.FastPgOrg(transactionContext, user.DepartmentId)
_, org, _ := factory.FastPgOrg(transactionContext, user.OrganizationId)
... ...
... ... @@ -3,6 +3,8 @@ package constant
import (
"fmt"
"os"
"strconv"
"strings"
)
var SERVICE_NAME = "allied-creation-user"
... ... @@ -10,6 +12,10 @@ var SERVICE_ENV = "dev"
var CACHE_PREFIX = "allied-creation-user-dev"
var LOG_LEVEL = "debug"
var CUSTOMER_ACCOUNT = []int64{3129687560814592, 3129687690100739, 3492238958608384}
const CUSTOMER_ACCOUNT_DELIMITER = ","
/***** 1.数据传输 *****/
const HeaderCompanyId = "companyId"
const HeaderUserId = "userId"
... ... @@ -19,5 +25,20 @@ func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
if os.Getenv("CUSTOMER_ACCOUNT") != "" {
account := os.Getenv("CUSTOMER_ACCOUNT")
accounts := strings.Split(account, CUSTOMER_ACCOUNT_DELIMITER)
var tmpAccounts []int64
for i := range accounts {
v, err := strconv.ParseInt(accounts[i], 10, 64)
if err != nil {
panic(err)
}
tmpAccounts = append(tmpAccounts, v)
}
if len(tmpAccounts) > 0 {
CUSTOMER_ACCOUNT = tmpAccounts
}
}
CACHE_PREFIX = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV)
}
... ...
package constant
import "os"
var (
IM_SERVICE_ADDRESS = "https://api.netease.im/nimserver"
IM_APP_KEY = "be7c0639c10e6a69f86ce3b4fa8dc8ec" //"ebf3ae278ee1b346773b99be5080f6a9"
IM_APP_SECRET = "9c5b60346613" //"67ea92e1ea45"
)
func init() {
if os.Getenv("IM_APP_KEY") != "" {
IM_APP_KEY = os.Getenv("IM_APP_KEY")
}
if os.Getenv("IM_APP_SECRET") != "" {
IM_APP_SECRET = os.Getenv("IM_APP_SECRET")
}
}
... ...
package domain
const (
RefreshImmediately = iota
RefreshWhenNotExists
)
// 冗余附加数据
type Im struct {
// 网易云信ID
... ...
package service
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
// PgImService 网易云信IM服务
type PgImService interface {
InitOrUpdateUserIMInfo(userId int64, flag int) (imInfo *domain.Im, err error)
}
... ...
package domainService
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/repository"
)
// PgCommonStatisticsService 通用统计服务
type PgCommonStatisticsService struct {
transactionContext *pgTransaction.TransactionContext
}
const (
// 累计组织用户
TotalOrganizationUser = iota + 1
)
var (
mapStatistics = map[int]string{
TotalOrganizationUser: "totalOrganizationUser",
}
)
// Scan 扫描需要统计的项
//
// keyFlags 统计项标识符号
// queryOption 查询参数
func (ptr *PgCommonStatisticsService) Scan(keyFlags []int, queryOption map[string]interface{}) (interface{}, error) {
var res = make(map[string]interface{})
for i := range keyFlags {
switch keyFlags[i] {
case TotalOrganizationUser:
queryTotalOrganizationUser, err := ptr.loadQueryOptions(queryOption, "companyId", "organizationId")
if err != nil {
return nil, err
}
if v, err := ptr.totalOrganizationUser(queryTotalOrganizationUser); err != nil {
return nil, err
} else {
res[v.key] = v.val
}
}
}
return res, nil
}
// totalOrganizationUser 统计组织用户
func (ptr *PgCommonStatisticsService) totalOrganizationUser(queryOption map[string]interface{}) (item, error) {
res := item{
key: mapStatistics[TotalOrganizationUser],
}
userRepository, _ := repository.NewUserRepository(ptr.transactionContext)
if total, _, err := userRepository.Find(queryOption); err != nil {
return res, err
} else {
res.val = map[string]interface{}{
"total": total,
}
}
return res, nil
}
func (ptr *PgCommonStatisticsService) loadQueryOptions(queryOption map[string]interface{}, keys ...string) (map[string]interface{}, error) {
var res = make(map[string]interface{})
for i := 0; i < len(keys); i++ {
k := keys[i]
if v, ok := queryOption[k]; ok {
res[k] = v
} else {
return nil, fmt.Errorf("参数 %v 不存在", k)
}
}
return res, nil
}
type item struct {
key string
val interface{}
}
... ...
... ... @@ -3,8 +3,10 @@ package domainService
import (
"fmt"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/im"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/repository"
)
// PgImService 网易云信IM服务
... ... @@ -12,54 +14,49 @@ type PgImService struct {
transactionContext *pgTransaction.TransactionContext
}
func (s *PgImService) InitOrUpdateUserIMInfo(userId int64, name string) (imInfo *domain.Im, err error) {
func (ptr *PgImService) InitOrUpdateUserIMInfo(userId int64, flag int) (*domain.Im, error) {
var (
//ImInfoRepository, _ = factory.CreateImInfoRepository(ctx)
checkImRequest *im.CheckImRequest = &im.CheckImRequest{}
IsCreated = false
checkImResponse *im.CheckImResponse
)
var errFind error
//imInfo, errFind = ImInfoRepository.FindOne(map[string]interface{}{"user_id": userId})
// 异常
//if errFind != nil && errFind != domain.QueryNoRow {
// err = errFind
// return
//}
// 不存在
//if errFind == domain.QueryNoRow {
// imInfo = &domain.Im{
// UserId: userId,
// CreateTime: time.Now(),
// }
//}
// 已存在
if errFind == nil && imInfo != nil {
userBaseRepository, _ := repository.NewUserBaseRepository(ptr.transactionContext)
userBase, err := userBaseRepository.FindOne(map[string]interface{}{"account": fmt.Sprintf("%v", userId)})
if err != nil || userBase == nil || userBase.Status != int(domain.UserStatusEnable) {
return nil, fmt.Errorf("账号不存在")
}
if userBase.Im != nil && len(userBase.Im.Accid) > 0 {
IsCreated = true
if flag == domain.RefreshWhenNotExists {
return userBase.Im, nil
}
} else {
id, err := repository.IdWorker.NextId()
if err != nil {
return nil, err
}
userBase.Im = &domain.Im{
Accid: fmt.Sprintf("%v", id),
}
if len(imInfo.Accid) == 0 {
//id, _ := utils.NewSnowflakeId()
//imInfo.ImId = fmt.Sprintf("%v", id)
}
checkImRequest = &im.CheckImRequest{
UserId: userId,
ImId: imInfo.Accid,
Uname: name,
CustomerImId: fmt.Sprintf("%v", imInfo.CsAccountId),
ImId: userBase.Im.Accid,
Uname: userBase.UserInfo.UserName,
CustomerImId: fmt.Sprintf("%v", userBase.Im.CsAccountId),
IsCreated: IsCreated,
}
if checkImResponse, err = CheckIm(checkImRequest); err != nil {
return
return nil, err
}
if len(imInfo.CsAccountId) == 0 {
imInfo.CsAccountId = getRandomCustomerAccount(userId)
if len(userBase.Im.CsAccountId) == 0 {
userBase.Im.CsAccountId = fmt.Sprintf("%v", getRandomCustomerAccount(userId))
}
imInfo.ImToken = checkImResponse.ImToken
//if _, err = ImInfoRepository.Save(imInfo); err != nil {
// return
//}
return
userBase.Im.ImToken = checkImResponse.ImToken
if userBase, err = userBaseRepository.Save(userBase); err != nil {
}
return userBase.Im, nil
}
// 检查ImToken
... ... @@ -139,21 +136,24 @@ func imRefreshToken(request *im.CheckImRequest, rsp *im.CheckImResponse) (err er
}
// 获取客服id
func getRandomCustomerAccount(userId int64) (acid string) {
//ImCustomerServiceRepository, _ := factory.CreateImCustomerServiceRepository(ctx)
//total, customers, err := ImCustomerServiceRepository.Find(map[string]interface{}{"sortById": domain.ASC})
//if err != nil {
// log.Error(err)
// return 0
//}
//if total == 0 {
// return 0
//}
//index := userId % total
//if int(index) < len(customers) {
// acid, _ = strconv.ParseInt(customers[index].ImId, 10, 64)
// return
//}
//acid, _ = strconv.ParseInt(customers[0].ImId, 10, 64)
return
func getRandomCustomerAccount(userId int64) int64 {
total, customers := len(constant.CUSTOMER_ACCOUNT), constant.CUSTOMER_ACCOUNT
if total == 0 {
return 0
}
index := (int(userId) & 0xFF) % int(total)
if int(index) < len(customers) {
return customers[index]
}
return customers[0]
}
func NewPgImService(transactionContext *pgTransaction.TransactionContext) (*PgImService, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &PgImService{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -2,11 +2,12 @@ package im
import (
"encoding/json"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/constant"
)
//func init() {
// InitImClient(constant.IM_SERVICE_ADDRESS, constant.IM_APP_KEY, constant.IM_APP_SECRET)
//}
func init() {
InitImClient(constant.IM_SERVICE_ADDRESS, constant.IM_APP_KEY, constant.IM_APP_SECRET)
}
type RequestParam interface {
Format() map[string]string
... ...
package repository
import (
"github.com/linmadan/egglib-go/utils/snowflake"
)
var IdWorker *snowflake.IdWorker
func init() {
worker, err := snowflake.NewIdWorker(2)
if err != nil {
//log.Logger.Panic("idWorker init err" + err.Error())
panic(err)
}
IdWorker = worker
}
... ...
... ... @@ -210,7 +210,7 @@ func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int
if v, ok := queryOptions["cooperationCompany"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`cooperation_info->>'cooperationCompany' like '%%%v%%'`, v))
}
query.SetOffsetAndLimit(999)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("user_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, users, err
... ...
... ... @@ -65,3 +65,11 @@ func (controller *AuthController) UserInfo() {
data, err := authService.UserInfo(userInfoQuery)
controller.Response(data, err)
}
func (controller *AuthController) RefreshIM() {
authService := service.NewAuthService(nil)
refreshIMCommand := &command.RefreshIMCommand{}
controller.Unmarshal(refreshIMCommand)
data, err := authService.RefreshIM(refreshIMCommand)
controller.Response(data, err)
}
... ...
... ... @@ -12,5 +12,5 @@ func init() {
web.Router("/auth/change-password", &controllers.AuthController{}, "Post:PhoneAuthChangePassword")
web.Router("/auth/reset-phone", &controllers.AuthController{}, "Post:PhoneAuthResetPhone")
web.Router("/auth/destroy-account", &controllers.AuthController{}, "Post:DestroyAccount")
web.Router("/auth/userInfo", &controllers.AuthController{}, "Post:UserInfo")
web.Router("/auth/refresh-im", &controllers.AuthController{}, "Post:RefreshIM")
}
... ...