Loading...
Loading...
Loading...
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
**NutriAves** is a complete poultry farm management system built for small to medium-scale chicken farms in Southern Chile. The application handles feed calculations, inventory management, egg production tracking, health/vaccination scheduling, and financial profitability analysis.
**Tech Stack:**
- Flask 3.0.0 (Python web framework)
- Pandas 2.1.4 for CSV data manipulation
- Chart.js 4.4.0 for interactive visualizations
- Jinja2 templates with inheritance pattern
- CSV-based data storage (no database)
## Running the Application
```bash
# Initial setup (first time only)
python3 -m venv venv
source venv/bin/activate # macOS/Linux
# venv\Scripts\activate # Windows
pip install -r requirements.txt
# Start development server
source venv/bin/activate
python app.py
# Access at: http://localhost:5000
```
**Important:** The application requires `numpy<2.0.0` due to pandas 2.1.4 compatibility. This is already specified in requirements.txt.
## Data Storage Architecture
All application data is stored in CSV files under `/data/` directory:
```
data/
├── inventory/
│ ├── flocks.csv # Bird flocks (lotes)
│ ├── movements.csv # Mortality/sales tracking
│ └── backups/ # Auto-generated backups
├── production/
│ ├── egg_production.csv # Daily egg collection records
│ └── backups/
├── health/
│ ├── vaccinations.csv # Vaccination schedule
│ ├── treatments.csv # Medical treatments
│ └── backups/
└── finance/
├── expenses.csv # Operating expenses
├── income.csv # Sales income
└── backups/
```
**Key Points:**
- CSV files are created automatically on first access
- Automatic backups are created before writes (timestamp-based)
- All CSV operations go through `DataManager` class in `utils/data_manager.py`
- Never directly use pandas I/O on CSV files - always use DataManager methods
## Core Architecture
### 1. BREED_DATA Dictionary (app.py)
The central data structure that drives breed-specific calculations. Contains consumption rates (grams/day), descriptions, and feeding recommendations for 11+ chicken breeds common in Southern Chile.
```python
BREED_DATA = {
'lohmann': {'name': 'Lohmann Brown', 'consumption': 115, ...},
'araucana': {'name': 'Araucana / Mapuche', 'consumption': 120, ...},
# ... 9 more breeds
}
```
This dictionary is used across:
- Feed calculator (original functionality)
- Inventory module (breed selection)
- Dashboard (consumption calculations)
- Health module (vaccine recommendations)
### 2. Flask Route Structure
18 routes organized by module:
```
/ → Redirect to dashboard
/dashboard → Main KPI dashboard
/calculator → Feed calculator (original feature)
/inventory/flocks → List all flocks (GET)
/inventory/add-flock → Add new flock (GET/POST)
/inventory/movements → Record mortality/sales (GET/POST)
/production/record → Daily egg entry (GET/POST)
/production/report → Production reports with Chart.js (GET)
/health/calendar → Vaccination calendar (GET)
/health/add-vaccination → Register vaccination (GET/POST)
/health/treatments → Medical treatments log (GET/POST)
/finance/expenses → Expense tracking (GET/POST)
/finance/income → Income tracking (GET/POST)
/finance/profitability → P&L analysis with charts (GET)
```
### 3. Utils Module Organization
**`utils/data_manager.py`** - CSV abstraction layer
- `read_csv_safe()`: Safe reading with auto-creation
- `write_csv()`: Writes with automatic backup
- `append_row()`: Add single row to CSV
- `get_next_id()`: Generate sequential IDs (F001, P002, etc.)
- `get_active_flocks()`: Query active flocks
- `update_flock_count()`: Update bird counts after movements
**`utils/calculators.py`** - Business logic
- `calculate_laying_rate()`: Egg production % by flock/period
- `get_production_timeline()`: Format data for Chart.js line graphs
- `calculate_profit_for_period()`: Net profit calculation
- `get_overdue_vaccinations()`: Alert system for health module
**`utils/validators.py`** - Input validation
- `validate_positive_number()`: Ensures quantities > 0
- `validate_date_not_future()`: Prevents future dates
- `validate_flock_data()`: Multi-field flock validation
- All validators raise `ValidationError` exceptions
### 4. Template Inheritance Pattern
```
base.html # Sidebar navigation, common structure
├── dashboard.html # KPI cards, alerts, recent flocks table
├── calculator.html # Original feed calculator (migrated)
├── inventory/
│ ├── flocks.html # Flock list table
│ ├── add_flock.html # Flock creation form
│ └── movements.html # Mortality/sales form
├── production/
│ ├── record_eggs.html # Daily egg entry form
│ └── production_report.html # Chart.js line graph + stats
├── health/
│ ├── calendar.html # Vaccination table with alerts
│ ├── add_vaccination.html
│ └── treatments.html
└── finance/
├── expenses.html # Expense entry + history table
├── income.html # Income entry + history table
└── profitability.html # Pie + Doughnut charts, P&L analysis
```
All templates extend `base.html` which provides:
- Sidebar navigation with module links
- Common CSS variables (`--primary`, `--secondary`, etc.)
- Block structure: `{% block title %}`, `{% block content %}`, `{% block extra_js %}`
## Key Development Patterns
### Adding a New CSV-backed Feature
1. Define CSV structure in DataManager with `default_columns`
2. Create route in app.py (GET for display, POST for submission)
3. Use `validators.py` functions for input validation
4. If calculations needed, add to `calculators.py`
5. Create template extending `base.html`
6. Follow existing form patterns (see `expenses.html` or `record_eggs.html`)
### Dashboard KPI Calculation Pattern
The dashboard aggregates data from all modules:
```python
# Example: Total active birds
flocks_df = DataManager.read_csv_safe('inventory/flocks.csv', ...)
active_flocks = flocks_df[flocks_df['status'] == 'active']
total_birds = active_flocks['current_count'].sum()
```
All KPIs follow: read CSV → filter → aggregate → pass to template.
### Alert System Pattern
Dashboard alerts are generated by checking thresholds:
```python
# Overdue vaccinations
vaccinations_df = DataManager.read_csv_safe('health/vaccinations.csv', ...)
overdue = vaccinations_df[vaccinations_df['next_due_date'] < today]
if len(overdue) > 0:
alerts.append({'type': 'danger', 'icon': '⚠️', 'message': '...'})
```
Alert types: `danger` (red), `warning` (yellow), `success` (green), `info` (blue).
### Chart.js Integration
Production and finance modules use Chart.js for visualization:
```javascript
// In template {% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script>
const ctx = document.getElementById('chartId').getContext('2d');
new Chart(ctx, {
type: 'line', // or 'pie', 'doughnut', 'bar'
data: {
labels: {{ labels|tojson|safe }},
datasets: [...]
}
});
</script>
```
Data is prepared in Flask route using `calculators.py` functions, then passed via Jinja2's `tojson` filter.
## Regional Context: Southern Chile
The application is optimized for Los Lagos and Los Ríos regions:
**Breeds Prioritized:**
- Lohmann Brown (commercial layers, 280-300 eggs/year)
- Araucana (blue eggs, heritage breed, 180-200 eggs/year)
- Brahma (extreme cold resistance)
- Criolla (rustic local breeds)
**Suppliers Referenced:**
- Fundo El Peumo (Puerto Montt) - feed
- Avícola Los Maitenes (Osorno) - chicks
- Cooprinsem - veterinary supplies
**Climate Considerations:**
- Feed calculator includes cold-weather adjustments
- Health module emphasizes respiratory disease alerts (high humidity)
- Production module tracks temperature correlation
## CSV File Schemas
### flocks.csv
```
flock_id,name,breed_key,initial_count,current_count,birth_date,acquisition_date,status,notes
F001,Ponedoras A,lohmann,50,48,2025-01-01,2025-02-15,active,Compradas Los Maitenes
```
### egg_production.csv
```
record_id,flock_id,date,eggs_collected,eggs_broken,eggs_dirty,temperature_c,notes
P001,F001,2026-01-21,42,1,2,18,Día lluvioso
```
### vaccinations.csv
```
vaccination_id,flock_id,vaccine_name,date_applied,next_due_date,vet_name,cost,notes
V001,F001,Newcastle,2025-02-15,2025-08-15,Cooprinsem,0,Incluida compra pollitas
```
### expenses.csv
```
expense_id,date,category,description,quantity,unit_cost,total_cost,supplier,flock_id
E001,2026-01-10,feed,Alimento Ponedora 16%,8,13000,104000,Fundo El Peumo,F001
```
### income.csv
```
income_id,date,product_type,quantity,unit_price,total_income,client,flock_id,notes
I001,2026-01-20,eggs_regular,60,250,15000,Feria local,F001,Docenas maple
```
## Troubleshooting
### Port 5000 already in use
```bash
# Use alternate port
python app.py --port 5001
# Or kill existing process
lsof -i :5000
kill <PID>
```
### NumPy compatibility error
```bash
# Force reinstall with correct version
pip install 'numpy<2.0.0' --force-reinstall
```
### CSV corruption
Auto-backups are in `data/*/backups/` with timestamp filenames. Restore by copying:
```bash
cp data/inventory/backups/flocks_backup_20260122_103045.csv data/inventory/flocks.csv
```
### Chart.js not rendering
- Check browser console (F12) for errors
- Verify internet connection (CDN dependency)
- Ensure data is properly formatted with `|tojson|safe` filter
## Code Style Notes
- Spanish is used for UI text, comments, and user-facing messages
- Variable names in English (PEP-8 style)
- All forms validate on both client-side (HTML5) and server-side (validators.py)
- Emojis are used extensively in UI for visual categorization (🌾 feed, 💊 medicine, etc.)
- Color scheme: Blue primary (#2563eb), Green secondary (#10b981)
- Date format: YYYY-MM-DD (ISO 8601) throughout
1. Application Archtect: myself, the human person guiding and suervising the development of the project.
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
A 24/7 emergency chat assistant for **first-time pet parents**. Users can ask questions about their pets' health, nutrition, behavior, and get immediate guidance during stressful situations. The AI has a friendly, supportive persona - like a knowledgeable friend who happens to know a lot about pets.