Refactor customer domain to use string IDs and integrate MongoDB ORM

- Updated Customer entity to embed MongoDB model and replace uuid.UUID with string for ID fields.
- Modified repository methods to accept string IDs instead of uuid.UUID, enhancing compatibility with MongoDB.
- Refactored service and handler methods to align with the new ID type, ensuring consistent usage across customer management functionality.
- Improved response handling in CustomerResponse to directly use string IDs.
- Streamlined index creation in the customer repository using the MongoDB ORM for better maintainability.
- Added new forms for customer suspension and updated validation rules.
- Enhanced Swagger documentation for customer-related endpoints to reflect changes in ID handling and request structures.
This commit is contained in:
n.nakhostin
2025-08-11 14:01:36 +03:30
parent 08cf927294
commit ce4f7e83d3
6 changed files with 604 additions and 618 deletions
+95 -116
View File
@@ -16,35 +16,35 @@ import (
// Service defines business logic for customer operations
type Service interface {
// Core customer operations
CreateCustomer(ctx context.Context, form *CreateCustomerForm, createdBy *uuid.UUID) (*Customer, error)
GetCustomerByID(ctx context.Context, id uuid.UUID) (*Customer, error)
UpdateCustomer(ctx context.Context, id uuid.UUID, form *UpdateCustomerForm, updatedBy *uuid.UUID) (*Customer, error)
DeleteCustomer(ctx context.Context, id uuid.UUID, deletedBy *uuid.UUID) error
CreateCustomer(ctx context.Context, form *CreateCustomerForm, createdBy *string) (*Customer, error)
GetCustomerByID(ctx context.Context, id string) (*Customer, error)
UpdateCustomer(ctx context.Context, id string, form *UpdateCustomerForm, updatedBy *string) (*Customer, error)
DeleteCustomer(ctx context.Context, id string, deletedBy *string) error
// Customer listing and search
ListCustomers(ctx context.Context, form *ListCustomersForm) (*CustomerListResponse, error)
GetCustomersByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*Customer, int64, error)
GetCustomersByCompanyID(ctx context.Context, companyID string, limit, offset int) ([]*Customer, int64, error)
GetCustomersByType(ctx context.Context, customerType CustomerType, limit, offset int) ([]*Customer, int64, error)
GetCustomersByStatus(ctx context.Context, status CustomerStatus, limit, offset int) ([]*Customer, int64, error)
// Customer management
UpdateCustomerStatus(ctx context.Context, id uuid.UUID, form *UpdateCustomerStatusForm, updatedBy *uuid.UUID) error
UpdateCustomerVerification(ctx context.Context, id uuid.UUID, form *UpdateCustomerVerificationForm, updatedBy *uuid.UUID) error
UpdateCustomerStatus(ctx context.Context, id string, form *UpdateCustomerStatusForm, updatedBy *string) error
UpdateCustomerVerification(ctx context.Context, id string, form *UpdateCustomerVerificationForm, updatedBy *string) error
// Mobile-specific operations (simplified)
CreateCustomerMobile(ctx context.Context, form *CreateCustomerMobileForm, createdBy *uuid.UUID) (*Customer, error)
UpdateCustomerMobile(ctx context.Context, id uuid.UUID, form *UpdateCustomerMobileForm, updatedBy *uuid.UUID) (*Customer, error)
CreateCustomerMobile(ctx context.Context, form *CreateCustomerMobileForm, createdBy *string) (*Customer, error)
UpdateCustomerMobile(ctx context.Context, id string, form *UpdateCustomerMobileForm, updatedBy *string) (*Customer, error)
// Business operations
VerifyCustomer(ctx context.Context, id uuid.UUID, verifiedBy *uuid.UUID) error
SuspendCustomer(ctx context.Context, id uuid.UUID, reason string, suspendedBy *uuid.UUID) error
ActivateCustomer(ctx context.Context, id uuid.UUID, activatedBy *uuid.UUID) error
VerifyCustomer(ctx context.Context, id string, verifiedBy *string) error
SuspendCustomer(ctx context.Context, id string, reason string, suspendedBy *string) error
ActivateCustomer(ctx context.Context, id string, activatedBy *string) error
// Authentication operations
Login(ctx context.Context, form *LoginForm) (*AuthResponse, error)
RefreshToken(ctx context.Context, refreshToken string) (*AuthResponse, error)
GetProfile(ctx context.Context, customerID uuid.UUID) (*Customer, error)
Logout(ctx context.Context, customerID uuid.UUID, accessToken string) error
GetProfile(ctx context.Context, customerID string) (*Customer, error)
Logout(ctx context.Context, customerID string, accessToken string) error
}
// customerService implements the Service interface
@@ -64,7 +64,7 @@ func NewCustomerService(repository Repository, logger logger.Logger, authService
}
// CreateCustomer creates a new customer
func (s *customerService) CreateCustomer(ctx context.Context, form *CreateCustomerForm, createdBy *uuid.UUID) (*Customer, error) {
func (s *customerService) CreateCustomer(ctx context.Context, form *CreateCustomerForm, createdBy *string) (*Customer, error) {
// Check if email already exists
existingCustomer, _ := s.repository.GetByEmail(ctx, form.Email)
if existingCustomer != nil {
@@ -96,27 +96,31 @@ func (s *customerService) CreateCustomer(ctx context.Context, form *CreateCustom
}
// Parse company ID if provided
var companyID *uuid.UUID
var companyID *string
if form.CompanyID != nil {
parsedID, err := uuid.Parse(*form.CompanyID)
if err != nil {
return nil, errors.New("invalid company ID")
}
companyID = &parsedID
companyID = form.CompanyID
}
// Hash password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)
if err != nil {
s.logger.Error("Failed to hash password", map[string]interface{}{
"error": err.Error(),
})
return nil, errors.New("failed to process password")
}
// Create customer
customer := &Customer{
ID: uuid.New(),
Type: CustomerType(form.Type),
Status: CustomerStatusActive,
Status: CustomerStatusPending,
CompanyID: companyID,
FirstName: form.FirstName,
LastName: form.LastName,
FullName: form.FullName,
Username: form.Username,
Email: form.Email,
Password: "", // Will be set after hashing
Password: string(hashedPassword),
Phone: form.Phone,
Mobile: form.Mobile,
CompanyName: form.CompanyName,
@@ -134,56 +138,43 @@ func (s *customerService) CreateCustomer(ctx context.Context, form *CreateCustom
Language: s.getDefaultLanguage(form.Language),
Currency: s.getDefaultCurrency(form.Currency),
Timezone: s.getDefaultTimezone(form.Timezone),
CreatedAt: time.Now().Unix(),
UpdatedAt: time.Now().Unix(),
CreatedBy: createdBy,
}
// Hash password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)
if err != nil {
s.logger.Error("Failed to hash password", map[string]interface{}{
"error": err.Error(),
})
return nil, errors.New("failed to process password")
}
customer.Password = string(hashedPassword)
// Save to database
err = s.repository.Create(ctx, customer)
if err != nil {
s.logger.Error("Failed to create customer", map[string]interface{}{
"error": err.Error(),
"email": form.Email,
"type": form.Type,
"created_by": createdBy.String(),
"error": err.Error(),
"email": form.Email,
"username": form.Username,
})
return nil, err
}
s.logger.Info("Customer created successfully", map[string]interface{}{
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"email": customer.Email,
"type": customer.Type,
"created_by": createdBy.String(),
"created_by": *createdBy,
})
return customer, nil
}
// GetCustomerByID retrieves a customer by ID
func (s *customerService) GetCustomerByID(ctx context.Context, id uuid.UUID) (*Customer, error) {
func (s *customerService) GetCustomerByID(ctx context.Context, id string) (*Customer, error) {
customer, err := s.repository.GetByID(ctx, id)
if err != nil {
s.logger.Error("Failed to get customer by ID", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return nil, err
}
s.logger.Info("Customer retrieved successfully", map[string]interface{}{
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"email": customer.Email,
})
@@ -191,13 +182,13 @@ func (s *customerService) GetCustomerByID(ctx context.Context, id uuid.UUID) (*C
}
// UpdateCustomer updates a customer
func (s *customerService) UpdateCustomer(ctx context.Context, id uuid.UUID, form *UpdateCustomerForm, updatedBy *uuid.UUID) (*Customer, error) {
func (s *customerService) UpdateCustomer(ctx context.Context, id string, form *UpdateCustomerForm, updatedBy *string) (*Customer, error) {
// Get existing customer
customer, err := s.repository.GetByID(ctx, id)
if err != nil {
s.logger.Error("Failed to get customer for update", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return nil, errors.New("customer not found")
}
@@ -253,11 +244,7 @@ func (s *customerService) UpdateCustomer(ctx context.Context, id uuid.UUID, form
}
if form.CompanyID != nil {
parsedID, err := uuid.Parse(*form.CompanyID)
if err != nil {
return nil, errors.New("invalid company ID")
}
customer.CompanyID = &parsedID
customer.CompanyID = form.CompanyID
}
if form.FirstName != nil {
@@ -329,22 +316,22 @@ func (s *customerService) UpdateCustomer(ctx context.Context, id uuid.UUID, form
if err != nil {
s.logger.Error("Failed to update customer", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return nil, errors.New("failed to update customer")
}
s.logger.Info("Customer updated successfully", map[string]interface{}{
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"email": customer.Email,
"updated_by": updatedBy.String(),
"updated_by": *updatedBy,
})
return customer, nil
}
// DeleteCustomer deletes a customer (soft delete)
func (s *customerService) DeleteCustomer(ctx context.Context, id uuid.UUID, deletedBy *uuid.UUID) error {
func (s *customerService) DeleteCustomer(ctx context.Context, id string, deletedBy *string) error {
// Get customer to check if exists
customer, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -359,14 +346,14 @@ func (s *customerService) DeleteCustomer(ctx context.Context, id uuid.UUID, dele
if err != nil {
s.logger.Error("Failed to delete customer", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return errors.New("failed to delete customer")
}
s.logger.Info("Customer deleted successfully", map[string]interface{}{
"customer_id": id.String(),
"deleted_by": deletedBy.String(),
"customer_id": id,
"deleted_by": deletedBy,
})
return nil
@@ -401,13 +388,9 @@ func (s *customerService) ListCustomers(ctx context.Context, form *ListCustomers
}
// Parse company ID if provided
var companyID *uuid.UUID
var companyID *string
if form.CompanyID != nil {
parsedID, err := uuid.Parse(*form.CompanyID)
if err != nil {
return nil, errors.New("invalid company ID")
}
companyID = &parsedID
companyID = form.CompanyID
}
// Get customers
@@ -439,12 +422,12 @@ func (s *customerService) ListCustomers(ctx context.Context, form *ListCustomers
}
// GetCustomersByCompanyID retrieves customers by company ID with pagination
func (s *customerService) GetCustomersByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*Customer, int64, error) {
func (s *customerService) GetCustomersByCompanyID(ctx context.Context, companyID string, limit, offset int) ([]*Customer, int64, error) {
customers, err := s.repository.GetByCompanyID(ctx, companyID, limit, offset)
if err != nil {
s.logger.Error("Failed to get customers by company ID", map[string]interface{}{
"error": err.Error(),
"company_id": companyID.String(),
"company_id": companyID,
})
return nil, 0, errors.New("failed to get customers by company")
}
@@ -454,7 +437,7 @@ func (s *customerService) GetCustomersByCompanyID(ctx context.Context, companyID
if err != nil {
s.logger.Error("Failed to count customers by company ID", map[string]interface{}{
"error": err.Error(),
"company_id": companyID.String(),
"company_id": companyID,
})
return customers, 0, nil // Return customers even if count fails
}
@@ -517,7 +500,7 @@ func (s *customerService) GetCustomersByStatus(ctx context.Context, status Custo
}
// UpdateCustomerStatus updates customer status
func (s *customerService) UpdateCustomerStatus(ctx context.Context, id uuid.UUID, form *UpdateCustomerStatusForm, updatedBy *uuid.UUID) error {
func (s *customerService) UpdateCustomerStatus(ctx context.Context, id string, form *UpdateCustomerStatusForm, updatedBy *string) error {
// Get customer to check if exists
_, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -530,23 +513,23 @@ func (s *customerService) UpdateCustomerStatus(ctx context.Context, id uuid.UUID
if err != nil {
s.logger.Error("Failed to update customer status", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
"status": form.Status,
})
return errors.New("failed to update customer status")
}
s.logger.Info("Customer status updated successfully", map[string]interface{}{
"customer_id": id.String(),
"customer_id": id,
"status": form.Status,
"updated_by": updatedBy.String(),
"updated_by": updatedBy,
})
return nil
}
// UpdateCustomerVerification updates customer verification status
func (s *customerService) UpdateCustomerVerification(ctx context.Context, id uuid.UUID, form *UpdateCustomerVerificationForm, updatedBy *uuid.UUID) error {
func (s *customerService) UpdateCustomerVerification(ctx context.Context, id string, form *UpdateCustomerVerificationForm, updatedBy *string) error {
// Get customer to check if exists
_, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -558,23 +541,23 @@ func (s *customerService) UpdateCustomerVerification(ctx context.Context, id uui
if err != nil {
s.logger.Error("Failed to update customer verification", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return errors.New("failed to update customer verification")
}
s.logger.Info("Customer verification updated successfully", map[string]interface{}{
"customer_id": id.String(),
"customer_id": id,
"is_verified": form.IsVerified,
"is_compliant": form.IsCompliant,
"updated_by": updatedBy.String(),
"updated_by": updatedBy,
})
return nil
}
// CreateCustomerMobile creates a new customer via mobile app (simplified)
func (s *customerService) CreateCustomerMobile(ctx context.Context, form *CreateCustomerMobileForm, createdBy *uuid.UUID) (*Customer, error) {
func (s *customerService) CreateCustomerMobile(ctx context.Context, form *CreateCustomerMobileForm, createdBy *string) (*Customer, error) {
// Check if email already exists
existingCustomer, _ := s.repository.GetByEmail(ctx, form.Email)
if existingCustomer != nil {
@@ -583,7 +566,6 @@ func (s *customerService) CreateCustomerMobile(ctx context.Context, form *Create
// Create customer with mobile form
customer := &Customer{
ID: uuid.New(),
Type: CustomerType(form.Type),
Status: CustomerStatusActive,
FirstName: form.FirstName,
@@ -601,8 +583,6 @@ func (s *customerService) CreateCustomerMobile(ctx context.Context, form *Create
Language: "en",
Currency: "USD",
Timezone: "UTC",
CreatedAt: time.Now().Unix(),
UpdatedAt: time.Now().Unix(),
CreatedBy: createdBy,
}
@@ -623,23 +603,23 @@ func (s *customerService) CreateCustomerMobile(ctx context.Context, form *Create
"error": err.Error(),
"email": form.Email,
"type": form.Type,
"created_by": createdBy.String(),
"created_by": createdBy,
})
return nil, err
}
s.logger.Info("Customer created via mobile successfully", map[string]interface{}{
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"email": customer.Email,
"type": customer.Type,
"created_by": createdBy.String(),
"created_by": *createdBy,
})
return customer, nil
}
// UpdateCustomerMobile updates a customer via mobile app (simplified)
func (s *customerService) UpdateCustomerMobile(ctx context.Context, id uuid.UUID, form *UpdateCustomerMobileForm, updatedBy *uuid.UUID) (*Customer, error) {
func (s *customerService) UpdateCustomerMobile(ctx context.Context, id string, form *UpdateCustomerMobileForm, updatedBy *string) (*Customer, error) {
// Get existing customer
customer, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -683,22 +663,22 @@ func (s *customerService) UpdateCustomerMobile(ctx context.Context, id uuid.UUID
if err != nil {
s.logger.Error("Failed to update customer via mobile", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return nil, errors.New("failed to update customer")
}
s.logger.Info("Customer updated via mobile successfully", map[string]interface{}{
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"email": customer.Email,
"updated_by": updatedBy.String(),
"updated_by": *updatedBy,
})
return customer, nil
}
// VerifyCustomer verifies a customer
func (s *customerService) VerifyCustomer(ctx context.Context, id uuid.UUID, verifiedBy *uuid.UUID) error {
func (s *customerService) VerifyCustomer(ctx context.Context, id string, verifiedBy *string) error {
// Get customer to check if exists
customer, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -710,21 +690,21 @@ func (s *customerService) VerifyCustomer(ctx context.Context, id uuid.UUID, veri
if err != nil {
s.logger.Error("Failed to verify customer", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return errors.New("failed to verify customer")
}
s.logger.Info("Customer verified successfully", map[string]interface{}{
"customer_id": id.String(),
"verified_by": verifiedBy.String(),
"customer_id": id,
"verified_by": verifiedBy,
})
return nil
}
// SuspendCustomer suspends a customer
func (s *customerService) SuspendCustomer(ctx context.Context, id uuid.UUID, reason string, suspendedBy *uuid.UUID) error {
func (s *customerService) SuspendCustomer(ctx context.Context, id string, reason string, suspendedBy *string) error {
// Get customer to check if exists
_, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -736,22 +716,22 @@ func (s *customerService) SuspendCustomer(ctx context.Context, id uuid.UUID, rea
if err != nil {
s.logger.Error("Failed to suspend customer", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return errors.New("failed to suspend customer")
}
s.logger.Info("Customer suspended successfully", map[string]interface{}{
"customer_id": id.String(),
"customer_id": id,
"reason": reason,
"suspended_by": suspendedBy.String(),
"suspended_by": suspendedBy,
})
return nil
}
// ActivateCustomer activates a customer
func (s *customerService) ActivateCustomer(ctx context.Context, id uuid.UUID, activatedBy *uuid.UUID) error {
func (s *customerService) ActivateCustomer(ctx context.Context, id string, activatedBy *string) error {
// Get customer to check if exists
_, err := s.repository.GetByID(ctx, id)
if err != nil {
@@ -763,14 +743,14 @@ func (s *customerService) ActivateCustomer(ctx context.Context, id uuid.UUID, ac
if err != nil {
s.logger.Error("Failed to activate customer", map[string]interface{}{
"error": err.Error(),
"customer_id": id.String(),
"customer_id": id,
})
return errors.New("failed to activate customer")
}
s.logger.Info("Customer activated successfully", map[string]interface{}{
"customer_id": id.String(),
"activated_by": activatedBy.String(),
"customer_id": id,
"activated_by": activatedBy,
})
return nil
@@ -795,7 +775,7 @@ func (s *customerService) Login(ctx context.Context, form *LoginForm) (*AuthResp
if customer.Status != CustomerStatusActive {
s.logger.Warn("Customer login failed - account not active", map[string]interface{}{
"username": form.Username,
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"status": string(customer.Status),
})
return nil, errors.New("account is not active")
@@ -805,7 +785,7 @@ func (s *customerService) Login(ctx context.Context, form *LoginForm) (*AuthResp
err = bcrypt.CompareHashAndPassword([]byte(customer.Password), []byte(form.Password))
if err != nil {
s.logger.Warn("Customer login failed - wrong password", map[string]interface{}{
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"email": customer.Email,
})
return nil, errors.New("invalid credentials")
@@ -814,11 +794,11 @@ func (s *customerService) Login(ctx context.Context, form *LoginForm) (*AuthResp
// Generate JWT tokens using authorization service
companyID := ""
if customer.CompanyID != nil {
companyID = customer.CompanyID.String()
companyID = *customer.CompanyID
}
tokenPair, err := s.authService.GenerateTokenPair(
customer.ID.String(),
customer.ID,
customer.Email,
"customer", // Role for customers
companyID,
@@ -826,14 +806,14 @@ func (s *customerService) Login(ctx context.Context, form *LoginForm) (*AuthResp
if err != nil {
s.logger.Error("Failed to generate JWT tokens", map[string]interface{}{
"error": err.Error(),
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
})
return nil, errors.New("failed to generate authentication tokens")
}
s.logger.Info("Customer login successful", map[string]interface{}{
"username": form.Username,
"customer_id": customer.ID.String(),
"customer_id": customer.ID,
"customer_type": string(customer.Type),
})
@@ -885,7 +865,7 @@ func (s *customerService) RefreshToken(ctx context.Context, refreshToken string)
return nil, errors.New("invalid token format")
}
customer, err := s.repository.GetByID(ctx, customerID)
customer, err := s.repository.GetByID(ctx, customerID.String())
if err != nil {
s.logger.Error("Failed to get customer for token refresh", map[string]interface{}{
"error": err.Error(),
@@ -900,8 +880,7 @@ func (s *customerService) RefreshToken(ctx context.Context, refreshToken string)
}
s.logger.Info("Access token refreshed successfully", map[string]interface{}{
"customer_id": customer.ID.String(),
"email": customer.Email,
"customer_id": customer.ID,
"customer_type": string(customer.Type),
})
@@ -914,22 +893,22 @@ func (s *customerService) RefreshToken(ctx context.Context, refreshToken string)
}
// GetProfile retrieves customer profile information
func (s *customerService) GetProfile(ctx context.Context, customerID uuid.UUID) (*Customer, error) {
func (s *customerService) GetProfile(ctx context.Context, customerID string) (*Customer, error) {
s.logger.Info("Getting customer profile", map[string]interface{}{
"customer_id": customerID.String(),
"customer_id": customerID,
})
customer, err := s.repository.GetByID(ctx, customerID)
if err != nil {
s.logger.Error("Failed to get customer profile", map[string]interface{}{
"error": err.Error(),
"customer_id": customerID.String(),
"customer_id": customerID,
})
return nil, errors.New("customer not found")
}
s.logger.Info("Customer profile retrieved successfully", map[string]interface{}{
"customer_id": customerID.String(),
"customer_id": customerID,
"customer_type": string(customer.Type),
})
@@ -937,9 +916,9 @@ func (s *customerService) GetProfile(ctx context.Context, customerID uuid.UUID)
}
// Logout handles customer logout
func (s *customerService) Logout(ctx context.Context, customerID uuid.UUID, accessToken string) error {
func (s *customerService) Logout(ctx context.Context, customerID string, accessToken string) error {
s.logger.Info("Customer logout", map[string]interface{}{
"customer_id": customerID.String(),
"customer_id": customerID,
"access_token": accessToken[:10] + "...", // Log only first 10 chars for security
})
@@ -948,13 +927,13 @@ func (s *customerService) Logout(ctx context.Context, customerID uuid.UUID, acce
if err != nil {
s.logger.Error("Failed to invalidate access token", map[string]interface{}{
"error": err.Error(),
"customer_id": customerID.String(),
"customer_id": customerID,
})
// Don't return error here as the customer should still be logged out
}
s.logger.Info("Customer logout successful", map[string]interface{}{
"customer_id": customerID.String(),
"customer_id": customerID,
})
return nil