Skip to content

vako-ai/animal-amr

Repository files navigation

AntimicrobialTracker (FarmTrack AMR)

A comprehensive digital platform for veterinary and agricultural professionals to track and manage antimicrobial usage on farms, featuring real-time analytics, AI-powered insights, and regulatory compliance tools.

πŸ—οΈ Architecture Overview

The application follows a modern full-stack architecture with offline-first capabilities:

  • Frontend: React 18 with TypeScript, Vite build system
  • Backend: Express.js with TypeScript
  • State Management: TanStack Query for server state, React Context for app state
  • UI Framework: Tailwind CSS with shadcn/ui components
  • Storage: In-memory storage with local persistence and sync capabilities
  • AI Integration: OpenAI API for intelligent features

πŸ“ Project Structure

β”œβ”€β”€ client/                    # Frontend React application
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/        # Reusable UI components
β”‚   β”‚   β”‚   β”œβ”€β”€ dashboard/     # Dashboard-specific components
β”‚   β”‚   β”‚   β”œβ”€β”€ layout/        # Layout components (Header, Sidebar, etc.)
β”‚   β”‚   β”‚   β”œβ”€β”€ onboarding/    # Onboarding wizard components
β”‚   β”‚   β”‚   └── ui/            # Base UI components (shadcn/ui)
β”‚   β”‚   β”œβ”€β”€ context/           # React context providers
β”‚   β”‚   β”œβ”€β”€ hooks/             # Custom React hooks
β”‚   β”‚   β”œβ”€β”€ lib/               # Utility libraries and configurations
β”‚   β”‚   β”œβ”€β”€ pages/             # Application pages/routes
β”‚   β”‚   └── App.tsx            # Main application component
β”œβ”€β”€ server/                    # Backend Express application
β”‚   β”œβ”€β”€ services/              # External service integrations
β”‚   β”œβ”€β”€ index.ts               # Server entry point
β”‚   β”œβ”€β”€ routes.ts              # API route definitions
β”‚   β”œβ”€β”€ storage.ts             # Data storage interface and implementation
β”‚   └── vite.ts                # Vite development server integration
β”œβ”€β”€ shared/                    # Shared types and schemas
β”‚   └── schema.ts              # Database schema and type definitions
└── package.json               # Project dependencies and scripts

πŸ”§ Core Components

Frontend Architecture

Context Providers

  • AuthContext: Manages user authentication state
  • NetworkContext: Handles online/offline status and data synchronization
  • OnboardingContext: Controls user onboarding flow and preferences

Key Pages

  • Dashboard: Main overview with quick stats and recent activities
  • LivestockRegistry: Animal management and tracking
  • TreatmentLogging: Antimicrobial treatment recording
  • VfdCompliance: Veterinary Feed Directive management
  • Analytics: Usage analytics and reporting
  • Reporting: Compliance report generation
  • AIFeatures: AI-powered tools and recommendations

Component Structure

// Layout Components
Header; // Top navigation with status indicators
Sidebar; // Desktop navigation menu
MobileNav; // Mobile bottom navigation

// Dashboard Components
QuickStats; // Key metrics display
QuickActions; // Common action shortcuts
RecentActivity; // Latest system activities

// Onboarding Components
OnboardingWizard; // Multi-step setup wizard
WelcomeStep; // Introduction step
RoleSelectionStep; // User role configuration
FarmTypeStep; // Farm type selection
AnimalTypesStep; // Animal type preferences
FeaturesStep; // Feature preferences
CompletionStep; // Setup completion summary

Backend Architecture

Storage System

interface IStorage {
  // User management
  getUser(id: number): Promise<User | undefined>;
  getUserByUsername(username: string): Promise<User | undefined>;
  createUser(user: InsertUser): Promise<User>;
  updateUser(id: number, user: Partial<InsertUser>): Promise<User | undefined>;

  // Livestock management
  getLivestock(id: number): Promise<Livestock | undefined>;
  getAllLivestock(): Promise<Livestock[]>;
  createLivestock(livestock: InsertLivestock): Promise<Livestock>;
  updateLivestock(
    id: number,
    livestock: Partial<InsertLivestock>,
  ): Promise<Livestock | undefined>;
  deleteLivestock(id: number): Promise<boolean>;

  // Treatment tracking
  getTreatment(id: number): Promise<Treatment | undefined>;
  getAllTreatments(): Promise<Treatment[]>;
  getTreatmentsByStatus(status: string): Promise<Treatment[]>;
  createTreatment(treatment: InsertTreatment): Promise<Treatment>;
  updateTreatment(
    id: number,
    treatment: Partial<InsertTreatment>,
  ): Promise<Treatment | undefined>;
  deleteTreatment(id: number): Promise<boolean>;

  // VFD management
  getVFD(id: number): Promise<VFD | undefined>;
  getAllVFDs(): Promise<VFD[]>;
  getVFDsByStatus(statuses: string[]): Promise<VFD[]>;
  createVFD(vfd: InsertVFD): Promise<VFD>;
  updateVFD(id: number, vfd: Partial<InsertVFD>): Promise<VFD | undefined>;
  deleteVFD(id: number): Promise<boolean>;

  // Report generation
  getReport(id: number): Promise<Report | undefined>;
  getAllReports(): Promise<Report[]>;
  createReport(report: InsertReport): Promise<Report>;
}

API Routes

// Authentication
POST   /api/auth/login
POST   /api/auth/logout
GET    /api/auth/me

// Livestock Management
GET    /api/livestock
GET    /api/livestock/:id
POST   /api/livestock
PATCH  /api/livestock/:id
DELETE /api/livestock/:id

// Treatment Logging
GET    /api/treatments
GET    /api/treatments/active
GET    /api/treatments/:id
POST   /api/treatments
PATCH  /api/treatments/:id
DELETE /api/treatments/:id

// VFD Compliance
GET    /api/vfds
GET    /api/vfds/active
GET    /api/vfds/stats
GET    /api/vfds/:id
POST   /api/vfds
PATCH  /api/vfds/:id
DELETE /api/vfds/:id

// Analytics & Reporting
GET    /api/reports
GET    /api/reports/:id
POST   /api/reports
GET    /api/reports/:id/download
GET    /api/analytics/quick-stats
GET    /api/analytics/recent-activities

// AI Features
POST   /api/ai/treatment-recommendations
POST   /api/ai/resistance-prediction
POST   /api/ai/generate-report
POST   /api/ai/identify-livestock

πŸ—„οΈ Data Models

Core Entities

User

interface User {
  id: number;
  username: string;
  email: string;
  firstName: string;
  lastName: string;
  role: string;
  createdAt: string;
  lastLogin: string | null;
  isActive: boolean;
}

Livestock

interface Livestock {
  id: number;
  identifier: string;
  type: string;
  breed: string | null;
  dateOfBirth: string | null;
  weight: number | null;
  healthStatus: string;
  location: string | null;
  dateAdded: string;
}

Treatment

interface Treatment {
  id: number;
  livestockId: string;
  drugName: string;
  drugClass: string;
  dosage: string;
  routeOfAdministration: string;
  treatmentReason: string;
  startDate: string;
  endDate: string | null;
  withdrawalPeriod: number | null;
  veterinarianId: string | null;
  status: string;
  notes: string | null;
  createdAt: string;
  updatedAt: string;
}

VFD (Veterinary Feed Directive)

interface VFD {
  id: number;
  vfdNumber: string;
  drugName: string;
  drugClass: string;
  livestockType: string;
  approximateNumber: number;
  issueDate: string;
  expirationDate: string;
  veterinarianId: string;
  farmId: string;
  feedMillId: string | null;
  status: string;
  notes: string | null;
  createdAt: string;
  updatedAt: string;
}

Report

interface Report {
  id: number;
  name: string;
  type: string;
  dateRange: string;
  parameters: Record<string, any>;
  status: string;
  generatedAt: string | null;
  filePath: string | null;
  createdBy: string;
  createdAt: string;
}

πŸ€– AI Integration

OpenAI Service Integration

The application integrates with OpenAI's API to provide intelligent features:

Treatment Recommendations

async function getTreatmentRecommendations(
  animalType: string,
  symptoms: string,
  healthHistory: string,
): Promise<TreatmentRecommendation>;

Resistance Prediction

async function predictResistancePatterns(
  usageData: any[],
): Promise<ResistancePrediction>;

Report Generation

async function generateReportWithInsights(reportData: {
  treatmentData: any[];
  timeframe: string;
  farmInfo: any;
}): Promise<GeneratedReport>;

Livestock Identification

async function identifyLivestockFromImage(
  imageBase64: string,
): Promise<LivestockIdentification>;

πŸ“± Features

Core Functionality

  • Real-time Treatment Tracking: Log and monitor antimicrobial treatments
  • Livestock Management: Comprehensive animal registry and health tracking
  • VFD Compliance: Automated compliance tracking for veterinary feed directives
  • Analytics Dashboard: Real-time usage statistics and trend analysis
  • Multi-format Reporting: Export data in CSV, Excel, PDF, and JSON formats

Advanced Features

  • Offline-first Architecture: Continue working without internet connectivity
  • Data Synchronization: Automatic sync when connection is restored
  • Personalized Onboarding: 6-step wizard tailored to user role and farm type
  • Role-based Customization: Interface adapts to user permissions and needs
  • Network Status Monitoring: Visual indicators for connection status

AI-Powered Tools

  • Intelligent Treatment Suggestions: AI recommendations based on symptoms and history
  • Predictive Analytics: Resistance pattern prediction and risk assessment
  • Automated Report Generation: AI-assisted compliance report creation
  • Image Recognition: Computer vision for livestock identification

🎨 UI/UX Design

Design System

  • Color Scheme: Pastel blue primary (#60a5fa) with modern gradients
  • Typography: Clean, readable fonts with proper hierarchy
  • Layout: Responsive grid system with mobile-first approach
  • Components: Consistent design language across all interfaces

Responsive Design

  • Desktop: Full sidebar navigation with comprehensive dashboard
  • Tablet: Adaptive layout with collapsible navigation
  • Mobile: Bottom navigation with touch-optimized controls

Accessibility

  • WCAG Compliance: Follows web accessibility guidelines
  • Keyboard Navigation: Full keyboard support for all interactions
  • Screen Reader Support: Proper ARIA labels and semantic HTML

πŸ”§ Development Setup

Development Prerequisites

  • Node.js 18+
  • pnpm package manager (recommended) or npm/yarn

Installation

# Clone the repository
git clone <repository-url>
cd farmtrack-amr

# Install pnpm globally (if not already installed)
npm install -g pnpm

# Install dependencies
pnpm install

# Start development server
pnpm run dev

Environment Variables

# Required for AI features
OPENAI_API_KEY=your_openai_api_key

# Optional for extended AI capabilities
ANTHROPIC_API_KEY=your_anthropic_api_key
PERPLEXITY_API_KEY=your_perplexity_api_key

Build Process

# Development build
pnpm run dev

# Production build
pnpm run build

# Start production server
pnpm run start

# Docker commands
pnpm run docker:build    # Build Docker image
pnpm run docker:run      # Run container
pnpm run docker:dev      # Development with Docker
pnpm run docker:prod     # Production with Docker Compose

πŸ”’ Security & Compliance

Data Protection

  • Local Storage: Sensitive data encrypted in browser storage
  • API Security: Request validation and sanitization
  • User Authentication: Secure session management

Regulatory Compliance

  • VFD Tracking: Automated compliance with FDA regulations
  • Audit Trail: Comprehensive logging of all activities
  • Data Retention: Configurable retention policies

πŸš€ Deployment

The application is designed for flexible deployment with Docker containerization:

Docker Deployment

Docker Prerequisites

  • Docker Engine 20.10 or later
  • Docker Compose 2.0 or later

Quick Start with Docker

# Build and run the production container
pnpm run docker:prod

# Or manually with Docker commands
docker build -t farmtrack-amr .
docker run -p 3000:3000 farmtrack-amr

Development with Docker

# Start development environment
pnpm run docker:dev

# Stop development environment
pnpm run docker:stop

Production Deployment

Environment Variables: Create a .env file with production settings:

NODE_ENV=production
PORT=3000
OPENAI_API_KEY=your_production_key
DATABASE_URL=your_database_url

Deploy with Docker Compose:

# Production deployment
docker-compose up -d

# With custom environment file
docker-compose --env-file .env.production up -d

Health Monitoring: The application includes built-in health checks:

  • Health endpoint: GET /health
  • Docker health checks configured
  • Automatic restart on failure

Container Features

  • Multi-stage Build: Optimized production images
  • Security: Non-root user execution
  • Health Checks: Built-in health monitoring
  • Alpine Base: Minimal image size
  • pnpm: Fast, disk-efficient package management

πŸ“Š Performance

Optimization Features

  • Code Splitting: Lazy loading of components
  • Caching: Intelligent data caching strategies
  • Bundle Optimization: Minimized JavaScript bundles
  • Image Optimization: Compressed and responsive images

Monitoring

  • Performance Metrics: Real-time performance tracking
  • Error Logging: Comprehensive error reporting
  • User Analytics: Usage pattern analysis

πŸ”„ Data Flow

Offline-First Architecture

  1. Local Storage: All data stored locally first
  2. Sync Queue: Changes queued for synchronization
  3. Background Sync: Automatic sync when online
  4. Conflict Resolution: Intelligent merge strategies

State Management

// Global State
AuthContext        // User authentication
NetworkContext     // Connection status
OnboardingContext  // User preferences

// Server State
TanStack Query     // API data caching
Local Storage      // Offline persistence

πŸ§ͺ Testing Strategy

Test Coverage

  • Unit Tests: Component and function testing
  • Integration Tests: API endpoint testing
  • E2E Tests: User workflow validation
  • Performance Tests: Load and stress testing

Quality Assurance

  • TypeScript: Strong typing for error prevention
  • ESLint: Code quality enforcement
  • Prettier: Consistent code formatting
  • Husky: Pre-commit hooks for quality gates

πŸ“ˆ Future Enhancements

Planned Features

  • Mobile Apps: Native iOS and Android applications
  • Advanced Analytics: Machine learning insights
  • Integration APIs: Third-party system connections
  • Multi-farm Management: Enterprise farm network support

Scalability Considerations

  • Database Migration: Transition from in-memory to persistent storage
  • Microservices: Service-oriented architecture
  • Load Balancing: Horizontal scaling capabilities
  • CDN Integration: Global content delivery

πŸ“ž Support & Maintenance

Documentation

  • API Documentation: Comprehensive endpoint documentation
  • User Guides: Step-by-step usage instructions
  • Developer Docs: Technical implementation guides
  • Troubleshooting: Common issue resolution

Maintenance

  • Regular Updates: Security patches and feature updates
  • Backup Procedures: Data protection protocols
  • Monitoring: 24/7 system health monitoring
  • Support Channels: Multiple support contact methods

This documentation provides a comprehensive overview of the AntimicrobialTracker application architecture, features, and implementation details. The system is designed to be scalable, maintainable, and user-friendly while meeting the complex requirements of antimicrobial stewardship in agricultural settings.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors