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:
+264
-265
@@ -7,162 +7,94 @@ import (
|
||||
"tm/pkg/logger"
|
||||
mongopkg "tm/pkg/mongo"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
// Repository defines the interface for customer data operations
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, customer *Customer) error
|
||||
GetByID(ctx context.Context, id uuid.UUID) (*Customer, error)
|
||||
GetByID(ctx context.Context, id string) (*Customer, error)
|
||||
GetByEmail(ctx context.Context, email string) (*Customer, error)
|
||||
GetByUsername(ctx context.Context, username string) (*Customer, error)
|
||||
GetByCompanyName(ctx context.Context, companyName string) (*Customer, error)
|
||||
GetByRegistrationNumber(ctx context.Context, registrationNumber string) (*Customer, error)
|
||||
GetByTaxID(ctx context.Context, taxID string) (*Customer, error)
|
||||
GetByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*Customer, error)
|
||||
GetByCompanyID(ctx context.Context, companyID string, limit, offset int) ([]*Customer, error)
|
||||
Update(ctx context.Context, customer *Customer) error
|
||||
Delete(ctx context.Context, id uuid.UUID) error
|
||||
Delete(ctx context.Context, id string) error
|
||||
List(ctx context.Context, limit, offset int) ([]*Customer, error)
|
||||
Search(ctx context.Context, search string, customerType *string, status *string, companyID *uuid.UUID, industry *string, isVerified *bool, isCompliant *bool, language *string, currency *string, limit, offset int, sortBy, sortOrder string) ([]*Customer, error)
|
||||
CountByCompanyID(ctx context.Context, companyID uuid.UUID) (int64, error)
|
||||
Search(ctx context.Context, search string, customerType *string, status *string, companyID *string, industry *string, isVerified *bool, isCompliant *bool, language *string, currency *string, limit, offset int, sortBy, sortOrder string) ([]*Customer, error)
|
||||
CountByCompanyID(ctx context.Context, companyID string) (int64, error)
|
||||
CountByType(ctx context.Context, customerType CustomerType) (int64, error)
|
||||
CountByStatus(ctx context.Context, status CustomerStatus) (int64, error)
|
||||
UpdateStatus(ctx context.Context, id uuid.UUID, status CustomerStatus) error
|
||||
UpdateVerification(ctx context.Context, id uuid.UUID, isVerified, isCompliant bool, complianceNotes *string) error
|
||||
UpdateStatus(ctx context.Context, id string, status CustomerStatus) error
|
||||
UpdateVerification(ctx context.Context, id string, isVerified, isCompliant bool, complianceNotes *string) error
|
||||
}
|
||||
|
||||
// customerRepository implements the Repository interface
|
||||
// customerRepository implements the Repository interface using the MongoDB ORM
|
||||
type customerRepository struct {
|
||||
collection *mongo.Collection
|
||||
logger logger.Logger
|
||||
ormRepo mongopkg.Repository[Customer]
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// NewCustomerRepository creates a new customer repository
|
||||
func NewCustomerRepository(mongoManager *mongopkg.ConnectionManager, logger logger.Logger) Repository {
|
||||
collection := mongoManager.GetCollection("customers")
|
||||
|
||||
// Create indexes
|
||||
repo := &customerRepository{
|
||||
collection: collection,
|
||||
logger: logger,
|
||||
// Create indexes using the ORM's index management
|
||||
indexes := []mongopkg.Index{
|
||||
*mongopkg.CreateUniqueIndex("email_idx", bson.D{{Key: "email", Value: 1}}),
|
||||
*mongopkg.CreateUniqueIndex("username_idx", bson.D{{Key: "username", Value: 1}}),
|
||||
*mongopkg.NewIndex("company_name_idx", bson.D{{Key: "company_name", Value: 1}}),
|
||||
*mongopkg.NewIndex("registration_number_idx", bson.D{{Key: "registration_number", Value: 1}}),
|
||||
*mongopkg.NewIndex("tax_id_idx", bson.D{{Key: "tax_id", Value: 1}}),
|
||||
*mongopkg.NewIndex("company_id_idx", bson.D{{Key: "company_id", Value: 1}}),
|
||||
*mongopkg.NewIndex("type_idx", bson.D{{Key: "type", Value: 1}}),
|
||||
*mongopkg.NewIndex("status_idx", bson.D{{Key: "status", Value: 1}}),
|
||||
*mongopkg.NewIndex("industry_idx", bson.D{{Key: "industry", Value: 1}}),
|
||||
*mongopkg.NewIndex("is_verified_idx", bson.D{{Key: "is_verified", Value: 1}}),
|
||||
*mongopkg.NewIndex("is_compliant_idx", bson.D{{Key: "is_compliant", Value: 1}}),
|
||||
*mongopkg.NewIndex("language_idx", bson.D{{Key: "language", Value: 1}}),
|
||||
*mongopkg.NewIndex("currency_idx", bson.D{{Key: "currency", Value: 1}}),
|
||||
*mongopkg.NewIndex("created_at_idx", bson.D{{Key: "created_at", Value: -1}}),
|
||||
*mongopkg.CreateTextIndex("search_idx", "first_name", "last_name", "full_name", "company_name", "email", "username"),
|
||||
}
|
||||
|
||||
repo.createIndexes()
|
||||
return repo
|
||||
}
|
||||
|
||||
// createIndexes creates necessary database indexes
|
||||
func (r *customerRepository) createIndexes() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Create indexes
|
||||
indexes := []mongo.IndexModel{
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "email", Value: 1},
|
||||
},
|
||||
Options: options.Index().SetUnique(true),
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "username", Value: 1},
|
||||
},
|
||||
Options: options.Index().SetUnique(true),
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "company_name", Value: 1},
|
||||
},
|
||||
Options: options.Index().SetSparse(true),
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "registration_number", Value: 1},
|
||||
},
|
||||
Options: options.Index().SetSparse(true),
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "tax_id", Value: 1},
|
||||
},
|
||||
Options: options.Index().SetSparse(true),
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "company_id", Value: 1},
|
||||
},
|
||||
Options: options.Index().SetSparse(true),
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "type", Value: 1},
|
||||
},
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "status", Value: 1},
|
||||
},
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "industry", Value: 1},
|
||||
},
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "created_at", Value: -1},
|
||||
},
|
||||
},
|
||||
{
|
||||
Keys: bson.D{
|
||||
{Key: "updated_at", Value: -1},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := r.collection.Indexes().CreateMany(ctx, indexes)
|
||||
err := mongoManager.CreateIndexes("customers", indexes)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to create customer indexes", map[string]interface{}{
|
||||
logger.Warn("Failed to create customer indexes", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
} else {
|
||||
r.logger.Info("Customer indexes created successfully", map[string]interface{}{})
|
||||
}
|
||||
|
||||
// Create ORM repository
|
||||
ormRepo := mongopkg.NewRepository[Customer](mongoManager.GetCollection("customers"), logger)
|
||||
|
||||
return &customerRepository{
|
||||
ormRepo: ormRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates a new customer
|
||||
func (r *customerRepository) Create(ctx context.Context, customer *Customer) error {
|
||||
// Set timestamps
|
||||
// Set created/updated timestamps using Unix timestamps
|
||||
now := time.Now().Unix()
|
||||
customer.CreatedAt = now
|
||||
customer.UpdatedAt = now
|
||||
customer.SetCreatedAt(now)
|
||||
customer.SetUpdatedAt(now)
|
||||
|
||||
// Set defaults if not provided
|
||||
if customer.Language == "" {
|
||||
customer.Language = "en"
|
||||
}
|
||||
if customer.Currency == "" {
|
||||
customer.Currency = "USD"
|
||||
}
|
||||
if customer.Timezone == "" {
|
||||
customer.Timezone = "UTC"
|
||||
}
|
||||
|
||||
_, err := r.collection.InsertOne(ctx, customer)
|
||||
// Use ORM to create customer
|
||||
err := r.ormRepo.Create(ctx, customer)
|
||||
if err != nil {
|
||||
if mongo.IsDuplicateKeyError(err) {
|
||||
return errors.New("customer with this email already exists")
|
||||
}
|
||||
r.logger.Error("Failed to create customer", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"email": customer.Email,
|
||||
"username": customer.Username,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
r.logger.Info("Customer created successfully", map[string]interface{}{
|
||||
"customer_id": customer.ID.String(),
|
||||
"customer_id": customer.ID,
|
||||
"email": customer.Email,
|
||||
"type": customer.Type,
|
||||
})
|
||||
@@ -171,107 +103,143 @@ func (r *customerRepository) Create(ctx context.Context, customer *Customer) err
|
||||
}
|
||||
|
||||
// GetByID retrieves a customer by ID
|
||||
func (r *customerRepository) GetByID(ctx context.Context, id uuid.UUID) (*Customer, error) {
|
||||
var customer Customer
|
||||
err := r.collection.FindOne(ctx, bson.M{"_id": id}).Decode(&customer)
|
||||
func (r *customerRepository) GetByID(ctx context.Context, id string) (*Customer, error) {
|
||||
customer, err := r.ormRepo.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
r.logger.Error("Failed to get customer by ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"customer_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &customer, nil
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
// GetByEmail retrieves a customer by email
|
||||
func (r *customerRepository) GetByEmail(ctx context.Context, email string) (*Customer, error) {
|
||||
var customer Customer
|
||||
err := r.collection.FindOne(ctx, bson.M{"email": email}).Decode(&customer)
|
||||
filter := bson.M{"email": email}
|
||||
customer, err := r.ormRepo.FindOne(ctx, filter)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
r.logger.Error("Failed to get customer by email", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"email": email,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &customer, nil
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
// GetByUsername retrieves a customer by username
|
||||
func (r *customerRepository) GetByUsername(ctx context.Context, username string) (*Customer, error) {
|
||||
var customer Customer
|
||||
err := r.collection.FindOne(ctx, bson.M{"username": username}).Decode(&customer)
|
||||
filter := bson.M{"username": username}
|
||||
customer, err := r.ormRepo.FindOne(ctx, filter)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
r.logger.Error("Failed to get customer by username", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"username": username,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &customer, nil
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
// GetByCompanyName retrieves a customer by company name
|
||||
func (r *customerRepository) GetByCompanyName(ctx context.Context, companyName string) (*Customer, error) {
|
||||
var customer Customer
|
||||
err := r.collection.FindOne(ctx, bson.M{"company_name": companyName}).Decode(&customer)
|
||||
filter := bson.M{"company_name": companyName}
|
||||
customer, err := r.ormRepo.FindOne(ctx, filter)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
r.logger.Error("Failed to get customer by company name", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_name": companyName,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &customer, nil
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
// GetByRegistrationNumber retrieves a customer by registration number
|
||||
func (r *customerRepository) GetByRegistrationNumber(ctx context.Context, registrationNumber string) (*Customer, error) {
|
||||
var customer Customer
|
||||
err := r.collection.FindOne(ctx, bson.M{"registration_number": registrationNumber}).Decode(&customer)
|
||||
filter := bson.M{"registration_number": registrationNumber}
|
||||
customer, err := r.ormRepo.FindOne(ctx, filter)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
r.logger.Error("Failed to get customer by registration number", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"registration_number": registrationNumber,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &customer, nil
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
// GetByTaxID retrieves a customer by tax ID
|
||||
func (r *customerRepository) GetByTaxID(ctx context.Context, taxID string) (*Customer, error) {
|
||||
var customer Customer
|
||||
err := r.collection.FindOne(ctx, bson.M{"tax_id": taxID}).Decode(&customer)
|
||||
filter := bson.M{"tax_id": taxID}
|
||||
customer, err := r.ormRepo.FindOne(ctx, filter)
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
if errors.Is(err, mongopkg.ErrDocumentNotFound) {
|
||||
return nil, errors.New("customer not found")
|
||||
}
|
||||
r.logger.Error("Failed to get customer by tax ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"tax_id": taxID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &customer, nil
|
||||
return customer, nil
|
||||
}
|
||||
|
||||
// GetByCompanyID retrieves customers by company ID with pagination
|
||||
func (r *customerRepository) GetByCompanyID(ctx context.Context, companyID uuid.UUID, limit, offset int) ([]*Customer, error) {
|
||||
filter := bson.M{"company_id": companyID}
|
||||
func (r *customerRepository) GetByCompanyID(ctx context.Context, companyID string, limit, offset int) ([]*Customer, error) {
|
||||
// Build pagination
|
||||
pagination := mongopkg.NewPaginationBuilder().
|
||||
Limit(limit).
|
||||
Skip(offset).
|
||||
SortDesc("created_at").
|
||||
Build()
|
||||
|
||||
opts := options.Find().
|
||||
SetLimit(int64(limit)).
|
||||
SetSkip(int64(offset)).
|
||||
SetSort(bson.D{{Key: "created_at", Value: -1}})
|
||||
// Filter by company ID and active status
|
||||
filter := bson.M{
|
||||
"company_id": companyID,
|
||||
"status": bson.M{"$ne": CustomerStatusInactive},
|
||||
}
|
||||
|
||||
cursor, err := r.collection.Find(ctx, filter, opts)
|
||||
// Use ORM to find customers
|
||||
result, err := r.ormRepo.FindAll(ctx, filter, pagination)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to get customers by company ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
var customers []*Customer
|
||||
if err = cursor.All(ctx, &customers); err != nil {
|
||||
return nil, err
|
||||
// Convert []Customer to []*Customer
|
||||
customers := make([]*Customer, len(result.Items))
|
||||
for i := range result.Items {
|
||||
customers[i] = &result.Items[i]
|
||||
}
|
||||
|
||||
return customers, nil
|
||||
@@ -279,22 +247,21 @@ func (r *customerRepository) GetByCompanyID(ctx context.Context, companyID uuid.
|
||||
|
||||
// Update updates a customer
|
||||
func (r *customerRepository) Update(ctx context.Context, customer *Customer) error {
|
||||
customer.UpdatedAt = time.Now().Unix()
|
||||
// Set updated timestamp using Unix timestamp
|
||||
customer.SetUpdatedAt(time.Now().Unix())
|
||||
|
||||
filter := bson.M{"_id": customer.ID}
|
||||
update := bson.M{"$set": customer}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
// Use ORM to update customer
|
||||
err := r.ormRepo.Update(ctx, customer)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to update customer", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"customer_id": customer.ID,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("customer not found")
|
||||
}
|
||||
|
||||
r.logger.Info("Customer updated successfully", map[string]interface{}{
|
||||
"customer_id": customer.ID.String(),
|
||||
"customer_id": customer.ID,
|
||||
"email": customer.Email,
|
||||
})
|
||||
|
||||
@@ -302,26 +269,29 @@ func (r *customerRepository) Update(ctx context.Context, customer *Customer) err
|
||||
}
|
||||
|
||||
// Delete deletes a customer (soft delete by setting status to inactive)
|
||||
func (r *customerRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
filter := bson.M{"_id": id}
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"status": CustomerStatusInactive,
|
||||
"updated_at": time.Now().Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
func (r *customerRepository) Delete(ctx context.Context, id string) error {
|
||||
// Get customer first
|
||||
customer, err := r.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("customer not found")
|
||||
// Update status to inactive
|
||||
customer.Status = CustomerStatusInactive
|
||||
customer.SetUpdatedAt(time.Now().Unix())
|
||||
|
||||
// Update in database
|
||||
err = r.ormRepo.Update(ctx, customer)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to delete customer", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"customer_id": id,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
r.logger.Info("Customer deleted successfully", map[string]interface{}{
|
||||
"customer_id": id.String(),
|
||||
"customer_id": id,
|
||||
})
|
||||
|
||||
return nil
|
||||
@@ -329,124 +299,125 @@ func (r *customerRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
|
||||
// List retrieves customers with pagination
|
||||
func (r *customerRepository) List(ctx context.Context, limit, offset int) ([]*Customer, error) {
|
||||
opts := options.Find().
|
||||
SetLimit(int64(limit)).
|
||||
SetSkip(int64(offset)).
|
||||
SetSort(bson.D{{Key: "created_at", Value: -1}})
|
||||
// Build pagination
|
||||
pagination := mongopkg.NewPaginationBuilder().
|
||||
Limit(limit).
|
||||
Skip(offset).
|
||||
SortDesc("created_at").
|
||||
Build()
|
||||
|
||||
cursor, err := r.collection.Find(ctx, bson.M{}, opts)
|
||||
// Only active customers by default
|
||||
filter := bson.M{"status": bson.M{"$ne": CustomerStatusInactive}}
|
||||
|
||||
// Use ORM to find customers
|
||||
result, err := r.ormRepo.FindAll(ctx, filter, pagination)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to list customers", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
var customers []*Customer
|
||||
if err = cursor.All(ctx, &customers); err != nil {
|
||||
return nil, err
|
||||
// Convert []Customer to []*Customer
|
||||
customers := make([]*Customer, len(result.Items))
|
||||
for i := range result.Items {
|
||||
customers[i] = &result.Items[i]
|
||||
}
|
||||
|
||||
return customers, nil
|
||||
}
|
||||
|
||||
// Search searches customers with filters
|
||||
func (r *customerRepository) Search(ctx context.Context, search string, customerType *string, status *string, companyID *uuid.UUID, industry *string, isVerified *bool, isCompliant *bool, language *string, currency *string, limit, offset int, sortBy, sortOrder string) ([]*Customer, error) {
|
||||
// Search retrieves customers with search and filters
|
||||
func (r *customerRepository) Search(ctx context.Context, search string, customerType *string, status *string, companyID *string, industry *string, isVerified *bool, isCompliant *bool, language *string, currency *string, limit, offset int, sortBy, sortOrder string) ([]*Customer, error) {
|
||||
// Build filter
|
||||
filter := bson.M{}
|
||||
|
||||
// Add search filter
|
||||
if search != "" {
|
||||
filter["$or"] = []bson.M{
|
||||
{"email": primitive.Regex{Pattern: search, Options: "i"}},
|
||||
{"company_name": primitive.Regex{Pattern: search, Options: "i"}},
|
||||
{"first_name": primitive.Regex{Pattern: search, Options: "i"}},
|
||||
{"last_name": primitive.Regex{Pattern: search, Options: "i"}},
|
||||
{"full_name": primitive.Regex{Pattern: search, Options: "i"}},
|
||||
}
|
||||
filter["$text"] = bson.M{"$search": search}
|
||||
}
|
||||
|
||||
// Add type filter
|
||||
if customerType != nil {
|
||||
filter["type"] = *customerType
|
||||
}
|
||||
|
||||
// Add status filter
|
||||
if status != nil {
|
||||
filter["status"] = *status
|
||||
}
|
||||
|
||||
// Add company ID filter
|
||||
if companyID != nil {
|
||||
filter["company_id"] = *companyID
|
||||
}
|
||||
|
||||
// Add industry filter
|
||||
if industry != nil {
|
||||
filter["industry"] = *industry
|
||||
}
|
||||
|
||||
// Add verification filter
|
||||
if isVerified != nil {
|
||||
filter["is_verified"] = *isVerified
|
||||
}
|
||||
|
||||
// Add compliance filter
|
||||
if isCompliant != nil {
|
||||
filter["is_compliant"] = *isCompliant
|
||||
}
|
||||
|
||||
// Add language filter
|
||||
if language != nil {
|
||||
filter["language"] = *language
|
||||
}
|
||||
|
||||
// Add currency filter
|
||||
if currency != nil {
|
||||
filter["currency"] = *currency
|
||||
}
|
||||
|
||||
// Set sort options
|
||||
sortDirection := 1
|
||||
if sortOrder == "desc" {
|
||||
sortDirection = -1
|
||||
// Build pagination
|
||||
pagination := mongopkg.NewPaginationBuilder().
|
||||
Limit(limit).
|
||||
Skip(offset)
|
||||
|
||||
// Set sort
|
||||
if sortBy != "" {
|
||||
if sortOrder == "desc" {
|
||||
pagination.SortDesc(sortBy)
|
||||
} else {
|
||||
pagination.SortAsc(sortBy)
|
||||
}
|
||||
} else {
|
||||
pagination.SortDesc("created_at") // Default sort
|
||||
}
|
||||
|
||||
var sortField string
|
||||
switch sortBy {
|
||||
case "email":
|
||||
sortField = "email"
|
||||
case "company_name":
|
||||
sortField = "company_name"
|
||||
case "updated_at":
|
||||
sortField = "updated_at"
|
||||
case "status":
|
||||
sortField = "status"
|
||||
default:
|
||||
sortField = "created_at"
|
||||
}
|
||||
|
||||
opts := options.Find().
|
||||
SetLimit(int64(limit)).
|
||||
SetSkip(int64(offset)).
|
||||
SetSort(bson.D{{Key: sortField, Value: sortDirection}})
|
||||
|
||||
cursor, err := r.collection.Find(ctx, filter, opts)
|
||||
// Use ORM to find customers
|
||||
result, err := r.ormRepo.FindAll(ctx, filter, pagination.Build())
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to search customers", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"search": search,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
|
||||
var customers []*Customer
|
||||
if err = cursor.All(ctx, &customers); err != nil {
|
||||
return nil, err
|
||||
// Convert []Customer to []*Customer
|
||||
customers := make([]*Customer, len(result.Items))
|
||||
for i := range result.Items {
|
||||
customers[i] = &result.Items[i]
|
||||
}
|
||||
|
||||
return customers, nil
|
||||
}
|
||||
|
||||
// CountByCompanyID counts customers by company ID
|
||||
func (r *customerRepository) CountByCompanyID(ctx context.Context, companyID uuid.UUID) (int64, error) {
|
||||
filter := bson.M{"company_id": companyID}
|
||||
count, err := r.collection.CountDocuments(ctx, filter)
|
||||
func (r *customerRepository) CountByCompanyID(ctx context.Context, companyID string) (int64, error) {
|
||||
filter := bson.M{
|
||||
"company_id": companyID,
|
||||
"status": bson.M{"$ne": CustomerStatusInactive},
|
||||
}
|
||||
|
||||
count, err := r.ormRepo.Count(ctx, filter)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to count customers by company ID", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"company_id": companyID,
|
||||
})
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -455,9 +426,17 @@ func (r *customerRepository) CountByCompanyID(ctx context.Context, companyID uui
|
||||
|
||||
// CountByType counts customers by type
|
||||
func (r *customerRepository) CountByType(ctx context.Context, customerType CustomerType) (int64, error) {
|
||||
filter := bson.M{"type": customerType}
|
||||
count, err := r.collection.CountDocuments(ctx, filter)
|
||||
filter := bson.M{
|
||||
"type": customerType,
|
||||
"status": bson.M{"$ne": CustomerStatusInactive},
|
||||
}
|
||||
|
||||
count, err := r.ormRepo.Count(ctx, filter)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to count customers by type", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"customer_type": customerType,
|
||||
})
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -467,8 +446,13 @@ func (r *customerRepository) CountByType(ctx context.Context, customerType Custo
|
||||
// CountByStatus counts customers by status
|
||||
func (r *customerRepository) CountByStatus(ctx context.Context, status CustomerStatus) (int64, error) {
|
||||
filter := bson.M{"status": status}
|
||||
count, err := r.collection.CountDocuments(ctx, filter)
|
||||
|
||||
count, err := r.ormRepo.Count(ctx, filter)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to count customers by status", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"status": status,
|
||||
})
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -476,50 +460,65 @@ func (r *customerRepository) CountByStatus(ctx context.Context, status CustomerS
|
||||
}
|
||||
|
||||
// UpdateStatus updates customer status
|
||||
func (r *customerRepository) UpdateStatus(ctx context.Context, id uuid.UUID, status CustomerStatus) error {
|
||||
filter := bson.M{"_id": id}
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"status": status,
|
||||
"updated_at": time.Now().Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
func (r *customerRepository) UpdateStatus(ctx context.Context, id string, status CustomerStatus) error {
|
||||
// Get customer first
|
||||
customer, err := r.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("customer not found")
|
||||
// Update status
|
||||
customer.Status = status
|
||||
customer.SetUpdatedAt(time.Now().Unix())
|
||||
|
||||
// Update in database
|
||||
err = r.ormRepo.Update(ctx, customer)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to update customer status", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"customer_id": id,
|
||||
"status": status,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
r.logger.Info("Customer status updated successfully", map[string]interface{}{
|
||||
"customer_id": id,
|
||||
"status": status,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateVerification updates customer verification status
|
||||
func (r *customerRepository) UpdateVerification(ctx context.Context, id uuid.UUID, isVerified, isCompliant bool, complianceNotes *string) error {
|
||||
filter := bson.M{"_id": id}
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"is_verified": isVerified,
|
||||
"is_compliant": isCompliant,
|
||||
"updated_at": time.Now().Unix(),
|
||||
},
|
||||
}
|
||||
|
||||
if complianceNotes != nil {
|
||||
update["$set"].(bson.M)["compliance_notes"] = *complianceNotes
|
||||
}
|
||||
|
||||
result, err := r.collection.UpdateOne(ctx, filter, update)
|
||||
func (r *customerRepository) UpdateVerification(ctx context.Context, id string, isVerified, isCompliant bool, complianceNotes *string) error {
|
||||
// Get customer first
|
||||
customer, err := r.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result.MatchedCount == 0 {
|
||||
return errors.New("customer not found")
|
||||
// Update verification fields
|
||||
customer.IsVerified = isVerified
|
||||
customer.IsCompliant = isCompliant
|
||||
customer.ComplianceNotes = complianceNotes
|
||||
customer.SetUpdatedAt(time.Now().Unix())
|
||||
|
||||
// Update in database
|
||||
err = r.ormRepo.Update(ctx, customer)
|
||||
if err != nil {
|
||||
r.logger.Error("Failed to update customer verification", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
"customer_id": id,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
r.logger.Info("Customer verification updated successfully", map[string]interface{}{
|
||||
"customer_id": id,
|
||||
"is_verified": isVerified,
|
||||
"is_compliant": isCompliant,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user