rpaas-core-service/pkg/services/branchService.go

58 lines
1.7 KiB
Go
Raw Normal View History

2024-05-03 11:57:03 +00:00
package services
2024-05-03 11:57:06 +00:00
import (
"context"
2024-05-03 12:41:51 +00:00
"errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"pkg.jojmatic.com/root/rpaas-core-service/pkg/logging"
2024-05-03 11:57:06 +00:00
"pkg.jojmatic.com/root/rpaas-core-service/pkg/models"
2024-05-03 12:41:51 +00:00
"time"
2024-05-03 11:57:06 +00:00
)
type BranchService interface {
2024-05-03 12:41:51 +00:00
RegisterBranch(body *models.BranchRegisterBody, info *models.CompanyInfo) (*models.BranchInfo, error)
2024-05-03 11:57:06 +00:00
}
type BranchServiceImpl struct {
2024-05-03 12:41:51 +00:00
branchcollection *mongo.Collection
ctx context.Context
2024-05-03 11:57:06 +00:00
}
2024-05-03 12:41:51 +00:00
func NewBranchService(collection *mongo.Collection, ctx context.Context) *BranchServiceImpl {
2024-05-03 11:57:06 +00:00
return &BranchServiceImpl{
2024-05-03 12:41:51 +00:00
branchcollection: collection,
ctx: ctx,
2024-05-03 11:57:06 +00:00
}
}
2024-05-03 12:41:51 +00:00
func (bc *BranchServiceImpl) RegisterBranch(body *models.BranchRegisterBody, info *models.CompanyInfo) (*models.BranchInfo, error) {
2024-05-03 11:57:06 +00:00
2024-05-03 12:41:51 +00:00
var branchexisting *models.BranchInfo
err := bc.branchcollection.FindOne(bc.ctx, bson.M{"$and": []bson.M{{"branch_name": body.BranchName}, {"company_id": body.CompanyID}}}).Decode(&branchexisting)
if err == nil {
logging.Logger().Warn("Branch name already exists", err)
return nil, errors.New("branch name already exists")
} else if !errors.Is(err, mongo.ErrNoDocuments) {
logging.Logger().Error(err)
return nil, errors.New("InternalServerError")
2024-05-03 11:57:06 +00:00
}
2024-05-03 12:41:51 +00:00
branchInfo := &models.BranchInfo{
BranchName: body.BranchName,
BranchID: primitive.NewObjectID().Hex(),
CompanyID: body.CompanyID,
Owner: info.Owner,
CreateAt: time.Now().UTC().Round(time.Second),
UpdateAt: time.Now().UTC().Round(time.Second),
2024-05-03 11:57:06 +00:00
}
2024-05-03 12:41:51 +00:00
_, err = bc.branchcollection.InsertOne(bc.ctx, branchInfo)
if err != nil {
logging.Logger().Error(err)
2024-05-03 11:57:06 +00:00
return nil, err
}
2024-05-03 12:41:51 +00:00
return branchInfo, nil
2024-05-03 11:57:06 +00:00
}