A comprehensive FastAPI backend system designed for equestrian facility management. This API provides complete control over horse care, employee management, inventory tracking, veterinary procedures, financial operations, and automated notifications via Telegram.
- Features
- Architecture
- Project Structure
- Requirements
- Installation
- Configuration
- Running the Application
- API Documentation
- Core Modules
- Telegram Integration
- Automated Scheduler
- Dashboard & Analytics
- API Usage Examples
- Development Guidelines
- π΄ Horse Management: Complete horse registry with photos, health records, nutritional plans, and owner assignments
- π¨βπΎ Employee Management: Staff administration with positions, contracts, salaries, absences, and shift scheduling
- π Owner Management: Owner profiles with payment tracking and monthly reports
- π Medicine Inventory: Advanced medication tracking with expiration alerts and stock monitoring
- πΎ Food Stock Control: Feed inventory management with supplier tracking and alpha control
- π° Financial Operations: Complete income and expense tracking with monthly analytics
- π Real-time Dashboard: Comprehensive analytics with cached data for optimal performance
- π€ Telegram Bot Integration: Automated notifications for veterinarians about medication alerts
- β° Automated Scheduler: Daily medication checks with smart notification system
- π Vaccination Plans: Scheduled vaccination programs with dose tracking
- π©Ί Horse Care Procedures: Medical procedures scheduling and application tracking
- π Monthly Owner Reports: Automated billing with detailed consumption reports
- π₯ Employee Shifts: Complete shift management system with employee assignments
- π User Authentication: Role-based access control with Supabase Auth
- π Pagination Support: Built-in pagination utilities for all list endpoints
This API follows a clean architecture pattern with clear separation of concerns:
βββββββββββββββββββ
β FastAPI App β
ββββββββββ¬βββββββββ
β
ββββββ΄βββββββββββββββββββββββββ
β β
βββββΌβββββ βββββββΌβββββββ
βRouters βββββββββββββββββββΊβ Schemas β
βββββ¬βββββ ββββββββββββββ
β
βββββΌβββββ ββββββββββββββ
β CRUD βββββββββββββββββββΊβ Supabase β
βββββ¬βββββ ββββββββββββββ
β
βββββΌβββββββββ
β Services β
ββββββββββββββ
- Routers: Handle HTTP requests and responses
- Schemas: Pydantic models for data validation
- CRUD: Database operations layer
- Services: Business logic and external integrations
- Utils: Shared utilities (pagination, helpers)
backend-Country/
βββ app/
β βββ main.py # Application entry point
β βββ config.py # Environment configuration
β βββ supabase_client.py # Supabase connection manager
β βββ scheduler.py # APScheduler for automated tasks
β β
β βββ crud/ # Database operations (25+ modules)
β β βββ employee.py
β β βββ horse.py
β β βββ medicine.py
β β βββ vaccination_plan.py
β β βββ ...
β β
β βββ routers/ # API endpoints (28+ routers)
β β βββ employee.py
β β βββ horse.py
β β βββ medicine.py
β β βββ dashboard.py # Analytics endpoint
β β βββ telegram.py # Telegram bot webhook
β β βββ ...
β β
β βββ schemas/ # Pydantic models (25+ schemas)
β β βββ employee.py
β β βββ horse.py
β β βββ medicine.py
β β βββ ...
β β
β βββ scripts/
β β βββ notifier.py # Telegram notification helper
β β
β βββ services/ # Business logic layer
β β
β βββ utils/
β βββ pagination.py # Pagination utilities
β
βββ requirements.txt # Python dependencies
βββ dataSchema.sql # Database schema reference
βββ README.md # This file- Python: 3.10 or newer
- pip: Package installer for Python
- Supabase Account: For database and authentication
- Telegram Bot (optional): For automated notifications
- Virtual Environment (recommended)
fastapi==0.116.1- Modern web frameworkuvicorn==0.35.0- ASGI serversupabase==2.18.1- Database clientpydantic==2.11.7- Data validationAPScheduler==3.10.4- Task schedulerpyTelegramBotAPI==4.29.1- Telegram bot integration
git clone <repository-url>
cd backend-Country# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtCreate a .env file in the project root (optional, as values are in config.py):
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
TELEGRAM_BOT_TOKEN=your-bot-token- Create a bot with @BotFather
- Get your bot token
- Update the
TELEGRAM_BOT_TOKENinconfig.pyor.env - Set your webhook URL in
main.py(line 69)
- Create a Supabase project
- Import the schema from
dataSchema.sql(for reference) - Update connection details in
config.py
uvicorn app.main:app --reloadThe API will be available at: http://127.0.0.1:8000
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4Once the server is running, access the interactive documentation:
- Swagger UI: http://127.0.0.1:8000/docs
- ReDoc: http://127.0.0.1:8000/redoc
| Category | Endpoints | Description |
|---|---|---|
| Horses | /horses |
CRUD operations + filter by owner |
| Employees | /employees |
Staff management + positions |
| Owners | /owners |
Owner profiles and reports |
| Medicine | /medicines |
Inventory with expiration tracking |
| Food Stock | /food_stock |
Feed inventory management |
| Food Providers | /food_provider |
Supplier information |
| Vaccination Plans | /vaccination_plan |
Vaccine schedules |
| Vaccination Applications | /vaccination_plan_application |
Vaccine administration records |
| Scheduled Procedures | /scheduled_procedure |
Annual procedure planning |
| Application Procedures | /application_procedure |
Procedure execution logs |
| Attention Horse | /attention_horse |
Medical attention records |
| Nutritional Plans | /nutritional_plan |
Diet planning |
| Nutritional Details | /nutritional_plan_details |
Diet specifications |
| Alpha Control | /alpha_control |
Alpha feed purchase tracking |
| Tasks | /task |
Task management |
| Task Categories | /task_category |
Task classification |
| Employee Absences | /employee_absence |
Vacation & absence tracking |
| Shifts | /shift_type, /shift_employed |
Shift management |
| Employee Shifts | /employees_shiftem |
Shift assignments |
| Expenses | /expenses |
Expense tracking |
| Income | /income |
Income tracking |
| Salary Payments | /salary_payment |
Employee salary records |
| Tip Payments | /tip_payment |
Employee tip tracking |
| Owner Reports | /owner_report_month |
Monthly billing reports |
| Horse Assignments | /horse_assignment |
Employee-horse assignments |
| Total Control | /total_control |
Complete horse cost calculations |
| Races | /race |
Horse breed management |
| User Roles | /user_role |
Role management |
| ERP Users | /erp_user |
User account management |
| Dashboard | /dashboard |
Analytics & statistics |
| Telegram | /telegram/webhook |
Bot webhook endpoint |
Complete horse lifecycle management with:
- Basic information (name, photo, birthdate, sex, color)
- Passport numbers and identification
- Location tracking (box, section, basket)
- State management (ACTIVO/INACTIVO)
- School status tracking
- Owner assignments
- Nutritional plan associations
- Race/breed information
Endpoints:
GET /horses- List all horses with paginationPOST /horses- Register new horseGET /horses/{id}- Get horse detailsPUT /horses/{id}- Update horse informationDELETE /horses/{id}- Remove horseGET /horses/by_owner/{id}- Filter horses by owner
Comprehensive HR system featuring:
- Personal information and photos
- Contract dates (start/end)
- Working hours (entry/exit time)
- Salary management
- Position assignments
- Active status tracking
- User account linking (UID)
Related Modules:
- Employee Positions: Job role definitions
- Employee Absences: Vacation and absence tracking
- Shift Management: Work schedule organization
- Salary Payments: Payment tracking with status
- Tip Payments: Additional compensation records
Advanced medication tracking with:
- Stock level monitoring (current/minimum)
- Expiration date tracking (box + opened dates)
- Days after opening calculations
- Automatic expiration status updates
- Stock status indicators
- Notification days configuration
- Source tracking (general/horse-specific)
- Active/inactive status
Smart Features:
- Automatic expiration calculation
- Low stock detection
- Telegram notifications for alerts
- Horse-specific medication tracking
Comprehensive immunization system:
- Vaccination Plans: Annual schedules with monthly doses
- Plan Applications: Execution records with observations
- Medicine association
- Alert status monitoring
- Employee tracking for administrations
- Horse-specific vaccination history
Complete feed planning system:
- Nutritional Plans: Diet programs with date ranges
- Plan Details: Food consumption per item
- Daily and monthly consumption tracking
- Period-based planning
- Horse assignment integration
- Food stock deduction
Full accounting system:
- Income Tracking: Revenue recording with descriptions
- Expense Tracking: Cost management with categories
- Owner Reports: Monthly billing with itemized charges
- Alpha Control: Feed purchase and sales tracking
- Total Control: Complete cost calculations per horse
Billing Items:
- Box/section/basket fees
- Alpha consumption
- Chala (feed) costs
- Veterinary services
- Vaccine applications
- Deworming
- Anemia exams
- External trainers
- Fines and other charges
Work organization system:
- Task creation with categories
- Employee assignments
- Status tracking (pending/in-progress/completed)
- Completion date monitoring
- Category-based organization
Medical procedure scheduling:
- Scheduled Procedures: Annual planning with monthly schedules
- Application Procedures: Execution tracking
- Alert label system
- Horse-specific procedure history
- Observation recording
/start- Initialize bot and link veterinarian account/help- Show available commands
The bot provides three main options:
- View All Medications - Complete inventory list
- Low/Out of Stock - Critical stock alerts
- Expiring/Expired - Expiration warnings
Automated alerts for:
- Low Stock: When medication reaches or falls below minimum stock
- Expiration Warnings: Configurable days before expiration
- Critical Alerts: Immediate notifications for critical situations
- Webhook-based architecture for real-time updates
- Automatic webhook registration on startup
- User linking via role-based system (Veterinarian = Role 8)
- Markdown formatting for rich messages
- Inline keyboard for interactive menus
The system runs automated checks daily at 9:30 PM Bolivia time (1:30 AM UTC):
- Stock Monitoring: Checks all active medications against minimum stock levels
- Expiration Tracking: Calculates days until expiration and sends alerts
- Smart Notifications: Sends aggregated alerts to all registered veterinarians
Located in app/scheduler.py:
scheduler.add_job(
lambda: asyncio.run(verificar_medicamentos()),
"cron",
hour=1, # 01 UTC = 21 Bolivia
minute=30,
)- Stock Alert:
stock <= minStock - Expiration Alert: Within configured warning period
- Target Users: All veterinarians (role 8) with registered Telegram chat_id
Returns comprehensive statistics with 30-second cache for optimal performance.
{
"stats": {
"totalHorses": 50,
"activeHorses": 45,
"schoolHorses": 12,
"totalEmployees": 25,
"activeEmployees": 23,
"totalOwners": 35,
"pendingTasks": 8,
"completedTasks": 42,
"monthlyIncome": 125000.50,
"monthlyExpenses": 87500.25,
"netBalance": 37500.25
},
"tasksSummary": [
{"status": "Pendiente", "count": 8},
{"status": "En progreso", "count": 3},
{"status": "Completada", "count": 42}
],
"recentAttentions": [
{
"idAttentionHorse": 123,
"date": "2026-01-25",
"description": "Vaccination",
"cost": 150.00,
"horseName": "Thunder",
"employeeName": "Dr. Smith"
}
],
"monthlyFinancials": [
{
"month": "2025-02",
"income": 120000.00,
"expenses": 85000.00
}
],
"dailyFinancials": [
{
"date": "2026-01-25",
"income": 4500.00,
"expenses": 3200.00
}
]
}- Real-time Statistics: Current counts for all major entities
- Financial Overview: 12-month financial history
- Task Analytics: Status breakdown of all tasks
- Recent Activity: Last 8 horse attentions with joins
- Daily Trends: Day-by-day income/expense tracking
- Performance Optimization: Smart caching with TTL
- Concurrent Queries: Async/await for parallel data fetching
curl -X POST http://127.0.0.1:8000/horses \
-H "Content-Type: application/json" \
-d '{
"horseName": "Thunder",
"birthdate": "2020-03-15",
"sex": "Male",
"color": "Brown",
"generalDescription": "Strong racing horse",
"passportNumber": 123456,
"box": true,
"section": false,
"basket": false,
"fk_idRace": 1,
"fk_idOwner": 5,
"state": "ACTIVO",
"stateSchool": false
}'curl -X POST http://127.0.0.1:8000/vaccination_plan \
-H "Content-Type: application/json" \
-d '{
"planName": "Annual Equine Vaccination",
"scheduledMonths": [1, 6, 12],
"dosesByMonth": {"1": 1, "6": 1, "12": 1},
"alertStatus": "ACTIVE",
"fk_idMedicine": 3
}'curl -X POST http://127.0.0.1:8000/attention_horse \
-H "Content-Type: application/json" \
-d '{
"date": "2026-01-27",
"dose": "10ml",
"cost": 250.00,
"description": "Routine vaccination and health check",
"fk_idHorse": 12,
"fk_idMedicine": 5,
"fk_idEmployee": 8
}'curl -X POST http://127.0.0.1:8000/medicines \
-H "Content-Type: application/json" \
-d '{
"name": "Ivermectin",
"description": "Antiparasitic medication",
"medicationType": "Injectable",
"stock": 50,
"minStock": 10,
"boxExpirationDate": "2026-12-31",
"openedOn": "2026-01-15",
"daysAfterOpening": 90,
"openedExpirationDate": "2026-04-15",
"expiryStatus": "ACTIVE",
"stockStatus": "ADEQUATE",
"notifyDaysBefore": "2026-04-08",
"isActive": true,
"source": "GENERAL"
}'curl -X POST http://127.0.0.1:8000/employees \
-H "Content-Type: application/json" \
-d '{
"fullName": "John Doe",
"ci": 1234567,
"phoneNumber": 77123456,
"startContractDate": "2026-01-01",
"endContractDate": "2026-12-31",
"startTime": "2026-01-01T08:00:00",
"exitTime": "2026-01-01T17:00:00",
"salary": 3500.00,
"status": true,
"fk_idPositionEmployee": 2
}'curl -X POST http://127.0.0.1:8000/owner_report_month \
-H "Content-Type: application/json" \
-d '{
"period": 202601,
"priceAlpha": 850.00,
"box": 500.00,
"section": 0.00,
"aBasket": 300.00,
"contributionCabFlyer": 150.00,
"VaccineApplication": 200.00,
"deworming": 100.00,
"AmeniaExam": 80.00,
"externalTeacher": 0.00,
"fine": 0.00,
"saleChala": 0.00,
"costPerBucket": 0.00,
"healthCardPayment": 50.00,
"other": 0.00,
"fk_idOwner": 5,
"state": "PENDING"
}'curl -X GET http://127.0.0.1:8000/dashboardcurl -X GET "http://127.0.0.1:8000/medicines?skip=0&limit=20"- Follow PEP 8 guidelines for Python code
- Use type hints for all function parameters and returns
- Write descriptive variable names and comments where necessary
- Keep functions small and focused (single responsibility)
- Never commit
.envfiles or secrets to version control - Use
.env.examplefor documenting required environment variables - Store all secrets in environment variables or secure vaults
- Schema First: Define Pydantic models in
schemas/ - CRUD Operations: Implement database operations in
crud/ - Router Endpoints: Create API endpoints in
routers/ - Register Router: Import and register in
main.py - Test Thoroughly: Use
/docsfor interactive testing
- Modify tables in Supabase dashboard
- Update
dataSchema.sqlfor reference - Update corresponding Pydantic schemas
- Update CRUD operations if needed
- Async/Await: Use async operations for all I/O
- Error Handling: Always handle exceptions with proper HTTP status codes
- Validation: Let Pydantic handle input validation
- Pagination: Use pagination utilities for list endpoints
- Caching: Implement caching for expensive operations (like dashboard)
- Security: Never expose internal errors to clients in production
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is proprietary software for Country Club ERP management.
For questions or issues, please contact the development team or open an issue in the repository.
Built with β€οΈ for equestrian facility management