Skip to content

Add MINIP NLV calculations and expose calculated soil supply values - #718

Merged
SvenVw merged 7 commits into
developmentfrom
FDM717
Jul 28, 2026
Merged

Add MINIP NLV calculations and expose calculated soil supply values#718
SvenVw merged 7 commits into
developmentfrom
FDM717

Conversation

@SvenVw

@SvenVw SvenVw commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added Nitrogen Supplying Capacity (NLV), shown in soil details, field dashboards, field tables, and the soil analysis atlas.
    • NLV can be calculated automatically from available soil data and is displayed in kg N/ha.
    • Added a clear “Calculated” indicator for automatically derived values.
  • Bug Fixes

    • Improved handling of missing soil values so unavailable data is not treated as valid.
    • Automatically calculated NLV values are presented as read-only to prevent accidental editing.

Closes #717

SvenVw added 3 commits July 27, 2026 16:58
… soil organic matter from soil) that can have a 'calculated' source
…lization from soil organic mattter. Rename `calculateNlvSupplyBySom` to `calculateNlvSupplyIncreaseBySomPotential`
…upply_base`) across soil cards, the field overview dashboard, fields table, and the soil analysis atlas map layer.
@SvenVw SvenVw self-assigned this Jul 27, 2026
@codecov

codecov Bot commented Jul 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@SvenVw, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 36 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c601b952-48b1-4ca6-ad62-7e92da6495de

📥 Commits

Reviewing files that changed from the base of the PR and between 71717ad and c442ed2.

📒 Files selected for processing (1)
  • fdm-core/src/soil.test.ts
📝 Walkthrough

Walkthrough

This PR adds the calculateNlv API, registers d_n_supply_base in core soil data, enriches missing NLV values in application loaders, and displays calculated NLV in soil cards, dashboards, fields tables, and the atlas.

Changes

NLV calculation API

Layer / File(s) Summary
Calculator implementation and exports
fdm-calculator/src/other/nlv-supply.ts, fdm-calculator/src/index.ts, fdm-calculator/src/other/nlv-supply.test.ts
Adds and tests calculateNlv and calculateNlvSupplyIncreaseBySomPotential, updates public exports, and replaces the previous calculator usage.
Calculator release documentation
fdm-docs/blog/2026-03-04-release-notes.mdx, .changeset/swift-ears-argue.md
Updates documented calculator names and records the minor release changeset.

Core soil contract

Layer / File(s) Summary
Soil parameter registration
fdm-core/src/soil.ts, fdm-core/src/soil.types.d.ts, .changeset/rich-masks-occur.md
Registers d_n_supply_base as a numeric kg N/ha soil parameter and excludes null or undefined parameter values during current-soil selection.

Application integration

Layer / File(s) Summary
Soil data enrichment and loaders
fdm-app/app/lib/soil.server.ts, fdm-app/app/routes/farm.$b_id_farm.$calendar...
Computes missing NLV values from SOM, clay, and C/N data, marks them as calculated, and applies enrichment across soil, field, atlas, and field-list routes.
NLV presentation surfaces
fdm-app/app/components/blocks/soil/cards.tsx, fdm-app/app/components/blocks/field-dashboard/tiles.tsx, fdm-app/app/components/blocks/fields/columns.tsx, fdm-app/app/components/blocks/atlas/atlas-soil-analysis.ts
Adds NLV to soil groups, dashboard tiles, field tables, and the nitrogen gradient, with calculated-source labels and calculator icons.

Atlas analytics

Layer / File(s) Summary
Selected atlas property tracking
fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas.soil-analysis._index.tsx, fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas.indicators.tsx
Includes the selected soil parameter or indicator property in atlas_viewed events and updates tracking dependencies.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RouteLoader
  participant SoilDataAPI
  participant SoilEnrichment
  participant NlvCalculator
  participant SoilUI
  RouteLoader->>SoilDataAPI: fetch current soil data
  SoilDataAPI-->>SoilEnrichment: return soil parameters
  SoilEnrichment->>NlvCalculator: calculate missing d_n_supply_base
  NlvCalculator-->>SoilEnrichment: return rounded NLV
  SoilEnrichment-->>SoilUI: render enriched soil data
Loading

Possibly related PRs

  • nmi-agro/fdm#108: Both modify core soil data retrieval and metadata behavior.
  • nmi-agro/fdm#274: Both extend the fields table type and column definitions.
  • nmi-agro/fdm#465: Both modify SOM-based N-mineralization calculations in the atlas field route.

Suggested labels: enhancement, fdm-app, fdm-core, fdm-calculator, fdm-docs

Suggested reviewers: borainevinmi

Poem

A rabbit watched the NLV numbers glow,
Through soil cards and maps below.
“Calculated!” the icons cheer,
New nitrogen data appears.
Hop, hop—the fields now know!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR exports calculateNlv, but it removes calculateNlvSupplyBySom and uses calculated instead of clientConfig.name for the new source label, so #717 isn't fully met. Restore calculateNlvSupplyBySom as a backward-compatible wrapper around calculateNlv, and set derived d_n_supply_base source/label from clientConfig.name.
Out of Scope Changes check ⚠️ Warning The PR includes unrelated edits like the field page title change to "Percelen" and analytics payload/dependency changes that are outside the NLV scope. Remove the unrelated title and analytics edits unless they are required for NLV behavior, and keep the PR focused on calculator, soil parameter, and display changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 73.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed Title check skipped as CodeRabbit has written the PR title.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch FDM717

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot changed the title @coderabbitai Add MINIP NLV calculations and expose calculated soil supply values Jul 27, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id._index.tsx (1)

234-260: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Inline await inside the Promise.all array breaks parallelism.

enrichCurrentSoilDataWithNlv(await getCurrentSoilData(...)) is evaluated as an array element with a suspending await. Because array elements are evaluated left-to-right, this pauses construction of the array before getSoilAnalyses(...) and getMeasures(...) (elements after it) are even invoked — those two calls no longer run concurrently with the rest, they now wait on getCurrentSoilData to finish first, adding sequential latency to the loader.

⚡ Proposed fix — enrich after Promise.all resolves
     fertilizerApplications,
     fertilizers,
-    enrichCurrentSoilDataWithNlv(
-      await getCurrentSoilData(fdm, session.principal_id, b_id, timeframe),
-    ),
+    currentSoilDataRaw,
     soilAnalyses,
     measures,
   ] = await Promise.all([
     getField(fdm, session.principal_id, b_id),
     getFields(fdm, session.principal_id, b_id_farm, timeframe),
     getCultivations(fdm, session.principal_id, b_id, timeframe),
     getCultivations(fdm, session.principal_id, b_id),
     getFertilizerApplications(fdm, session.principal_id, b_id, timeframe),
     getFertilizers(fdm, session.principal_id, b_id_farm),
-    getSoilAnalyses(fdm, session.principal_id, b_id, {
+    getCurrentSoilData(fdm, session.principal_id, b_id, timeframe),
+    getSoilAnalyses(fdm, session.principal_id, b_id, {
       start: null,
       end: timeframe.end,
     }),
     getMeasures(fdm, session.principal_id, b_id, timeframe),
   ])
+
+  const currentSoilData = enrichCurrentSoilDataWithNlv(currentSoilDataRaw)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@fdm-app/app/routes/farm`.$b_id_farm.$calendar.field.$b_id._index.tsx around
lines 234 - 260, Remove the inline await from the Promise.all array in the
loader, keeping getCurrentSoilData as its own parallel promise alongside
getSoilAnalyses and getMeasures. After Promise.all resolves, pass the resolved
current soil data through enrichCurrentSoilDataWithNlv before returning or using
the loader results, preserving the existing enriched value for currentSoilData.
fdm-app/app/components/blocks/soil/cards.tsx (1)

107-118: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep calculated NLV traceable to its source analysis.

The enrichment preserves the originating a_id and sampling date, but this change removes the view link and hides the date for source === "calculated". Users see “Berekend” without being able to inspect the analysis behind the value. Keep a view-only link and display the inherited source date.

As per coding guidelines, numbers must remain transparent and auditable and connected insights discoverable.

Proposed direction
-  const EditIcon = canModify ? Pencil : ExternalLink
+  const EditIcon = source === "calculated" || !canModify ? ExternalLink : Pencil

-        {source !== "nl-other-nmi" && source !== "calculated" ? (
+        {source !== "nl-other-nmi" ? (

-          <TooltipContent>{canModify ? "Bewerken" : "Bekijken"}</TooltipContent>
+          <TooltipContent>
+            {source === "calculated" || !canModify ? "Bekijken" : "Bewerken"}
+          </TooltipContent>

-          {!(!date || source === "nl-other-nmi" || source === "calculated") && (
+          {!(!date || source === "nl-other-nmi") && (

Also applies to: 148-177

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@fdm-app/app/components/blocks/soil/cards.tsx` around lines 107 - 118, Update
the soil card rendering around the source-based edit/view link and date display
so source === "calculated" retains a view-only NavLink to the inherited
analysis, using canModify to prevent editing. Restore the preserved sampling
date for calculated NLV entries, while keeping existing exclusions for
nl-other-nmi and the current behavior for other sources unchanged.

Source: Coding guidelines

🧹 Nitpick comments (1)
fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas.soil-analysis._index.tsx (1)

96-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated NLV derivation logic — consider reusing enrichCurrentSoilDataWithNlv.

This reimplements the same som/clay/cn extraction, calculateNlv call, and 1-decimal rounding already implemented in fdm-app/app/lib/soil.server.ts. Since the logic is correct here (it does guard against overwriting an existing value), the main risk is drift if the formula/rounding changes in one place but not the other — e.g., field.tsx already reimplements this without the existing-value guard.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@fdm-app/app/routes/farm`.$b_id_farm.$calendar.atlas.soil-analysis._index.tsx
around lines 96 - 119, The field feature-building logic duplicates NLV
enrichment already provided by enrichCurrentSoilDataWithNlv in soil.server.ts.
Reuse that helper for current soil data before constructing soilProps,
preserving the existing-value guard and removing the local som/clay/cn
extraction, calculateNlv call, and rounding logic from the fields map.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.changeset/swift-ears-argue.md:
- Line 5: Update the changeset text to correct “calulate” to “calculate” and
“mattter” to “matter”, and reference the exported function as `calculateNlv`
with lowercase “l” instead of `calculateNLv`; preserve the existing rename
description for `calculateNlvSupplyBySom`.

In `@fdm-app/app/routes/farm`.$b_id_farm.$calendar.field.tsx:
- Around line 192-206: Update the NLV derivation near d_n_supply_base to first
reuse an existing currentSoilData entry whose parameter is d_n_supply_base,
preserving its measured value instead of recalculating it. Only call
calculateNlv when no existing value is present, and align the behavior with
enrichCurrentSoilDataWithNlv and the atlas soil-analysis loader.

In `@fdm-calculator/src/other/nlv-supply.ts`:
- Around line 39-90: Update calculateNlv with overloads that narrow the return
type: number when format is omitted or "number", and Decimal when format is
"decimal". Keep the existing calculation and runtime branching unchanged, while
ensuring the implementation signature remains compatible with both overloads.

In `@fdm-core/src/db/schema.ts`:
- Around line 677-680: Remove the “calculated” option from the persisted
soil-analysis source options and the editable enum/options generation used by
SoilAnalysisForm. If display of derived results is required, expose it through a
separate derived-source/display-only option rather than the a_source enum,
ensuring users cannot persist “Berekend” as an analysis source.

---

Outside diff comments:
In `@fdm-app/app/components/blocks/soil/cards.tsx`:
- Around line 107-118: Update the soil card rendering around the source-based
edit/view link and date display so source === "calculated" retains a view-only
NavLink to the inherited analysis, using canModify to prevent editing. Restore
the preserved sampling date for calculated NLV entries, while keeping existing
exclusions for nl-other-nmi and the current behavior for other sources
unchanged.

In `@fdm-app/app/routes/farm`.$b_id_farm.$calendar.field.$b_id._index.tsx:
- Around line 234-260: Remove the inline await from the Promise.all array in the
loader, keeping getCurrentSoilData as its own parallel promise alongside
getSoilAnalyses and getMeasures. After Promise.all resolves, pass the resolved
current soil data through enrichCurrentSoilDataWithNlv before returning or using
the loader results, preserving the existing enriched value for currentSoilData.

---

Nitpick comments:
In `@fdm-app/app/routes/farm`.$b_id_farm.$calendar.atlas.soil-analysis._index.tsx:
- Around line 96-119: The field feature-building logic duplicates NLV enrichment
already provided by enrichCurrentSoilDataWithNlv in soil.server.ts. Reuse that
helper for current soil data before constructing soilProps, preserving the
existing-value guard and removing the local som/clay/cn extraction, calculateNlv
call, and rounding logic from the fields map.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9d49687c-538b-4155-8d35-267289b52105

📥 Commits

Reviewing files that changed from the base of the PR and between 54e0933 and 51edad7.

📒 Files selected for processing (24)
  • .changeset/grumpy-mirrors-see.md
  • .changeset/rich-masks-occur.md
  • .changeset/swift-ears-argue.md
  • fdm-app/app/components/blocks/atlas/atlas-soil-analysis.ts
  • fdm-app/app/components/blocks/field-dashboard/tiles.tsx
  • fdm-app/app/components/blocks/fields/columns.tsx
  • fdm-app/app/components/blocks/soil/cards.tsx
  • fdm-app/app/lib/soil.server.ts
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas.fields.$centroid.tsx
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas.soil-analysis._index.tsx
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas_.soil-analysis.$b_id.soil._index.tsx
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.atlas_.soil-analysis.$b_id.soil.analysis.$a_id.tsx
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id._index.tsx
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil._index.tsx
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.tsx
  • fdm-calculator/src/index.ts
  • fdm-calculator/src/other/nlv-supply-by-som.test.ts
  • fdm-calculator/src/other/nlv-supply-by-som.ts
  • fdm-calculator/src/other/nlv-supply.test.ts
  • fdm-calculator/src/other/nlv-supply.ts
  • fdm-core/src/db/schema.ts
  • fdm-core/src/soil.ts
  • fdm-core/src/soil.types.d.ts
  • fdm-docs/blog/2026-03-04-release-notes.mdx
💤 Files with no reviewable changes (2)
  • fdm-calculator/src/other/nlv-supply-by-som.test.ts
  • fdm-calculator/src/other/nlv-supply-by-som.ts

Comment thread .changeset/swift-ears-argue.md Outdated
Comment thread fdm-app/app/routes/farm.$b_id_farm.$calendar.field.tsx Outdated
Comment thread fdm-calculator/src/other/nlv-supply.ts Outdated
Comment thread fdm-core/src/db/schema.ts Outdated
@SvenVw
SvenVw merged commit 322d99f into development Jul 28, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor NLV Calculation & Display (d_n_supply_base) Across Soil Surfaces

1 participant