# Backend Specification

## 1. System Summary

**System Name:** Todo Task Demo

**Description:** A single-page application that collects name and email submissions and displays them in a list. This is a minimal demo application that allows anonymous users to submit their name and email address through a form, with all submissions displayed in reverse chronological order below the form.

**Primary Purpose:** Demonstrate basic form submission collection and display functionality with a simple backend API.

## 2. Source Input Summary

This specification is derived from the following source materials:

- **DDL Schema:** `schema.sql` defining the `submissions` table with fields: id, name, email, created_at, updated_at
- **PRD Document:** `full_prd.md` describing a minimal form submission and list display application
- **Additional Context:** Instructions for building a simple demo app with basic CRUD operations

The system focuses on providing a straightforward submission management feature without authentication or complex business logic.

## 3. Generation Mode

**Mode:** `strict`

The backend will be generated according to strict adherence to the provided schema and requirements. All validations, field constraints, and business rules specified in the source materials will be enforced without deviation.

## 4. Backend Scope

The backend encompasses a single module responsible for managing form submissions:

**Module:** `submission`

**Capabilities:**
- Create new submissions via POST endpoint
- Retrieve all submissions via GET endpoint
- Validate name and email inputs according to specified rules
- Store submissions with automatic timestamp management
- Return submissions in reverse chronological order

**Out of Scope:**
- User authentication and authorization
- Submission editing or deletion
- Search and filtering capabilities
- Pagination
- Email verification
- Data export functionality

## 5. Roles

| Role | Description | Permissions |
|------|-------------|-------------|
| Anonymous User | Any user accessing the application without authentication | Can create new submissions and view all submissions |

**Note:** This application does not implement role-based access control. All endpoints are publicly accessible.

## 6. Entities and Fields

### 6.1 Submission

**Table Name:** `submissions`

**Description:** Represents a single form submission containing a user's name and email address.

| Field Name | Type | Required | Description | Constraints |
|------------|------|----------|-------------|-------------|
| id | str | Yes | Unique identifier (UUID) | Primary key, auto-generated |
| name | str | Yes | Name entered by the user | Min length: 1 (after trim), Max length: 100 |
| email | str | Yes | Email address entered by the user | Must match email format, Max length: 254 |
| created_at | datetime | Yes | Timestamp when the submission was created | Auto-generated on creation |
| updated_at | datetime | Yes | Timestamp when the submission was last updated | Auto-updated on modification |

**Status Management:** This entity does not have status field management.

## 7. Enumerations

This system does not define any enumerations.

## 8. Relationships

This system does not define any relationships between entities. The `Submission` entity is independent and self-contained.

## 9. API Endpoints

### 9.1 Create Submission

**Endpoint:** `POST /submissions`

**Description:** Creates a new submission with the provided name and email.

**Request Body:**
```json
{
  "name": "string",
  "email": "string"
}
```

**Validation:**
- Name: required, 1-100 characters after trimming, non-empty
- Email: required, valid email format, max 254 characters

**Response:** `201 Created`
```json
{
  "id": "uuid-string",
  "name": "string",
  "email": "string",
  "created_at": "2024-01-01T12:00:00Z",
  "updated_at": "2024-01-01T12:00:00Z"
}
```

**Error Responses:**
- `400 Bad Request` - Validation errors
- `500 Internal Server Error` - Server errors

### 9.2 List Submissions

**Endpoint:** `GET /submissions`

**Description:** Retrieves all submissions ordered by creation date (newest first).

**Query Parameters:** None

**Response:** `200 OK`
```json
[
  {
    "id": "uuid-string",
    "name": "string",
    "email": "string",
    "created_at": "2024-01-01T12:00:00Z",
    "updated_at": "2024-01-01T12:00:00Z"
  }
]
```

**Ordering:** Results are sorted by `created_at` in descending order (newest first).

**Error Responses:**
- `500 Internal Server Error` - Server errors

## 10. Workflow Logic

### 10.1 Form Submission Workflow

**Workflow Name:** User Submission and Display

**Description:** A user fills out the form with their name and email, submits it, and immediately sees their new submission appear at the top of the list below the form.

**Steps:**

1. **User Input:** User enters name and email in the frontend form
2. **Client Validation:** Frontend performs basic validation (optional but recommended)
3. **API Request:** Frontend sends POST request to `/submissions` with form data
4. **Backend Validation:** Backend validates name and email against business rules
5. **Data Persistence:** If valid, backend creates new submission record with auto-generated id and timestamps
6. **Response:** Backend returns the created submission with 201 status
7. **UI Update:** Frontend refreshes the submission list by calling GET `/submissions`
8. **Display:** New submission appears at the top of the list

**Error Handling:**
- If validation fails, return 400 with error details
- Frontend displays error message to user
- User corrects input and resubmits

## 11. Business Logic

### 11.1 Submission Creation Rules

1. **Name Requirements:**
   - Must be provided (required field)
   - Cannot be empty after trimming whitespace
   - Minimum length: 1 character (after trimming)
   - Maximum length: 100 characters
   - Leading and trailing whitespace should be trimmed before storage

2. **Email Requirements:**
   - Must be provided (required field)
   - Must match basic email format pattern: `^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$`
   - Maximum length: 254 characters (RFC 5321 standard)
   - Case is preserved as entered

3. **Duplicate Handling:**
   - Duplicate combinations of name and email are allowed
   - No uniqueness constraint is enforced
   - Each submission is treated as an independent record

4. **Timestamp Management:**
   - `created_at` is automatically set to the current UTC timestamp on creation
   - `updated_at` is automatically set to the current UTC timestamp on creation
   - `updated_at` should be updated if the record is ever modified (though not supported in current scope)

### 11.2 Submission Retrieval Rules

1. **Ordering:**
   - All submissions must be returned in reverse chronological order
   - Sort by `created_at` field in descending order (newest first)

2. **Data Completeness:**
   - All fields of each submission must be returned
   - No filtering or pagination is applied in the current implementation

## 12. Validation Rules

### 12.1 Field-Level Validations

**Name Field:**
- **Required:** Yes
- **Type:** String
- **Trimming:** Apply `TRIM()` before validation
- **Non-Empty Check:** `LENGTH(TRIM(name)) > 0`
- **Maximum Length:** 100 characters
- **Error Messages:**
  - Empty/whitespace: "Name cannot be empty"
  - Too long: "Name must not exceed 100 characters"

**Email Field:**
- **Required:** Yes
- **Type:** String
- **Format Validation:** Must match regex `^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$`
- **Maximum Length:** 254 characters
- **Error Messages:**
  - Missing: "Email is required"
  - Invalid format: "Email must be a valid email address"
  - Too long: "Email must not exceed 254 characters"

### 12.2 Request-Level Validations

**POST /submissions:**
- Request body must be valid JSON
- All required fields (name, email) must be present
- Field types must match expected types (string for both)
- All field-level validations must pass

### 12.3 Validation Implementation

Validations are implemented using Pydantic v2 models with custom validators:
- Field type checking (automatic via Pydantic)
- String length constraints (via Pydantic field validators)
- Regex pattern matching (via Pydantic field validators)
- Custom trimming and non-empty validation (via Pydantic field validators)

## 13. Implementation Notes

### 13.1 Technology Stack

**Framework:** FastAPI
- Asynchronous request handling
- Automatic request/response validation
- Built-in OpenAPI documentation at `/docs` and `/redoc`
- JSON serialization/deserialization

**ORM:** SQLAlchemy ORM
- Database abstraction layer
- Model definitions with declarative base
- Session management for transactions

**Database:** SQLite
- File-based database for development and demo purposes
- Simple setup with no external dependencies
- Database file stored locally

**Validation:** Pydantic v2
- Request/response schema definitions
- Automatic validation and serialization
- Type safety and IDE support

**Dependency Management:** uv
- Fast Python package installer and resolver
- Virtual environment management
- Dependency locking for reproducible builds

### 13.2 Architecture Patterns

**Service Layer Pattern:**
- Separation of concerns between API routes and business logic
- Service classes encapsulate business operations
- Routes handle HTTP concerns, services handle domain logic

**Dependency Injection:**
- Database sessions injected via `Depends(get_db)`
- Clean separation of database lifecycle from business logic
- Automatic session cleanup after request completion

**Repository Pattern (Implicit):**
- SQLAlchemy queries encapsulated in service methods
- Abstraction of data access from business logic

### 13.3 Project Structure

```
backend/
├── app/
│   ├── __init__.py
│   ├── main.py                 # FastAPI application instance
│   ├── database.py             # Database configuration and session management
│   ├── models/
│   │   ├── __init__.py
│   │   └── submission.py       # SQLAlchemy model
│   ├── schemas/
│   │   ├── __init__.py
│   │   └── submission.py       # Pydantic schemas
│   ├── services/
│   │   ├── __init__.py
│   │   └── submission.py       # Business logic
│   └── routers/
│       ├── __init__.py
│       └── submission.py       # API endpoints
├── pyproject.toml              # Project dependencies
└── README.md
```

### 13.4 API Documentation

**Automatic OpenAPI Documentation:**
- Interactive API documentation available at `/docs` (Swagger UI)
- Alternative documentation available at `/redoc` (ReDoc)
- OpenAPI JSON schema available at `/openapi.json`
- All endpoints, request/response schemas, and validations automatically documented

### 13.5 Error Handling

- Pydantic validation errors automatically converted to 422 responses
- Custom business logic errors returned as 400 responses
- Database errors caught and returned as 500 responses
- Consistent error response format across all endpoints

## 14. Assumptions

1. **No Authentication Required:** The application is publicly accessible without user authentication or session management.

2. **Independent Submissions:** All submissions are independent entities with no relationships to other data or entities.

3. **Descending Chronological Order:** When retrieving submissions, they are always sorted by `created_at` in descending order (newest first) without option for alternative sorting.

4. **Basic CRUD Only:** The application supports only Create and Read operations. Update and Delete operations are not implemented in the current scope.

5. **Single-Page Application:** The backend serves as an API for a single-page frontend application, returning JSON responses only.

6. **No Pagination:** All submissions are returned in a single response without pagination, suitable for demo purposes with limited data.

7. **No Duplicate Prevention:** The system allows multiple submissions with identical name and email combinations, treating each as a unique entry.

8. **UTC Timestamps:** All datetime values use UTC timezone for consistency.

9. **No Email Verification:** Email addresses are validated for format only; no verification emails are sent or delivery confirmed.

10. **Development Environment:** The initial implementation uses SQLite and is optimized for development/demo rather than production deployment.

## 15. Future Improvements

### 15.1 Database and Migrations

**Alembic Integration:**
- Implement Alembic for database migration management
- Version-controlled schema changes
- Safe rollback capabilities
- Production-ready database evolution

**PostgreSQL Support:**
- Migrate from SQLite to PostgreSQL for production use
- Better concurrency handling
- Advanced features like full-text search
- Improved performance at scale

### 15.2 Authentication and Authorization

**JWT Authentication:**
- Implement JSON Web Token authentication
- Secure user registration and login
- Token refresh mechanism
- Session management

**Role-Based Access Control (RBAC):**
- Define user roles (admin, user, etc.)
- Implement permission-based access to endpoints
- Restrict submission deletion/editing to owners or admins

### 15.3 Testing

**Unit Tests:**
- Test service layer business logic
- Test validation rules
- Mock database interactions

**Integration Tests:**
- Test complete API endpoint flows
- Test database transactions
- Test error handling scenarios

**Test Coverage:**
- Aim for >80% code coverage
- Automated test execution in CI/CD pipeline

### 15.4 Deployment and Operations

**Docker Containerization:**
- Dockerfile for backend application
- Docker Compose for multi-container setup (app + database)
- Environment-based configuration
- Production-ready container images

**Environment Configuration:**
- Separate configurations for development, staging, and production
- Environment variable management
- Secrets management for sensitive data

### 15.5 Feature Enhancements

**Pagination:**
- Implement cursor or offset-based pagination
- Configurable page size
- Performance optimization for large datasets

**Search and Filtering:**
- Full-text search on name and email fields
- Filter by date range
- Sort by different fields

**CRUD Completion:**
- Add PUT/PATCH endpoints for updating submissions
- Add DELETE endpoint for removing submissions
- Implement soft delete with status field

**Data Export:**
- Export submissions to CSV format
- Export to JSON format
- Scheduled export jobs

**Email Verification:**
- Integration with email service provider (SendGrid, AWS SES)
- Send verification emails on submission
- Track verification status
- Resend verification capability

**Rate Limiting:**
- Implement rate limiting to prevent abuse
- Per-IP request throttling
- Configurable rate limit rules

**Audit Logging:**
- Log all data modifications
- Track user actions (when authentication is added)
- Compliance and debugging support
