Skip to main content

repti-commerce Service

Commerce and marketplace functionality
Service Type: Commerce Service
Port: 8003
Database: repti_commerce_db
Status: Planned
Team Owner: Commerce Team

Purpose & Responsibilities

repti-commerce handles all marketplace and sales functionality, enabling breeders to list animals for sale and buyers to discover and purchase reptiles with confidence.

Core Responsibilities

Marketplace Listings

  • Animal listing creation and management
  • Listing visibility and promotion
  • Search and discovery optimization
  • Featured listings and advertising
  • Listing performance analytics

Sales & Transactions

  • Purchase order processing
  • Payment coordination via repti-core
  • Transaction status management
  • Refund and dispute handling
  • Sales tax calculations

Inventory Management

  • Animal availability tracking
  • Reservation and hold systems
  • Breeding inventory planning
  • Seasonal availability patterns
  • Automated listing updates

Commerce Analytics

  • Sales performance tracking
  • Market trend analysis
  • Pricing optimization suggestions
  • Buyer behavior insights
  • Revenue reporting

API Endpoints

Marketplace Listings

GET    /marketplace/listings            # Browse available animals
POST   /marketplace/listings            # Create new listing
GET    /marketplace/listings/{listing_id}  # Listing details
PUT    /marketplace/listings/{listing_id}  # Update listing
DELETE /marketplace/listings/{listing_id}  # Remove listing
POST   /marketplace/listings/{listing_id}/promote  # Promote listing
GET    /marketplace/search              # Advanced search
GET    /marketplace/categories          # Browse by categories

Inventory Management

GET    /inventory                       # Breeder inventory overview
GET    /inventory/{breeder_id}          # Specific breeder inventory
POST   /inventory/animals               # Add animal to inventory
PUT    /inventory/animals/{animal_id}   # Update inventory status
DELETE /inventory/animals/{animal_id}   # Remove from inventory
POST   /inventory/reserve               # Reserve animal for sale
POST   /inventory/release               # Release reservation
GET    /inventory/analytics             # Inventory insights

Orders & Transactions

GET    /orders                          # List orders (buyer/seller view)
POST   /orders                          # Create purchase order
GET    /orders/{order_id}               # Order details
PUT    /orders/{order_id}/status        # Update order status
POST   /orders/{order_id}/shipping      # Add shipping information
POST   /orders/{order_id}/complete      # Mark order complete
POST   /orders/{order_id}/refund        # Process refund
GET    /orders/{order_id}/tracking      # Shipping tracking

Sales Inquiries & Communication

GET    /inquiries                       # List inquiries
POST   /inquiries                       # Send inquiry to seller
GET    /inquiries/{inquiry_id}          # Inquiry details
POST   /inquiries/{inquiry_id}/respond  # Respond to inquiry
PUT    /inquiries/{inquiry_id}/status   # Update inquiry status
POST   /inquiries/{inquiry_id}/convert  # Convert to order

Analytics & Reporting

GET    /analytics/sales                 # Sales analytics
GET    /analytics/listings              # Listing performance
GET    /analytics/market                # Market trends
GET    /analytics/pricing               # Pricing insights
POST   /analytics/export                # Export sales data

Database Schema

Core Tables

-- Marketplace listings
CREATE TABLE marketplace_listings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL,
    animal_id UUID NOT NULL, -- References repti-animal service
    title VARCHAR(255) NOT NULL,
    description TEXT,
    price_cents INTEGER NOT NULL,
    currency VARCHAR(3) DEFAULT 'USD',
    status VARCHAR(20) DEFAULT 'active',
    visibility VARCHAR(20) DEFAULT 'public',
    featured BOOLEAN DEFAULT FALSE,
    featured_until TIMESTAMP WITH TIME ZONE,
    shipping_info JSONB DEFAULT '{}',
    terms_conditions TEXT,
    view_count INTEGER DEFAULT 0,
    inquiry_count INTEGER DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Listing categories and tags
CREATE TABLE listing_categories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    listing_id UUID REFERENCES marketplace_listings(id) ON DELETE CASCADE,
    category VARCHAR(100) NOT NULL,
    subcategory VARCHAR(100),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Listing promotion history
CREATE TABLE listing_promotions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    listing_id UUID REFERENCES marketplace_listings(id) ON DELETE CASCADE,
    promotion_type VARCHAR(50) NOT NULL,
    start_date TIMESTAMP WITH TIME ZONE NOT NULL,
    end_date TIMESTAMP WITH TIME ZONE NOT NULL,
    cost_cents INTEGER,
    impressions INTEGER DEFAULT 0,
    clicks INTEGER DEFAULT 0,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Animal inventory
CREATE TABLE animal_inventory (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL,
    animal_id UUID NOT NULL, -- References repti-animal service
    status VARCHAR(20) DEFAULT 'available',
    listing_id UUID REFERENCES marketplace_listings(id),
    reserved_until TIMESTAMP WITH TIME ZONE,
    reserved_by UUID, -- References user
    acquisition_cost_cents INTEGER,
    target_price_cents INTEGER,
    min_price_cents INTEGER,
    feeding_schedule JSONB DEFAULT '{}',
    care_notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(animal_id)
);

-- Inventory status history
CREATE TABLE inventory_status_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    inventory_id UUID REFERENCES animal_inventory(id) ON DELETE CASCADE,
    previous_status VARCHAR(20),
    new_status VARCHAR(20) NOT NULL,
    reason VARCHAR(255),
    changed_by UUID NOT NULL,
    changed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Purchase orders
CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    order_number VARCHAR(50) UNIQUE NOT NULL,
    buyer_id UUID NOT NULL,
    seller_id UUID NOT NULL,
    listing_id UUID REFERENCES marketplace_listings(id),
    animal_id UUID NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',
    subtotal_cents INTEGER NOT NULL,
    tax_cents INTEGER DEFAULT 0,
    shipping_cents INTEGER DEFAULT 0,
    total_cents INTEGER NOT NULL,
    currency VARCHAR(3) DEFAULT 'USD',
    payment_status VARCHAR(20) DEFAULT 'pending',
    payment_intent_id VARCHAR(255), -- Stripe payment intent
    shipping_address JSONB NOT NULL,
    billing_address JSONB NOT NULL,
    special_instructions TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Order status tracking
CREATE TABLE order_status_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    order_id UUID REFERENCES orders(id) ON DELETE CASCADE,
    status VARCHAR(20) NOT NULL,
    notes TEXT,
    updated_by UUID,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Shipping information
CREATE TABLE order_shipping (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    order_id UUID REFERENCES orders(id) ON DELETE CASCADE,
    carrier VARCHAR(100),
    tracking_number VARCHAR(255),
    shipping_method VARCHAR(100),
    estimated_delivery DATE,
    actual_delivery DATE,
    shipping_notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- Sales inquiries
CREATE TABLE sales_inquiries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    listing_id UUID REFERENCES marketplace_listings(id),
    animal_id UUID NOT NULL,
    inquirer_id UUID NOT NULL,
    seller_id UUID NOT NULL,
    subject VARCHAR(255),
    message TEXT NOT NULL,
    status VARCHAR(20) DEFAULT 'open',
    priority VARCHAR(10) DEFAULT 'normal',
    responded_at TIMESTAMP WITH TIME ZONE,
    converted_to_order_id UUID REFERENCES orders(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Inquiry responses
CREATE TABLE inquiry_responses (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    inquiry_id UUID REFERENCES sales_inquiries(id) ON DELETE CASCADE,
    respondent_id UUID NOT NULL,
    message TEXT NOT NULL,
    is_seller_response BOOLEAN NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Event Publishing & Subscriptions

Published Events

Marketplace Events:
  • marketplace.listing.created - New animal listing
  • marketplace.listing.updated - Listing information changed
  • marketplace.listing.featured - Listing promoted
  • marketplace.listing.expired - Listing expired
  • marketplace.search.performed - Search analytics
Inventory Events:
  • inventory.animal.added - Animal added to inventory
  • inventory.status.changed - Availability status changed
  • inventory.reserved - Animal reserved for purchase
  • inventory.released - Reservation released
  • inventory.transferred - Animal ownership transferred
Sales Events:
  • sales.inquiry.received - New inquiry from buyer
  • sales.inquiry.responded - Seller responded to inquiry
  • sales.order.created - Purchase order placed
  • sales.order.updated - Order status changed
  • sales.payment.completed - Payment processed
  • sales.transaction.completed - Sale finalized
Commerce Analytics Events:
  • analytics.sale.recorded - Sale data for analytics
  • analytics.listing.viewed - Listing view tracking
  • analytics.price.updated - Price change tracking

Event Subscriptions

  • animal.created - Auto-create inventory record
  • animal.updated - Update listing information
  • animal.transferred - Update ownership and inventory
  • billing.subscription.updated - Adjust marketplace access
  • payment.completed - Process order fulfillment
  • media.uploaded - Update listing photos

Business Logic & Features

Pricing Intelligence

async def suggest_pricing(animal_id: UUID, organization_id: UUID):
    """
    AI-powered pricing suggestions based on market data
    """
    animal_data = await get_animal_details(animal_id)
    market_data = await get_market_comparisons(animal_data.species, animal_data.morphs)
    
    # Analyze comparable sales
    comparable_sales = await find_comparable_sales(
        species=animal_data.species,
        morphs=animal_data.morphs,
        age_range=(animal_data.age - 30, animal_data.age + 30),
        time_period_days=180
    )
    
    # Calculate suggested price range
    base_price = calculate_median_price(comparable_sales)
    quality_multiplier = assess_animal_quality(animal_data)
    rarity_multiplier = calculate_rarity_factor(animal_data.morphs)
    
    suggested_price = base_price * quality_multiplier * rarity_multiplier
    
    return {
        "suggested_price": suggested_price,
        "confidence_level": calculate_confidence(comparable_sales),
        "price_range": {
            "min": suggested_price * 0.8,
            "max": suggested_price * 1.2
        },
        "market_factors": {
            "seasonal_demand": get_seasonal_factor(animal_data.species),
            "supply_level": calculate_supply_level(animal_data.morphs),
            "recent_trends": analyze_price_trends(comparable_sales)
        }
    }

Smart Matching Algorithm

async def match_buyers_to_listings(buyer_preferences: Dict):
    """
    Match buyers with relevant listings based on preferences
    """
    # Get buyer criteria
    species_preferences = buyer_preferences.get("species", [])
    morph_preferences = buyer_preferences.get("morphs", [])
    price_range = buyer_preferences.get("price_range", {})
    location_preferences = buyer_preferences.get("location", {})
    
    # Find matching listings
    query_filters = build_search_filters(buyer_preferences)
    potential_matches = await search_listings(query_filters)
    
    # Score and rank matches
    scored_matches = []
    for listing in potential_matches:
        score = calculate_match_score(listing, buyer_preferences)
        if score > 0.6:  # Minimum relevance threshold
            scored_matches.append({
                "listing": listing,
                "score": score,
                "match_reasons": explain_match(listing, buyer_preferences)
            })
    
    # Sort by relevance and return top matches
    return sorted(scored_matches, key=lambda x: x["score"], reverse=True)[:20]

Performance & Scaling

Search Optimization

  • Elasticsearch Integration: Fast, faceted search across listings
  • Search Result Caching: Popular search query caching
  • Auto-complete: Species and morph name suggestions
  • Faceted Navigation: Multi-dimensional filtering

Transaction Processing

  • Payment Processing: Async payment handling via repti-core
  • Inventory Locking: Prevent overselling during checkout
  • Order State Management: Reliable order status tracking
  • Refund Processing: Automated refund workflows

Integration Points

Internal Dependencies

  • repti-core: Authentication, billing, payment processing
  • repti-animal: Animal data, ownership validation
  • repti-media: Listing photos and videos
  • repti-community: Search indexing, notifications

External Integrations

  • Shipping Carriers: UPS, FedEx, USPS integration
  • Tax Services: Automated sales tax calculation
  • Payment Gateways: Stripe, PayPal via repti-core
  • Analytics Platforms: Commerce tracking and insights

Monitoring & Key Metrics

Business Metrics

  • Listing Conversion Rate: Listings to sales ratio
  • Average Order Value: Revenue per transaction
  • Time to Sale: Days from listing to sale
  • Inquiry Response Rate: Seller responsiveness
  • Buyer Satisfaction: Transaction ratings

Technical Metrics

  • Search Performance: Query response times
  • Payment Success Rate: Transaction completion rate
  • API Response Times: Marketplace operation speed
  • Database Performance: Complex commerce queries

Security & Fraud Prevention

  • Transaction Monitoring: Unusual payment patterns
  • Seller Verification: Account authenticity checks
  • Buyer Protection: Dispute resolution tracking
  • Financial Reconciliation: Payment accuracy monitoring

repti-commerce enables the marketplace ecosystem that allows ReptiDex users to buy and sell animals while maintaining the platform’s focus on verified lineage and transparent transactions.