TotalApp Docs

Quality & Crop Health Operations

Soil and pest surveillance, chemical compliance with PHI/MRL enforcement, and the farm-to-fork digital product passport — the quality assurance backbone of a growing season.

What this group does

This is the most interconnected group in Agriculture & Agro-Tech Operations. Soil & Water Testing and Pest & Disease Alerts both feed pesticide/fertilizer applications logged in Agro-Chemical Analytics, which enforces a PHI (Pre-Harvest Interval) harvest lockout. Crop Health Checklist gates pre-harvest clearance. Farm-to-Fork Traceability compiles all of it — plus Crop Yield Dashboard's weighbridge data — into a per-lot digital product passport.

Soil & Water Testing
Crop Health Checklist
Pest & Disease Alerts
Agro-Chemical Analytics
Farm-to-Fork Traceability

All five screens share one service file, src/services/qualityCropHealthService.ts, and reach into agroTechExecutionService.ts and harvestSupplyInventoryService.ts for field orders, harvest schedules, yield records, and the silo registry.

1. Soil & Water Testing

Purpose: Log lab results for soil and water samples — pH, EC salinity, macro/micronutrients, heavy metals — against SOP-defined bounds, and trigger remediation when a sample falls out of range.

Key features

  • Sample typestopsoil_profile, subsoil_profile, irrigation_water, hydroponic_runoff, each test coded SWT-2026-XXXX.
  • Status lifecyclesample_collected → in_lab_analysis → report_published → action_required.
  • Lab readings — pH level, EC salinity (mS/cm), nitrogen/phosphorus/potassium (ppm), organic matter (%), a list of micronutrient readings (ppm, deficiency flag) and heavy-metal flags (ppm, exceeds-safe-limit flag).
  • Soil Health ScorecomputeSoilHealthScore() compares pH and EC against the crop recipe's target growth-stage thresholds.
  • SOP bounds checkisOutOfSopBounds() flags a sample whose pH falls outside the recipe's min/max, or whose EC deviates >25% from target — the trigger condition for a remediation order.

Integration triggers

ActionWhat it does
syncTestToFieldProfileUpdates the master parcel's soil characteristics (last soil test date) directly on the ProductionAreaItem record in Fields & Greenhouses.
createFieldWorkOrderWhen pH or nutrient levels fall out of SOP bounds, creates a soil amendment/lime application field order (task type fertigation, status scheduled) directly in Field/Greenhouse Orders — see Agro-Tech Execution.
syncChemicalRequirementsFeeds fertilizer adjustment requirements (derived from N/P/K deficits) into this same service's own Agro-Chemical Analytics ledger as a new fertilizer application record.

2. Crop Health Checklist

Purpose: Conduct field agronomic audits — routine, pre-harvest, or post-treatment — scoring crop condition on a set of 1-5 field ratings and percentage metrics, and gate harvest authorization.

Key features

  • Inspection typesroutine_agronomic, pre_harvest_audit, post_treatment_check, each checklist coded CHC-2026-XXXX.
  • Status lifecyclepassed, requires_attention, quarantine_flagged.
  • 1-5 field rating scale — chlorophyll health, weed density, irrigation uniformity, insect pressure, plus percentage metrics for canopy density, foliage vigor, and root structure health.
  • Health Index ScorecomputeHealthIndexScore() averages the normalized ratings and percentage metrics into a single 0-100 score.
  • Deficiency flags — a list of symptom/severity entries (e.g. "Nitrogen deficiency — yellowing lower leaves").
  • Pre-harvest linkage — a pre_harvest_audit checklist can be linked to a Season & Harvest Scheduling schedule via linkedScheduleId.

Integration triggers

ActionWhat it does
escalateChecklistToAlertWhen isPestPressureCritical() is true (insect pressure rating ≥ 4), generates an alert directly in this service's own Pest & Disease Alert ledger, severity derived from the rating (5→critical_quarantine, 4→moderate).
approvePreHarvestChecklistSets preHarvestClearanceApproved on the linked harvest schedule in Season & Harvest Scheduling, unlocking harvest authorization — see Agro-Tech Execution.
requestSoilTestingWhen hasNutrientDeficiencySymptoms() matches a deficiency flag's symptom text, dispatches a sample-collection task directly into this service's own Soil & Water Testing ledger (status sample_collected).

3. Pest & Disease Alerts

Purpose: Track active pest/disease outbreaks by field, assess spread risk, and dispatch an emergency pesticide response.

Key features

  • Outbreak severitylow, moderate, critical_quarantine, each alert coded PDA-2026-XXXX.
  • Response statusactive_threat → spray_scheduled → contained → resolved.
  • Spread Risk ScorecomputeSpreadRiskScore() blends a severity base score with a climate boost from ambient humidity (>70%) and temperature (22-32°C), pulled from IoT telemetry when available.
  • Diagnostic findings & target active ingredients — a list of lab-confirmable findings, and a list of target active ingredients each with a dosage rate limit and PHI days.
  • Source linkage — an alert can carry sourceChecklistId when escalated from a Crop Health Checklist audit, and linkedYieldRecordId for projecting yield loss onto a specific yield record.

Integration triggers

ActionWhat it does
dispatchEmergencyPesticideOrderCreates an urgent pesticide_spraying field order directly in Field/Greenhouse Orders, noting the active ingredient in the operator observations — see Agro-Tech Execution.
logChemicalActiveIngredientRegisters the alert's target active ingredient, dosage limit, and PHI window directly into this service's own Agro-Chemical Analytics ledger, MRL status set to phi_restricted.
projectYieldLossPenaltySends the estimated crop loss percentage to discount the affected product's ML yield baseline (discountMlBaselineYield in targetHarvestService) and reduces the linked Crop Yield record's target baseline proportionally.

4. Agro-Chemical Analytics

Purpose: Track every chemical application against its Pre-Harvest Interval (PHI) countdown and Maximum Residue Limit (MRL) compliance, enforcing a harvest lockout while restricted.

Key features

  • Record codesACA-2026-XXXX, each application linked to a chemical product name, active ingredient, total dosage (L/ha), and application date.
  • MRL statuscompliant, phi_restricted, mrl_violation_risk.
  • PHI countdown & harvest lockoutcomputePhiDaysRemaining() derives days left in the interval from the application date and window length; isPhiLockoutActive() is true while any days remain — the trigger condition for locking harvest on that field.
  • Applicator license verification — a verified-license flag and license number per application, plus an MSDS URL.
  • Residue lab tests — a list of lab test results (residue ppm, export-market MRL threshold, test date) attached per application.
  • Source linkage — a record can carry sourceTestId (auto-derived from a Soil & Water Testing fertilizer deficit) or sourceAlertId (auto-derived from a Pest & Disease Alerts escalation).

Integration triggers

ActionWhat it does
toggleHarvestLockoutSets harvestLockoutActive on every Season & Harvest Scheduling schedule targeting that field while the PHI countdown is active — see Agro-Tech Execution.
deductInventoryStockReconciles the applied chemical volume against stored stock in Agro-Input Staging (deductStagingStock) — see Harvest & Supply Inventory.
attachComplianceToPassportPushes a residue-clearance certificate reference directly into this service's own Farm-to-Fork Traceability ledger for the matching batch's digital passport.

5. Farm-to-Fork Traceability

Purpose: Compile a per-lot digital product passport that aggregates lineage data from field orders, soil/water tests, chemical applications, and yield/weighbridge data, then export a public QR code for consumer-facing verification.

Key features

  • Lot codesLOT-2026-XXXX, each linked to a harvest batch code, crop variety, origin field, and optionally a storage silo.
  • Certification statusnot_certified, globalgap_pending, globalgap_certified, organic_certified.
  • Compliance statusverified_complete, missing_lab_clearance, quarantined.
  • Digital Product Passport modal — compiles agronomicTreatmentHistory, a list of LineageDataSource entries (source type, id, code, compiled timestamp) drawn from field orders and agro-chemical records.
  • Supply Chain Lineage ScorecomputeLineageScore() is a 6-factor completeness gauge: planting date set, treatment history non-empty, residue clearance attached, weighbridge reading present, cold-chain log summary present, storage silo linked. Each factor passed contributes 1/6 to the 0-100 score.
  • Public QR export — generates a consumer-facing verification token once the passport is compiled.

Integration triggers

ActionWhat it does
compileBatchPassportAggregates lineage data from Field/Greenhouse Orders and Agro-Chemical Analytics (filtered by origin field), and pulls the weighbridge reading from the linked Crop Yield record, writing the combined result into agronomicTreatmentHistory and setting passportCompiled.
exportPublicQrPassportGenerates a public QR token and sets qrPassportExported, written directly onto this service's own traceability record.
verifyStorageOriginValidates the lot's intake parameters against the Silo & Storage Management registry and links storageSiloId/storageSiloCode once matched — see Harvest & Supply Inventory.

Under the hood — the passport is real aggregation, not a mock

compileBatchPassport performs real cross-service reads against agroTechExecutionService.ts (field orders, yield records) and this same file's own agro-chemical ledger — it is not placeholder text. The one gap: verifyStorageOrigin checks against the silo registry directly rather than a dedicated screen's own validation UI, since Silo & Storage Management's registry only recently moved out of agroTechExecutionService.ts (see the implementation note in Harvest & Supply Inventory).

End-to-end data flow

Source screen / functionWritesTarget screen / record
Soil & Water Testing — syncTestToFieldProfileUpdates last soil test dateFields & Greenhouses (ProductionAreaItem)
Soil & Water Testing — createFieldWorkOrderNew fertigation field orderField/Greenhouse Orders
Soil & Water Testing — syncChemicalRequirementsNew fertilizer application recordAgro-Chemical Analytics (same file)
Crop Health Checklist — escalateChecklistToAlertNew pest/disease alertPest & Disease Alerts (same file)
Crop Health Checklist — approvePreHarvestChecklistSets preHarvestClearanceApprovedSeason & Harvest Scheduling
Crop Health Checklist — requestSoilTestingNew soil sample testSoil & Water Testing (same file)
Pest & Disease Alerts — dispatchEmergencyPesticideOrderNew pesticide_spraying field orderField/Greenhouse Orders
Pest & Disease Alerts — logChemicalActiveIngredientNew chemical application recordAgro-Chemical Analytics (same file)
Pest & Disease Alerts — projectYieldLossPenaltyDiscounts ML yield baselineTarget Harvests + Crop Yield Dashboard
Agro-Chemical Analytics — toggleHarvestLockoutSets harvestLockoutActiveSeason & Harvest Scheduling
Agro-Chemical Analytics — deductInventoryStockDeducts staging stockAgro-Input Staging
Agro-Chemical Analytics — attachComplianceToPassportAttaches residue clearanceFarm-to-Fork Traceability (same file)
Farm-to-Fork Traceability — compileBatchPassportCompiles lineage historyOwn record (aggregates 3 upstream screens)
Farm-to-Fork Traceability — verifyStorageOriginLinks storage siloSilo & Storage Management registry

Frequently Asked Questions

What triggers a harvest lockout on a field?
Any Agro-Chemical Analytics application whose PHI (Pre-Harvest Interval) window hasn't elapsed yet. toggleHarvestLockout sets harvestLockoutActive on every harvest schedule targeting that field, and it isn't cleared until computePhiDaysRemaining() reaches zero.
How is a pest/disease alert automatically opened from a field audit?
When a Crop Health Checklist audit's insect pressure rating is 4 or 5, isPestPressureCritical() returns true and escalateChecklistToAlert opens a new alert record directly — severity critical_quarantine for a 5 rating, moderate for a 4.
What exactly does the Supply Chain Lineage Score measure?
Six completeness checks on a traceability lot: planting date set, treatment history non-empty, residue clearance attached, weighbridge reading present, cold-chain log summary present, and storage silo linked. Each passed check contributes one-sixth of the 0-100 score — it measures data completeness, not product quality.
Can a fertilizer application from a soil test skip the PHI/MRL workflow?
No — syncChemicalRequirements writes fertilizer adjustments into the same Agro-Chemical Analytics ledger as pesticide applications, just with a compliant MRL status and a zero PHI window by default, so they still show up in the same compliance table.
What data sources feed the Digital Product Passport?
compileBatchPassport pulls from Field/Greenhouse Orders and Agro-Chemical Analytics (both filtered to the lot's origin field) plus the weighbridge reading from the linked Crop Yield Dashboard record. Storage silo linkage is added separately by verifyStorageOrigin.
Why does verifying storage origin check the silo registry directly instead of a dedicated screen?
At the time verifyStorageOrigin was written, the silo registry lived only as a minimal store inside agroTechExecutionService.ts. It has since moved to harvestSupplyInventoryService.ts with a full management screen (Silo & Storage Management) — the validation logic still works the same way, just against the now-canonical store.