Skip to content

Add calendar/timeframe, update URLs & state; remove React context#106

Merged
SvenVw merged 60 commits into
developmentfrom
implement-seasons
Apr 1, 2025
Merged

Add calendar/timeframe, update URLs & state; remove React context#106
SvenVw merged 60 commits into
developmentfrom
implement-seasons

Conversation

@SvenVw
Copy link
Copy Markdown
Collaborator

@SvenVw SvenVw commented Mar 13, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a calendar option in the sidebar that lets users filter assets and actions by year.
    • Navigation links now dynamically include the selected calendar for a more tailored routing experience.
    • The create farm wizard now temporarily disables sidebar links to prevent accidental navigation.
  • Enhancements

    • Yield measurement displays have been updated to show values in kilograms, ensuring unit accuracy.
    • Improved filtering and state management result in a smoother, more consistent user experience.
    • Added functionality to filter cultivations, harvests, and soil analyses based on specified timeframes.

@SvenVw SvenVw self-assigned this Mar 13, 2025
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Mar 13, 2025

🦋 Changeset detected

Latest commit: 78ae975

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@svenvw/fdm-app Minor
@svenvw/fdm-core Minor
@svenvw/fdm-calculator Patch

Not sure what this means? Click here to learn what changesets are.

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 13, 2025

Walkthrough

This set of changes introduces a new “Kalender” option into the application’s sidebar and integrates dynamic calendar management throughout the front-end and back-end. URL paths, loader functions, and data fetching routines are updated to handle additional parameters—in particular a new timeframe parameter—to filter assets such as cultivations, fields, fertilizers, harvests, and soil analyses. The updates also refactor state management to use Zustand stores for both calendar and farm identification and include adjustments to test cases and dependency lists.

Changes

Files Change Summary
.changeset/* New changeset files document patches: addition of the Kalender option; unit corrections; refactoring of farm context to use Zustand; updates to function signatures adding a timeframe argument; and migration file renaming.
fdm-app/app/components/custom/{farm-header.tsx, harvest/form.tsx, harvest/list.tsx, sidebar-app.tsx} UI components updated to import useCalendarStore, use dynamic calendar state in URL paths, update yield unit displays, and improve sidebar navigation logic with a collapsible calendar menu.
fdm-app/app/routes/** Multiple route loaders and actions are modified to import and use getCalendar and getTimeframe, injecting calendar and timeframe into data retrieval functions and dynamic URL construction.
fdm-app/app/store/{calendar.tsx, farm.tsx} New Zustand stores created for managing calendar state and farm ID.
fdm-app/package.json Dependencies updated: added @radix-ui/react-collapsible and zustand.
fdm-core/src/{cultivation.ts, fertilizer.ts, field.ts, harvest.ts, soil.ts, timeframe.d.ts, index.ts} and corresponding test files Core functions now accept an optional timeframe parameter for SQL filtering, new helper functions for constructing date range conditions are added, and tests are extended to cover these time-based queries.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Sidebar
    participant CalendarStore
    participant RouteLoader
    participant fdmCore

    User->>Sidebar: Select a calendar year ("Kalender" option)
    Sidebar->>CalendarStore: Update calendar state
    Sidebar->>RouteLoader: Build dynamic URLs with calendar and timeframe
    RouteLoader->>fdmCore: Request filtered data (cultivations, fields, etc.)
    fdmCore-->>RouteLoader: Return results based on timeframe filtering
    RouteLoader-->>User: Render updated view with calendar context
Loading

Possibly related PRs

  • Integrate Harvest Management: Update Schemas, Data Fields, and UI #71: The changes in the main PR, which introduce a new Kalender option for filtering assets, are related to the retrieved PR as both involve modifications to the handling of harvest-related data, specifically through the integration of new properties and functionalities that enhance the management of cultivations and harvests.
  • Add field management and soil analysis features #30: The changes in the main PR, which introduce a Kalender option for filtering assets, are related to the retrieved PR as both involve modifications to the handling of calendar data and its integration into the application, specifically affecting the sidebar and routing logic.

Poem

Oh, I’m a rabbit with code in my toes,
Hopping through calendars where the new feature grows.
The sidebar sparkles with a time-tuned beat,
URL paths change in a rhythm so sweet.
In Zustand’s garden my state’s set free—
Carrots and code, a festive jubilee!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b77f446 and 78ae975.

📒 Files selected for processing (2)
  • fdm-core/src/cultivation.test.ts (6 hunks)
  • fdm-core/src/soil.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
fdm-core/src/cultivation.test.ts (4)
fdm-core/src/cultivation.ts (6)
  • addCultivation (152-301)
  • getCultivations (390-457)
  • getCultivationPlan (535-772)
  • buildDateRangeCondition (1047-1068)
  • buildDateRangeConditionEnding (1071-1104)
  • isCultivationWithinTimeframe (774-789)
fdm-core/src/db/schema.ts (1)
  • cultivations (259-270)
fdm-core/src/field.ts (1)
  • addField (46-114)
fdm-core/src/fertilizer.ts (1)
  • addFertilizerApplication (625-684)
🔇 Additional comments (14)
fdm-core/src/cultivation.test.ts (10)

1-31: Good handling of the schema import change.

The change from type-only import to a value import at line 30 correctly addresses the "ReferenceError: schema is not defined" issue that was mentioned in previous review comments. The code now properly imports schema as a value for use at runtime.


264-316: Well-structured test for filtering cultivations by timeframe.

This test case thoroughly validates the timeframe filtering functionality with multiple scenarios:

  1. Filtering cultivations within a specific date range (2024-02-01 to 2024-05-03)
  2. Filtering with a different date range (2024-04-01 to 2024-08-01)
  3. Testing with a single-day timeframe (2024-06-01)

The assertions correctly verify both the count of returned cultivations and their specific dates.


744-750: Clear error handling test for non-existent farm.

The test correctly verifies that attempting to access the cultivation plan for a non-existent farm returns a permission denied error rather than exposing internal details.


752-863: Comprehensive test for complex cultivation plan scenarios.

This test thoroughly validates the cultivation plan functionality with multiple cultivations and fields. It sets up two different cultivation types (Wheat and Corn) across two fields and verifies that:

  1. The correct number of cultivation types are returned
  2. Fields are properly associated with the correct cultivations
  3. Fertilizer applications are correctly linked to each field

The test structure makes it easy to understand the expected relationships between cultivations, fields, and fertilizer applications.


865-887: Good edge case test for no fertilizer applications.

This test properly verifies that the cultivation plan handles the case where no fertilizer applications are present by checking that the returned plan includes the cultivation and field, but with an empty fertilizer_applications array.


889-943: Well-designed timeframe filtering test for cultivation plans.

This test effectively validates that the timeframe parameter correctly filters cultivations based on the specified date range. It sets up cultivations both within and outside the timeframe, then verifies that only those within the timeframe are included in the results.


945-1046: Good boundary tests for timeframe filtering.

These tests check important edge cases for timeframe filtering:

  1. When the timeframe includes all cultivations, all should be returned
  2. When the timeframe excludes all cultivations, an empty array should be returned

These tests help ensure robust handling of all possible timeframe scenarios.


1085-1120: Thorough unit tests for buildDateRangeCondition.

These tests comprehensively verify the behavior of the buildDateRangeCondition function with different input combinations:

  • When both dates are null or undefined
  • When only dateStart is provided
  • When only dateEnd is provided
  • When both dates are provided

The assertions correctly check that the appropriate SQL conditions (gte, lte, and) are returned.


1122-1183: Comprehensive tests for buildDateRangeConditionEnding.

Similar to the buildDateRangeCondition tests, these tests thoroughly validate the more complex buildDateRangeConditionEnding function, which handles the special case of ending dates. The tests verify that the function properly constructs the expected SQL conditions (or, gte, lte, and, isNotNull) for all input combinations.


1185-1318: Extensive validation of isCultivationWithinTimeframe.

This test suite thoroughly covers numerous scenarios for the timeframe inclusion logic:

  • Cultivation starts within timeframe
  • Cultivation ends within timeframe
  • Cultivation spans the entire timeframe
  • Cultivation is entirely before the timeframe
  • Cultivation is entirely after the timeframe
  • Edge cases with dates at the boundaries
  • Handling of null end dates

These tests ensure the function correctly determines timeframe inclusion under all possible scenarios.

fdm-core/src/soil.test.ts (4)

281-421: Well-structured test for soil analyses timeframe filtering.

This test thoroughly validates the timeframe filtering functionality for soil analyses with multiple scenarios:

  1. Filtering with a specific month range (April 2023)
  2. Filtering with a wider date range (April-May 2023)
  3. Filtering with a range that includes all analyses (March-June 2023)
  4. Testing with only a start date
  5. Testing with only an end date
  6. Testing with no timeframe

Each scenario includes appropriate assertions to verify that the returned analyses have sampling dates within the specified timeframe.


488-587: Comprehensive test for current soil data timeframe filtering.

This test effectively verifies that the getCurrentSoilData function correctly filters soil data based on the provided timeframe. It tests two key scenarios:

  1. A timeframe that excludes the latest analysis, verifying that older values are returned
  2. A timeframe that includes all analyses, verifying that the most recent values are returned

The test also properly checks that parameters not present in older analyses (like b_gwl_class) are undefined when filtering to an earlier timeframe.


589-615: Good test for empty result when no data in timeframe.

This test verifies the correct behavior when the specified timeframe doesn't include any soil analyses, confirming that an empty array is returned rather than throwing an error or returning incorrect data.


617-643: Proper test for one-sided timeframe filtering.

This test validates that when only a start date is provided in the timeframe (with no end date), the function correctly returns all data from that point forward. This is an important edge case to verify.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@SvenVw SvenVw linked an issue Mar 13, 2025 that may be closed by this pull request
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 13, 2025

Codecov Report

Attention: Patch coverage is 98.27586% with 4 lines in your changes missing coverage. Please review.

Project coverage is 92.63%. Comparing base (41b720c) to head (78ae975).
Report is 61 commits behind head on development.

Files with missing lines Patch % Lines
fdm-core/src/cultivation.ts 98.09% 2 Missing ⚠️
fdm-core/src/fertilizer.ts 90.47% 2 Missing ⚠️
Additional details and impacted files
@@               Coverage Diff               @@
##           development     #106      +/-   ##
===============================================
+ Coverage        92.06%   92.63%   +0.56%     
===============================================
  Files               43       44       +1     
  Lines             4475     4696     +221     
  Branches           440      502      +62     
===============================================
+ Hits              4120     4350     +230     
+ Misses             354      345       -9     
  Partials             1        1              
Flag Coverage Δ
fdm-calculator 92.68% <ø> (ø)
fdm-core 92.55% <98.27%> (+0.60%) ⬆️
fdm-data 94.64% <ø> (ø)

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.

@SvenVw SvenVw added this to the Alpha release milestone Mar 13, 2025
@SvenVw SvenVw requested a review from gerardhros March 18, 2025 13:31
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

♻️ Duplicate comments (1)
fdm-core/src/cultivation.ts (1)

774-789: 🛠️ Refactor suggestion

Implementation of the isCultivationWithinTimeframe function needs refinement.

The function immediately returns false if !b_lu_start || !timeframe.start || !timeframe.end (line 779), which means it will always return false if either timeframe.start or timeframe.end is missing, even if filtering could still be done with the available date. This doesn't match how timeframe filtering is handled elsewhere in the code.

Consider refining the implementation to handle cases where only one of the timeframe boundaries is defined:

export function isCultivationWithinTimeframe(
    b_lu_start: Date | null,
    b_lu_end: Date | null,
    timeframe: Timeframe,
): boolean {
-    if (!b_lu_start || !timeframe.start || !timeframe.end) return false
+    if (!b_lu_start) return false
+    // Handle cases where only start or end date is provided
+    if (!timeframe.start && !timeframe.end) return true

    if (b_lu_end) {
+        if (timeframe.start && timeframe.end) {
            return (
                (b_lu_start >= timeframe.start && b_lu_start <= timeframe.end) ||
                (b_lu_end >= timeframe.start && b_lu_end <= timeframe.end) ||
                (b_lu_start <= timeframe.start && b_lu_end >= timeframe.end)
            )
+        } else if (timeframe.start) {
+            return b_lu_end >= timeframe.start
+        } else if (timeframe.end) {
+            return b_lu_start <= timeframe.end
+        }
    }
-    return b_lu_start >= timeframe.start && b_lu_start <= timeframe.end
+    if (timeframe.start && timeframe.end) {
+        return b_lu_start >= timeframe.start && b_lu_start <= timeframe.end
+    } else if (timeframe.start) {
+        return b_lu_start >= timeframe.start
+    } else if (timeframe.end) {
+        return b_lu_start <= timeframe.end
+    }
+    return true
}
🧹 Nitpick comments (2)
.changeset/eager-nails-draw.md (1)

5-5: Grammar Suggestion: Add a Determiner for Clarity.
The changelog message reads "Add Kalender to sidebar." Consider adding the article "the" before "sidebar" for better clarity, e.g., "Add Kalender to the sidebar."

-Add `Kalender` to sidebar. This enables users to filter assets and actions based on the selected year or to show all of them.
+Add `Kalender` to the sidebar. This enables users to filter assets and actions based on the selected year or to show all of them.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: You might be missing the article “the” here.
Context: .../fdm-app": minor --- Add Kalender to sidebar. This enables users to filter assets an...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

fdm-core/src/cultivation.test.ts (1)

29-31: Added imports for database operations and timeframe type.

The imports for database operations from drizzle-orm, the schema types, and the Timeframe type have been correctly added. However, the schema import could use the import type syntax since it's only used for types.

Consider using import type syntax for the schema import since it's only used for types:

- import * as schema from "./db/schema"
+ import type * as schema from "./db/schema"
🧰 Tools
🪛 Biome (1.9.4)

[error] 31-31: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e82d4b and f48e88e.

📒 Files selected for processing (8)
  • .changeset/eager-nails-draw.md (1 hunks)
  • .changeset/salty-nights-buy.md (1 hunks)
  • fdm-app/app/routes/farm.create.$b_id_farm.$calendar.cultivations.$b_lu_catalogue.crop.harvest.$b_id_harvesting.tsx (3 hunks)
  • fdm-core/src/cultivation.test.ts (6 hunks)
  • fdm-core/src/cultivation.ts (13 hunks)
  • fdm-core/src/fertilizer.ts (4 hunks)
  • fdm-core/src/field.test.ts (2 hunks)
  • fdm-core/src/harvest.test.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • .changeset/salty-nights-buy.md
  • fdm-app/app/routes/farm.create.$b_id_farm.$calendar.cultivations.$b_lu_catalogue.crop.harvest.$b_id_harvesting.tsx
  • fdm-core/src/harvest.test.ts
🧰 Additional context used
🧠 Learnings (1)
fdm-core/src/cultivation.test.ts (1)
Learnt from: SvenVw
PR: SvenVw/fdm#87
File: fdm-core/src/farm.ts:22-25
Timestamp: 2025-03-12T14:05:51.527Z
Learning: In the FDM codebase, functions that insert/create data (like `addFarm`) intentionally use `principal_id: string` instead of `PrincipalId` to enforce that only a single principal ID can be used for creation operations, while read operations use the more flexible `PrincipalId` type which supports both single IDs and arrays of IDs.
🧬 Code Definitions (2)
fdm-core/src/cultivation.ts (1)
fdm-core/src/timeframe.d.ts (1) (1)
  • Timeframe (1:4)
fdm-core/src/fertilizer.ts (1)
fdm-core/src/db/schema.ts (1) (1)
  • fertilizerApplicationTypeSelect (173:174)
🪛 Biome (1.9.4)
fdm-core/src/cultivation.test.ts

[error] 31-31: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

🪛 LanguageTool
.changeset/eager-nails-draw.md

[uncategorized] ~5-~5: You might be missing the article “the” here.
Context: .../fdm-app": minor --- Add Kalender to sidebar. This enables users to filter assets an...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

🪛 GitHub Check: codecov/patch
fdm-core/src/cultivation.ts

[warning] 696-697: fdm-core/src/cultivation.ts#L696-L697
Added lines #L696 - L697 were not covered by tests

fdm-core/src/fertilizer.ts

[warning] 721-721: fdm-core/src/fertilizer.ts#L721
Added line #L721 was not covered by tests


[warning] 727-727: fdm-core/src/fertilizer.ts#L727
Added line #L727 was not covered by tests

🔇 Additional comments (23)
.changeset/eager-nails-draw.md (1)

1-3: Changeset Header and Version Bump Looks Good.
The header separators and version bump for "@svenvw/fdm-app": minor are correctly formatted.

fdm-core/src/fertilizer.ts (4)

1-1: Import of necessary types and functions for timeframe filtering.

The imports have been updated to include gte and lte from drizzle-orm for date comparisons and the Timeframe type from "./timeframe". These are appropriate additions for implementing date range filtering.

Also applies to: 13-13


667-668: Updated documentation for the new timeframe parameter.

The JSDoc comment has been appropriately updated to document the new optional timeframe parameter.


675-675: Added optional timeframe parameter to function signature.

The function signature has been updated to include an optional timeframe parameter of type Timeframe, which allows filtering fertilizer applications by date range.


712-730: Implemented conditional timeframe filtering for fertilizer applications.

The query has been enhanced with date range filtering logic that applies when a timeframe is provided. The implementation correctly handles:

  1. Filtering by b_id when no timeframe is provided
  2. Adding date range conditions using gte and lte when timeframe start/end dates are available
  3. Properly handling cases where only one of start or end date is provided

The static analysis indicates that lines 721 and 727 (the undefined checks) aren't covered by tests.

Consider adding test cases that specifically verify behavior when only start or only end date is provided in the timeframe to improve test coverage.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 721-721: fdm-core/src/fertilizer.ts#L721
Added line #L721 was not covered by tests


[warning] 727-727: fdm-core/src/fertilizer.ts#L727
Added line #L727 was not covered by tests

fdm-core/src/field.test.ts (5)

8-8: Added import for FdmType.

The import for FdmType is necessary for the type annotation in the new test cases.


82-109: Added comprehensive tests for the getFields function with proper setup.

The test setup includes creating a test environment with a dedicated FDM instance and farm, which is a good practice for isolated test cases.


110-171: Thoroughly validates field retrieval by farm ID.

This test case properly validates that multiple fields can be retrieved for a farm, ensuring the basic functionality works correctly before testing more complex scenarios.


173-180: Verifies proper permission handling.

This test correctly verifies that an error is thrown when an invalid principal ID is used, which is essential for security validation.


182-363: Comprehensive testing of timeframe-based field retrieval.

This test case is particularly thorough, covering multiple scenarios:

  1. Creating fields with different start and end dates
  2. Testing timeframes that include specific fields
  3. Testing with only start date specified
  4. Testing with only end date specified

The expected results are clearly defined and the assertions validate both the number of fields returned and their identity, which is excellent.

fdm-core/src/cultivation.test.ts (4)

5-7: Added imports for new helper functions.

The additional imports for the new helper functions (buildDateRangeCondition, buildDateRangeConditionEnding, and isCultivationWithinTimeframe) are correctly added.

Also applies to: 11-11


264-316: Added tests for retrieving cultivations within a timeframe.

This test case thoroughly validates that cultivations can be retrieved within a specified timeframe. It creates multiple cultivations with different start and end dates and tests various timeframe ranges to ensure proper filtering.


744-1046: Added comprehensive tests for cultivation plan with timeframe filtering.

These tests thoroughly cover:

  1. Error handling for non-existent farms
  2. Multiple cultivations and fields retrieval
  3. Cases where no fertilizer applications are present
  4. Various timeframe filtering scenarios including when timeframes include or exclude specific cultivations

The tests provide excellent coverage for the new timeframe filtering functionality in the cultivation plan feature.


1085-1318: Added unit tests for helper functions.

The tests for the helper functions (buildDateRangeCondition, buildDateRangeConditionEnding, and isCultivationWithinTimeframe) are comprehensive, covering:

  1. Various combinations of null/undefined dates
  2. Different date range scenarios
  3. Edge cases with dates at the boundaries of timeframes
  4. Cases with cultivations that span, fall within, or are outside timeframes

These tests ensure the helper functions work correctly under all expected scenarios.

fdm-core/src/cultivation.ts (9)

1-12: Added necessary imports for timeframe functionality.

The imports have been updated to include additional SQL operators for date comparison (gte, lte) and the Timeframe type. These are necessary for implementing the timeframe filtering functionality.

Also applies to: 25-25


382-383: Updated getCultivations function to support timeframe filtering.

The function signature and documentation have been appropriately updated to include an optional timeframe parameter, allowing for date-based filtering of cultivations.

Also applies to: 394-394


406-415: Implemented date range condition building for cultivation filtering.

The code creates appropriate date range conditions based on the provided timeframe, handling both starting dates and ending dates through dedicated helper functions.


445-447: Applied timeframe conditions to the database query.

The where clause has been correctly modified to combine the field ID condition with timeframe conditions, ensuring cultivations are filtered by both field and date range when a timeframe is provided.


470-470: Updated getCultivationPlan function to support timeframe filtering.

Similar to the getCultivations function, the getCultivationPlan function has been updated with an optional timeframe parameter and appropriate documentation.

Also applies to: 539-539


554-562: Added date range condition building for cultivation plan filtering.

The implementation mirrors the approach used in getCultivations, reusing the same helper functions for consistency.


672-672: Applied timeframe conditions to the cultivation plan query.

The timeframe clause has been correctly added to the database query's where condition.


688-698: Added additional timeframe check for individual cultivations.

The code includes a secondary check using isCultivationWithinTimeframe to verify each cultivation is within the specified timeframe. However, there's a code coverage issue reported for lines 696-697, which handle the case when a cultivation is outside the timeframe.

Consider adding a test case that specifically checks that cultivations outside the timeframe are excluded from the results to improve code coverage for this conditional branch.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 696-697: fdm-core/src/cultivation.ts#L696-L697
Added lines #L696 - L697 were not covered by tests


1046-1104: Helper functions for building date range conditions.

The implementation of buildDateRangeCondition and buildDateRangeConditionEnding looks solid. They correctly handle different combinations of start and end dates, returning appropriate SQL conditions or undefined when no dates are provided.

Comment thread fdm-app/app/lib/calendar.ts
Copy link
Copy Markdown
Collaborator

@gerardhros gerardhros left a comment

Choose a reason for hiding this comment

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

nice. Good to add some definitions related to state-year-caldender-timeframe in supporting documentation later.

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: 2

🧹 Nitpick comments (3)
fdm-core/src/soil.test.ts (2)

327-335: Consider using forEach instead of map for test validations.

The current code uses map() for validation operations but doesn't use the returned array. Since you're only iterating to perform assertions, forEach() would be more semantically appropriate.

-analyses1.map((analysis) => {
+analyses1.forEach((analysis) => {

Apply the same change to all similar instances in this test.

Also applies to: 348-356, 369-377, 390-395, 408-413


415-416: Add validation for the expected number of analyses in all test cases.

You're validating the count for the no-timeframe case, but not for the other test cases. Consider adding count validations for each timeframe scenario to verify not just that the returned records are within the date range, but also that the correct number of records is being returned.

// Example for the first timeframe
const analyses1 = await getSoilAnalyses(fdm, principal_id, b_id, timeframe1)
+expect(analyses1).toHaveLength(1) // April should only include one analysis
analyses1.forEach((analysis) => {
    // existing validations
})
fdm-app/app/components/custom/sidebar-app.tsx (1)

212-303: Well-implemented calendar selection UI.

The calendar selection UI is well-implemented with:

  1. Proper conditional rendering
  2. Clear visual indication of the selected calendar
  3. Smooth collapsible interaction
  4. URL path maintenance during navigation

One suggestion for improvement:

Consider extracting the regex pattern /\/(\d{4}|all)/ into a constant or utility function for better maintainability, especially if it's used elsewhere in the application:

+ // At the top of the file or in a separate utils file
+ const CALENDAR_PATH_REGEX = /\/(\d{4}|all)\//

  // Then in the component
  const newUrl = location.pathname.replace(
-     /\/(\d{4}|all)/,
+     CALENDAR_PATH_REGEX,
      `/${item}`
  )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01081b3 and 74802f2.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • fdm-app/app/components/custom/sidebar-app.tsx (6 hunks)
  • fdm-app/app/routes/farm.create.$b_id_farm.$calendar.atlas.tsx (4 hunks)
  • fdm-app/app/routes/farm.tsx (4 hunks)
  • fdm-app/package.json (2 hunks)
  • fdm-core/src/index.ts (1 hunks)
  • fdm-core/src/soil.test.ts (1 hunks)
  • fdm-core/src/soil.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • fdm-app/package.json
  • fdm-core/src/index.ts
  • fdm-app/app/routes/farm.create.$b_id_farm.$calendar.atlas.tsx
🧰 Additional context used
🪛 GitHub Actions: Tests
fdm-core/src/soil.test.ts

[error] 231-231: BaseError: Exception for getSoilAnalyses. Caused by: ReferenceError: sql is not defined


[error] 273-273: BaseError: Exception for getSoilAnalyses. Caused by: ReferenceError: sql is not defined


[error] 321-321: BaseError: Exception for getCurrentSoilData. Caused by: ReferenceError: sql is not defined


[error] 460-460: BaseError: Exception for getCurrentSoilData. Caused by: ReferenceError: sql is not defined

🪛 Biome (1.9.4)
fdm-core/src/soil.ts

[error] 15-15: Shouldn't redeclare 'getSoilAnalysisType'. Consider to delete it or rename it.

'getSoilAnalysisType' is defined here:

(lint/suspicious/noRedeclare)

🔇 Additional comments (13)
fdm-core/src/soil.ts (3)

241-242: Implementation of timeframe parameter looks good.

The function signature has been appropriately updated to include the optional timeframe parameter with proper JSDoc documentation.

Also applies to: 246-251


262-281: Well-structured filtering logic for timeframe parameter.

The implementation of the timeframe filtering logic is clean and handles all possible combinations of start and end dates correctly:

  • Both start and end dates provided
  • Only start date provided
  • Only end date provided
  • No timeframe provided

This approach allows for flexible date-range filtering of soil analyses.


303-303: Query correctly uses dynamically constructed whereClause.

The SQL query has been properly modified to use the dynamically constructed whereClause instead of the hardcoded field equality condition.

fdm-core/src/soil.test.ts (1)

277-417: Comprehensive test coverage for timeframe functionality.

The new test case thoroughly covers all key scenarios for the timeframe parameter:

  • Filtering for a specific month (April 2023)
  • Date range spanning multiple months (April-May 2023)
  • Complete date range covering all test data (March-June 2023)
  • Open-ended ranges (from May 2023 onwards)
  • Ranges with only end date (up to April 2023)
  • Default behavior with no timeframe specified

For each scenario, the test correctly verifies that returned analyses have sampling dates within the specified timeframe.

🧰 Tools
🪛 GitHub Actions: Tests

[error] 321-321: BaseError: Exception for getCurrentSoilData. Caused by: ReferenceError: sql is not defined

fdm-app/app/routes/farm.tsx (5)

17-18: Good implementation of state management with Zustand stores.

The addition of these imports aligns with the PR objective to remove React context in favor of Zustand stores for state management. This is a good architectural choice for better maintainability and scalability.


72-72: Good refactoring from local state to centralized store.

Moving from local state to Zustand store for farm ID management is a positive architectural change that improves state consistency across components.


76-76: Correctly added dependency to useEffect.

The addition of setFarmId to the dependency array follows React's best practices for hooks.


93-101: Solid implementation of calendar state extraction and management.

This implementation effectively extracts calendar data from route parameters and synchronizes it with the Zustand store. The code pattern is consistent with the farm ID implementation, making the codebase more predictable.


114-124: Clean component structure after removing context provider.

The component structure is clean and properly nested. The removal of the FarmContext provider successfully completes the migration to Zustand stores.

fdm-app/app/components/custom/sidebar-app.tsx (4)

89-89: Effective use of store selectors.

Using the selector pattern from Zustand to extract only needed state is an efficient approach that prevents unnecessary re-renders.


91-94: Well-structured calendar state management setup.

The calendar state implementation is clear and follows best practices by:

  1. Using store selectors for global state
  2. Using local state only for UI concerns (collapsible state)
  3. Separating the calendar options retrieval

This creates a clean separation of concerns.


103-130: Robust conditional URL generation.

The conditional URL generation based on application state (create wizard, farm ID, calendar) ensures consistent navigation. The pattern of declaring variables first and then setting them based on conditions improves readability.


244-248:

Details

❓ Verification inconclusive

Verify URL replacement logic for edge cases.

The URL replacement logic assumes that the calendar parameter is always present in the URL in a specific format.


🏁 Script executed:

#!/bin/bash
# Check for potential edge cases in URL patterns

# Look for all routes that might include calendar parameter
rg -A 2 "path.*:calendar" --glob "*.{ts,tsx}"

# Check how calendar parameters are extracted from URLs
rg -A 2 "params\.calendar" --glob "*.{ts,tsx}"

# Look for URL construction with calendar parameter
rg "\/\$\{.*calendar.*\}\/" --glob "*.{ts,tsx}"

Length of output: 613


Attention: Verify Robustness of URL Replacement Logic

Please ensure that the replacement in fdm-app/app/components/custom/sidebar-app.tsx (lines 244-248) correctly handles all expected and unexpected URL formats. In particular:

  • Confirm that the regex /\/(\d{4}|all)/ reliably matches the intended calendar segment. If the pathname lacks a matching segment (e.g., when the calendar parameter is missing or formatted differently), verify that the new URL remains valid.
  • Verify that only the desired occurrence is replaced, even if similar patterns appear elsewhere in the URL.
  • Consider adding conditional logic or tests to gracefully handle cases where the expected calendar segment is absent.

Comment thread fdm-core/src/soil.ts Outdated
Comment thread fdm-core/src/soil.ts
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

🧹 Nitpick comments (1)
fdm-core/src/cultivation.test.ts (1)

29-31: Ensure types are imported properly for schema.

The schema import should be marked as a type import to optimize the code.

-import * as schema from "./db/schema"
-import { Timeframe } from "./timeframe"
+import type * as schema from "./db/schema"
+import type { Timeframe } from "./timeframe"
🧰 Tools
🪛 Biome (1.9.4)

[error] 31-31: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc510e1 and 27f5b4e.

⛔ Files ignored due to path filters (2)
  • fdm-core/src/db/migrations/meta/_journal.json is excluded by !fdm-core/src/db/migrations/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • fdm-app/app/components/custom/farm/farm-header.tsx (6 hunks)
  • fdm-app/app/components/custom/sidebar-app.tsx (6 hunks)
  • fdm-app/app/routes/farm.create._index.tsx (1 hunks)
  • fdm-app/package.json (2 hunks)
  • fdm-core/src/cultivation.test.ts (6 hunks)
  • fdm-core/src/fertilizer.test.ts (2 hunks)
  • fdm-core/src/fertilizer.ts (4 hunks)
  • fdm-core/src/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • fdm-core/src/index.ts
  • fdm-app/package.json
  • fdm-app/app/routes/farm.create._index.tsx
  • fdm-app/app/components/custom/sidebar-app.tsx
  • fdm-app/app/components/custom/farm/farm-header.tsx
🧰 Additional context used
🧬 Code Definitions (1)
fdm-core/src/fertilizer.test.ts (1)
fdm-core/src/fertilizer.ts (2)
  • addFertilizerApplication (625-684)
  • getFertilizerApplications (846-912)
🪛 Biome (1.9.4)
fdm-core/src/cultivation.test.ts

[error] 31-31: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

fdm-core/src/fertilizer.test.ts

[error] 34-34: Shouldn't redeclare 'disableFertilizerCatalogue'. Consider to delete it or rename it.

'disableFertilizerCatalogue' is defined here:

(lint/suspicious/noRedeclare)


[error] 35-35: Shouldn't redeclare 'enableFertilizerCatalogue'. Consider to delete it or rename it.

'enableFertilizerCatalogue' is defined here:

(lint/suspicious/noRedeclare)

🪛 GitHub Check: codecov/patch
fdm-core/src/fertilizer.ts

[warning] 896-896: fdm-core/src/fertilizer.ts#L896
Added line #L896 was not covered by tests


[warning] 902-902: fdm-core/src/fertilizer.ts#L902
Added line #L902 was not covered by tests

🔇 Additional comments (15)
fdm-core/src/fertilizer.test.ts (4)

943-990: Well-structured test for timeframe filtering.

This test effectively validates the new timeframe filtering functionality for fertilizer applications. The implementation correctly tests the filtering logic for date ranges and verifies that applications are within the specified timeframe.


992-1010: Good edge case handling.

This test properly verifies that an empty array is returned when no fertilizer applications exist within the provided timeframe, covering an important edge case.


1012-1027: Appropriate error handling test for non-existing fields.

The test correctly verifies permission error handling when attempting to add a fertilizer application to a non-existent field.


1029-1042: Good validation for non-existing fertilizer error handling.

This test effectively verifies the error handling when attempting to use a non-existent fertilizer, ensuring the expected error message is thrown.

fdm-core/src/fertilizer.ts (4)

1-1: Clean import addition for date filtering operators.

The addition of gte and lte operators from drizzle-orm is appropriate for implementing the timeframe filtering functionality.


13-13: Appropriate type import for the new timeframe parameter.

The import of the Timeframe type aligns with the function signature update.


850-850: Clear function signature update for timeframe filtering.

The addition of the optional timeframe parameter to the function signature properly enables date-based filtering of fertilizer applications.


887-905:

Details

❓ Verification inconclusive

Well-implemented conditional timeframe filtering.

The modified where clause elegantly handles the presence or absence of the timeframe parameter and its start/end dates. The code correctly applies date filtering when a timeframe is provided and falls back to the original filtering when it's not.

Note: Static analysis indicates lines 896 and 902 may not be covered by tests. Consider adding test cases for edge cases where either start or end date is undefined.


🏁 Script executed:

#!/bin/bash
# Check test coverage for the timeframe filtering implementation

# Check for test coverage of partial timeframes (only start or only end)
echo "Looking for test cases that cover partial timeframes..."
rg -A 3 -B 3 "timeframe.*start.*undefined|timeframe.*end.*undefined" ./fdm-core/src/fertilizer.test.ts

Length of output: 225


Subject: Verify Test Coverage for Partial Timeframe Cases

The conditional timeframe filtering is well implemented and effectively handles both scenarios of a provided timeframe and its absence. However, our initial search for tests in fdm-core/src/fertilizer.test.ts did not reveal explicit cases covering scenarios where only the start or only the end date is defined (notably around lines 896 and 902). Please verify manually—or consider adding new tests—to ensure that these edge cases are adequately covered.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 896-896: fdm-core/src/fertilizer.ts#L896
Added line #L896 was not covered by tests


[warning] 902-902: fdm-core/src/fertilizer.ts#L902
Added line #L902 was not covered by tests

fdm-core/src/cultivation.test.ts (7)

5-11: Well-organized imports for the new helper functions.

The imports for the new date range condition builders and timeframe validation function are appropriately added.


264-316: Comprehensive test for timeframe-filtered cultivations.

This test thoroughly verifies the functionality of retrieving cultivations within specific timeframes. The different test cases cover various scenarios with overlapping timeframes and check sorting order.


752-887: Thorough testing of cultivation plan with multiple entities.

These tests thoroughly validate the cultivation plan functionality with multiple fields and cultivation types. The tests ensure that fertilizer applications are properly associated with their respective fields and cultivations.


889-1046: Complete testing of timeframe filtering for cultivation plans.

The tests comprehensively cover different timeframe scenarios for cultivation plans, including:

  1. Timeframes that include only some cultivations
  2. Timeframes that include all cultivations
  3. Timeframes that exclude all cultivations

This ensures the timeframe filtering is robust across various scenarios.


1085-1120: Well-structured unit tests for buildDateRangeCondition.

These tests thoroughly validate the behavior of the buildDateRangeCondition function with different combinations of inputs:

  1. Both parameters null/undefined
  2. Only start date provided
  3. Only end date provided
  4. Both dates provided

This ensures the function behaves as expected in all scenarios.


1122-1183: Comprehensive tests for buildDateRangeConditionEnding.

The tests for buildDateRangeConditionEnding are thorough and cover all edge cases and combinations of input parameters, validating the complex condition building logic that handles cultivation ending dates.


1185-1318: Extensive testing of isCultivationWithinTimeframe.

This test suite is comprehensive, covering a wide range of scenarios for the timeframe validation function, including:

  1. Cultivations completely within timeframe
  2. Cultivations spanning timeframe boundaries
  3. Cultivations outside timeframe
  4. Cultivations with missing dates
  5. Cultivations with single-day durations

The thoroughness ensures the function works as expected in all scenarios.

Comment thread fdm-core/src/fertilizer.test.ts Outdated
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

🧹 Nitpick comments (3)
fdm-core/src/soil.ts (1)

347-356: Added timeframe filtering for getCurrentSoilData.

Good implementation of timeframe filtering specifically for the "end" date to filter out future analyses. The comment on line 347 has a small typo ("analyes" instead of "analyses").

-        // Filter out "future" analyes
+        // Filter out "future" analyses
fdm-core/src/fertilizer.test.ts (1)

938-986: Great test coverage for timeframe-based retrieval.
This ensures that multiple fertilizer applications in different date ranges are accurately filtered.

Consider adding coverage or clarifications around potential timezone differences, ensuring date comparisons remain consistent in various environments.

fdm-core/src/cultivation.test.ts (1)

264-316: Timeframe-based cultivation test.
This test asserts ordering of returned cultivations. If the underlying query changes its default sort order, the test may fail.

Consider specifying the query’s order explicitly or allowing flexible order checks to avoid fragile tests.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 27f5b4e and b77f446.

📒 Files selected for processing (6)
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil._index.tsx (3 hunks)
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil.analysis.$a_id.tsx (1 hunks)
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil.analysis.new.tsx (0 hunks)
  • fdm-core/src/cultivation.test.ts (6 hunks)
  • fdm-core/src/fertilizer.test.ts (1 hunks)
  • fdm-core/src/soil.ts (9 hunks)
💤 Files with no reviewable changes (1)
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil.analysis.new.tsx
✅ Files skipped from review due to trivial changes (1)
  • fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil.analysis.$a_id.tsx
🧰 Additional context used
🧬 Code Definitions (4)
fdm-core/src/fertilizer.test.ts (1)
fdm-core/src/fertilizer.ts (2)
  • addFertilizerApplication (625-684)
  • getFertilizerApplications (846-912)
fdm-core/src/cultivation.test.ts (2)
fdm-core/src/cultivation.ts (6)
  • addCultivation (152-301)
  • getCultivations (390-457)
  • getCultivationPlan (535-772)
  • buildDateRangeCondition (1047-1068)
  • buildDateRangeConditionEnding (1071-1104)
  • isCultivationWithinTimeframe (774-789)
fdm-core/src/db/schema.ts (1)
  • cultivations (259-270)
fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil._index.tsx (1)
fdm-core/src/soil.ts (1)
  • getCurrentSoilData (331-409)
fdm-core/src/soil.ts (1)
fdm-core/src/index.ts (1)
  • Timeframe (81-81)
🪛 GitHub Check: core (20)
fdm-core/src/cultivation.test.ts

[failure] 1167-1167: src/cultivation.test.ts > buildDateRangeConditionEnding > should return and condition with or conditions when both dateStart and dateEnd are provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1167:25


[failure] 1151-1151: src/cultivation.test.ts > buildDateRangeConditionEnding > should return or condition with lte when only dateEnd is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1151:21


[failure] 1137-1137: src/cultivation.test.ts > buildDateRangeConditionEnding > should return or condition with gte when only dateStart is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1137:21


[failure] 1115-1115: src/cultivation.test.ts > buildDateRangeCondition > should return and condition when both dateStart and dateEnd are provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1115:21


[failure] 1105-1105: src/cultivation.test.ts > buildDateRangeCondition > should return lte condition when only dateEnd is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1105:17


[failure] 1097-1097: src/cultivation.test.ts > buildDateRangeCondition > should return gte condition when only dateStart is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1097:17

🪛 GitHub Actions: Tests
fdm-core/src/cultivation.test.ts

[error] 97-97: ReferenceError: schema is not defined


[error] 105-105: ReferenceError: schema is not defined


[error] 115-115: ReferenceError: schema is not defined


[error] 137-137: ReferenceError: schema is not defined


[error] 151-151: ReferenceError: schema is not defined


[error] 167-167: ReferenceError: schema is not defined

🔇 Additional comments (26)
fdm-app/app/routes/farm.$b_id_farm.$calendar.field.$b_id.soil._index.tsx (5)

7-7: New import for timeframe functionality.

The added import for getTimeframe from the calendar library supports the new timeframe filtering feature being implemented across the application.


15-15: Added Timeframe type import.

Good addition of the Timeframe type import, which is needed for proper typing with the updated function signatures.


68-70: Added timeframe extraction from URL parameters.

The code now extracts timeframe data from URL parameters, enabling filtering of soil data by date ranges. This aligns with the PR objective of adding calendar functionality.


81-86: Passing timeframe to getSoilAnalyses function.

The timeframe parameter is now correctly passed to the getSoilAnalyses function, allowing filtering of soil analyses by date range.


89-94: Passing timeframe to getCurrentSoilData function.

The timeframe parameter is now correctly passed to the getCurrentSoilData function, ensuring consistency with the timeframe filtering implementation across the application.

fdm-core/src/soil.ts (7)

1-1: Added missing SQL template tag import.

The sql template tag was previously missing but is used on line 377 for custom SQL ordering. This fixes the issue previously reported in a code review.


8-8: Added Timeframe type import.

Good addition of the Timeframe type import from the timeframe module, which is necessary for the updated function signatures.


240-240: Updated getSoilAnalyses function signature with timeframe parameter.

The function signature and JSDoc have been updated to include an optional timeframe parameter, aligning with the PR objective to add calendar filtering functionality.

Also applies to: 249-249


261-280: Added comprehensive timeframe filtering logic.

Good implementation of conditional timeframe filtering. The code handles all possible combinations of start and end dates:

  1. Both start and end dates (date range)
  2. Only start date (from a specific date)
  3. Only end date (until a specific date)
  4. No timeframe (all dates)

This provides flexible filtering options for the application's calendar feature.


302-302: Updated where clause to use dynamic timeframe filtering.

The query now uses the dynamically constructed whereClause based on the timeframe parameters instead of the static field ID filter.


324-324: Updated getCurrentSoilData function signature with timeframe parameter.

The function signature and JSDoc have been updated to include an optional timeframe parameter, consistent with the overall approach to implement calendar filtering.

Also applies to: 335-335


374-374: Updated where clause to use dynamic timeframe filtering.

The query now uses the dynamically constructed whereClause based on the timeframe parameters, consistent with the implementation in getSoilAnalyses.

fdm-core/src/fertilizer.test.ts (3)

988-1006: Looks good for empty results validation.
This correctly verifies that no applications are returned outside the given timeframe.


1008-1023: Confirm the expected error message for a non-existing field.
The test expects a permission error, but addFertilizerApplication might throw a different error (Field with b_id ... does not exist). Ensure this mismatch is intentional or update accordingly.


1025-1038: Accurate check for non-existing fertilizer.
This test aligns with the function’s behavior of throwing an "Exception for addFertilizerApplication" when the fertilizer does not exist.

fdm-core/src/cultivation.test.ts (11)

5-6: No issues with these new imports.
These function imports appear consistent with the tests below.


11-11: Importing 'isCultivationWithinTimeframe' is fine.
The corresponding tests thoroughly validate this function’s logic.


744-750: Accurate permission check for non-existing farm.
This test properly expects a denial when attempting to access a non-existent farm.


752-863: Comprehensive multi-field plan coverage.
This test thoroughly ensures that multiple cultivations and fertilizer applications across multiple fields are retrieved correctly.


865-887: Correctly handles zero fertilizer applications.
Verifies that the plan includes cultivations even when no fertilizers are present.


889-946: Valid timeframe filtration in cultivation plan.
Checks that 'Corn' (outside timeframe) is excluded, while 'Wheat' is included.


945-999: Timeframe includes all cultivations.
Ensures that multiple cultivations are retrieved when the timeframe covers their entire range.


1001-1046: Empty plan test for out-of-range timeframe.
Properly confirms that cultivations are excluded if they fall outside the specified timeframe.


1084-1120: Reference to 'schema' at runtime triggers a pipeline failure.
Same root cause as in the import statements above.

🧰 Tools
🪛 GitHub Check: core (20)

[failure] 1115-1115: src/cultivation.test.ts > buildDateRangeCondition > should return and condition when both dateStart and dateEnd are provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1115:21


[failure] 1105-1105: src/cultivation.test.ts > buildDateRangeCondition > should return lte condition when only dateEnd is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1105:17


[failure] 1097-1097: src/cultivation.test.ts > buildDateRangeCondition > should return gte condition when only dateStart is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1097:17


1122-1183: 'schema' usage again encountered at runtime.
Same issue with type-only import.

🧰 Tools
🪛 GitHub Check: core (20)

[failure] 1167-1167: src/cultivation.test.ts > buildDateRangeConditionEnding > should return and condition with or conditions when both dateStart and dateEnd are provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1167:25


[failure] 1151-1151: src/cultivation.test.ts > buildDateRangeConditionEnding > should return or condition with lte when only dateEnd is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1151:21


[failure] 1137-1137: src/cultivation.test.ts > buildDateRangeConditionEnding > should return or condition with gte when only dateStart is provided
ReferenceError: schema is not defined
❯ src/cultivation.test.ts:1137:21


1185-1318: Extensive edge-case coverage for 'isCultivationWithinTimeframe'.
These tests thoroughly validate start/end boundary conditions.

Comment thread fdm-core/src/cultivation.test.ts
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.

Add seasons to fdm

2 participants