package services import ( "context" "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" "pkg.jojmatic.com/root/rpaas-core-service/pkg/models" "time" ) type BranchService interface { RegisterBranch(body *models.BranchRegisterBody, info *models.CompanyInfo) (*models.BranchInfo, error) } type BranchServiceImpl struct { branchcollection *mongo.Collection ctx context.Context } func NewBranchService(collection *mongo.Collection, ctx context.Context) *BranchServiceImpl { return &BranchServiceImpl{ branchcollection: collection, ctx: ctx, } } func (bc *BranchServiceImpl) RegisterBranch(body *models.BranchRegisterBody, info *models.CompanyInfo) (*models.BranchInfo, error) { 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") } 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), } _, err = bc.branchcollection.InsertOne(bc.ctx, branchInfo) if err != nil { logging.Logger().Error(err) return nil, err } return branchInfo, nil }