50c018af62
continuous-integration/drone/push Build is passing
- Introduced CompanyContextMiddleware to resolve the active company context for customer requests, ensuring that tender recommendations and company-scoped APIs remain in sync with the database. - Updated public routes to utilize the new CompanyContextMiddleware alongside the existing AuthMiddleware, improving the handling of company-specific requests. - Added unit tests for the pickActiveCompanyID function to validate the logic for selecting the appropriate company context based on customer assignments and requested company IDs. This update enhances the accuracy and reliability of company context management in the application, improving user experience and data consistency.
50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package customer
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
var errCompanyNotAssigned = errors.New("company is not assigned to customer")
|
|
|
|
// pickActiveCompanyID chooses the company context for a customer request.
|
|
// When requestedCompanyID is set it must be in assigned; otherwise a still-valid
|
|
// token company is kept; if the token company was removed, the first assignment is used.
|
|
func pickActiveCompanyID(assigned []string, tokenCompanyID, requestedCompanyID string) (string, error) {
|
|
if len(assigned) == 0 {
|
|
return "", nil
|
|
}
|
|
|
|
requested := strings.TrimSpace(requestedCompanyID)
|
|
if requested != "" {
|
|
for _, id := range assigned {
|
|
if id == requested {
|
|
return requested, nil
|
|
}
|
|
}
|
|
return "", errCompanyNotAssigned
|
|
}
|
|
|
|
token := strings.TrimSpace(tokenCompanyID)
|
|
if token != "" {
|
|
for _, id := range assigned {
|
|
if id == token {
|
|
return token, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
return assigned[0], nil
|
|
}
|
|
|
|
// ResolveActiveCompanyID resolves the active company for an authenticated customer.
|
|
func (s *customerService) ResolveActiveCompanyID(ctx context.Context, customerID, tokenCompanyID, requestedCompanyID string) (string, error) {
|
|
customer, err := s.repository.GetByID(ctx, customerID)
|
|
if err != nil {
|
|
return "", errors.New("customer not found")
|
|
}
|
|
|
|
return pickActiveCompanyID(customer.Companies, tokenCompanyID, requestedCompanyID)
|
|
}
|