add get user by id in amo client
This commit is contained in:
parent
ae64ee452e
commit
3c70c13edc
@ -6,6 +6,7 @@ import (
|
|||||||
"amocrm/internal/repository"
|
"amocrm/internal/repository"
|
||||||
"amocrm/internal/server/http"
|
"amocrm/internal/server/http"
|
||||||
"amocrm/internal/service"
|
"amocrm/internal/service"
|
||||||
|
"amocrm/internal/workers/data_updater"
|
||||||
"amocrm/internal/workers/tokens"
|
"amocrm/internal/workers/tokens"
|
||||||
amoClient2 "amocrm/pkg/amoClient"
|
amoClient2 "amocrm/pkg/amoClient"
|
||||||
"amocrm/pkg/closer"
|
"amocrm/pkg/closer"
|
||||||
@ -83,7 +84,14 @@ func Run(ctx context.Context, config initialize.Config, logger *zap.Logger) erro
|
|||||||
Logger: logger,
|
Logger: logger,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
dataUpdater := data_updater.NewDataUpdaterWC(data_updater.Deps{
|
||||||
|
Repo: repo,
|
||||||
|
AmoClient: amoClient,
|
||||||
|
Logger: logger,
|
||||||
|
})
|
||||||
|
|
||||||
go tokenUpdater.Start(ctx)
|
go tokenUpdater.Start(ctx)
|
||||||
|
go dataUpdater.Start(ctx)
|
||||||
|
|
||||||
server := http.NewServer(http.ServerConfig{
|
server := http.NewServer(http.ServerConfig{
|
||||||
Controllers: []http.Controller{
|
Controllers: []http.Controller{
|
||||||
@ -104,6 +112,7 @@ func Run(ctx context.Context, config initialize.Config, logger *zap.Logger) erro
|
|||||||
shutdownGroup.Add(closer.CloserFunc(mdb.Client().Disconnect))
|
shutdownGroup.Add(closer.CloserFunc(mdb.Client().Disconnect))
|
||||||
shutdownGroup.Add(closer.CloserFunc(rateLimiter.Stop))
|
shutdownGroup.Add(closer.CloserFunc(rateLimiter.Stop))
|
||||||
shutdownGroup.Add(closer.CloserFunc(tokenUpdater.Stop))
|
shutdownGroup.Add(closer.CloserFunc(tokenUpdater.Stop))
|
||||||
|
shutdownGroup.Add(closer.CloserFunc(dataUpdater.Stop))
|
||||||
|
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
|
|
||||||
|
@ -107,3 +107,54 @@ type AmocrmUserInformation struct {
|
|||||||
} `json:"datetime_settings" bson:"datetime_settings"`
|
} `json:"datetime_settings" bson:"datetime_settings"`
|
||||||
} `json:"_embedded" bson:"_embedded"`
|
} `json:"_embedded" bson:"_embedded"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type LeadRights struct {
|
||||||
|
View string `json:"view"`
|
||||||
|
Edit string `json:"edit"`
|
||||||
|
Add string `json:"add"`
|
||||||
|
Delete string `json:"delete"`
|
||||||
|
Export string `json:"export"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ContactRights struct {
|
||||||
|
View string `json:"view"`
|
||||||
|
Edit string `json:"edit"`
|
||||||
|
Add string `json:"add"`
|
||||||
|
Delete string `json:"delete"`
|
||||||
|
Export string `json:"export"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompanyRights struct {
|
||||||
|
View string `json:"view"`
|
||||||
|
Edit string `json:"edit"`
|
||||||
|
Add string `json:"add"`
|
||||||
|
Delete string `json:"delete"`
|
||||||
|
Export string `json:"export"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskRights struct {
|
||||||
|
Edit string `json:"edit"`
|
||||||
|
Delete string `json:"delete"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type StatusRight struct {
|
||||||
|
EntityType string `json:"entity_type"`
|
||||||
|
PipelineID int `json:"pipeline_id"`
|
||||||
|
StatusID int `json:"status_id"`
|
||||||
|
Rights LeadRights `json:"rights"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type OneUserInfo struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Lang string `json:"lang"`
|
||||||
|
Role *string `json:"role,omitempty"`
|
||||||
|
UUID *string `json:"uuid,omitempty"`
|
||||||
|
Rights Rights `json:"rights"`
|
||||||
|
Links struct {
|
||||||
|
Self struct {
|
||||||
|
Href string `json:"href"`
|
||||||
|
} `json:"self"`
|
||||||
|
} `json:"_links"`
|
||||||
|
}
|
||||||
|
@ -15,7 +15,7 @@ type User struct {
|
|||||||
/* - айдишник пользвателя, который подключал интеграцию*/
|
/* - айдишник пользвателя, который подключал интеграцию*/
|
||||||
Amouserid int `json:"AmoUserID" bson:"Amouserid"`
|
Amouserid int `json:"AmoUserID" bson:"Amouserid"`
|
||||||
/* - связь с аккаунтом в амо*/
|
/* - связь с аккаунтом в амо*/
|
||||||
Amocrmid int `json:"AmocrmID" bson:"Amocrmid"`
|
Amocrmid int64 `json:"AmocrmID" bson:"Amocrmid"`
|
||||||
/* - страна указанная в настройках амо*/
|
/* - страна указанная в настройках амо*/
|
||||||
Country string `json:"Country" bson:"Country"`
|
Country string `json:"Country" bson:"Country"`
|
||||||
/* - таймштамп создания аккаунта*/
|
/* - таймштамп создания аккаунта*/
|
||||||
|
@ -2,8 +2,6 @@ package repository
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"amocrm/internal/models"
|
"amocrm/internal/models"
|
||||||
amo2 "amocrm/internal/models/amo"
|
|
||||||
"amocrm/internal/tools"
|
|
||||||
"context"
|
"context"
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
@ -58,18 +56,19 @@ func (r *Repository) CreateAccount(ctx context.Context, accountID string) error
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Repository) UpdateAccount(ctx context.Context, accountID string, userInfo *amo2.AmocrmUserInformation) error {
|
func (r *Repository) UpdateAccount(ctx context.Context, accountID string, userInfo models.User) error {
|
||||||
filter := bson.M{"AccountID": accountID}
|
filter := bson.M{"AccountID": accountID}
|
||||||
// todo надо как то получить роль и почту
|
|
||||||
update := bson.M{
|
update := bson.M{
|
||||||
"$set": bson.M{
|
"$set": bson.M{
|
||||||
"ID": userInfo.UUID, // uuid аккаунта
|
"ID": userInfo.ID,
|
||||||
"Name": userInfo.Name, // имя аккаунта амо
|
"Name": userInfo.Name,
|
||||||
"Amocrmid": userInfo.ID, // id аккаунта амо
|
"Amocrmid": userInfo.Amocrmid,
|
||||||
"Amouserid": userInfo.CurrentUserID, // id текущего пользователя в амо
|
"Amouserid": userInfo.Amouserid,
|
||||||
"Group": tools.ConvertUserGroups(userInfo), // группы пользователя
|
"Country": userInfo.Country,
|
||||||
"Country": userInfo.Country, // страна в настройках амо
|
"Subdomain": userInfo.Subdomain,
|
||||||
"Subdomain": userInfo.Subdomain, // поддомен организации
|
"Group": userInfo.Group,
|
||||||
|
"Role": userInfo.Role,
|
||||||
|
"Email": userInfo.Email,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,6 +3,7 @@ package service
|
|||||||
import (
|
import (
|
||||||
"amocrm/internal/models"
|
"amocrm/internal/models"
|
||||||
"amocrm/internal/models/amo"
|
"amocrm/internal/models/amo"
|
||||||
|
"amocrm/internal/tools"
|
||||||
"context"
|
"context"
|
||||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@ -35,20 +36,38 @@ func (s *Service) WebhookCreate(ctx context.Context, req ParamsWebhookCreate) er
|
|||||||
s.logger.Error("error getting webhook in Service:", zap.Error(err))
|
s.logger.Error("error getting webhook in Service:", zap.Error(err))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// получаем информацию о пользователе по аксес токену
|
|
||||||
|
// получаем информацию о пользователе по аксес токену и затем по его id
|
||||||
userInfo, err := s.amoClient.GetUserInfo(tokens.AccessToken)
|
userInfo, err := s.amoClient.GetUserInfo(tokens.AccessToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.logger.Error("error getting UserInfo in Service:", zap.Error(err))
|
s.logger.Error("error getting UserInfo in Service:", zap.Error(err))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// апдейтим информацио о аккаунте
|
|
||||||
err = s.repository.UpdateAccount(ctx, accountID, userInfo)
|
userInfoByID, err := s.amoClient.GetUserByID(tokens.AccessToken, userInfo.ID)
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Error("error getting GetUserByID in Service:", zap.Error(err))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
toUpdate := models.User{
|
||||||
|
ID: *userInfoByID.UUID,
|
||||||
|
Name: userInfoByID.Name,
|
||||||
|
Subdomain: userInfo.Subdomain,
|
||||||
|
Amocrmid: userInfo.ID,
|
||||||
|
Amouserid: userInfo.CurrentUserID,
|
||||||
|
Email: userInfoByID.Email,
|
||||||
|
Group: tools.ConvertUserGroups(userInfo),
|
||||||
|
Country: userInfo.Country,
|
||||||
|
Role: *userInfoByID.Role,
|
||||||
|
}
|
||||||
|
|
||||||
|
err = s.repository.UpdateAccount(ctx, accountID, toUpdate)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.logger.Error("error update account in mongo on service WebhookCreate", zap.Error(err))
|
s.logger.Error("error update account in mongo on service WebhookCreate", zap.Error(err))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// заносим в монгу токены обновлять токены видимо стоит где то за 2 минуты до их истечения то есть на 17-18 минутах
|
|
||||||
err = s.repository.WebhookCreate(ctx, models.Token{
|
err = s.repository.WebhookCreate(ctx, models.Token{
|
||||||
ObjID: primitive.NewObjectID(),
|
ObjID: primitive.NewObjectID(),
|
||||||
RefreshToken: tokens.RefreshToken,
|
RefreshToken: tokens.RefreshToken,
|
||||||
|
@ -288,7 +288,7 @@ func (a *Amo) GetUserInfo(accessToken string) (*amo2.AmocrmUserInformation, erro
|
|||||||
for _, err := range errs {
|
for _, err := range errs {
|
||||||
a.logger.Error("error sending request in GetUserInfo", zap.Error(err))
|
a.logger.Error("error sending request in GetUserInfo", zap.Error(err))
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("request GetListTags failed: %v", errs[0])
|
return nil, fmt.Errorf("request GetUserInfo failed: %v", errs[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
if statusCode != fiber.StatusOK {
|
if statusCode != fiber.StatusOK {
|
||||||
@ -309,3 +309,36 @@ func (a *Amo) GetUserInfo(accessToken string) (*amo2.AmocrmUserInformation, erro
|
|||||||
time.Sleep(a.rateLimiter.interval)
|
time.Sleep(a.rateLimiter.interval)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *Amo) GetUserByID(accessToken string, id int64) (*amo2.OneUserInfo, error) {
|
||||||
|
for {
|
||||||
|
if a.rateLimiter.Check() {
|
||||||
|
uri := fmt.Sprintf("%s/api/v4/users/%d?with=role,uuid", a.baseApiURL, id)
|
||||||
|
agent := a.fiberClient.Get(a.baseApiURL + uri)
|
||||||
|
agent.Set("Authorization", "Bearer "+accessToken)
|
||||||
|
statusCode, resBody, errs := agent.Bytes()
|
||||||
|
if len(errs) > 0 {
|
||||||
|
for _, err := range errs {
|
||||||
|
a.logger.Error("error sending request in GetUserByID", zap.Error(err))
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("request GetUserByID failed: %v", errs[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
if statusCode != fiber.StatusOK {
|
||||||
|
errorMessage := fmt.Sprintf("received an incorrect response from GetUserByID: %d", statusCode)
|
||||||
|
a.logger.Error(errorMessage, zap.Int("status", statusCode))
|
||||||
|
return nil, fmt.Errorf(errorMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
var userInfo amo2.OneUserInfo
|
||||||
|
err := json.Unmarshal(resBody, &userInfo)
|
||||||
|
if err != nil {
|
||||||
|
a.logger.Error("error unmarshal OneUserInfo:", zap.Error(err))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &userInfo, nil
|
||||||
|
}
|
||||||
|
time.Sleep(a.rateLimiter.interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user