This guide provides comprehensive instructions for setting up and contributing to the Portfolio Coach development environment.
- Python 3.11+
- Node.js 18.0+
- Docker & Docker Compose
- PostgreSQL 13+
- Git
- VS Code with extensions:
- Python
- JavaScript/TypeScript
- Docker
- GitLens
- Prettier
- ESLint
git clone https://github.com/yourusername/portfolio-coach.git
cd portfolio-coach# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Set up environment variables
cp env.example .env
# Edit .env with your configurationcd frontend
npm install# Using Docker
docker run --name portfolio-postgres \
-e POSTGRES_DB=portfolio_coach \
-e POSTGRES_USER=portfolio_user \
-e POSTGRES_PASSWORD=portfolio_password \
-p 9853:5432 \
-d postgres:13
# Or using local PostgreSQL
createdb portfolio_coach# Activate virtual environment
source venv/bin/activate
# Run Flask development server
python run.py --mode webcd frontend
npm start# Start all services
docker compose -f docker/docker-compose-simple.yml up -d
# View logs
docker compose -f docker/docker-compose-simple.yml logs -f# Deploy with production configuration
./scripts/deploy_complete.shportfolio-coach/
├── src/ # Backend source code
│ ├── api/ # API endpoints
│ ├── services/ # Business logic services
│ ├── database/ # Database models and migrations
│ ├── utils/ # Utility functions
│ └── web/ # Flask application
├── frontend/ # React frontend
│ ├── src/
│ │ ├── components/ # React components
│ │ ├── pages/ # Page components
│ │ ├── context/ # React context
│ │ └── utils/ # Frontend utilities
│ └── public/ # Static assets
├── docker/ # Docker configuration
├── docs/ # Documentation
├── scripts/ # Deployment and utility scripts
├── tests/ # Test files
└── requirements.txt # Python dependencies
- Formatter: Black
- Linter: Flake8
- Type Checking: mypy
- Import Sorting: isort
# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py311']
[tool.isort]
profile = "black"
multi_line_output = 3# Install pre-commit
pip install pre-commit
pre-commit install
# Run manually
pre-commit run --all-files- Formatter: Prettier
- Linter: ESLint
- Type Checking: TypeScript (optional)
// .prettierrc
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}# Run all tests
python -m pytest tests/
# Run with coverage
python -m pytest tests/ --cov=src --cov-report=html
# Run specific test file
python -m pytest tests/test_portfolio_service.py
# Run with verbose output
python -m pytest tests/ -vcd frontend
# Run unit tests
npm test
# Run with coverage
npm test -- --coverage
# Run specific test
npm test -- --testNamePattern="Portfolio"# Run integration tests
./tests/test_integration.sh
# Test API endpoints
curl -X GET http://localhost:9854/api/health
curl -X GET http://localhost:9855/api/portfolio-summary# Create new migration
flask db migrate -m "Add user preferences table"
# Apply migrations
flask db upgrade
# Rollback migration
flask db downgrade# Load sample data
python scripts/seed_data.py
# Reset database
python scripts/reset_db.py- Create endpoint in
src/web/app.py
@app.route('/api/new-endpoint', methods=['GET'])
def new_endpoint():
try:
# Business logic
result = some_service.process()
return jsonify({'success': True, 'data': result})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500- Add service in
src/services/
class NewService:
def __init__(self):
self.db = Database()
def process(self):
# Implementation
pass- Add tests in
tests/
def test_new_endpoint():
response = client.get('/api/new-endpoint')
assert response.status_code == 200
assert 'data' in response.jsonUpdate API documentation in docs/API.md when adding new endpoints.
- Create component in
frontend/src/components/
import React from 'react';
const NewComponent = ({ data }) => {
return (
<div className="bg-white rounded-lg shadow p-4">
<h2 className="text-lg font-semibold">{data.title}</h2>
<p className="text-gray-600">{data.description}</p>
</div>
);
};
export default NewComponent;- Add to page in
frontend/src/pages/
import NewComponent from '../components/NewComponent';
const NewPage = () => {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data
fetchData().then(setData);
}, []);
return (
<div className="container mx-auto px-4">
<NewComponent data={data} />
</div>
);
};Use React Context for global state:
// frontend/src/context/AppContext.js
import React, { createContext, useContext, useReducer } from 'react';
const AppContext = createContext();
export const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
export const useApp = () => useContext(AppContext);# Add debug logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Use debugger
import pdb; pdb.set_trace()
# Flask debug mode
export FLASK_ENV=development
export FLASK_DEBUG=1// Browser console
console.log('Debug info:', data);
// React DevTools
// Install React Developer Tools browser extension
// Debug with VS Code
// Add breakpoints in VS Code debugger# View container logs
docker logs <container_name>
# Execute commands in container
docker exec -it <container_name> /bin/bash
# View container resources
docker stats-
Database Queries
- Use indexes
- Optimize queries
- Use connection pooling
-
Caching
- Redis for session data
- In-memory caching
- CDN for static assets
-
Async Processing
- Background tasks
- Message queues
- Parallel processing
-
Code Splitting
- Lazy loading
- Dynamic imports
- Route-based splitting
-
Bundle Optimization
- Tree shaking
- Minification
- Compression
-
Performance Monitoring
- Lighthouse audits
- Core Web Vitals
- Bundle analysis
-
Input Validation
- Sanitize all inputs
- Use validation libraries
- Prevent SQL injection
-
Authentication
- JWT tokens
- Password hashing
- Rate limiting
-
Data Protection
- Encryption at rest
- HTTPS only
- Secure headers
-
XSS Prevention
- Sanitize user inputs
- Use Content Security Policy
- Escape HTML content
-
CSRF Protection
- CSRF tokens
- SameSite cookies
- Secure headers
# Build and run with Docker
docker compose -f docker/docker-compose-simple.yml up --build
# Or run services individually
python run.py --mode web &
cd frontend && npm start# Deploy to production
./scripts/deploy_complete.sh
# Monitor deployment
docker compose -f docker/docker-compose-simple.yml logs -f-
Create feature branch
git checkout -b feature/amazing-feature
-
Make changes
- Follow coding standards
- Add tests
- Update documentation
-
Run tests
# Backend tests python -m pytest tests/ # Frontend tests cd frontend && npm test
-
Submit pull request
- Clear description
- Link to issues
- Include screenshots if UI changes
- Code follows style guidelines
- Tests pass
- Documentation updated
- No security vulnerabilities
- Performance impact considered
- Error handling implemented
-
Port conflicts
# Check port usage lsof -i :9855 # Kill process using port kill -9 <PID>
-
Database connection issues
# Check database status docker logs portfolio-postgres # Reset database docker-compose down -v docker-compose up -d
-
Frontend build issues
# Clear cache rm -rf frontend/node_modules npm install # Rebuild npm run build
- Documentation: Check
docs/directory - Issues: Search existing GitHub issues
- Discussions: Use GitHub Discussions
- Support: Contact development team
- Postman - API testing
- pgAdmin - Database management
- Docker Desktop
- VS Code - Code editor