Skip to content

Hotfix/20250618 nutrient balance#169

Merged
SvenVw merged 4 commits into
mainfrom
hotfix/20250618-nutrient-balance
Jun 18, 2025
Merged

Hotfix/20250618 nutrient balance#169
SvenVw merged 4 commits into
mainfrom
hotfix/20250618-nutrient-balance

Conversation

@SvenVw
Copy link
Copy Markdown
Collaborator

@SvenVw SvenVw commented Jun 18, 2025

@coderabbitai summart

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of missing or null numeric values in nitrogen balance calculations to prevent errors and ensure calculations proceed smoothly.
    • Fixed redirects on the harvest details page to correctly include the calendar parameter in URLs.
  • Chores

    • Updated package versions for both the app and calculator.
    • Added changelog entries documenting recent fixes and updates.

@SvenVw SvenVw self-assigned this Jun 18, 2025
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Jun 18, 2025

⚠️ No Changeset found

Latest commit: 01596ba

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 18, 2025

Walkthrough

This update introduces robust handling for potential null or undefined numeric values across multiple nitrogen balance calculation modules by defaulting them to zero. It also ensures consistent retrieval and usage of the calendar parameter in farm-related route handling. Version numbers and changelogs are updated for both the app and calculator packages.

Changes

File(s) Change Summary
fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.cultivation.$b_lu.harvest.$b_id_harvesting.tsx Ensures calendar parameter is consistently retrieved and used in loader, action, and URLs.
fdm-calculator/src/balance/nitrogen/index.ts, .../removal/residue.ts, .../supply/fertilizers/compost.ts, .../manure.ts, .../mineral.ts, .../other.ts, .../supply/mineralization.ts, .../target.ts, .../volatization/residues.ts Adds nullish coalescing (?? 0) to numeric fields to prevent errors from null/undefined values.
fdm-app/CHANGELOG.md, fdm-calculator/CHANGELOG.md Adds changelog entries for new patch versions and documents fixes.
fdm-app/package.json, fdm-calculator/package.json Updates package versions (fdm-app to 0.19.6, fdm-calculator to 0.3.3).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Loader
    participant Action
    participant getCalendar

    User->>Loader: Request page with route params
    Loader->>getCalendar: Extract calendar from params
    getCalendar-->>Loader: Return calendar value
    Loader-->>User: Return data including calendar

    User->>Action: Submit form with route params
    Action->>getCalendar: Extract calendar from params
    getCalendar-->>Action: Return calendar value
    Action-->>User: Redirect using calendar in URL
Loading

Possibly related PRs

Suggested labels

fdm-app

Suggested reviewers

  • gerardhros

Poem

A hop, a skip, a leap through code,
Nulls and undefineds now safely stowed.
Calendars in routes, all neat and clear,
Patch versions rise—let’s give a cheer!
With every Decimal, errors subside,
The fields and farms with balance abide.
🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch hotfix/20250618-nutrient-balance

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 18, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 93.07%. Comparing base (2542c7e) to head (01596ba).
Report is 5 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #169   +/-   ##
=======================================
  Coverage   93.07%   93.07%           
=======================================
  Files          68       68           
  Lines        8061     8063    +2     
  Branches      957      974   +17     
=======================================
+ Hits         7503     7505    +2     
  Misses        556      556           
  Partials        2        2           
Flag Coverage Δ
fdm-calculator 94.70% <100.00%> (+<0.01%) ⬆️
fdm-core 92.75% <ø> (ø)
fdm-data 92.92% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot added bug Something isn't working fdm-calculator labels Jun 18, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (3)
fdm-calculator/src/balance/nitrogen/volatization/residues.ts (1)

69-72: Potential crash still lurking here

analysisWithYield.b_lu_yield is passed straight to new Decimal(...) without a ?? 0 guard.
If the analysis contains null this line will still throw. Apply the same pattern as the other conversions.

-yieldForThisHarvest = new Decimal(analysisWithYield.b_lu_yield)
+yieldForThisHarvest = new Decimal(analysisWithYield.b_lu_yield ?? 0)
fdm-calculator/src/balance/nitrogen/supply/fertilizers/compost.ts (1)

1-1: Incorrect import style – will break at runtime

decimal.js exports a default. Using a named import { Decimal } results in undefined, so every new Decimal(...) will crash.

-import { Decimal } from "decimal.js"
+import Decimal from "decimal.js"

Make sure other modules don’t use the same pattern.

fdm-calculator/src/balance/nitrogen/target.ts (1)

112-114: Duplicate assignment hides the intended 115 kg N ha⁻¹ value

targetValue is immediately overwritten from 115 to 125, making the first assignment dead code and potentially skewing results for the clay-dry class.

-        targetValue = new Decimal(115)
-        targetValue = new Decimal(125)
+        targetValue = new Decimal(115)

Please confirm which value is correct and remove the redundant line.

🧹 Nitpick comments (8)
.changeset/vast-onions-judge.md (1)

5-5: Polish the changelog wording for clarity

Fixes redirects at harvest details pageFixes redirects on the harvest-details page.

Clearer wording and correct preposition will make the changeset more professional.

.changeset/cyan-peaches-wait.md (1)

5-5: Refine the description to read naturally

Current sentence is a bit clunky. Consider:

-Fix at balance calculation to convert null values to 0 and prevent exception due to Decimal
+Fix balance calculations by converting null values to 0, preventing Decimal-constructor exceptions
fdm-calculator/src/balance/nitrogen/volatization/residues.ts (3)

78-81: Consistent defaulting looks good, but avoid magic Decimal(0) literals everywhere

The null-coalescing on b_lu_yield is correct. To avoid scattering ?? 0 / new Decimal(0) across the codebase, consider a tiny helper:

export const toDecimal = (v: number | string | null | undefined) =>
    new Decimal(v ?? 0)

Then:

- yieldForThisHarvest = new Decimal(cultivationDetail.b_lu_yield ?? 0)
+ yieldForThisHarvest = toDecimal(cultivationDetail.b_lu_yield)

92-93: Same helper could tidy this block

Repeated new Decimal(x ?? 0) pattern again – the suggested helper would reduce duplication and risk of forgetting the default in future edits.


98-99: Minor spacing nit

??0?? 0 for consistency with the rest of the file.

-const b_lu_hi = new Decimal(cultivationDetail.b_lu_hi ??0)
+const b_lu_hi = new Decimal(cultivationDetail.b_lu_hi ?? 0)
fdm-calculator/src/balance/nitrogen/supply/fertilizers/compost.ts (1)

52-53: Mirror the helper suggestion

Same duplication comment as in residues.ts – a shared toDecimal() helper would keep this conversion terse and consistent.

fdm-calculator/src/balance/nitrogen/target.ts (2)

30-39: Replace map with forEach (or some) to clarify intent

cultivations.map(...) is used purely for its side-effects; the resulting array is discarded.
Using forEach (or some if you want an early exit) better communicates intent and avoids the tiny overhead/allocation of an unused array.

-cultivations.map((cultivation) => {
+cultivations.forEach((cultivation) => {

129-129: Avoid double-wrapping Decimal and keep the fallback concise

targetValue is already a Decimal (when defined). Wrapping it again is harmless but unnecessary.
A clearer pattern:

-const target = new Decimal(targetValue ?? 0).times(timeFrameFraction)
+const target = (targetValue ?? new Decimal(0)).times(timeFrameFraction)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2542c7e and 94a82f6.

📒 Files selected for processing (12)
  • .changeset/cyan-peaches-wait.md (1 hunks)
  • .changeset/vast-onions-judge.md (1 hunks)
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.cultivation.$b_lu.harvest.$b_id_harvesting.tsx (6 hunks)
  • fdm-calculator/src/balance/nitrogen/index.ts (2 hunks)
  • fdm-calculator/src/balance/nitrogen/removal/residue.ts (2 hunks)
  • fdm-calculator/src/balance/nitrogen/supply/fertilizers/compost.ts (2 hunks)
  • fdm-calculator/src/balance/nitrogen/supply/fertilizers/manure.ts (2 hunks)
  • fdm-calculator/src/balance/nitrogen/supply/fertilizers/mineral.ts (2 hunks)
  • fdm-calculator/src/balance/nitrogen/supply/fertilizers/other.ts (2 hunks)
  • fdm-calculator/src/balance/nitrogen/supply/mineralization.ts (1 hunks)
  • fdm-calculator/src/balance/nitrogen/target.ts (1 hunks)
  • fdm-calculator/src/balance/nitrogen/volatization/residues.ts (2 hunks)
🧰 Additional context used
🪛 LanguageTool
.changeset/vast-onions-judge.md

[uncategorized] ~5-~5: The preposition ‘to’ seems more likely in this position.
Context: ...vw/fdm-app": patch --- Fixes redirects at harvest details page

(AI_HYDRA_LEO_REPLACE_AT_TO)

⏰ Context from checks skipped due to timeout of 300000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: core (22)
  • GitHub Check: calculator (22)
🔇 Additional comments (12)
fdm-calculator/src/balance/nitrogen/supply/mineralization.ts (1)

45-48: 👍 Redundant Decimal constructor call removed

mineralizationValue is already a Decimal; deleting the extra wrapper avoids an unnecessary allocation while preserving behaviour. Nice cleanup.

fdm-calculator/src/balance/nitrogen/supply/fertilizers/compost.ts (1)

41-42: Good null-safety addition

Defaulting p_n_rt to zero prevents Decimal constructor errors. Once the import is fixed this line is solid.

fdm-calculator/src/balance/nitrogen/supply/fertilizers/manure.ts (2)

40-41: Good guard against null/undefined nitrogen rate

The ?? 0 fallback prevents Decimal construction errors when p_n_rt is missing. 👍


51-52: Consistent null-safe handling for application amount

Same remark as above—this hardens the calculation path.
No further issues spotted here.

fdm-calculator/src/balance/nitrogen/supply/fertilizers/mineral.ts (2)

39-40: Null-safe nitrogen rate looks good

The ?? 0 plus unit conversion is correct and prevents crashes.
LGTM.


50-51: Application amount fallback is correct

Keeps calculations robust when data is incomplete. No objections.

fdm-calculator/src/balance/nitrogen/supply/fertilizers/other.ts (2)

36-37: Safe default for p_n_rt

Nullish coalescing prevents runtime issues. Looks good.


51-52: Safe default for p_app_amount

Same positive comment as above. Implementation is sound.

fdm-calculator/src/balance/nitrogen/index.ts (2)

200-203: Graceful handling of missing b_area

Defaulting to zero avoids NaNs in farm-level aggregates. 👍


222-223: Field-level area fallback consistent with farm-level logic

Change mirrors the total-area fix. All good.

fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.cultivation.$b_lu.harvest.$b_id_harvesting.tsx (1)

84-85: ```shell
#!/usr/bin/env bash
set -e

echo "=== Listing project-level lib directory ==="
ls -1 fdm-app/lib || echo "fdm-app/lib not found"

echo
echo "=== Calendar library files at fdm-app/lib ==="
ls -1 fdm-app/lib/calendar* || echo "No calendar files in fdm-app/lib"

echo
echo "=== getCalendar implementation in calendar files ==="
rg -n -C3 "export (async )?function getCalendar" -g "fdm-app/lib/calendar*"


</details>
<details>
<summary>fdm-calculator/src/balance/nitrogen/removal/residue.ts (1)</summary>

`90-101`: **Good defensive defaults added**

Using `?? 0` before constructing new `Decimal` objects prevents `DecimalError: NaN` exceptions when backend data is `null`. This hardens the calculation path.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread fdm-calculator/src/balance/nitrogen/removal/residue.ts
@coderabbitai coderabbitai Bot added the fdm-app label Jun 18, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
fdm-app/CHANGELOG.md (1)

7-7: Refine preposition in commit message
Use “on the harvest details page” instead of “at harvest details page” for clarity.
Apply this diff:

- - f2b1fc6: Fixes redirects at harvest details page
+ - f2b1fc6: Fixes redirects on the harvest details page
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94a82f6 and 01596ba.

📒 Files selected for processing (5)
  • fdm-app/CHANGELOG.md (1 hunks)
  • fdm-app/package.json (1 hunks)
  • fdm-calculator/CHANGELOG.md (1 hunks)
  • fdm-calculator/package.json (1 hunks)
  • fdm-calculator/src/balance/nitrogen/removal/residue.ts (2 hunks)
✅ Files skipped from review due to trivial changes (3)
  • fdm-calculator/CHANGELOG.md
  • fdm-app/package.json
  • fdm-calculator/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • fdm-calculator/src/balance/nitrogen/removal/residue.ts
🧰 Additional context used
🪛 LanguageTool
fdm-app/CHANGELOG.md

[uncategorized] ~7-~7: The preposition ‘to’ seems more likely in this position.
Context: ...tch Changes - f2b1fc6: Fixes redirects at harvest details page - Updated dependen...

(AI_HYDRA_LEO_REPLACE_AT_TO)

⏰ Context from checks skipped due to timeout of 300000ms (5)
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: calculator (22)
  • GitHub Check: data (22)
  • GitHub Check: core (22)
🔇 Additional comments (2)
fdm-app/CHANGELOG.md (2)

3-5: Consistent formatting for new version entry
The header ## 0.19.6 and its “Patch Changes” section match the style of prior entries—no changes needed here.


8-9: Verify dependency update commit and version
Ensure that commit 94a82f6 corresponds to the release of @svenvw/fdm-calculator@0.3.3.
Run this script to confirm via GitHub’s API:

#!/bin/bash
# Verify commit exists in fdm-calculator and tag v0.3.3 is present
curl -s https://api.github.com/repos/SvenVw/fdm-calculator/commits/94a82f6 | jq '{sha: .sha, message: .commit.message}'
curl -s https://api.github.com/repos/SvenVw/fdm-calculator/tags | jq '.[] | select(.name=="v0.3.3")'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working fdm-app fdm-calculator

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant