# Backend Specification

## 1. System Summary

**System Name:** Todo Task Submission System

**Description:** A single-page web application that allows users to submit their name and email through a form and view all submitted entries in a table. The system provides a simple interface for collecting user information and displaying all submissions in reverse chronological order without any authentication requirements.

**Key Features:**
- Form-based data submission (name and email)
- Real-time display of all submissions in a table
- Automatic timestamp management
- Client and server-side validation
- Public access without authentication

## 2. Source Input Summary

This backend specification is generated from the following source inputs:

- **DDL Schema File:** `/home/ubuntu/dpg/pipeline/step-02-prd-generation/output/20260514_025553/schema.sql`
  - Defines `submissions` table with fields: id (UUID), name, email, created_at, updated_at
  - Uses PostgreSQL-specific functions (gen_random_uuid())
  
- **PRD File:** `/home/ubuntu/dpg/pipeline/step-02-prd-generation/output/20260514_025553/full_prd.md`
  - Describes form submission and data display workflows
  - Specifies validation requirements and business rules
  
- **Prompt:** Provided instructions for a simple single-page application

- **Images:** Not provided

## 3. Generation Mode

**Mode:** `strict`

This specification adheres strictly to the requirements defined in the source inputs. All entities, fields, validation rules, and workflows are derived directly from the provided DDL schema and PRD documentation without additional interpretation or extension.

## 4. Backend Scope

The backend system encompasses the following modules:

| Module | Description | Entities |
|--------|-------------|----------|
| submission | Handles form submission data collection and display | Submission |

**Responsibilities:**
- Accept and validate form submissions via REST API
- Store submission data persistently in database
- Retrieve and return all submissions ordered by creation date
- Enforce validation rules on all inputs
- Manage automatic timestamp generation

## 5. Roles

| Role | Description | Permissions |
|------|-------------|-------------|
| Anonymous User | Any user accessing the application without authentication | - Submit new entries<br>- View all submissions |

**Note:** The system does not implement authentication or authorization. All users have equal access to all functionality.

## 6. Entities and Fields

### Submission

**Table Name:** `submissions`

**Description:** Represents a single form submission with user name and email

| Field Name | Type | Required | Description | Constraints |
|------------|------|----------|-------------|-------------|
| id | str (UUID) | Yes | Unique identifier | Primary key, auto-generated |
| name | str | Yes | User's name | Max 100 characters, non-empty |
| email | str | Yes | User's email address | Max 255 characters, valid email format |
| created_at | datetime | Yes | Timestamp when submission was created | Auto-managed by system |
| updated_at | datetime | Yes | Timestamp when submission was last updated | Auto-managed by system |

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

## 7. Enumerations

No enumerations are defined for this system.

## 8. Relationships

No relationships exist between entities as the system contains only a single entity (Submission).

## 9. API Endpoints

### 9.1 Create Submission

**Endpoint:** `POST /api/submissions`

**Description:** Create a new submission with name and email

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

**Validation:**
- `name`: Required, 1-100 characters, non-empty/non-whitespace
- `email`: Required, 5-255 characters, valid email format

**Response (201 Created):**
```json
{
  "id": "uuid",
  "name": "string",
  "email": "string",
  "created_at": "datetime",
  "updated_at": "datetime"
}
```

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

### 9.2 List Submissions

**Endpoint:** `GET /api/submissions`

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

**Query Parameters:** None (pagination may be added in future)

**Response (200 OK):**
```json
[
  {
    "id": "uuid",
    "name": "string",
    "email": "string",
    "created_at": "datetime",
    "updated_at": "datetime"
  }
]
```

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

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

## 10. Workflow Logic

### 10.1 Page Load Workflow

**Trigger:** User navigates to the application

**Steps:**
1. Frontend loads the HTML page with empty form
2. Frontend automatically calls `GET /api/submissions`
3. Backend queries all submission records from database
4. Backend orders results by `created_at` DESC
5. Backend returns list of submissions
6. Frontend renders each submission as a table row

**Success Criteria:** Form is displayed and table is populated with existing submissions

### 10.2 Form Submission Workflow

**Trigger:** User enters name and email, then clicks submit button

**Steps:**
1. Frontend performs client-side validation on name and email fields
2. If validation passes, frontend sends `POST /api/submissions` request
3. Backend receives request and performs server-side validation
4. If validation fails, backend returns 400 error with validation messages
5. If validation passes, backend generates UUID for new submission
6. Backend sets `created_at` and `updated_at` to current timestamp
7. Backend inserts new record into `submissions` table
8. Backend returns newly created submission with 201 status
9. Frontend adds new entry to the top of the table
10. Frontend clears the form fields for next submission

**Success Criteria:** New submission appears in table and form is reset

**Error Handling:** Validation errors are displayed to user without clearing form

### 10.3 Data Retrieval and Display Workflow

**Trigger:** Page load or after successful submission

**Steps:**
1. System queries all records from `submissions` table
2. System applies ORDER BY `created_at` DESC
3. System serializes records to JSON format
4. System returns array of submission objects
5. Frontend iterates through array and renders table rows

**Success Criteria:** All submissions are visible in reverse chronological order

## 11. Business Logic

### 11.1 Submission Creation Rules

1. **Unique Identifier Generation:** Each submission must have a unique auto-generated UUID identifier
2. **Timestamp Management:** `created_at` and `updated_at` timestamps are automatically set by the system on creation
3. **Duplicate Handling:** Duplicate submissions (same name and email) are allowed and treated as separate entries
4. **Permanent Storage:** All submissions are permanently stored with no automatic deletion
5. **Public Visibility:** All submissions are visible to all users without privacy filtering

### 11.2 Data Display Rules

1. **Ordering:** Submissions must be displayed in reverse chronological order (newest first)
2. **Completeness:** All fields (id, name, email, created_at, updated_at) are returned for each submission
3. **No Filtering:** No privacy or access control filtering is applied to the results

### 11.3 Validation Business Rules

1. **Name Validation:**
   - Must not be empty or contain only whitespace
   - Must be between 1 and 100 characters in length
   
2. **Email Validation:**
   - Must not be empty
   - Must match standard email regex pattern: `^[^\s@]+@[^\s@]+\.[^\s@]+$`
   - Must be between 5 and 255 characters in length

3. **Dual Validation:** Both client-side and server-side validation must be performed for all inputs

## 12. Validation Rules

### 12.1 Field-Level Validation

| Field | Rule | Error Message |
|-------|------|---------------|
| name | Required | "Name is required" |
| name | Non-empty/non-whitespace | "Name cannot be empty or contain only whitespace" |
| name | Max length 100 | "Name must not exceed 100 characters" |
| email | Required | "Email is required" |
| email | Valid email format | "Email must be a valid email address" |
| email | Min length 5 | "Email must be at least 5 characters" |
| email | Max length 255 | "Email must not exceed 255 characters" |

### 12.2 Email Format Validation

**Pattern:** `^[^\s@]+@[^\s@]+\.[^\s@]+$`

**Requirements:**
- Must contain exactly one @ symbol
- Must have characters before the @ symbol
- Must have domain name after @ symbol
- Must have top-level domain after a period
- Must not contain whitespace

### 12.3 Validation Implementation

**Client-Side:**
- Implemented in frontend JavaScript before form submission
- Provides immediate feedback to users
- Prevents unnecessary API calls for invalid data

**Server-Side:**
- Implemented in FastAPI endpoint handlers using Pydantic models
- Serves as authoritative validation layer
- Protects against malicious or bypassed client validation
- Returns structured error responses with field-specific messages

## 13. Implementation Notes

### 13.1 Technology Stack

- **Framework:** FastAPI (Python web framework)
- **ORM:** SQLAlchemy ORM with SQLite database for development
- **Validation:** Pydantic v2 for request/response models and validation
- **Dependency Injection:** FastAPI `Depends(get_db)` for database session management
- **Package Manager:** uv for fast Python package management
- **API Documentation:** Automatic OpenAPI (Swagger) documentation via FastAPI

### 13.2 Architecture Pattern

**Service Layer Pattern:**
- **Router Layer:** FastAPI routers handle HTTP requests/responses
- **Service Layer:** Business logic encapsulated in service functions
- **Repository Layer:** Database operations abstracted through SQLAlchemy ORM
- **Model Layer:** Pydantic models for validation and serialization

### 13.3 Database Session Management

- Database sessions are managed using FastAPI dependency injection
- `get_db()` generator function provides session per request
- Automatic session cleanup via try/finally blocks
- Connection pooling handled by SQLAlchemy

### 13.4 API Documentation

- Automatic OpenAPI schema generation at `/docs` (Swagger UI)
- Alternative documentation at `/redoc` (ReDoc)
- Schema available at `/openapi.json`

### 13.5 Error Handling

- Validation errors return 400 status with detailed field errors
- Database errors are caught and return 500 status
- All errors include descriptive messages for debugging

### 13.6 CORS Configuration

- CORS middleware configured to allow frontend access
- Appropriate origins configured for development and production environments

## 14. Assumptions

1. **No Authentication:** No user authentication or authorization is required for any functionality
2. **Equal Access:** All users have equal access to view all submissions without restrictions
3. **Database Technology:** System uses PostgreSQL database in production as indicated by `gen_random_uuid()` function in DDL schema
4. **Development Database:** SQLite is used for local development and testing
5. **Deployment Domain:** Application is deployed to `https://freemeal.dev.dalfin.ai` domain
6. **HTTPS Enforcement:** HTTPS is enforced by the domain/infrastructure configuration
7. **No Pagination Initially:** No pagination is required initially, or default pagination applies if submissions exceed reasonable limit (suggested threshold: 1,000 records)
8. **Rate Limiting:** No strict rate limiting is required but recommended at 100 requests per IP per minute to prevent abuse
9. **Data Retention:** All submissions are retained indefinitely with no automatic cleanup or archival
10. **Single Region:** Application operates in a single geographic region without multi-region considerations
11. **Synchronous Processing:** All operations are synchronous without background job processing

## 15. Future Improvements

### 15.1 Database and Migrations

- **Alembic Migrations:** Implement Alembic for database schema version control and migrations
- **PostgreSQL Production:** Ensure PostgreSQL is used in production environment with proper connection pooling
- **Database Indexing:** Add indexes on `created_at` field for optimized sorting queries
- **Backup Strategy:** Implement automated database backup and recovery procedures

### 15.2 Authentication and Authorization

- **JWT Authentication:** Implement JSON Web Token (JWT) based authentication system
- **RBAC (Role-Based Access Control):** Add role-based permissions for different user types
- **User Management:** Create user registration, login, and profile management
- **Submission Ownership:** Associate submissions with authenticated users

### 15.3 Testing

- **Unit Tests:** Comprehensive unit tests for service layer and business logic
- **Integration Tests:** API endpoint integration tests using TestClient
- **Database Tests:** Tests using in-memory SQLite or test database
- **Test Coverage:** Achieve minimum 80% code coverage
- **Load Testing:** Performance testing for concurrent user scenarios

### 15.4 Containerization and Deployment

- **Docker:** Create Dockerfile for containerized deployment
- **Docker Compose:** Multi-container setup for development environment
- **CI/CD Pipeline:** Automated testing and deployment pipeline
- **Environment Configuration:** Proper environment variable management for different deployment stages

### 15.5 Feature Enhancements

- **Pagination:** Implement cursor-based or offset pagination when submissions exceed 1,000 records
- **Search and Filter:** Add search functionality for name and email fields
- **Sorting Options:** Allow frontend to specify sort field and direction
- **Edit Capability:** Add `PUT /api/submissions/{id}` endpoint for updating submissions
- **Delete Capability:** Add `DELETE /api/submissions/{id}` endpoint for removing submissions
- **Export Functionality:** Add CSV and Excel export endpoints for submissions data
- **Real-time Updates:** Implement WebSockets for live updates in multi-user scenarios
- **Analytics Dashboard:** Add endpoints for submission trends and statistics over time
- **Email Notifications:** Send confirmation emails upon successful submission
- **Rate Limiting:** Implement Redis-based rate limiting with configurable thresholds
- **Audit Logging:** Track all create/update/delete operations with timestamps and IP addresses
