# FocusFlow Product Requirements Document (PRD)

## 1. Introduction

### 1.1 Purpose
The purpose of this PRD is to outline the requirements for the development of FocusFlow, a comprehensive todo platform designed to help users manage personal tasks, collaborate within teams, and oversee projects involving multiple teams. This document provides detailed information to guide developers in building the application to meet the specified functionalities and goals.

### 1.2 Background
FocusFlow aims to simplify task management by providing an integrated platform that combines personal todos, team collaboration, and project oversight. By leveraging Google OAuth2 for authentication and providing an intuitive interface, FocusFlow seeks to enhance productivity and streamline workflows for individuals and organizations.

### 1.3 Scope
This document covers the core functionalities, technical specifications, database models, API endpoints, implementation guidelines, and other critical aspects necessary for developing FocusFlow. It serves as a comprehensive guide for developers to understand the application's requirements and to ensure consistency throughout the development process.

## 2. Goals and Objectives
- Provide a seamless task management experience for individual users.
- Enable efficient team collaboration through team creation and management features.
- Facilitate project oversight by allowing project creation, team assignments, and project management roles.
- Ensure secure authentication and authorization using industry standards (Google OAuth2 and JWT).
- Offer an intuitive user interface that enhances usability and user engagement.
- Provide analytics and dashboards to give users insights into their tasks, teams, and projects.

## 3. Core Functionalities

### 3.1 User Authentication

#### Google OAuth2 Integration:
- Users can sign up and log in using their Google accounts.
- On successful authentication, user details are stored in the local database.

#### JWT Tokens for Authorization:
- After authentication, users receive JWT tokens valid for 14 days.
- Tokens are used to authorize API requests.

### 3.2 Todo Management

#### Create, Edit, and Delete Todos:
- Users can create personal todos.
- Users can edit or delete their own todos.

#### View and Filter Todos:
- Users can view a list of their todos.
- Filtering options:
  - By teams.
  - By projects.
  - By status (pending, in progress, completed).

### 3.3 Team Management

#### Create Teams:
- Users can create teams for collaboration.
- The creator becomes the "Team Leader."

#### Manage Team Members:
- Team Leaders can add or remove team members.

#### Assign Todos to Teams:
- Teams can have multiple todos assigned to them.

### 3.4 Project Management

#### Create Projects:
- Users can create projects to group multiple teams.
- The creator becomes the "Project Owner."

#### Assign Teams to Projects:
- Project Managers can add teams to projects.

#### Designate Project Managers:
- Project Owners can assign a "Project Manager" role to another user.

### 3.5 User Profile Management

#### View and Edit Profile Information:
- Users can view and update their name and profile picture.

### 3.6 Analytics Dashboard

#### Overview of Todos, Teams, and Projects:
- Users can access a dashboard displaying their activities.

#### Progress Analytics:
- Visualization of task completion rates and other key metrics.

## 4. Database Modeling

### 4.1 User Model

#### Fields:
- id: Primary key.
- email: Unique email address (from Google OAuth2).
- name: User's name (from Google OAuth2).
- profile_picture: URL to the user's profile picture (from Google OAuth2).
- created_at, updated_at: Timestamps.

#### Relationships:
- todos: Todos created by the user.
- teams: Teams the user is a member of.
- owned_teams: Teams where the user is the leader.
- owned_projects: Projects where the user is the owner.
- managed_projects: Projects where the user is the manager.

### 4.2 Todo Model

#### Fields:
- id: Primary key.
- title: Title of the todo.
- description: Detailed description.
- status: Status of the todo (pending, in_progress, completed).
- user_id: Foreign key to the creator (User).
- team_id: Foreign key to the associated team (nullable).
- created_at, updated_at: Timestamps.

#### Relationships:
- owner: The user who created the todo.
- team: Associated team (if any).

### 4.3 Team Model

#### Fields:
- id: Primary key.
- name: Name of the team.
- team_leader_id: Foreign key to the team leader (User).
- created_at, updated_at: Timestamps.

#### Relationships:
- team_leader: The user who leads the team.
- members: Users who are members of the team.
- todos: Todos assigned to the team.
- projects: Projects the team is part of.

### 4.4 TeamMembership Model

#### Fields:
- id: Primary key.
- user_id, team_id: Foreign keys to User and Team.
- created_at: Timestamp.

#### Constraints:
- Unique constraint on user_id and team_id to prevent duplicate memberships.

#### Relationships:
- user: The user in the membership.
- team: The team in the membership.

### 4.5 Project Model

#### Fields:
- id: Primary key.
- name: Name of the project.
- description: Project description.
- project_owner_id: Foreign key to the project owner (User).
- project_manager_id: Foreign key to the project manager (User), nullable.
- created_at, updated_at: Timestamps.

#### Relationships:
- project_owner: The user who owns the project.
- project_manager: The user who manages the project.
- teams: Teams associated with the project.

### 4.6 ProjectTeam Model

#### Fields:
- id: Primary key.
- project_id, team_id: Foreign keys to Project and Team.
- added_at: Timestamp.

#### Constraints:
- Unique constraint on project_id and team_id.

#### Relationships:
- project: The project in the association.
- team: The team in the association.

### 4.7 Considerations

#### Role Management:
- Roles like "Team Leader" and "Project Manager" are attributes within the Team and Project models.

#### Permissions:
- Use middleware or dependency injections in FastAPI to enforce permissions based on roles.

#### Data Validation:
- Utilize Pydantic models to ensure data conforms to the expected schema.

#### Timestamps:
- created_at and updated_at fields help track changes.

## 5. Technical Specifications

### 5.1 Backend

#### Technologies & Frameworks
- Programming Language: Python 3.10 or higher.
- Framework: FastAPI (latest version) with asynchronous capabilities.
- Database: PostgreSQL with SQLAlchemy ORM.
- Data Modeling: Pydantic models for data validation.
- Authentication: Google OAuth2 using oauthlib or similar libraries.
- Authorization: JWT tokens with PyJWT, expiring after 14 days.
- Migrations: Alembic for database migrations.

#### Authentication and Authorization

##### Google OAuth2
- Integration with Google's OAuth2 API for user authentication.
- User Details Storage: On successful authentication, store user details in the local database.
- JWT Token Exchange: Exchange the Google OAuth2 token for a local JWT token.

##### JWT Tokens
- Library: Use PyJWT to generate and validate JWT tokens.
- Token Payload:
  - Include user ID and expiration.
  - Expiration: Set token expiration to 14 days.

##### Role-Based Access Control (RBAC)
- Roles:
  - Regular User
  - Team Leader
  - Project Manager
  - Project Owner
- Access Control:
  - Implement decorators or middleware to enforce access control on protected endpoints.

### 5.2 Frontend

#### Technologies & Frameworks
- Framework: Next.js 14
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- State Management: React Query

#### Interface Design
- Responsive Design: Ensure the application is responsive across devices.
- User Experience:
  - Intuitive navigation.
  - Clear call-to-action buttons.
  - Consistent styling and theming.

## 6. API Endpoints

### 6.1 Google OAuth2 Authentication

#### 1. Initiate Authentication
- Endpoint: `GET /auth/google/login`
- Description: Redirects the user to Google's OAuth2 consent screen to initiate the authentication process.

#### 2. Handle OAuth2 Callback
- Endpoint: `GET /auth/google/callback`
- Description:
  - Handles the callback from Google after user authentication.
  - Retrieves the authorization code and exchanges it for tokens.
  - Creates or updates the user in the database.
  - Generates a JWT token with a 14-day expiry.

### 6.2 User Profile Endpoints

#### 1. Get Current User Profile
- Endpoint: `GET /users/me`
- Description: Retrieves the profile of the authenticated user.
- Permissions: Authenticated users.
- Response:
  - User data including id, email, name, profile_picture.

#### 2. Update Current User Profile
- Endpoint: `PUT /users/me`
- Description: Updates the profile information of the authenticated user.
- Permissions: Authenticated users.
- Request Body:
  - name: Optional.
  - profile_picture: Optional.
- Response:
  - Updated user data.

### 6.3 Todo Endpoints

#### 1. Create a New Todo
- Endpoint: `POST /todos`
- Description: Creates a new todo item.
- Permissions: Authenticated users.
- Request Body:
  - title: Required.
  - description: Optional.
  - status: Optional (pending by default).
  - team_id: Optional (if associating with a team).
- Business Logic:
  - If team_id is provided, verify that the user is a member of the team.
- Response:
  - Details of the created todo item.

#### 2. Get Todos with Filtering
- Endpoint: `GET /todos`
- Description: Retrieves a list of todos for the authenticated user.
- Permissions: Authenticated users.
- Query Parameters:
  - status: Optional (e.g., pending, completed).
  - team_id: Optional.
  - project_id: Optional.
- Business Logic:
  - Filter todos based on the provided parameters.
  - If team_id is provided, include todos associated with that team (if the user is a member).
  - If project_id is provided, include todos from teams within the project (if the user is a member of those teams).
- Response:
  - List of todos.

#### 3. Get a Specific Todo
- Endpoint: `GET /todos/{todo_id}`
- Description: Retrieves details of a specific todo.
- Permissions: Authenticated users who own the todo or are members of the associated team.
- Response:
  - Todo details.

#### 4. Update a Todo
- Endpoint: `PUT /todos/{todo_id}`
- Description: Updates an existing todo.
- Permissions: Authenticated users who own the todo.
- Request Body:
  - title: Optional.
  - description: Optional.
  - status: Optional.
- Response:
  - Updated todo item.

#### 5. Delete a Todo
- Endpoint: `DELETE /todos/{todo_id}`
- Description: Deletes a todo.
- Permissions: Authenticated users who own the todo.
- Response:
  - Confirmation of deletion.

### 6.4 Team Endpoints

#### 1. Create a Team
- Endpoint: `POST /teams`
- Description: Creates a new team.
- Permissions: Authenticated users.
- Request Body:
  - name: Required.
- Business Logic:
  - The authenticated user becomes the "Team Leader".
- Response:
  - Details of the created team.

#### 2. Get Teams
- Endpoint: `GET /teams`
- Description: Retrieves a list of teams the user is a member of.
- Permissions: Authenticated users.
- Response:
  - List of teams.

#### 3. Get a Specific Team
- Endpoint: `GET /teams/{team_id}`
- Description: Retrieves details of a specific team.
- Permissions: Authenticated users who are members of the team.
- Response:
  - Team details.

#### 4. Update a Team
- Endpoint: `PUT /teams/{team_id}`
- Description: Updates a team's information.
- Permissions: Team Leader.
- Request Body:
  - name: Optional.
- Response:
  - Updated team details.

#### 5. Delete a Team
- Endpoint: `DELETE /teams/{team_id}`
- Description: Deletes a team.
- Permissions: Team Leader.
- Business Logic:
  - Ensure all associated todos are handled (e.g., set their team_id to NULL or delete them).
- Response:
  - Confirmation of deletion.

#### 6. Manage Team Members

##### Add a Member
- Endpoint: `POST /teams/{team_id}/members`
- Description: Adds a user to the team.
- Permissions: Team Leader.
- Request Body:
  - user_email: Email of the user to add.
- Business Logic:
  - Verify the user exists.
- Response:
  - Confirmation of addition.

##### Remove a Member
- Endpoint: `DELETE /teams/{team_id}/members/{user_id}`
- Description: Removes a user from the team.
- Permissions: Team Leader.
- Business Logic:
  - Ensure the team doesn't lose all members unintentionally.
- Response:
  - Confirmation of removal.

#### 7. Get Team Todos
- Endpoint: `GET /teams/{team_id}/todos`
- Description: Retrieves todos associated with the team.
- Permissions: Team members.
- Response:
  - List of team todos.

### 6.5 Project Endpoints

#### 1. Create a Project
- Endpoint: `POST /projects`
- Description: Creates a new project.
- Permissions: Authenticated users.
- Request Body:
  - name: Required.
  - description: Optional.
- Business Logic:
  - The authenticated user becomes the "Project Owner".
- Response:
  - Details of the created project.

#### 2. Get Projects
- Endpoint: `GET /projects`
- Description: Retrieves projects the user is associated with (owned or managed).
- Permissions: Authenticated users.
- Response:
  - List of projects.

#### 3. Get a Specific Project
- Endpoint: `GET /projects/{project_id}`
- Description: Retrieves details of a specific project.
- Permissions: Project Owner, Project Manager, or members of associated teams.
- Response:
  - Project details.

#### 4. Update a Project
- Endpoint: `PUT /projects/{project_id}`
- Description: Updates a project's information.
- Permissions: Project Owner.
- Request Body:
  - name: Optional.
  - description: Optional.
- Response:
  - Updated project details.

#### 5. Delete a Project
- Endpoint: `DELETE /projects/{project_id}`
- Description: Deletes a project.
- Permissions: Project Owner.
- Business Logic:
  - Handle associations with teams (e.g., remove all teams from the project).
- Response:
  - Confirmation of deletion.

#### 6. Assign Project Manager
- Endpoint: `POST /projects/{project_id}/manager`
- Description: Assigns a project manager.
- Permissions: Project Owner.
- Request Body:
  - user_id: ID of the user to assign.
- Business Logic:
  - Verify the user exists.
- Response:
  - Confirmation of assignment.

#### 7. Manage Project Teams

##### Add a Team to Project
- Endpoint: `POST /projects/{project_id}/teams`
- Description: Adds a team to the project.
- Permissions: Project Manager.
- Request Body:
  - team_id: ID of the team to add.
- Business Logic:
  - Verify the team exists.
- Response:
  - Confirmation of addition.

##### Remove a Team from Project
- Endpoint: `DELETE /projects/{project_id}/teams/{team_id}`
- Description: Removes a team from the project.
- Permissions: Project Manager.
- Business Logic:
  - Handle any dependencies.
- Response:
  - Confirmation of removal.

#### 8. Get Project Todos
- Endpoint: `GET /projects/{project_id}/todos`
- Description: Retrieves all todos across teams under the project.
- Permissions: Project Manager.
- Response:
  - List of project todos.

### 6.6 Additional Considerations

#### Pagination:
- Implement pagination for endpoints returning lists to handle large data sets.

#### Filtering and Sorting:
- Allow query parameters to filter and sort the results.

#### Error Handling:
- Return appropriate HTTP status codes and error messages.
  - 401 Unauthorized: For authentication failures.
  - 403 Forbidden: When a user lacks permissions.
  - 404 Not Found: If a resource doesn't exist.
  - 400 Bad Request: For validation errors.

#### Security:
- Implement HTTPS for secure communication.
- Sanitize inputs to prevent SQL injection.

### 6.7 Dependency Injection for Permissions
- Utilize FastAPI's dependency injection to enforce permissions at the endpoint level.
- Implement reusable dependencies for checking roles and permissions.

## 7. Implementation Guidelines

### 7.1 Development Practices

#### Version Control:
- Use Git for version control.
- Follow branching strategies (e.g., main, develop, feature branches).

#### Code Style:
- Python: Follow PEP 8 guidelines.
- JavaScript/TypeScript: Use ESLint for linting.

#### Configuration Management:
- Use environment variables for configuration (e.g., database credentials, API keys).
- Ensure that sensitive information is not hard-coded.

### 7.2 Directory Structure

## 5. Directory Structure

### 5.1 Main Project Directory

```
FocusFlow/
├── backend/
└── frontends/
    └── web/
```

### 5.2 Backend Directory Structure

Instructions:
- Use the least number of files and directories while maintaining code clarity.
- Group related functionalities logically.

Structure:

```
FocusFlow/
├── backend/
    ├── app/
        ├── __init__.py                    # Package initialization
        ├── main.py                        # FastAPI app instance and routing
        ├── models.py                      # SQLAlchemy models
        ├── schemas.py                     # Pydantic schemas
        ├── routes.py                      # API route definitions
        ├── utils.py                       # Utilities (auth, JWT, etc.)
        ├── db.py                          # Database setup and session
        ├── config.py                      # Configuration settings
    ├── requirements.txt                   # Python dependencies
    ├── alembic/                           # Migrations
    ├── alembic.ini                        # Alembic configuration
    ├── .env                               # Environment variables
    └── README.md                          # Backend documentation
```

Descriptions:
- main.py:
  - Initializes the FastAPI application.
  - Includes middleware and exception handlers.
  - Imports and includes routes from routes.py.
- models.py:
  - Contains all SQLAlchemy models defining the database structure and relationships.
- schemas.py:
  - Contains Pydantic models for request and response validation.
- routes.py:
  - Defines all API endpoints, grouped logically:
    - Authentication Routes: Google OAuth2, JWT handling.
    - User Routes: Profile retrieval and update.
    - Todo Routes: CRUD operations for todos.
    - Team Routes: CRUD operations for teams and team member management.
    - Project Routes: CRUD operations for projects and team assignments.
- utils.py:
  - Helper functions and utilities:
    - Authentication Utilities: JWT token generation and validation.
    - OAuth2 Configuration: Setup for Google OAuth2 client.
    - Miscellaneous Utilities: Additional helper functions (e.g., input sanitization).
- db.py:
  - Database configuration:
    - Engine and Session Setup: Create asynchronous database engine and session maker.
    - Dependency Injection: Provide database session to routes.
- config.py:
  - Configuration management using environment variables.
- alembic/:
  - Directory for database migration scripts.

### 5.3 Web-Based Frontend Directory Structure

Instructions:
- Minimize the number of files and directories without compromising code readability.
- Consolidate files where appropriate.

Structure:

```
frontends/
└── web/
    ├── app/
        ├── layout.js                     # Root layout and global components
        ├── page.js                       # Home page with "Login with Google"
        ├── dashboard/
            └── page.js                   # Dashboard page
        ├── todos/
            └── page.js                   # Todos page
        ├── teams/
            └── page.js                   # Teams page
        ├── projects/
            └── page.js                   # Projects page
        ├── profile/
            └── page.js                   # Profile page
    ├── components/
        ├── index.js                      # Central export for all components
        ├── Layout/
            ├── Navbar.js                 # Navigation bar
            ├── Sidebar.js                # Sidebar for navigation
            ├── Footer.js                 # Footer component
        ├── Dashboard/
            ├── OverviewCard.js           # Overview components
            ├── AnalyticsChart.js         # Analytics chart component
        ├── Todos/
            ├── TodoList.js               # List of todos
            ├── TodoItem.js               # Individual todo display
            ├── TodoFilters.js            # Filtering options
        ├── Teams/
            ├── TeamList.js               # List of teams
            ├── TeamItem.js               # Individual team display
        ├── Projects/
            ├── ProjectList.js            # List of projects
            ├── ProjectItem.js            # Individual project display
    ├── utils/
        ├── api.js                        # API interaction functions
        ├── auth.js                       # Authentication utilities
    ├── context/
        ├── AuthContext.js                # Authentication context provider
    ├── public/
        ├── logo.png                      # Platform logo
    ├── styles/
        ├── globals.css                   # Global styles (Tailwind CSS)
    ├── .env.local                        # Environment variables
    ├── next.config.js                    # Next.js configuration
    ├── tailwind.config.js                # Tailwind CSS configuration
    ├── postcss.config.js                 # PostCSS configuration
    ├── package.json                      # Project dependencies and scripts
    └── README.md                         # Frontend documentation
```

Descriptions:
- app/:
  - Utilizes Next.js App Router.
  - Each directory under app/ corresponds to a route in the application.
  - layout.js: Contains root layout, including Navbar and Footer.
  - page.js: The home page with a "Login with Google" button.
  - Subdirectories like dashboard/, todos/, contain their respective page.js.
- components/:
  - Reusable components organized by functionality.
  - index.js: Exports all components for easy import.
  - Layout/: Components related to layout structure.
  - Dashboard/, Todos/, Teams/, Projects/: Components specific to each feature.
- utils/:
  - api.js: Functions to interact with backend APIs (GET, POST, PUT, DELETE requests).
  - auth.js: Functions to handle authentication, token storage, and OAuth flows.
- context/:
  - AuthContext.js: Provides authentication state and functions throughout the app.
- styles/:
  - globals.css: Global CSS styles and Tailwind directives.
- public/:
  - Contains static assets like images and icons.


## 8. Testing and Quality Assurance
- Unit Testing:
  - Write unit tests for individual functions and components.
- Integration Testing:
  - Test interactions between different parts of the application.
- End-to-End Testing:
  - Simulate user interactions using tools like Selenium or Cypress.
- Continuous Integration:
  - Set up CI pipelines to run tests automatically on code commits.
- Code Reviews:
  - Implement peer reviews to ensure code quality and maintainability.

## 9. Documentation
- README Files:
  - Maintain README.md files in main directories with setup instructions.
- API Documentation:
  - Use FastAPI's auto-generated API docs for API endpoint documentation.
- Code Comments and Docstrings:
  - Include clear comments and docstrings in the codebase.
- Developer Guide:
  - Provide documentation on how to set up the development environment, run the application, and contribute to the project.

## 10. Security Considerations
- Input Validation:
  - Validate and sanitize all user inputs.
- Authentication Security:
  - Use secure methods to handle JWT and OAuth tokens.
- Sensitive Data Protection:
  - Encrypt sensitive data at rest and in transit.
- Dependency Management:
  - Keep third-party libraries up to date.
  - Monitor for known vulnerabilities.

## 11. Performance and Scalability
- Performance Optimization:
  - Use efficient algorithms and database indexing.
- Asynchronous Operations:
  - Utilize asynchronous capabilities of FastAPI for improved performance.
- Scalability:
  - Design the application to handle increased loads.
  - Consider load balancing and database scaling strategies.


## 14. Appendices

### 14.1 Glossary
- JWT: JSON Web Token, a standard for securely transmitting information.
- OAuth2: An authorization framework that enables applications to obtain limited access to user accounts.
- ORM: Object-Relational Mapping, a technique for converting data between incompatible systems.
- RBAC: Role-Based Access Control, a method of regulating access based on the roles of individual users.

### 14.2 References
- FastAPI Documentation: https://fastapi.tiangolo.com/
- Next.js Documentation: https://nextjs.org/docs
- Tailwind CSS Documentation: https://tailwindcss.com/docs
- Pydantic Documentation: https://pydantic-docs.helpmanual.io/
- Alembic Documentation: https://alembic.sqlalchemy.org/en/latest/

--------------------
Convert the above PRD into 3 main sections;
1. Project: which included the information about the entire project
2. Backend: Which includes everything mentioned in the PRD about the backend
3. Frontend: Whcih includes everything mentioned in the PRD about the frontend