Skip to main content

repti-animal Service

Core business logic for reptile-specific functionality
Service Type: Business Logic Service
Port: 8002
Database: repti_animal_db
Status: Planned Team Owner: Business Logic Team

Purpose & Responsibilities

repti-animal handles all core reptile-related business logic, from individual animal records to complex lineage tracking and genetic analysis.

Core Responsibilities

Animal Registry

  • Individual animal record management
  • Comprehensive metadata tracking
  • Photo and media associations
  • Health and veterinary records
  • Animal identification and tagging

Lineage & Pedigree

  • Ancestry tracking and validation
  • Pedigree tree generation (N generations)
  • Lineage verification and corrections
  • Breeding history preservation
  • Family tree visualization data

Genetics & Traits

  • Morph and trait tracking
  • Genetic prediction algorithms
  • Allele combination analysis
  • Breeding outcome predictions
  • Genetic diversity calculations

Breeding Management

  • Breeding pair formation
  • Clutch and offspring tracking
  • Breeding attempt logging
  • Hatch rate analytics
  • Breeding program optimization

Species Taxonomy

  • Species and subspecies classification
  • Morph definitions and standards
  • Trait inheritance patterns
  • Canonical naming conventions
  • Scientific classification updates

API Endpoints

Animal Management

GET    /animals                 # List animals with filtering
POST   /animals                 # Create new animal record
GET    /animals/{animal_id}     # Animal details
PUT    /animals/{animal_id}     # Update animal record
DELETE /animals/{animal_id}     # Archive animal record
POST   /animals/{animal_id}/photos  # Add animal photos
GET    /animals/{animal_id}/health  # Health records

Lineage & Pedigree

GET    /animals/{animal_id}/lineage     # Get ancestry tree
PUT    /animals/{animal_id}/parents     # Set/update parents
GET    /animals/{animal_id}/offspring   # List offspring
GET    /animals/{animal_id}/pedigree/{generations}  # N-generation pedigree
POST   /lineage/validate               # Validate lineage data
GET    /lineage/stats                  # Lineage statistics

Genetics & Analysis

GET    /animals/{animal_id}/genetics   # Genetic profile
POST   /genetics/predict               # Breeding outcome predictions
GET    /genetics/traits/{species}      # Species trait definitions
POST   /genetics/analyze               # Genetic analysis
GET    /genetics/diversity             # Population diversity metrics

Breeding Management

GET    /breeding/pairs                 # List breeding pairs
POST   /breeding/pairs                 # Create breeding pair
GET    /breeding/pairs/{pair_id}       # Pair details
POST   /breeding/pairs/{pair_id}/attempts  # Log breeding attempt
GET    /breeding/clutches              # List clutches
POST   /breeding/clutches              # Record new clutch
GET    /breeding/clutches/{clutch_id}  # Clutch details
POST   /breeding/clutches/{clutch_id}/hatch  # Record hatch data

Species & Taxonomy

GET    /taxonomy/species               # List species
GET    /taxonomy/species/{species_id}  # Species details
GET    /taxonomy/morphs/{species_id}   # Species morphs
POST   /taxonomy/morphs                # Define new morph
GET    /taxonomy/traits                # Trait definitions
POST   /taxonomy/traits                # Create trait definition

Database Schema

Core Tables

-- Main animals table
CREATE TABLE animals (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    vivarium_id UUID NOT NULL,
    name VARCHAR(255) NOT NULL,
    assigned_id VARCHAR(50),
    species_id UUID REFERENCES species(id),
    morph_combination JSONB DEFAULT '[]',
    sex VARCHAR(10) CHECK (sex IN ('male', 'female', 'unknown')),
    birth_date DATE,
    age_classification VARCHAR(20), -- hatchling, juvenile, adult
    acquisition_date DATE,
    acquisition_method VARCHAR(50),
    acquisition_cost DECIMAL(10,2),
    source VARCHAR(255),
    owner_id UUID, -- References users or organizations
    status VARCHAR(20) DEFAULT 'active',
    weight_grams INTEGER,
    length_mm INTEGER,
    notes TEXT,
    visibility VARCHAR(20) DEFAULT 'private',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Animal health records
CREATE TABLE animal_health_records (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    animal_id UUID REFERENCES animals(id) ON DELETE CASCADE,
    record_type VARCHAR(50) NOT NULL,
    date_recorded DATE NOT NULL,
    reporter VARCHAR(255),
    notes TEXT,
    attachments JSONB DEFAULT '[]',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Animal media associations
CREATE TABLE animal_media (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    animal_id UUID REFERENCES animals(id) ON DELETE CASCADE,
    media_id UUID NOT NULL, -- References repti-media service
    media_type VARCHAR(20),
    is_primary BOOLEAN DEFAULT FALSE,
    caption TEXT,
    display_order INTEGER DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Lineage relationships
CREATE TABLE lineage (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    offspring_id UUID REFERENCES animals(id) ON DELETE CASCADE,
    parent_id UUID REFERENCES animals(id) ON DELETE CASCADE,
    parent_type VARCHAR(10) CHECK (parent_type IN ('sire', 'dam')),
    confidence_level VARCHAR(20) DEFAULT 'confirmed',
    verified_by UUID, -- References users
    verification_date TIMESTAMP WITH TIME ZONE,
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(offspring_id, parent_id, parent_type)
);

-- Lineage verification logs
CREATE TABLE lineage_verifications (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    lineage_id UUID REFERENCES lineage(id) ON DELETE CASCADE,
    verified_by UUID NOT NULL,
    verification_method VARCHAR(50),
    confidence_score DECIMAL(3,2),
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Breeding pairs
CREATE TABLE breeding_pairs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL,
    sire_id UUID REFERENCES animals(id),
    dam_id UUID REFERENCES animals(id),
    pairing_date DATE,
    status VARCHAR(20) DEFAULT 'active',
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(sire_id, dam_id, pairing_date)
);

-- Breeding attempts
CREATE TABLE breeding_attempts (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    pair_id UUID REFERENCES breeding_pairs(id) ON DELETE CASCADE,
    attempt_date DATE NOT NULL,
    successful BOOLEAN,
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Clutches and offspring
CREATE TABLE clutches (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    pair_id UUID REFERENCES breeding_pairs(id),
    laid_date DATE,
    incubation_start DATE,
    expected_hatch_date DATE,
    actual_hatch_date DATE,
    total_eggs INTEGER,
    viable_eggs INTEGER,
    hatched_count INTEGER,
    temperature_scale VARCHAR(20) DEFAULT 'celsius',
    incubation_temp DECIMAL(4,2),
    incubation_humidity_percent INTEGER,
    substrate VARCHAR(100),
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Species taxonomy
CREATE TABLE species (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    scientific_name VARCHAR(255) UNIQUE NOT NULL,
    common_name VARCHAR(255),
    family VARCHAR(100),
    genus VARCHAR(100),
    species VARCHAR(100),
    subspecies VARCHAR(100),
    description TEXT,
    care_requirements JSONB DEFAULT '{}', -- break into separate table
    breeding_info JSONB DEFAULT '{}', -- break into separate table
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Morphs and genetic traits
CREATE TABLE morphs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    species_id UUID REFERENCES species(id),
    name VARCHAR(255) NOT NULL,
    genetic_type VARCHAR(50), -- dominant, recessive, co-dominant, etc.
    allele_symbol VARCHAR(10),
    description TEXT,
    inheritance_pattern JSONB DEFAULT '{}',
    visual_traits JSONB DEFAULT '[]',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Animal genetic profiles
CREATE TABLE animal_genetics (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    animal_id UUID REFERENCES animals(id) ON DELETE CASCADE,
    morph_id UUID REFERENCES morphs(id),
    expression_level VARCHAR(20), -- homozygous, heterozygous, visual, etc.
    confirmed BOOLEAN DEFAULT FALSE,
    confidence_score DECIMAL(3,2),
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Event Publishing & Subscriptions

Published Events

Animal Events:
  • animal.created - New animal registered
  • animal.updated - Animal information changed
  • animal.transferred - Ownership change
  • animal.archived - Animal archived/sold
  • animal.media.attached - Photo/media added
Lineage Events:
  • lineage.updated - Ancestry information changed
  • lineage.validated - Lineage verification completed
  • pedigree.generated - Pedigree chart created
  • lineage.correction - Ancestry correction applied
Breeding Events:
  • breeding.paired - New breeding pair formed
  • breeding.attempt - Breeding attempt logged
  • breeding.clutch.created - New clutch recorded
  • breeding.clutch.hatched - Hatch results recorded
  • breeding.offspring.registered - Offspring added to system
Genetics Events:
  • genetics.prediction.updated - AI prediction results
  • genetics.trait.defined - New trait definition
  • genetics.analysis.completed - Genetic analysis finished
Taxonomy Events:
  • taxonomy.species.added - New species added
  • taxonomy.morph.defined - New morph definition
  • taxonomy.trait.updated - Trait information updated

Event Subscriptions

  • auth.user.created - Setup initial animal data context
  • org.member.added - Update access permissions
  • media.uploaded - Process animal photo attachments
  • config.feature.toggled - Adjust feature availability

Business Logic & Algorithms

Pedigree Generation

async def generate_pedigree(animal_id: UUID, generations: int = 5):
    """
    Generate multi-generation pedigree tree with genetic analysis
    """
    pedigree_data = {
        "animal": await get_animal_details(animal_id),
        "generations": [],
        "genetic_analysis": {},
        "completeness_score": 0.0
    }
    
    # Recursive pedigree building
    current_generation = [animal_id]
    for gen in range(generations):
        next_generation = []
        generation_data = []
        
        for animal in current_generation:
            parents = await get_parents(animal)
            if parents:
                generation_data.extend(parents)
                next_generation.extend([p.id for p in parents])
        
        if not generation_data:
            break
            
        pedigree_data["generations"].append(generation_data)
        current_generation = next_generation
    
    # Calculate genetic predictions
    pedigree_data["genetic_analysis"] = await analyze_genetics(pedigree_data)
    pedigree_data["completeness_score"] = calculate_completeness(pedigree_data)
    
    return pedigree_data

Genetic Prediction Engine

async def predict_breeding_outcomes(sire_id: UUID, dam_id: UUID):
    """
    Predict offspring genetics based on parent genetics
    """
    sire_genetics = await get_animal_genetics(sire_id)
    dam_genetics = await get_animal_genetics(dam_id)
    
    # Mendelian genetics calculations
    predictions = []
    for trait in get_species_traits(sire_genetics.species_id):
        outcome = calculate_trait_probability(
            sire_genetics.get_trait(trait.id),
            dam_genetics.get_trait(trait.id),
            trait.inheritance_pattern
        )
        predictions.append(outcome)
    
    # Calculate rarity and market value implications
    rarity_scores = await calculate_outcome_rarity(predictions)
    
    return {
        "predictions": predictions,
        "rarity_analysis": rarity_scores,
        "confidence_level": calculate_confidence(sire_genetics, dam_genetics)
    }

Performance & Scaling

Caching Strategy

  • Animal Profiles: Frequently accessed animal data
  • Pedigree Trees: Generated pedigree visualizations
  • Genetic Predictions: Breeding outcome calculations
  • Species Data: Taxonomy and trait definitions

Database Optimization

  • Lineage Indexes: Optimized for recursive queries
  • Genetic Queries: Efficient trait combination searches
  • Breeding Analytics: Aggregated statistics tables
  • Full-Text Search: Animal name and description search

Integration Points

Internal Dependencies

  • repti-core: Authentication, configuration, event publishing
  • repti-media: Photo and document management
  • repti-commerce: Animal sales and inventory

External Integrations

  • Genetics Labs: Future integration for DNA testing
  • Registry APIs: Integration with reptile registries
  • Research Databases: Scientific genetic data

Monitoring & Key Metrics

Business Metrics

  • Animal Registration Rate: New animals per organization
  • Lineage Completeness: Percentage of complete pedigrees
  • Breeding Success Rate: Successful breeding attempts
  • Genetic Diversity: Population genetic health metrics

Technical Metrics

  • API Response Times: Query performance tracking
  • Database Performance: Complex lineage query optimization
  • Cache Hit Rates: Genetic prediction cache efficiency
  • Event Processing: Real-time lineage updates

repti-animal is the heart of ReptiDex’s business logic, handling the complex relationships between animals, their genetics, and breeding outcomes that make lineage tracking possible.