# Tender Management System Documentation

Welcome to the Tender Management System documentation. This directory contains all the documentation for the Go backend API following Clean Architecture principles with Domain-Driven Design (DDD) patterns.

## 📚 Documentation Structure

### 📖 Main Documentation
- **[README.md](./README.md)** - Main project documentation and overview
- **[AEC_TenderManagement.md](./AEC_TenderManagement.md)** - Comprehensive project requirements and specifications

### 🔧 Setup & Configuration
- **[setup/HTTP_SERVER_SETUP.md](./setup/HTTP_SERVER_SETUP.md)** - HTTP server configuration and setup guide
- **[setup/SWAGGER_SETUP.md](./setup/SWAGGER_SETUP.md)** - Swagger/OpenAPI documentation setup
- **[setup/SWAGGER_SUCCESS.md](./setup/SWAGGER_SUCCESS.md)** - Swagger implementation success guide

### 🚀 Implementation
- **[implementation/IMPLEMENTATION_SUMMARY.md](./implementation/IMPLEMENTATION_SUMMARY.md)** - Implementation details and architecture overview

### 📡 API Documentation
- **[examples/API_EXAMPLES.md](./examples/API_EXAMPLES.md)** - API usage examples and endpoints documentation

## 🏗️ Project Architecture

### Clean Architecture Layers
- **Domain Layer** (`internal/{domain}/`): Business entities, aggregates, interfaces, and core business rules
- **Service Layer** (`internal/{domain}/service.go`): Business logic and use cases
- **Handler Layer** (`internal/{domain}/handler.go`): HTTP controllers and request/response handling
- **Repository Layer** (`internal/{domain}/repository.go`): Data access implementations
- **Infrastructure Layer** (`infra/`): External dependencies (DB, cache, queues, config)

### Domain Structure Pattern
Each domain follows this flat structure:
```
internal/{domain}/
├── entity.go                  # Core domain entities
├── aggregate.go               # Aggregate roots and DTOs
├── repository.go              # Repository interface and implementation
├── service.go                 # Business logic and use cases
├── form.go                    # Request/response forms with validation
└── handler.go                 # HTTP controllers and request/response handling
```

## 🚀 Quick Start

1. **Setup Environment**
   - Follow the setup guides in the `setup/` directory
   - Configure MongoDB and other dependencies

2. **Run the Application**
   ```bash
   make run
   ```

3. **Access API Documentation**
   - Swagger UI: `http://localhost:8081/swagger/index.html`
   - API Base URL: `http://localhost:8081/api/v1`

## 📋 Key Features

- **Clean Architecture**: Follows DDD principles with clear separation of concerns
- **MongoDB Integration**: Robust data persistence with proper indexing
- **Structured Logging**: Comprehensive logging with context
- **Input Validation**: Govalidator integration for request validation
- **Error Handling**: Consistent error responses and logging
- **Time Handling**: Unix timestamps throughout the application
- **API Documentation**: Auto-generated Swagger documentation

## 🔧 Development Guidelines

### Code Organization
- All domain files use the same package name for easy access
- Repository interfaces and implementations are in the same file
- Use dependency injection through constructors
- Follow Go naming conventions and best practices

### Time Handling
- **Input**: Accept Unix timestamps (int64) for all time fields
- **Storage**: Store as Unix timestamps (int64) in MongoDB
- **Output**: Return Unix timestamps (int64) for all time fields
- **Consistency**: All time operations use Unix timestamps throughout

### Validation
- Use govalidator for all request validation
- Define validation tags in request structs
- Register custom validators for complex rules
- Validate at handler level before calling services

## 📝 Logging Standards

### Structured Logging
```go
log.Info("Customer authenticated successfully", map[string]interface{}{
    "customer_id": customer.ID.Hex(),
    "email":       customer.Email,
    "ip":          clientIP,
})
```

### Log Levels
- `Debug`: Detailed debugging information
- `Info`: General operational messages
- `Warn`: Warning conditions that should be addressed
- `Error`: Error conditions that need attention
- `Fatal`: Critical errors that cause program termination

## 🗄️ Database Patterns

### MongoDB Integration
- Use BSON tags for field mapping
- Create indexes in repository constructors
- Handle duplicate key errors appropriately
- Use Unix timestamps for all time fields
- Implement proper pagination with limit/offset

### Repository Pattern
```go
type CustomerRepository interface {
    Create(ctx context.Context, customer *Customer) error
    GetByID(ctx context.Context, id string) (*Customer, error)
    Update(ctx context.Context, customer *Customer) error
    Delete(ctx context.Context, id string) error
    List(ctx context.Context, limit, offset int) ([]*Customer, error)
}
```

## 🌐 HTTP Handler Guidelines

### Request Handling
- Validate all incoming requests using govalidator
- Use proper HTTP status codes
- Return consistent API response format
- Handle CORS appropriately
- Accept Unix timestamps (int64) for all time fields

### Response Format
```json
{
    "success": true,
    "data": {...},
    "message": "Operation successful",
    "metadata": {...}
}
```

## 🔐 Security Best Practices

- Validate and sanitize all inputs
- Use proper authentication middleware
- Implement rate limiting
- Never log sensitive information
- Use HTTPS in production
- Validate JWT tokens properly

## 🧪 Testing Guidelines

- Write unit tests for all business logic
- Use table-driven tests for multiple scenarios
- Mock external dependencies using interfaces
- Test error cases, not just happy paths
- Use meaningful test names

## 📦 Dependencies

### Core Dependencies
- **Echo**: HTTP framework
- **MongoDB**: Database driver
- **Govalidator**: Request validation
- **JWT**: Authentication
- **Swagger**: API documentation

### Development Dependencies
- **Swag**: Swagger documentation generation
- **Testify**: Testing utilities

## 🚨 Common Issues & Solutions

### Time Handling
- **Issue**: Inconsistent time formats
- **Solution**: Always use Unix timestamps (int64) throughout

### Validation
- **Issue**: Missing request validation
- **Solution**: Use govalidator tags in request structs

### Error Handling
- **Issue**: Exposed internal errors
- **Solution**: Use structured error responses

## 📞 Support

For questions or issues:
1. Check the implementation documentation
2. Review API examples
3. Consult the setup guides
4. Check the main README for project overview

---

**Last Updated**: $(date)
**Version**: 1.0.0 