# Product Requirements Document: BMI Calculator Application

## 1. Overview

The BMI Calculator Application is a web-based tool that enables users to calculate their Body Mass Index (BMI) by inputting their height and weight measurements. The application provides instant BMI calculations, categorizes results according to WHO standards, displays historical tracking of BMI measurements, and offers personalized health insights based on the calculated values.

## 2. User Roles

### Anonymous User
- Can access the BMI calculator without registration
- Can input height and weight to calculate BMI
- Can view their current BMI result and category
- Cannot save calculation history
- Cannot access historical trends

### Registered User
- All permissions of Anonymous User
- Can create an account and log in
- Can save BMI calculations to their profile
- Can view historical BMI calculations and trends
- Can edit or delete their saved calculations
- Can set and track BMI goals
- Can update profile information (name, age, gender)
- Can export their BMI history

### Administrator
- All permissions of Registered User
- Can view system-wide analytics and usage statistics
- Can manage user accounts (view, disable, delete)
- Can configure BMI category thresholds 
- Can manage system settings and configurations
- Can view system logs and audit trails

## 3. Core Entities

### User
Represents a registered user account in the system.
- **Attributes**: userId, email, passwordHash, firstName, lastName, dateOfBirth, gender, createdAt, updatedAt, isActive, lastLoginAt

### Profile
Extended user information for personalized experience.
- **Attributes**: profileId, userId, preferredUnit (metric/imperial), targetBMI, targetWeight, heightCm, currentWeightKg, createdAt, updatedAt

### BMICalculation
A single BMI calculation record.
- **Attributes**: calculationId, userId (nullable for anonymous), heightCm, weightKg, bmiValue, bmiCategory, unit (metric/imperial), calculatedAt, notes, isDeleted

### BMICategory
Reference data for BMI classification ranges.
- **Attributes**: categoryId, categoryName, minBMI, maxBMI, description, colorCode, healthRisk, recommendations

### Goal
User-defined BMI or weight goals.
- **Attributes**: goalId, userId, goalType (BMI/weight), targetValue, currentValue, startDate, targetDate, status (active/achieved/abandoned), createdAt, updatedAt

### AuditLog
System activity tracking for security and debugging.
- **Attributes**: logId, userId (nullable), action, entityType, entityId, timestamp, ipAddress, userAgent, details

## 4. Entity Relationships

### User ↔ Profile
- **Relationship**: One-to-One
- Each User has exactly one Profile
- Profile cannot exist without a User

### User ↔ BMICalculation
- **Relationship**: One-to-Many
- A User can have zero or many BMICalculations
- A BMICalculation may belong to zero or one User (nullable for anonymous calculations)

### BMICalculation ↔ BMICategory
- **Relationship**: Many-to-One
- Each BMICalculation is associated with one BMICategory
- A BMICategory can be referenced by many BMICalculations

### User ↔ Goal
- **Relationship**: One-to-Many
- A User can have zero or many Goals
- Each Goal belongs to exactly one User

### User ↔ AuditLog
- **Relationship**: One-to-Many
- A User can have many AuditLog entries
- An AuditLog entry may reference zero or one User (nullable for system actions)

## 5. Key Workflows

### Workflow 1: Anonymous BMI Calculation
1. User lands on the calculator page
2. User selects unit system (metric or imperial)
3. User enters height value(s)
   - Metric: centimeters or meters
   - Imperial: feet and inches
4. User enters weight value
   - Metric: kilograms
   - Imperial: pounds
5. System validates input (positive numbers, reasonable ranges)
6. User clicks "Calculate BMI"
7. System calculates BMI using formula: weight(kg) / (height(m))²
8. System determines BMI category based on WHO standards
9. System displays:
   - Calculated BMI value
   - BMI category with color coding
   - Health risk information
   - General recommendations
10. User can reset and calculate again

### Workflow 2: User Registration and Login
1. User clicks "Sign Up" or "Register"
2. User provides email, password, first name, last name, date of birth, gender
3. System validates email format and password strength
4. System checks for duplicate email
5. System creates User account with hashed password
6. System creates associated Profile with default settings
7. System sends verification email (optional)
8. User is redirected to login page or automatically logged in
9. For login: User enters email and password
10. System validates credentials
11. System creates session/token
12. User is redirected to dashboard

### Workflow 3: Registered User BMI Calculation with History
1. Logged-in user navigates to calculator
2. System pre-fills height from Profile if available
3. User enters current weight
4. User optionally adds notes (e.g., "after workout", "morning weight")
5. User clicks "Calculate and Save"
6. System performs BMI calculation
7. System creates BMICalculation record linked to user
8. System updates Profile with current weight
9. System displays result with historical comparison
10. System shows trend graph if multiple calculations exist
11. User can view detailed history on separate page

### Workflow 4: Goal Setting and Tracking
1. Logged-in user navigates to "Goals" section
2. User clicks "Set New Goal"
3. User selects goal type (target BMI or target weight)
4. User enters target value and target date
5. System validates target is realistic (within healthy ranges)
6. System calculates required change and weekly rate
7. System creates Goal record with status "active"
8. System displays goal progress on dashboard
9. On each new BMI calculation:
   - System checks if goal is achieved
   - System updates goal progress percentage
   - System updates goal status if achieved
10. User can edit or abandon goal at any time

### Workflow 5: Administrator User Management
1. Admin logs in with admin credentials
2. Admin navigates to "User Management" section
3. System displays paginated list of all users
4. Admin can search/filter users by email, name, registration date, status
5. Admin selects a user to view details
6. System displays user profile, calculation history, and activity
7. Admin can perform actions:
   - Disable/enable user account
   - Delete user account (with confirmation)
   - View audit logs for user
8. System records all admin actions in AuditLog
9. System sends notification to affected user (if applicable)

## 6. Features & Requirements

### Module: Authentication & Authorization

#### F-AUTH-001: User Registration
- System shall provide registration form with fields: email, password, confirm password, first name, last name, date of birth, gender
- System shall validate email format using RFC 5322 standard
- System shall enforce password requirements: minimum 8 characters, at least one uppercase, one lowercase, one number
- System shall check for duplicate email addresses
- System shall hash passwords using bcrypt or Argon2
- System shall create user profile automatically upon registration
- System shall send welcome email upon successful registration

#### F-AUTH-002: User Login
- System shall provide login form with email and password fields
- System shall validate credentials against stored hash
- System shall implement rate limiting: maximum 5 failed attempts per 15 minutes
- System shall create secure session token (JWT) upon successful login
- System shall record last login timestamp
- System shall support "Remember Me" functionality (optional)

#### F-AUTH-003: Password Reset
- System shall provide "Forgot Password" link on login page
- System shall send password reset email with time-limited token (valid 1 hour)
- System shall validate reset token before allowing password change
- System shall enforce same password requirements as registration

#### F-AUTH-004: Session Management
- System shall maintain user session for 24 hours of inactivity
- System shall provide logout functionality
- System shall invalidate session token on logout
- System shall support concurrent sessions from different devices

### Module: BMI Calculator

#### F-CALC-001: Unit Selection
- System shall support metric units (cm, kg)
- System shall support imperial units (feet, inches, pounds)
- System shall remember unit preference for registered users
- System shall provide toggle or dropdown for unit selection
- System shall convert between units automatically

#### F-CALC-002: Input Fields
- System shall provide height input field(s) based on selected unit
  - Metric: single field for cm or m
  - Imperial: two fields for feet and inches
- System shall provide weight input field
- System shall validate inputs are positive numbers
- System shall enforce reasonable ranges:
  - Height: 50-300 cm (1.6-9.8 feet)
  - Weight: 10-500 kg (22-1100 lbs)
- System shall display input validation errors in real-time

#### F-CALC-003: BMI Calculation
- System shall calculate BMI using formula: BMI = weight(kg) / (height(m))²
- System shall convert imperial measurements to metric before calculation
- System shall round BMI result to one decimal place
- System shall determine BMI category based on calculated value
- System shall perform calculation on button click or form submission

#### F-CALC-004: Result Display
- System shall display calculated BMI value prominently
- System shall display BMI category name with color coding
- System shall display category description and health risk level
- System shall display healthy BMI range (18.5-24.9)
- System shall display general health recommendations
- System shall show visual indicator (gauge, chart, or color bar)

#### F-CALC-005: Anonymous Calculation
- System shall allow calculations without user login
- System shall not persist anonymous calculations
- System shall display prompt to register for history tracking
- System shall maintain calculation in session for current page view

### Module: User Profile

#### F-PROF-001: Profile Management
- System shall display user profile page with editable fields
- System shall allow editing: first name, last name, date of birth, gender
- System shall allow setting preferred unit system
- System shall allow setting default height
- System shall validate all profile updates
- System shall display success/error messages after updates

#### F-PROF-002: Profile Display
- System shall display current BMI on profile dashboard
- System shall display last calculation date
- System shall display total number of calculations
- System shall display current goal status (if any)
- System shall calculate and display age from date of birth

### Module: Calculation History

#### F-HIST-001: Save Calculation
- System shall automatically save calculations for logged-in users
- System shall store: height, weight, BMI value, category, timestamp, notes
- System shall associate calculation with user account
- System shall confirm successful save with notification

#### F-HIST-002: View History
- System shall display paginated list of past calculations
- System shall show: date, BMI value, category, weight, notes
- System shall sort by date (newest first) by default
- System shall allow sorting by BMI value or date
- System shall display 10-20 records per page
- System shall provide search/filter by date range

#### F-HIST-003: Edit Calculation
- System shall allow editing notes on saved calculations
- System shall not allow editing height, weight, or BMI values
- System shall record edit timestamp
- System shall display "last edited" indicator

#### F-HIST-004: Delete Calculation
- System shall allow users to delete their calculations
- System shall implement soft delete (set isDeleted flag)
- System shall require confirmation before deletion
- System shall not display deleted calculations in history
- System shall allow administrators to permanently delete records

#### F-HIST-005: History Visualization
- System shall display line chart of BMI over time
- System shall display weight trend chart
- System shall highlight BMI category zones on chart
- System shall show data points for each calculation
- System shall allow toggling between BMI and weight views
- System shall support date range filtering on charts

#### F-HIST-006: Export History
- System shall provide "Export" functionality
- System shall support CSV format export
- System shall support PDF format export
- System shall include all calculation data in export
- System shall name export file with username and date

### Module: Goals

#### F-GOAL-001: Create Goal
- System shall provide goal creation form
- System shall allow selecting goal type: target BMI or target weight
- System shall require target value and target date
- System shall validate target is within healthy ranges
- System shall calculate required weekly change
- System shall warn if goal is unrealistic (>1kg/week loss)
- System shall create goal with status "active"

#### F-GOAL-002: View Goals
- System shall display all user goals (active and completed)
- System shall show current progress as percentage
- System shall show days remaining to target date
- System shall show required weekly change to meet goal
- System shall highlight overdue goals

#### F-GOAL-003: Update Goal
- System shall allow editing target value and target date
- System shall allow changing goal status (active/abandoned)
- System shall recalculate progress after updates
- System shall record update timestamp

#### F-GOAL-004: Goal Tracking
- System shall automatically update goal progress on new calculations
- System shall mark goal as "achieved" when target is reached
- System shall send congratulatory message when goal achieved
- System shall suggest new goal after achievement

#### F-GOAL-005: Goal Notifications
- System shall send reminder if no calculation in 7 days (optional)
- System shall send encouragement if progress is on track
- System shall send alert if progress is significantly off track

### Module: Administration

#### F-ADMIN-001: User Management
- System shall display list of all registered users
- System shall show: email, name, registration date, last login, status
- System shall provide search by email or name
- System shall provide filter by status (active/inactive)
- System shall allow viewing user details and calculation history
- System shall allow disabling/enabling user accounts
- System shall allow deleting user accounts with confirmation

#### F-ADMIN-002: System Analytics
- System shall display total number of users
- System shall display total number of calculations
- System shall display calculations per day/week/month chart
- System shall display distribution of BMI categories
- System shall display average BMI by age group and gender
- System shall display user registration trend

#### F-ADMIN-003: BMI Category Management
- System shall display list of BMI categories
- System shall allow editing category thresholds
- System shall allow editing category descriptions and recommendations
- System shall validate category ranges don't overlap
- System shall require admin confirmation for changes

#### F-ADMIN-004: Audit Logs
- System shall display audit log entries
- System shall show: timestamp, user, action, entity, details
- System shall provide filtering by date range, user, action type
- System shall support exporting audit logs
- System shall retain logs for minimum 90 days

## 7. Business Rules

### BR-001: BMI Calculation
- BMI must be calculated using the formula: weight(kg) / (height(m))²
- BMI result must be rounded to one decimal place
- Calculations must use metric units internally; imperial inputs must be converted

### BR-002: BMI Categories (WHO Standard)
- Underweight: BMI < 18.5
- Normal weight: BMI 18.5 - 24.9
- Overweight: BMI 25.0 - 29.9
- Obese Class I: BMI 30.0 - 34.9
- Obese Class II: BMI 35.0 - 39.9
- Obese Class III: BMI ≥ 40.0

### BR-003: Input Validation
- Height must be between 50 cm and 300 cm (1.6 - 9.8 feet)
- Weight must be between 10 kg and 500 kg (22 - 1100 lbs)
- All numeric inputs must be positive numbers
- Date of birth must result in age between 2 and 120 years

### BR-004: User Account Rules
- Email addresses must be unique across the system
- Passwords must be minimum 8 characters with at least one uppercase, one lowercase, and one number
- Users must be at least 13 years old to register (COPPA compliance)
- Inactive accounts (no login for 2 years) may be archived

### BR-005: Calculation History
- Anonymous calculations are not persisted to database
- Registered users can have unlimited calculation history
- Deleted calculations are soft-deleted (flagged, not removed)
- Calculations cannot be modified after creation (except notes)

### BR-006: Goal Rules
- Users can have maximum 3 active goals simultaneously
- Target BMI must be between 18.5 and 30.0 (healthy to slightly overweight)
- Target date must be at least 7 days in the future
- Target date must not exceed 2 years from creation
- Weight loss goals exceeding 1 kg/week must show warning
- Goals are automatically marked "achieved" when target is reached

### BR-007: Data Retention
- User accounts and data are retained indefinitely unless user requests deletion
- Deleted user data must be permanently removed within 30 days (GDPR compliance)
- Audit logs must be retained for minimum 90 days
- Anonymous calculation data in session expires after 24 hours

### BR-008: Access Control
- Anonymous users can only calculate BMI, not save history
- Registered users can only access their own data
- Administrators can view all user data but cannot modify user calculations
- System actions (automated processes) are logged with null userId

### BR-009: Unit Conversion
- 1 inch = 2.54 cm
- 1 foot = 12 inches = 30.48 cm
- 1 pound = 0.453592 kg
- Conversions must maintain precision to 2 decimal places

### BR-010: Session and Security
- Failed login attempts are limited to 5 per 15-minute window per IP address
- Sessions expire after 24 hours of inactivity
- Password reset tokens expire after 1 hour
- All passwords must be hashed using bcrypt (cost factor 10+) or Argon2

## 8. Non-Functional Requirements

### NFR-001: Performance
- BMI calculation must complete within 100ms
- Page load time must not exceed 2 seconds on 3G connection
- API response time must be under 500ms for 95th percentile
- System must support 100 concurrent users without degradation
- Database queries must be optimized with appropriate indexes
- Chart rendering must complete within 1 second for up to 100 data points

### NFR-002: Scalability
- System must be designed to scale horizontally
- Database must support up to 100,000 registered users
- System must handle up to 10,000 calculations per day
- File storage for exports must support up to 1GB per user
- System architecture must support load balancing

### NFR-003: Security
- All passwords must be hashed using bcrypt or Argon2
- All API endpoints must use HTTPS/TLS 1.2 or higher
- Authentication tokens must be signed and encrypted (JWT)
- System must implement CSRF protection
- System must sanitize all user inputs to prevent XSS attacks
- System must use parameterized queries to prevent SQL injection
- Sensitive data (passwords, tokens) must never be logged
- System must implement rate limiting on all public endpoints
- Admin panel must require additional authentication (2FA recommended)

### NFR-004: Availability
- System must maintain 99.5% uptime during business hours
- Planned maintenance must be scheduled during low-usage periods
- System must have automated health checks every 5 minutes
- Database must have automated daily backups
- Backup retention period must be minimum 30 days
- System must have disaster recovery plan with RTO < 4 hours

### NFR-005: Usability
- User interface must be intuitive and require no training
- Calculator must be accessible within 2 clicks from any page
- Error messages must be clear and actionable
- System must provide inline help text for complex fields
- Forms must show real-time validation feedback
- System must be responsive and work on mobile devices (320px width minimum)

### NFR-006: Accessibility
- System must comply with WCAG 2.1 Level AA standards
- All interactive elements must be keyboard accessible
- All images must have alt text
- Color must not be the only means of conveying information
- Text must have minimum contrast ratio of 4.5:1
- Forms must have properly associated labels
- System must support screen readers

### NFR-007: Browser Compatibility
- System must support latest 2 versions of Chrome, Firefox, Safari, Edge
- System must gracefully degrade on older browsers
- JavaScript must not be required for basic calculation (progressive enhancement)
- System must work on mobile browsers (iOS Safari, Chrome Mobile)

### NFR-008: Data Privacy & Compliance
- System must comply with GDPR requirements
- System must comply with CCPA requirements
- Users must be able to export their data in machine-readable format
- Users must be able to request account deletion
- System must provide privacy policy and terms of service
- System must obtain consent for non-essential cookies
- System must not share user data with third parties without consent

### NFR-009: Monitoring & Logging
- System must log all errors with stack traces
- System must log all authentication attempts
- System must log all administrative actions
- System must monitor API response times
- System must monitor database performance
- System must alert administrators of critical errors
- Logs must not contain sensitive personal information

### NFR-010: Maintainability
- Code must follow consistent style guide
- Code must have minimum 70% test coverage
- API must be documented using OpenAPI/Swagger
- Database schema must be version controlled
- System must use semantic versioning
- All dependencies must be kept up to date
- System must have comprehensive README and deployment documentation

### NFR-011: Localization (Future)
- System architecture must support internationalization (i18n)
- All user-facing text must be externalized to resource files
- Date and number formats must respect user locale
- System must support UTF-8 character encoding

### NFR-012: Mobile Responsiveness
- UI must adapt to screen sizes from 320px to 2560px width
- Touch targets must be minimum 44x44 pixels
- Forms must use appropriate input types for mobile keyboards
- Charts must be touch-enabled for mobile interaction
- Navigation must be optimized for mobile (hamburger menu acceptable)

---

**Document Version:** 1.0  
**Last Updated:** 2025-01-XX  
**Document Owner:** Product Management  
**Status:** Ready for Development