diff --git a/schema-documentation.md b/schema-documentation.md index 8e1035c..70cea80 100644 --- a/schema-documentation.md +++ b/schema-documentation.md @@ -7,21 +7,25 @@ This comprehensive database schema is designed for a modern agricultural technol ## Table of Contents 1. [Core User Management](#core-user-management) -2. [Farm Management](#farm-management) -3. [Product & Variant System](#product--variant-system) -4. [Procurement & Trading](#procurement--trading) -5. [Weather & Climate Data](#weather--climate-data) -6. [Input Management](#input-management) -7. [Labor Management](#labor-management) -8. [Equipment & Asset Management](#equipment--asset-management) -9. [Pest & Disease Management](#pest--disease-management) -10. [Financial Management](#financial-management) -11. [Soil Analysis](#soil-analysis) -12. [Communication System](#communication-system) -13. [Market Intelligence](#market-intelligence) -14. [Training & Certification](#training--certification) -15. [Knowledge Base](#knowledge-base) -16. [Attachment Systems](#attachment-systems) +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) --- @@ -110,6 +114,78 @@ This comprehensive database schema is designed for a modern agricultural technol --- +## 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 @@ -300,6 +376,172 @@ This comprehensive database schema is designed for a modern agricultural technol --- +## 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 @@ -609,21 +851,75 @@ This comprehensive database schema is designed for a modern agricultural technol --- -## Communication System +## 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**: Platform-wide communication and notification system +**Purpose**: Direct communication between platform users **Key Features**: -- Multi-type messaging support -- Priority-based delivery -- Attachment support -- Delivery status tracking +- Personal messaging support +- Group communication +- Attachment handling +- Message threading **Message Types**: - Personal messages between users -- Broadcast announcements -- System notifications and alerts -- Emergency communications +- Group discussions +- Administrative communications +- Support conversations **Delivery Management**: - Priority levels (low to critical) @@ -787,7 +1083,51 @@ This comprehensive database schema is designed for a modern agricultural technol --- -## Enums and Data Types +## 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 @@ -796,9 +1136,21 @@ This comprehensive database schema is designed for a modern agricultural technol - `Gender`: MALE, FEMALE, OTHER - `MaritalStatus`: SINGLE, MARRIED, DIVORCED, WIDOWED, SEPARATED - `IdentityType`: KTP, PASSPORT, DRIVING_LICENSE, OTHER -- `EducationLevel`: NO_FORMAL_EDUCATION to DOCTORATE - `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. @@ -825,22 +1177,50 @@ This comprehensive database schema is designed for a modern agricultural technol **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) --- @@ -919,4 +1299,51 @@ This comprehensive database schema is designed for a modern agricultural technol --- -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. \ No newline at end of file +## 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. \ No newline at end of file diff --git a/schema.prisma b/schema.prisma index 44339a4..330ee2f 100644 --- a/schema.prisma +++ b/schema.prisma @@ -24,6 +24,7 @@ model User { farmer Farmer? buyer Buyer? administrator Administrator? + notifications NotificationRecipient[] @@map("users") } @@ -40,14 +41,17 @@ model Farmer { maritalStatus MaritalStatus? spouseName String? numberOfChildren Int? @default(0) - religion Religion? - nationality String? @default("Indonesian") + religionId String? + religion Religion? @relation(fields: [religionId], references: [id]) + nationalityId String? @default("indonesia") + nationality Country? @relation("FarmerNationality", fields: [nationalityId], references: [id]) address String? village String? district String? province String? postalCode String? - country String? @default("Indonesia") + countryId String? @default("indonesia") + country Country? @relation("FarmerCountry", fields: [countryId], references: [id]) // Location data latitude Float? @@ -77,9 +81,10 @@ model Farmer { // Farming experience farmingExperience Int? // years of experience - educationLevel EducationLevel? + educationLevelId String? + educationLevel EducationLevel? @relation(fields: [educationLevelId], references: [id]) occupation String? // primary occupation if not full-time farmer - monthlyIncome Float? // estimated monthly income + monthlyIncome Decimal? // estimated monthly income landOwnership LandOwnership? primaryCrop String? farmingMethods String[] // organic, conventional, etc. @@ -115,6 +120,8 @@ model Farmer { assets Asset[] financialRecords FinancialRecord[] reviews BuyerReview[] + contracts Contract[] + seasonHarvests SeasonHarvest[] @@map("farmers") } @@ -136,19 +143,19 @@ model Buyer { contactPerson String? contactPersonPhone String? paymentTerms Int? // days - creditLimit Float? + creditLimit Decimal? preferredProducts String[] qualityRequirements String? // Location and logistics warehouseAddress String? deliveryPreference String? - operatingRadius Float? // km + operatingRadius Decimal? // km // Business details businessSize BusinessSize? yearEstablished Int? - annualVolume Float? // estimated annual purchase volume + annualVolume Decimal? // estimated annual purchase volume employeeCount Int? website String? @@ -172,8 +179,8 @@ model Buyer { // Preferences preferredPickupDays String[] // Mon, Tue, Wed, etc. preferredPickupTime String? - minimumOrderQuantity Float? - maximumOrderQuantity Float? + minimumOrderQuantity Decimal? + maximumOrderQuantity Decimal? notes String? createdAt DateTime @default(now()) @@ -183,6 +190,7 @@ model Buyer { user User @relation(fields: [userId], references: [id], onDelete: Cascade) procurements Procurement[] reviews BuyerReview[] + contracts Contract[] @@map("buyers") } @@ -212,7 +220,7 @@ model Farm { district String? province String? postalCode String? - area Float? // in hectares + area Decimal? // in hectares // Location data latitude Float? @@ -247,8 +255,8 @@ model Farm { // Agricultural details establishedYear Int? - totalInvestment Float? - annualProduction Float? // estimated kg per year + totalInvestment Decimal? + annualProduction Decimal? // estimated kg per year mainCrops String[] // primary crops grown farmingSystem FarmingSystem? organicCertified Boolean? @default(false) @@ -282,7 +290,7 @@ model Plot { id String @id @default(cuid()) farmId String name String - area Float? // in hectares + area Decimal? // in hectares productId String? variantId String? plantedDate DateTime? @@ -307,6 +315,7 @@ model Plot { pestDiseaseRecords PestDiseaseRecord[] financialRecords FinancialRecord[] soilTests SoilTest[] + seasons PlotSeason[] @@map("plots") } @@ -317,11 +326,11 @@ model Harvest { farmId String plotId String? variantId String - quantity Float // in kg + quantity Decimal // in kg harvestDate DateTime qualityGrade QualityGrade - waterContent Float? // percentage - density Float? // kg/m3 + waterContent Decimal? // percentage + density Decimal? // kg/m3 notes String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -346,18 +355,18 @@ model Procurement { variantId String // Quantity and quality details - quantity Float // in kg + quantity Decimal // in kg qualityGrade QualityGrade - waterContent Float? // percentage - density Float? // kg/m3 + waterContent Decimal? // percentage + density Decimal? // kg/m3 // Pricing details - basePrice Float // price per kg - premiumRate Float @default(0) // percentage - totalPrice Float - transportCost Float? @default(0) - processingCost Float? @default(0) - finalAmount Float // total amount to be paid + basePrice Decimal // price per kg + premiumRate Decimal @default(0) // percentage + totalPrice Decimal + transportCost Decimal? @default(0) + processingCost Decimal? @default(0) + finalAmount Decimal // total amount to be paid // Location and logistics pickupLocation String? @@ -370,7 +379,7 @@ model Procurement { assessedBy String? // quality assessor ID assessmentDate DateTime? assessmentNotes String? - rejectedQuantity Float? @default(0) + rejectedQuantity Decimal? @default(0) rejectionReason String? // Payment details @@ -387,6 +396,7 @@ model Procurement { completedDate DateTime? // Documentation + contractId String? // link to formal contract contractNumber String? invoiceNumber String? receiptNumber String? @@ -400,6 +410,7 @@ model Procurement { buyer Buyer? @relation(fields: [buyerId], references: [id]) harvest Harvest @relation(fields: [harvestId], references: [id]) variant ProductVariant @relation(fields: [variantId], references: [id]) + contract Contract? @relation(fields: [contractId], references: [id]) attachments ProcurementAttachment[] @@map("procurements") @@ -410,7 +421,7 @@ model HarvestModifier { harvestId String modifierId String value String // actual value applied - adjustment Float? // calculated price adjustment + adjustment Decimal? // calculated price adjustment createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -577,7 +588,7 @@ model Article { tags String[] author String? status ArticleStatus @default(DRAFT) - views Int @default(0) + views BigInt @default(0) publishedAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -600,9 +611,12 @@ model Product { plots Plot[] variants ProductVariant[] modifiers ProductModifier[] + contracts Contract[] priceHistory PriceHistory[] marketPrices MarketPrice[] marketDemand MarketDemand[] + plotSeasons PlotSeason[] + seasonHarvests SeasonHarvest[] @@map("products") } @@ -613,7 +627,7 @@ model ProductVariant { name String // e.g., "Black Pepper", "White Pepper" code String @unique description String? - basePrice Float? // default base price + basePrice Decimal? // default base price isActive Boolean @default(true) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -623,9 +637,12 @@ model ProductVariant { plots Plot[] harvests Harvest[] procurements Procurement[] + contracts Contract[] priceHistory PriceHistory[] marketPrices MarketPrice[] marketDemand MarketDemand[] + plotSeasons PlotSeason[] + seasonHarvests SeasonHarvest[] @@map("product_variants") } @@ -639,8 +656,8 @@ model ProductModifier { selectionType ModifierSelectionType @default(INPUT) nominalType NominalType @default(NOMINAL) options String[] // For dropdown selections - minimum Float? - maximum Float? + minimum Decimal? + maximum Decimal? unit String? // %, kg/m3, etc isRequired Boolean @default(false) isActive Boolean @default(true) @@ -660,10 +677,10 @@ model ProductModifierRule { id String @id @default(cuid()) modifierId String condition RuleCondition - priceAdjustment Float // amount to adjust price + priceAdjustment Decimal // amount to adjust price value String? // For equals condition - minValue Float? // For lessThan or between conditions - maxValue Float? // For greaterThan or between conditions + minValue Decimal? // For lessThan or between conditions + maxValue Decimal? // For greaterThan or between conditions description String? isActive Boolean @default(true) createdAt DateTime @default(now()) @@ -680,9 +697,9 @@ model PriceHistory { productId String? variantId String? qualityGrade QualityGrade - basePrice Float - marketPrice Float? - premiumRate Float @default(0) + basePrice Decimal + marketPrice Decimal? + premiumRate Decimal @default(0) effectiveDate DateTime region String? notes String? @@ -753,9 +770,9 @@ model FarmInput { inputType InputType productName String brand String? - quantity Float + quantity Decimal unit String - cost Float + cost Decimal supplier String? supplierContact String? batchNumber String? @@ -764,7 +781,7 @@ model FarmInput { applicationMethod String? applicationRate String? // per hectare or per plant activeIngredient String? // for pesticides/fertilizers - concentration Float? // percentage + concentration Decimal? // percentage notes String? invoiceNumber String? receiptUrl String? @@ -785,13 +802,13 @@ model InputSchedule { inputType InputType productName String scheduledDate DateTime - quantity Float + quantity Decimal unit String method String? status ScheduleStatus @default(PENDING) appliedDate DateTime? appliedBy String? - actualQuantity Float? + actualQuantity Decimal? notes String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -833,8 +850,8 @@ model FarmWorker { identityNumber String? role WorkerRole skillLevel SkillLevel? - dailyWage Float? - monthlyWage Float? + dailyWage Decimal? + monthlyWage Decimal? paymentMethod PaymentMethod? bankAccount String? emergencyContact String? @@ -862,14 +879,14 @@ model LaborRecord { workerId String? plotId String? workType WorkType - hoursWorked Float - wages Float + hoursWorked Decimal + wages Decimal workDate DateTime startTime DateTime? endTime DateTime? description String? supervisor String? // supervisor name or ID - qualityRating Float? // 1-5 rating + qualityRating Decimal? // 1-5 rating weather String? notes String? approved Boolean @default(false) @@ -897,8 +914,8 @@ model LaborSchedule { plotId String? workType WorkType scheduledDate DateTime - estimatedHours Float - estimatedWage Float? + estimatedHours Decimal + estimatedWage Decimal? status ScheduleStatus @default(PENDING) assignedBy String? notes String? @@ -925,8 +942,8 @@ model Equipment { model String? serialNumber String? purchaseDate DateTime? - purchasePrice Float? - currentValue Float? + purchasePrice Decimal? + currentValue Decimal? condition EquipmentCondition status EquipmentStatus @default(ACTIVE) location String? // where equipment is stored @@ -939,8 +956,8 @@ model Equipment { insuranceExpiry DateTime? lastMaintenance DateTime? nextMaintenance DateTime? - maintenanceCost Float? - operatingHours Float? // total operating hours + maintenanceCost Decimal? + operatingHours Decimal? // total operating hours isActive Boolean @default(true) notes String? photoUrl String? @@ -961,12 +978,12 @@ model MaintenanceRecord { equipmentId String maintenanceType MaintenanceType description String - cost Float + cost Decimal serviceProvider String? serviceDate DateTime nextServiceDue DateTime? partsReplaced String[] - laborHours Float? + laborHours Decimal? invoiceNumber String? receiptUrl String? performedBy String? @@ -989,11 +1006,11 @@ model EquipmentUsage { usageDate DateTime startTime DateTime? endTime DateTime? - hoursUsed Float - fuelConsumed Float? + hoursUsed Decimal + fuelConsumed Decimal? workType WorkType? description String? - meterReading Float? // odometer, hour meter reading + meterReading Decimal? // odometer, hour meter reading notes String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -1015,9 +1032,9 @@ model Asset { category String? // building, land improvement, infrastructure description String? purchaseDate DateTime? - purchasePrice Float? - currentValue Float? - depreciation Float? // annual depreciation rate + purchasePrice Decimal? + currentValue Decimal? + depreciation Decimal? // annual depreciation rate condition AssetCondition location String? size String? // dimensions, area @@ -1043,7 +1060,7 @@ model BuyerReview { id String @id @default(cuid()) buyerId String farmerId String - rating Float // 1-5 rating + rating Decimal // 1-5 rating comment String? reviewType ReviewType procurementId String? // reference to procurement if applicable @@ -1066,13 +1083,13 @@ model PestDiseaseRecord { name String scientificName String? severity SeverityLevel - affectedArea Float? // percentage or hectares + affectedArea Decimal? // percentage or hectares identifiedDate DateTime identifiedBy String? // farmer, expert, etc. symptoms String? treatmentApplied String? treatmentDate DateTime? - treatmentCost Float? + treatmentCost Decimal? treatmentMethod String? preventionTaken String? resolved Boolean @default(false) @@ -1098,15 +1115,16 @@ model FinancialRecord { type TransactionType category String subcategory String? - amount Float - currency String @default("IDR") + amount Decimal + currencyId String @default("idr") + currency Currency @relation(fields: [currencyId], references: [id]) description String transactionDate DateTime paymentMethod PaymentMethod? receiptNumber String? invoiceNumber String? referenceNumber String? - taxAmount Float? @default(0) + taxAmount Decimal? @default(0) bankAccount String? payee String? // who received payment approvedBy String? // admin who approved @@ -1130,43 +1148,43 @@ model SoilTest { plotId String? testCode String @unique testDate DateTime - sampleDepth Float? // cm + sampleDepth Decimal? // cm sampleLocation String? gpsCoordinates Json? // GeoJSON point // Basic soil properties - pH Float? - organicMatter Float? // percentage + pH Decimal? + organicMatter Decimal? // percentage soilTexture String? // clay, sand, loam, etc. - bulkDensity Float? // g/cm³ - porosity Float? // percentage + bulkDensity Decimal? // g/cm³ + porosity Decimal? // percentage // Nutrients (ppm) - nitrogen Float? - phosphorus Float? - potassium Float? - calcium Float? - magnesium Float? - sulfur Float? + nitrogen Decimal? + phosphorus Decimal? + potassium Decimal? + calcium Decimal? + magnesium Decimal? + sulfur Decimal? // Micronutrients (ppm) - zinc Float? - iron Float? - manganese Float? - copper Float? - boron Float? + zinc Decimal? + iron Decimal? + manganese Decimal? + copper Decimal? + boron Decimal? // Other properties - conductivity Float? // dS/m - cationExchangeCapacity Float? // cmol/kg - baseStaturation Float? // percentage - carbonNitrogenRatio Float? + conductivity Decimal? // dS/m + cationExchangeCapacity Decimal? // cmol/kg + baseStaturation Decimal? // percentage + carbonNitrogenRatio Decimal? // Analysis details recommendations String? testLaboratory String? technicianName String? - testCost Float? + testCost Decimal? reportUrl String? notes String? @@ -1180,6 +1198,67 @@ model SoilTest { @@map("soil_tests") } +model EducationLevel { + id String @id @default(cuid()) + name String @unique + level Int // 0=No formal, 1=Elementary, etc. + description String? + isActive Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + farmers Farmer[] + + @@map("education_levels") +} + +model Currency { + id String @id // ISO currency code like "idr", "usd" + name String @unique + code String @unique // ISO 4217 currency code + symbol String // €, $, Rp, etc. + isActive Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + financialRecords FinancialRecord[] + + @@map("currencies") +} + +model Country { + id String @id // ISO country code like "indonesia", "malaysia" + name String @unique + code String @unique // ISO 3166-1 alpha-2 code + region String? + continent String? + isActive Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + farmerNationalities Farmer[] @relation("FarmerNationality") + farmerCountries Farmer[] @relation("FarmerCountry") + + @@map("countries") +} + +model Religion { + id String @id @default(cuid()) + name String @unique + description String? + isActive Boolean @default(true) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + farmers Farmer[] + + @@map("religions") +} + model Message { id String @id @default(cuid()) senderId String @@ -1206,12 +1285,12 @@ model MarketPrice { variantId String? market String region String - price Float + price Decimal unit String @default("kg") qualityGrade QualityGrade priceDate DateTime source String? // where price data came from - volume Float? // trading volume + volume Decimal? // trading volume trend PriceTrend? verified Boolean @default(false) verifiedBy String? @@ -1225,19 +1304,330 @@ model MarketPrice { @@map("market_prices") } +model Contract { + id String @id @default(cuid()) + contractNumber String @unique + farmerId String + buyerId String + productId String? + variantId String? + + // Contract terms + title String + description String? + contractType AgreementType @default(PURCHASE_AGREEMENT) + + // Pricing and quantity + agreedPrice Decimal // price per unit + minimumQuantity Decimal? + maximumQuantity Decimal? + totalValue Decimal? + unit String @default("kg") + + // Quality specifications + qualityGrade QualityGrade? + qualityRequirements String? + + // Timeline + startDate DateTime + endDate DateTime + deliverySchedule String? // delivery frequency/schedule + + // Payment terms + paymentTerms String? // payment conditions + paymentMethod PaymentMethod? + advancePayment Decimal? @default(0) + advancePercentage Decimal? @default(0) + + // Legal and compliance + terms String? // full terms and conditions + penalties String? // penalty clauses + forcemajeure String? // force majeure clause + governingLaw String? // applicable law + + // Status and tracking + status ContractStatus @default(DRAFT) + signedDate DateTime? + signedByFarmer Boolean @default(false) + signedByBuyer Boolean @default(false) + farmerSignature String? // signature data or URL + buyerSignature String? // signature data or URL + witnessName String? + witnessSignature String? + + // Performance tracking + totalDelivered Decimal? @default(0) + totalPaid Decimal? @default(0) + deliveryCount Int @default(0) + + // Renewal and amendments + renewalDate DateTime? + amendmentCount Int @default(0) + parentContractId String? // for contract renewals + + // Documentation + documentUrl String? // contract document + attachmentUrls String[] // supporting documents + + notes String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + farmer Farmer @relation(fields: [farmerId], references: [id]) + buyer Buyer @relation(fields: [buyerId], references: [id]) + product Product? @relation(fields: [productId], references: [id]) + variant ProductVariant? @relation(fields: [variantId], references: [id]) + parentContract Contract? @relation("ContractRenewal", fields: [parentContractId], references: [id]) + renewalContracts Contract[] @relation("ContractRenewal") + procurements Procurement[] // deliveries under this contract + + @@map("contracts") +} + +model Notification { + id String @id @default(cuid()) + title String + message String + type NotificationType + category NotificationCategory @default(GENERAL) + priority Priority @default(NORMAL) + + // Recipients + recipientId String? // specific user ID + recipientType UserRole? // or broadcast to user type + recipientIds String[] // multiple specific users + + // Targeting + farmerIds String[] // specific farmers + buyerIds String[] // specific buyers + region String? // geographic targeting + productIds String[] // product-specific notifications + + // Content and media + content String? // detailed content/body + imageUrl String? + actionUrl String? // deep link or action URL + actionLabel String? // button text + + // Scheduling + scheduledAt DateTime? // for scheduled notifications + expiresAt DateTime? // expiration date + + // Status tracking + status NotificationStatus @default(PENDING) + sentAt DateTime? + deliveredCount Int @default(0) + readCount Int @default(0) + clickCount Int @default(0) + + // Metadata + source String? // system, admin, automated, etc. + sourceId String? // reference to source entity + tags String[] // for categorization + metadata Json? // additional data + + // Tracking + isRead Boolean @default(false) + readAt DateTime? + isClicked Boolean @default(false) + clickedAt DateTime? + + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + recipients NotificationRecipient[] + + @@map("notifications") +} + +model NotificationRecipient { + id String @id @default(cuid()) + notificationId String + userId String + isRead Boolean @default(false) + readAt DateTime? + isClicked Boolean @default(false) + clickedAt DateTime? + isDelivered Boolean @default(false) + deliveredAt DateTime? + createdAt DateTime @default(now()) + + // Relations + notification Notification @relation(fields: [notificationId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([notificationId, userId]) + @@map("notification_recipients") +} + +model Season { + id String @id @default(cuid()) + name String // e.g., "Wet Season 2024", "Dry Season 2024" + seasonType SeasonType + year Int + + // Timeline + startDate DateTime + endDate DateTime + + // Weather characteristics + avgRainfall Decimal? // mm + avgTemperature Float? // celsius + avgHumidity Decimal? // percentage + + // Agricultural phases + plantingStart DateTime? + plantingEnd DateTime? + growingStart DateTime? + growingEnd DateTime? + harvestStart DateTime? + harvestEnd DateTime? + + // Region and scope + region String? + province String? + country String @default("Indonesia") + + // Crop recommendations + recommendedCrops String[] // suitable crops for this season + notRecommendedCrops String[] // crops to avoid + + // Market expectations + expectedDemand DemandLevel? + priceOutlook PriceTrend? + marketNotes String? + + // Agricultural activities + activities Json? // structured data for farming activities + + // Status + isActive Boolean @default(true) + isCurrent Boolean @default(false) + + description String? + notes String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + plots PlotSeason[] + harvests SeasonHarvest[] + weatherData SeasonWeather[] + + @@unique([seasonType, year, region]) + @@map("seasons") +} + +model PlotSeason { + id String @id @default(cuid()) + plotId String + seasonId String + productId String? + variantId String? + + // Planting details + plantedDate DateTime? + plantedArea Decimal? // hectares actually planted + seedVariety String? + + // Expected outcomes + expectedYield Decimal? // kg per hectare + expectedHarvest Decimal? // total kg expected + expectedHarvestDate DateTime? + + // Actual outcomes + actualYield Decimal? // kg per hectare + actualHarvest Decimal? // total kg harvested + actualHarvestDate DateTime? + + status PlantingStatus @default(PLANNED) + notes String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + // Relations + plot Plot @relation(fields: [plotId], references: [id]) + season Season @relation(fields: [seasonId], references: [id]) + product Product? @relation(fields: [productId], references: [id]) + variant ProductVariant? @relation(fields: [variantId], references: [id]) + + @@unique([plotId, seasonId]) + @@map("plot_seasons") +} + +model SeasonHarvest { + id String @id @default(cuid()) + seasonId String + farmerId String + productId String + variantId String? + + totalQuantity Decimal + averageQuality QualityGrade + totalValue Decimal + + harvestCount Int @default(1) + firstHarvest DateTime + lastHarvest DateTime? + + notes String? + createdAt DateTime @default(now()) + + // Relations + season Season @relation(fields: [seasonId], references: [id]) + farmer Farmer @relation(fields: [farmerId], references: [id]) + product Product @relation(fields: [productId], references: [id]) + variant ProductVariant? @relation(fields: [variantId], references: [id]) + + @@map("season_harvests") +} + +model SeasonWeather { + id String @id @default(cuid()) + seasonId String + region String + + // Aggregated weather data + totalRainfall Decimal? // mm + avgTemperature Float? // celsius + minTemperature Float? // celsius + maxTemperature Float? // celsius + avgHumidity Decimal? // percentage + + // Extreme events + droughtDays Int? @default(0) + floodDays Int? @default(0) + stormCount Int? @default(0) + + // Impact assessment + cropDamage Decimal? // percentage + yieldImpact Decimal? // percentage change + + notes String? + createdAt DateTime @default(now()) + + // Relations + season Season @relation(fields: [seasonId], references: [id]) + + @@unique([seasonId, region]) + @@map("season_weather") +} + model MarketDemand { id String @id @default(cuid()) productId String variantId String? region String demandLevel DemandLevel - estimatedVolume Float? + estimatedVolume Decimal? priceRange String? season String? factors String[] // factors affecting demand forecastDate DateTime forecastBy String? - accuracy Float? // percentage + accuracy Decimal? // percentage notes String? createdAt DateTime @default(now()) @@ -1325,16 +1715,7 @@ enum IdentityType { OTHER } -enum EducationLevel { - NO_FORMAL_EDUCATION - ELEMENTARY - MIDDLE_SCHOOL - HIGH_SCHOOL - DIPLOMA - BACHELOR - MASTER - DOCTORATE -} +// EducationLevel enum converted to table above enum FarmerStatus { ACTIVE @@ -1364,15 +1745,7 @@ enum MaritalStatus { SEPARATED } -enum Religion { - ISLAM - CHRISTIAN - CATHOLIC - HINDU - BUDDHIST - CONFUCIAN - OTHER -} +// Religion enum converted to table above enum LandOwnership { OWNER @@ -1721,6 +2094,47 @@ enum TransactionStatus { FAILED } +// Notification Enums +enum NotificationType { + SYSTEM + ANNOUNCEMENT + ALERT + REMINDER + PROMOTION + UPDATE + WARNING + INFO + SUCCESS + ERROR +} + +enum NotificationCategory { + GENERAL + PROCUREMENT + PAYMENT + QUALITY + WEATHER + PRICE_ALERT + TRAINING + CERTIFICATION + MAINTENANCE + HARVEST + PLANTING + MARKET + CONTRACT + COMPLIANCE +} + +enum NotificationStatus { + PENDING + SCHEDULED + SENT + DELIVERED + FAILED + CANCELLED + EXPIRED +} + // Communication Enums enum MessageType { PERSONAL @@ -1747,6 +2161,55 @@ enum MessageStatus { PENDING } +// Contract Enums +enum AgreementType { + PURCHASE_AGREEMENT + SUPPLY_CONTRACT + EXCLUSIVE_SUPPLY + SEASONAL_CONTRACT + FORWARD_CONTRACT + SPOT_CONTRACT + CONSIGNMENT + PARTNERSHIP +} + +enum ContractStatus { + DRAFT + PENDING_REVIEW + PENDING_SIGNATURE + ACTIVE + FULFILLED + EXPIRED + TERMINATED + CANCELLED + BREACH + RENEWED +} + +// Season Enums +enum SeasonType { + WET_SEASON + DRY_SEASON + TRANSITION + YEAR_ROUND + SPRING + SUMMER + FALL + WINTER +} + +enum PlantingStatus { + PLANNED + PLANTED + GROWING + FLOWERING + FRUITING + HARVESTING + HARVESTED + FAILED + ABANDONED +} + // Market Intelligence Enums enum PriceTrend { RISING