roadmap/schema-documentation.md

1349 lines
36 KiB
Markdown

# Agricultural Platform Database Schema Documentation
## Overview
This comprehensive database schema is designed for a modern agricultural technology platform that connects farmers with markets through direct procurement, training programs, and development initiatives. The schema supports the complete agricultural value chain from farm management to market delivery.
## Table of Contents
1. [Core User Management](#core-user-management)
2. [Reference Data Management](#reference-data-management)
3. [Farm Management](#farm-management)
4. [Product & Variant System](#product--variant-system)
5. [Procurement & Trading](#procurement--trading)
6. [Contract Management](#contract-management)
7. [Season & Cycle Management](#season--cycle-management)
8. [Weather & Climate Data](#weather--climate-data)
9. [Input Management](#input-management)
10. [Labor Management](#labor-management)
11. [Equipment & Asset Management](#equipment--asset-management)
12. [Pest & Disease Management](#pest--disease-management)
13. [Financial Management](#financial-management)
14. [Soil Analysis](#soil-analysis)
15. [Communication & Notifications](#communication--notifications)
16. [Market Intelligence](#market-intelligence)
17. [Training & Certification](#training--certification)
18. [Knowledge Base](#knowledge-base)
19. [Attachment Systems](#attachment-systems)
20. [Data Types & Performance](#data-types--performance)
---
## Core User Management
### User
**Purpose**: Base user authentication and role management
**Key Features**:
- Role-based access control (Farmer, Buyer, Administrator)
- Email and phone-based authentication
- User status management
**Fields**:
- `id`: Unique identifier
- `email`: User email (unique)
- `phone`: Contact number
- `name`: Full name
- `role`: User role (enum)
- `isActive`: Account status
- `createdAt`, `updatedAt`: Timestamps
**Relations**: One-to-one with Farmer, Buyer, or Administrator
### Farmer
**Purpose**: Comprehensive farmer profile management
**Key Features**:
- Detailed personal information including family details
- Geographic location tracking
- Identity verification system
- Banking information for payments
- Farming experience and education tracking
- Technology access assessment
**Personal Information**:
- Basic details: name, email, phone, date of birth, gender
- Family: marital status, spouse name, number of children
- Demographics: religion, nationality, education level
- Location: complete address with GPS coordinates
**Professional Information**:
- Farming experience (years)
- Primary occupation and monthly income
- Land ownership type
- Primary crops and farming methods
- Vehicle and technology access
**Verification System**:
- Identity document management
- Admin verification workflow
- Photo attachments (profile, ID cards)
- Verification notes and status
**Relations**: Connected to farms, training, certifications, procurements, equipment, and financial records
### Buyer
**Purpose**: Enhanced buyer profile for procurement management
**Key Features**:
- Business classification and verification
- Payment terms and credit management
- Quality requirements and preferences
- Logistics and delivery preferences
**Business Details**:
- Company information and size classification
- Business license and tax registration
- Annual volume and employee count
- Operating radius and warehouse locations
**Trading Preferences**:
- Preferred products and quality requirements
- Payment terms and credit limits
- Pickup schedules and delivery preferences
- Minimum/maximum order quantities
**Verification & Status**:
- Business document verification
- Admin approval workflow
- Status management (active, suspended, etc.)
**Relations**: Connected to procurements and reviews
### Administrator
**Purpose**: Platform administration and oversight
**Fields**: Basic profile information for system administrators
**Relations**: Connected to User model
---
## Reference Data Management
### Country
**Purpose**: Standardized country and nationality management
**Key Features**:
- ISO standard country codes and names
- Regional and continental classification
- Support for nationality vs. residence country
- Centralized country data management
**Fields**:
- `id`: ISO country code (e.g., "indonesia", "malaysia")
- `name`: Full country name
- `code`: ISO 3166-1 alpha-2 code (e.g., "ID", "MY")
- `region`: Geographic region
- `continent`: Continental classification
- `isActive`: Status flag
**Relations**: Connected to Farmer nationality and country fields
### Currency
**Purpose**: Multi-currency support for financial transactions
**Key Features**:
- ISO 4217 currency standard compliance
- Symbol and formatting support
- Active currency management
- Financial system integration
**Fields**:
- `id`: ISO currency code (e.g., "idr", "usd")
- `name`: Full currency name
- `code`: ISO 4217 currency code (e.g., "IDR", "USD")
- `symbol`: Currency symbol (₹, $, Rp, etc.)
- `isActive`: Status flag
**Relations**: Connected to FinancialRecord for multi-currency transactions
### Religion
**Purpose**: Religious affiliation reference data
**Key Features**:
- Standardized religious categories
- Descriptive information
- Cultural sensitivity support
- Demographic analysis capability
**Fields**:
- `id`: Unique identifier
- `name`: Religion name (e.g., "Islam", "Christianity")
- `description`: Additional information
- `isActive`: Status flag
**Relations**: Connected to Farmer religious affiliation
### EducationLevel
**Purpose**: Hierarchical education level classification
**Key Features**:
- Structured education levels
- Numerical hierarchy for analysis
- International education standards
- Progress tracking support
**Fields**:
- `id`: Unique identifier
- `name`: Education level name
- `level`: Numerical hierarchy (0=No formal, 1=Elementary, etc.)
- `description`: Level details
- `isActive`: Status flag
**Relations**: Connected to Farmer education tracking
---
## Farm Management
### Farm
**Purpose**: Comprehensive farm property management
**Key Features**:
- Detailed location and boundary mapping
- Agricultural characteristics assessment
- Infrastructure and facility tracking
- Legal ownership documentation
- Financial investment tracking
**Location & Geography**:
- Complete address with GPS coordinates
- Farm boundaries (GeoJSON polygon)
- Elevation and slope information
- Climate classification
**Agricultural Characteristics**:
- Soil type and pH levels
- Water source and irrigation systems
- Farm size and established year
- Organic certification status
**Infrastructure Assessment**:
- Utilities: electricity, water access
- Facilities: storage, processing units
- Road access classification
- Equipment and vehicle access
**Documentation**:
- Photo management (main, aerial, soil)
- Land certificates and legal documents
- Investment and production tracking
**Relations**: Connected to plots, harvests, weather data, inputs, labor, equipment, and financial records
### Plot
**Purpose**: Individual field/plot management within farms
**Key Features**:
- Crop-specific plot management
- Boundary mapping for precision farming
- Product variant tracking
- Planting and harvest scheduling
**Geographic Data**:
- Plot boundaries (GeoJSON polygon)
- Area measurement in hectares
- GPS coordinate tracking
**Agricultural Data**:
- Product and variant assignments
- Planting dates and crop cycles
- Growth stage monitoring
**Relations**: Connected to harvests, weather data, inputs, labor, equipment usage, and soil tests
---
## Product & Variant System
### Product
**Purpose**: Base product category management (e.g., Pepper)
**Key Features**:
- Product categorization and classification
- Unit standardization
- Modifier configuration
**Fields**:
- `name`: Product name (e.g., "Pepper")
- `code`: Unique product code
- `category`: Product classification
- `unit`: Standard measurement unit (kg, ton)
- `description`: Product details
**Relations**: Connected to variants, modifiers, plots, and market data
### ProductVariant
**Purpose**: Specific product variations (e.g., Black Pepper, White Pepper)
**Key Features**:
- Variant-specific pricing
- Quality differentiation
- Market positioning
**Fields**:
- `name`: Variant name (e.g., "Black Pepper")
- `code`: Unique variant code
- `basePrice`: Default pricing
- `description`: Variant specifications
**Relations**: Connected to harvests, procurements, and market pricing
### ProductModifier
**Purpose**: Dynamic pricing modifiers based on quality metrics
**Key Features**:
- Configurable quality parameters
- Rule-based price adjustments
- Input validation (dropdown/input)
- Unit specification
**Configuration Options**:
- Selection type: dropdown or manual input
- Value constraints: minimum/maximum
- Nominal vs. percentage adjustments
- Required vs. optional parameters
**Examples**:
- Water Content: affects pricing based on moisture levels
- Density: quality metric for physical properties
- Purity: percentage-based quality assessment
**Relations**: Connected to modifier rules and harvest applications
### ProductModifierRule
**Purpose**: Automated pricing rules based on modifier values
**Key Features**:
- Condition-based pricing (equals, less than, greater than, between)
- Automatic price adjustments
- Business rule enforcement
**Rule Types**:
- Equals: exact value matching
- Less than: threshold-based reductions
- Greater than: premium pricing
- Between: range-based adjustments
### HarvestModifier
**Purpose**: Actual modifier values applied to specific harvests
**Key Features**:
- Real-world quality measurements
- Calculated price adjustments
- Traceability and audit trail
---
## Procurement & Trading
### Procurement
**Purpose**: Complete procurement transaction management
**Key Features**:
- End-to-end transaction tracking
- Quality assessment workflow
- Logistics and delivery management
- Financial settlement processing
**Transaction Details**:
- Procurement codes and references
- Quantity and quality specifications
- Pricing calculations with modifiers
- Cost breakdowns (transport, processing)
**Quality Management**:
- Assessment by qualified personnel
- Rejection handling and reasons
- Quality grade verification
- Photo documentation
**Logistics Coordination**:
- Pickup and delivery scheduling
- Location management
- Transport method tracking
- Route optimization support
**Financial Processing**:
- Payment method selection
- Reference number tracking
- Multi-stage payment approval
- Invoice and receipt management
**Status Workflow**:
- Pending → Quality Assessment → Approved → In Transit → Delivered → Invoiced → Paid → Completed
**Relations**: Connected to farmers, buyers, harvests, variants, and attachments
### ProcurementAttachment
**Purpose**: Visual documentation throughout procurement process
**Key Features**:
- Photo documentation at each stage
- GPS-tagged evidence
- Document verification
- Quality control support
**Attachment Types**:
- Product photos and quality assessment
- Weighing and packaging documentation
- Loading and delivery proof
- Contract and payment documents
- Signature verification
---
## Contract Management
### Contract
**Purpose**: Formal farmer-buyer agreement management
**Key Features**:
- Comprehensive contract lifecycle management
- Multi-type agreement support
- Legal compliance and documentation
- Performance tracking and analytics
**Agreement Details**:
- Contract identification and numbering
- Agreement type classification (purchase, supply, exclusive, etc.)
- Title, description, and terms documentation
- Legal framework and governing law
**Commercial Terms**:
- Pricing structure and payment terms
- Quantity specifications (minimum/maximum)
- Quality requirements and grading
- Delivery schedules and logistics
**Financial Management**:
- Agreed pricing per unit
- Total contract value calculation
- Advance payment terms and percentages
- Payment method specification
**Legal Framework**:
- Terms and conditions documentation
- Penalty clauses and enforcement
- Force majeure provisions
- Governing law specification
**Status Management**:
- Contract lifecycle stages (draft → active → fulfilled)
- Digital signature support
- Witness documentation
- Amendment and renewal tracking
**Performance Tracking**:
- Delivery quantity monitoring
- Payment completion tracking
- Contract fulfillment analytics
- Breach and dispute management
**Relations**: Connected to farmers, buyers, products, variants, and procurement deliveries
---
## Season & Cycle Management
### Season
**Purpose**: Agricultural season and cycle planning
**Key Features**:
- Seasonal calendar management
- Weather pattern integration
- Crop recommendation system
- Market outlook planning
**Season Definition**:
- Season naming and type classification
- Annual calendar integration
- Geographic scope (region, province, country)
- Start and end date management
**Agricultural Phases**:
- Planting window definition
- Growing period tracking
- Harvest season planning
- Activity scheduling support
**Weather Integration**:
- Average rainfall and temperature
- Humidity and climate conditions
- Historical weather pattern analysis
- Forecast integration
**Crop Management**:
- Recommended crop varieties
- Crops to avoid listing
- Seasonal suitability analysis
- Agricultural activity planning
**Market Intelligence**:
- Expected demand forecasting
- Price outlook analysis
- Market trend integration
- Supply chain planning
**Relations**: Connected to plot seasons, harvest summaries, and weather data
### PlotSeason
**Purpose**: Individual plot seasonal planning and tracking
**Key Features**:
- Plot-specific seasonal management
- Crop variety assignment
- Yield planning and tracking
- Performance comparison
**Planting Management**:
- Planted area tracking
- Seed variety specification
- Planting date documentation
- Growth stage monitoring
**Yield Planning**:
- Expected yield per hectare
- Total harvest projections
- Harvest date estimation
- Planning vs. actual comparison
**Performance Analytics**:
- Actual yield measurement
- Productivity analysis
- Seasonal performance comparison
- Optimization recommendations
**Relations**: Connected to plots, seasons, products, and variants
### SeasonHarvest
**Purpose**: Aggregated seasonal harvest analytics
**Key Features**:
- Farmer-level seasonal summaries
- Product performance analysis
- Quality and value tracking
- Multi-harvest aggregation
**Performance Metrics**:
- Total quantity harvested
- Average quality grades
- Total financial value
- Harvest frequency tracking
**Timeline Management**:
- First and last harvest dates
- Harvest window analysis
- Seasonal duration tracking
- Peak harvest identification
**Relations**: Connected to seasons, farmers, products, and variants
### SeasonWeather
**Purpose**: Seasonal weather analysis and impact assessment
**Key Features**:
- Aggregated weather data
- Extreme event tracking
- Agricultural impact analysis
- Climate pattern documentation
**Weather Analytics**:
- Cumulative rainfall totals
- Temperature range analysis
- Humidity and climate summaries
- Weather pattern identification
**Impact Assessment**:
- Crop damage evaluation
- Yield impact analysis
- Weather correlation studies
- Risk factor identification
**Relations**: Connected to seasons for regional weather analysis
---
## Weather & Climate Data
### WeatherData
**Purpose**: Real-time weather monitoring and historical data
**Key Features**:
- Comprehensive weather metrics
- Farm and plot-specific data
- Multiple data sources
- Historical trend analysis
**Metrics Tracked**:
- Temperature and humidity
- Rainfall and wind conditions
- Atmospheric pressure and UV index
- Visibility and weather conditions
**Data Sources**:
- Manual farmer input
- Weather station integration
- Third-party API services
- IoT sensor networks
**Relations**: Connected to farms and plots for location-specific data
### WeatherForecast
**Purpose**: Weather prediction and planning support
**Key Features**:
- Multi-day forecasting
- Confidence levels
- Planning assistance
- Risk assessment support
**Forecast Data**:
- Temperature ranges (min/max)
- Precipitation probability
- Wind and weather conditions
- Forecast accuracy tracking
---
## Input Management
### FarmInput
**Purpose**: Agricultural input tracking and cost management
**Key Features**:
- Complete input lifecycle management
- Cost tracking and supplier management
- Application rate and method documentation
- Batch tracking and expiry management
**Input Categories**:
- Seeds and planting materials
- Fertilizers (organic and synthetic)
- Pesticides, herbicides, fungicides
- Equipment rental and fuel
- Irrigation water and other inputs
**Supplier Management**:
- Supplier contact and terms
- Batch numbers and expiry dates
- Invoice and receipt tracking
- Quality certifications
**Application Tracking**:
- Application dates and methods
- Application rates per hectare
- Active ingredient concentrations
- Effectiveness monitoring
**Relations**: Connected to farms, plots, and suppliers
### InputSchedule
**Purpose**: Planned input applications and scheduling
**Key Features**:
- Application planning and timing
- Resource allocation
- Schedule optimization
- Actual vs. planned tracking
**Schedule Management**:
- Planned application dates
- Estimated quantities and costs
- Assignment to personnel
- Schedule status tracking
### Supplier
**Purpose**: Input supplier management and relationships
**Key Features**:
- Supplier classification and contact management
- Payment and delivery terms
- Quality certification tracking
- Performance evaluation
**Supplier Types**:
- Specialized suppliers (seeds, fertilizers, equipment)
- General suppliers and cooperatives
- Government agencies
---
## Labor Management
### FarmWorker
**Purpose**: Comprehensive worker profile and contract management
**Key Features**:
- Worker classification and skill assessment
- Contract and payment management
- Emergency contact information
- Performance tracking
**Worker Classification**:
- Role types: permanent, seasonal, daily, contractor
- Skill levels: beginner to expert
- Specialization areas
- Contract terms and duration
**Payment Management**:
- Daily and monthly wage structures
- Payment method preferences
- Bank account information
- Performance-based incentives
**Relations**: Connected to farmers, labor records, and schedules
### LaborRecord
**Purpose**: Detailed work activity and payment tracking
**Key Features**:
- Time tracking and productivity measurement
- Work quality assessment
- Weather impact documentation
- Approval and payment workflow
**Work Documentation**:
- Start/end times and hours worked
- Work type and plot assignment
- Supervisor and quality ratings
- Weather conditions during work
**Payment Processing**:
- Wage calculations and approvals
- Payment status tracking
- Performance bonuses
- Overtime and special rates
### LaborSchedule
**Purpose**: Work planning and resource allocation
**Key Features**:
- Work scheduling and assignment
- Resource planning and optimization
- Schedule vs. actual comparison
- Productivity analysis
---
## Equipment & Asset Management
### Equipment
**Purpose**: Farm equipment lifecycle management
**Key Features**:
- Complete equipment inventory
- Maintenance scheduling and tracking
- Usage monitoring and efficiency
- Asset valuation and depreciation
**Equipment Details**:
- Technical specifications (brand, model, serial)
- Purchase information and current value
- Fuel type, capacity, and power ratings
- Warranty and insurance tracking
**Maintenance Management**:
- Scheduled maintenance intervals
- Service history and costs
- Parts replacement tracking
- Performance monitoring
**Relations**: Connected to maintenance records and usage tracking
### MaintenanceRecord
**Purpose**: Equipment service history and cost tracking
**Key Features**:
- Service type classification
- Cost tracking and budgeting
- Service provider management
- Next service scheduling
**Maintenance Types**:
- Preventive, corrective, emergency
- Overhauls and inspections
- Calibration services
### EquipmentUsage
**Purpose**: Equipment utilization and efficiency tracking
**Key Features**:
- Operating hours and fuel consumption
- Work type and productivity measurement
- Operator tracking and performance
- Cost per hour calculations
### Asset
**Purpose**: Farm asset inventory and valuation
**Key Features**:
- Asset categorization and valuation
- Depreciation tracking
- Insurance and warranty management
- Condition assessment
**Asset Categories**:
- Buildings and infrastructure
- Land improvements
- Vehicles and machinery
- Technology and equipment
---
## Pest & Disease Management
### PestDiseaseRecord
**Purpose**: Comprehensive pest and disease tracking
**Key Features**:
- Identification and classification
- Severity assessment and impact measurement
- Treatment tracking and effectiveness
- Prevention strategy documentation
**Identification Data**:
- Common and scientific names
- Pest/disease type classification
- Affected area and severity levels
- Symptom documentation
**Treatment Management**:
- Treatment methods and costs
- Application dates and personnel
- Effectiveness monitoring
- Recurrence tracking
**Photo Documentation**:
- Identification photos
- Treatment application
- Recovery progress
- Prevention measures
---
## Financial Management
### FinancialRecord
**Purpose**: Complete farm financial tracking and management
**Key Features**:
- Multi-currency transaction support
- Transaction categorization and approval
- Tax calculation and compliance
- Audit trail and documentation
**Transaction Types**:
- Income: sales, grants, subsidies
- Expenses: inputs, labor, equipment
- Investments: infrastructure, equipment
- Loans and repayments
**Financial Controls**:
- Approval workflow for large transactions
- Tax calculation and tracking
- Reference number management
- Supporting document attachment
**Reporting Support**:
- Profit and loss calculations
- Cash flow analysis
- Budget vs. actual comparison
- Tax preparation assistance
---
## Soil Analysis
### SoilTest
**Purpose**: Comprehensive soil health monitoring and management
**Key Features**:
- Complete nutrient analysis
- Soil physical property assessment
- GPS-tagged sample locations
- Laboratory integration
**Basic Properties**:
- pH levels and organic matter
- Soil texture and bulk density
- Porosity and water retention
**Nutrient Analysis**:
- Primary nutrients (N, P, K)
- Secondary nutrients (Ca, Mg, S)
- Micronutrients (Zn, Fe, Mn, Cu, B)
**Advanced Testing**:
- Cation exchange capacity
- Base saturation levels
- Carbon-nitrogen ratios
- Electrical conductivity
**Recommendations**:
- Fertilizer recommendations
- Soil amendment suggestions
- pH adjustment requirements
- Organic matter improvement
---
## Communication & Notifications
### Notification
**Purpose**: Comprehensive notification and alert system
**Key Features**:
- Multi-channel notification delivery
- Targeted and personalized messaging
- Scheduled notification support
- Analytics and engagement tracking
**Notification Management**:
- Rich content support (text, images, actions)
- Deep linking and call-to-action buttons
- Expiration date management
- Priority-based delivery
**Targeting Options**:
- Individual user targeting
- Role-based broadcasting (farmers, buyers)
- Geographic targeting (region, province)
- Product-specific notifications
- Custom audience segments
**Content Types**:
- System alerts and warnings
- Market price updates
- Weather warnings and forecasts
- Training and certification reminders
- Payment and procurement notifications
- Maintenance and equipment alerts
**Analytics and Tracking**:
- Delivery confirmation
- Read receipt tracking
- Click-through analytics
- Engagement measurement
- Performance optimization
**Relations**: Connected to all user types through NotificationRecipient
### NotificationRecipient
**Purpose**: Individual notification delivery and tracking
**Key Features**:
- Per-user delivery status
- Read and interaction tracking
- Delivery confirmation
- User-specific analytics
**Tracking Metrics**:
- Delivery status and timestamp
- Read status and time
- Click tracking and engagement
- User response patterns
**Relations**: Connected to notifications and users
### Message
**Purpose**: Direct communication between platform users
**Key Features**:
- Personal messaging support
- Group communication
- Attachment handling
- Message threading
**Message Types**:
- Personal messages between users
- Group discussions
- Administrative communications
- Support conversations
**Delivery Management**:
- Priority levels (low to critical)
- Read receipt tracking
- Delivery status monitoring
- Failed delivery handling
---
## Market Intelligence
### MarketPrice
**Purpose**: Real-time market pricing and trend analysis
**Key Features**:
- Multi-market price tracking
- Quality-based pricing
- Trend analysis and forecasting
- Price verification system
**Price Data**:
- Market-specific pricing
- Quality grade differentiation
- Trading volume information
- Price trend indicators
**Verification System**:
- Admin price verification
- Source credibility tracking
- Accuracy monitoring
### MarketDemand
**Purpose**: Market demand forecasting and analysis
**Key Features**:
- Demand level assessment
- Volume estimation
- Seasonal trend analysis
- Price range forecasting
**Demand Analysis**:
- Current demand levels
- Volume estimates and trends
- Influencing factors
- Forecast accuracy tracking
---
## Training & Certification
### Training
**Purpose**: Farmer education and skill development
**Key Features**:
- Course content management
- Difficulty level classification
- Duration tracking
- Category organization
**Course Management**:
- Structured learning content
- Beginner to advanced levels
- Time-based progression
- Category-based organization
### FarmerTraining
**Purpose**: Individual training progress and achievement tracking
**Key Features**:
- Enrollment and progress tracking
- Score and completion management
- Certificate generation
- Learning analytics
**Progress Tracking**:
- Enrollment status and progress percentage
- Score tracking and assessments
- Completion certificates
- Learning path optimization
### Certification
**Purpose**: Professional certification and credential management
**Key Features**:
- Certification program management
- Validity period tracking
- Requirements documentation
- Industry recognition
### FarmerCertification
**Purpose**: Individual certification status and management
**Key Features**:
- Certification status tracking
- Issue and expiry date management
- Certificate number assignment
- Renewal notifications
---
## Knowledge Base
### Article
**Purpose**: Agricultural knowledge and information management
**Key Features**:
- Content categorization and tagging
- Publication workflow
- View tracking and analytics
- Search optimization
**Content Management**:
- Title, content, and excerpt
- Category and tag organization
- Author attribution
- Publication status (draft, published, archived)
**Analytics**:
- View count tracking
- Popular content identification
- User engagement metrics
---
## Attachment Systems
### FarmerAttachment
**Purpose**: Farmer document and photo management
**Key Features**:
- Document type classification
- Verification workflow
- File metadata tracking
- Secure storage
**Attachment Types**:
- Profile photos and ID cards
- Licenses and certificates
- Bank statements and contracts
- Other supporting documents
### FarmAttachment
**Purpose**: Farm visual documentation and records
**Key Features**:
- Location-tagged photos
- Document verification
- Photo metadata tracking
- GPS coordinate storage
**Photo Types**:
- Main farm photos and aerial views
- Infrastructure and equipment
- Soil and crop conditions
- Legal documents and surveys
### ProcurementAttachment
**Purpose**: Procurement process documentation
**Key Features**:
- Process stage documentation
- Quality control photos
- Contract and payment proof
- GPS-tagged evidence
**Documentation Stages**:
- Product quality and weighing
- Packaging and loading
- Delivery and payment
- Contract and signatures
---
## Data Types & Performance
### Data Type Optimization
**Financial Precision**:
All financial and monetary fields use `Decimal` type for precision:
- Pricing fields (basePrice, totalPrice, finalAmount)
- Cost tracking (transportCost, processingCost, wages)
- Financial amounts (income, investment, credit limits)
- Currency amounts and exchange rates
**Measurement Precision**:
Scientific and agricultural measurements use `Decimal` for accuracy:
- Quantities (harvest amounts, procurement volumes)
- Percentages (water content, premiums, tax rates)
- Chemical concentrations and soil nutrients
- Area measurements and yield calculations
- Quality ratings and scores
**Geographic Coordinates**:
Location data uses `Float` for standard GPS compatibility:
- Latitude and longitude coordinates
- Elevation and distance measurements
- Weather data (temperature, pressure, wind speed)
**Large Value Support**:
High-volume counters use `BigInt`:
- Article view counts
- Large transaction volumes
- System usage statistics
### Normalized Reference Data
**Benefits of Normalization**:
- Improved data consistency and integrity
- Enhanced maintainability and updates
- Support for internationalization
- Better analytics and reporting capabilities
- Reduced storage redundancy
**Normalized Tables**:
- `Country`: ISO-compliant country and nationality data
- `Currency`: Multi-currency support with ISO 4217 standards
- `Religion`: Standardized religious classification
- `EducationLevel`: Hierarchical education tracking
### Key Enumerations
**User Management**:
- `UserRole`: FARMER, BUYER, ADMINISTRATOR
- `Gender`: MALE, FEMALE, OTHER
- `MaritalStatus`: SINGLE, MARRIED, DIVORCED, WIDOWED, SEPARATED
- `IdentityType`: KTP, PASSPORT, DRIVING_LICENSE, OTHER
- `FarmerStatus`: ACTIVE, INACTIVE, SUSPENDED, PENDING_VERIFICATION, BLACKLISTED
**Contract Management**:
- `AgreementType`: PURCHASE_AGREEMENT, SUPPLY_CONTRACT, EXCLUSIVE_SUPPLY, etc.
- `ContractStatus`: DRAFT, PENDING_REVIEW, ACTIVE, FULFILLED, EXPIRED, etc.
**Season Management**:
- `SeasonType`: WET_SEASON, DRY_SEASON, TRANSITION, YEAR_ROUND, etc.
- `PlantingStatus`: PLANNED, PLANTED, GROWING, HARVESTING, HARVESTED, etc.
**Notification System**:
- `NotificationType`: SYSTEM, ANNOUNCEMENT, ALERT, REMINDER, etc.
- `NotificationCategory`: GENERAL, PROCUREMENT, PAYMENT, WEATHER, etc.
- `NotificationStatus`: PENDING, SCHEDULED, SENT, DELIVERED, FAILED, etc.
**Agricultural Operations**:
- `QualityGrade`: A, B, C
- `InputType`: SEED, FERTILIZER, PESTICIDE, HERBICIDE, FUNGICIDE, etc.
- `WorkType`: PLANTING, WEEDING, FERTILIZING, HARVESTING, etc.
- `PestDiseaseType`: PEST, DISEASE, WEED, NUTRIENT_DEFICIENCY, etc.
- `SeverityLevel`: LOW, MEDIUM, HIGH, CRITICAL, CATASTROPHIC
**Business Operations**:
- `ProcurementStatus`: PENDING to COMPLETED (11 stages)
- `PaymentMethod`: CASH, BANK_TRANSFER, MOBILE_MONEY, etc.
- `BuyerType`: INDIVIDUAL, WHOLESALER, RETAILER, PROCESSOR, etc.
- `TransactionType`: INCOME, EXPENSE, INVESTMENT, LOAN, etc.
**Equipment and Assets**:
- `EquipmentType`: TRACTOR, HARVESTER, IRRIGATION_SYSTEM, etc.
- `EquipmentCondition`: EXCELLENT, GOOD, FAIR, POOR, etc.
- `MaintenanceType`: PREVENTIVE, CORRECTIVE, EMERGENCY, etc.
---
## Database Relationships
### Key Relationship Patterns
**User Hierarchy**:
- User → Farmer/Buyer/Administrator (one-to-one)
- User → NotificationRecipient (one-to-many)
- Farmer → Farms (one-to-many)
- Farm → Plots (one-to-many)
**Reference Data Integration**:
- Farmer → Country (nationality and residence)
- Farmer → Religion (religious affiliation)
- Farmer → EducationLevel (education tracking)
- FinancialRecord → Currency (multi-currency support)
**Agricultural Operations**:
- Plot → Harvests (one-to-many)
- Plot → PlotSeason (seasonal planning)
- Harvest → Procurement (one-to-one)
- Product → Variants → Harvests (hierarchical)
- Season → PlotSeason → Plot (seasonal management)
**Contract Management**:
- Farmer ↔ Buyer → Contract (bilateral agreements)
- Contract → Procurement (contract fulfillment)
- Product/Variant → Contract (product specifications)
**Seasonal Planning**:
- Season → PlotSeason (plot-level planning)
- Season → SeasonHarvest (aggregated outcomes)
- Season → SeasonWeather (seasonal climate data)
- Plot → PlotSeason → Season (cyclical relationships)
**Communication Systems**:
- Notification → NotificationRecipient (delivery tracking)
- User → NotificationRecipient (user-specific delivery)
- Message → User (direct communication)
**Support Systems**:
- Farm/Plot → Weather Data (location-based)
- Farm/Plot → Input Applications (activity-based)
- Farm/Plot → Labor Records (work-based)
- Equipment → MaintenanceRecord (service history)
- Equipment → EquipmentUsage (utilization tracking)
**Documentation**:
- All major entities → Attachments (comprehensive documentation)
- Financial Records → Multiple entities (cost allocation)
- Contract → Attachments (legal documentation)
---
## Performance Considerations
### Indexing Strategy
**Primary Indexes**:
- All foreign keys for join optimization
- Unique codes for fast lookups
- Date fields for temporal queries
- Geographic coordinates for spatial queries
**Composite Indexes**:
- Farm + Plot for agricultural operations
- Date + Location for weather data
- Product + Variant for market analysis
### Data Partitioning
**Time-based Partitioning**:
- Weather data by month/year
- Financial records by fiscal year
- Market prices by quarter
**Geographic Partitioning**:
- Regional data separation
- Location-based optimization
---
## Security and Privacy
### Data Protection
**Personal Information**:
- Encrypted storage for sensitive data
- Access control for personal details
- Audit logging for data access
**Financial Data**:
- Secure payment information storage
- Transaction audit trails
- Compliance with financial regulations
**Business Intelligence**:
- Anonymized market data
- Aggregated reporting
- Privacy-preserving analytics
---
## Integration Points
### External Systems
**Weather Services**:
- Weather API integration
- IoT sensor connectivity
- Satellite data integration
**Financial Services**:
- Payment gateway integration
- Banking API connectivity
- Mobile money platforms
**Market Data**:
- Price feed integrations
- Commodity exchange connectivity
- Supply chain platforms
**Government Systems**:
- Agricultural statistics
- Subsidy management
- Certification authorities
---
## Schema Evolution and Improvements
### Recent Enhancements
**Data Type Optimization (v2.0)**:
- Migrated from `Float` to `Decimal` for all financial and precise measurement fields
- Implemented `BigInt` for high-volume counters
- Maintained `Float` for geographic coordinates and weather data
**Reference Data Normalization (v2.0)**:
- Converted static enums to dynamic reference tables
- Implemented Country, Currency, Religion, and EducationLevel tables
- Enhanced internationalization and maintainability
**Contract Management System (v2.0)**:
- Added comprehensive contract lifecycle management
- Integrated legal compliance and performance tracking
- Connected procurement deliveries to contract fulfillment
**Advanced Notification System (v2.0)**:
- Implemented rich notification management with targeting
- Added delivery tracking and engagement analytics
- Integrated with all system workflows and alerts
**Seasonal Planning Framework (v2.0)**:
- Added Season, PlotSeason, SeasonHarvest, and SeasonWeather models
- Implemented agricultural cycle planning and tracking
- Enhanced yield planning and performance analytics
### Benefits of Current Schema
**Financial Accuracy**: Decimal precision ensures accurate financial calculations and eliminates floating-point errors in monetary transactions.
**Scalability**: Normalized reference data and optimized data types support platform growth and international expansion.
**Compliance**: Formal contract management and audit trails meet legal and regulatory requirements.
**User Experience**: Advanced notification system provides targeted, relevant information to users.
**Agricultural Intelligence**: Seasonal planning framework enables data-driven farming decisions and optimization.
**Data Integrity**: Comprehensive relationships and constraints ensure data consistency across the platform.
**Performance**: Optimized data types and indexing strategies support high-volume operations and fast queries.
---
This comprehensive schema provides the foundation for a complete agricultural technology platform that supports farmers from production planning through market delivery, with integrated training, certification, and financial management capabilities. The recent enhancements ensure scalability, accuracy, and compliance while providing advanced features for contract management, seasonal planning, and user engagement.