Skip to content

Enhance Fertilizer System: Catalog, UI, and Test Updates#111

Merged
SvenVw merged 58 commits into
developmentfrom
add-custom-fertilizer
Apr 1, 2025
Merged

Enhance Fertilizer System: Catalog, UI, and Test Updates#111
SvenVw merged 58 commits into
developmentfrom
add-custom-fertilizer

Conversation

@SvenVw
Copy link
Copy Markdown
Collaborator

@SvenVw SvenVw commented Mar 26, 2025

Summary by CodeRabbit

  • New Features

    • Introduced dedicated pages for viewing, adding, and updating fertilizers—providing a streamlined interface for fertilizer management.
    • Enhanced farm navigation by integrating a dropdown option for selecting custom fertilizers.
    • Rolled out an interactive table for fertilizer data with sorting, filtering, and detailed views.
    • Added functionality for managing custom fertilizers tailored to specific farms.
    • Implemented a validation schema for fertilizer forms to ensure data integrity.
    • Added a new page to display a list of fertilizers available on the farm.
    • Introduced a new page for adding new fertilizer entries for a farm.
    • Enhanced the FarmHeader component with fertilizer selection options.
    • Introduced new methods for hashing fertilizers and cultivation items to improve data integrity.
    • Enhanced the output of fertilizer retrieval functions to include additional details.
  • Improvements

    • Upgraded underlying dependencies and synchronization processes to boost performance and data integrity.
    • Updated the fertilizer management functions to include new parameters for better context and validation.
    • Modified the structure of fertilizer data to allow for more flexible input options.
    • Enforced non-null constraints on critical fields in the database schema to enhance data integrity.
    • Corrected a typographical error in the variable naming within the database schema.

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

changeset-bot Bot commented Mar 26, 2025

🦋 Changeset detected

Latest commit: 5a3d4b5

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

This PR includes changesets to release 4 packages
Name Type
@svenvw/fdm-core Minor
@svenvw/fdm-data Minor
@svenvw/fdm-app 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 26, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces multiple enhancements across the fertilizer management system. It updates several packages with minor version bumps, adds new functions for adding and updating fertilizers in the catalogue (including custom fertilizers), and modifies data retrieval and hashing logic. UI components and forms have been extended to support fertilizer selection and editing, while routes and loaders now handle new fertilizer flows. Additionally, the test suites for catalogue synchronization and fertilizer operations have been refined, and a new dependency for advanced table functionality has been added.

Changes

Files Grouped Change Summary
.changeset/bright-buckets-rush.md, .changeset/red-oranges-drop.md, .changeset/light-rockets-fly.md Minor version updates for @svenvw/fdm-core and @svenvw/fdm-app; updates include function output enhancements and enabling custom fertilizer catalogues.
.changeset/cute-tires-type.md, .changeset/forty-parts-bet.md, .changeset/vast-lies-go.md New pages introduced for displaying fertilizer lists and details with minor package updates for @svenvw/fdm-app.
.changeset/dirty-pumas-cry.md, .changeset/eleven-dancers-brush.md Added new hashing functions (hashFertilizer and hashCultivation) plus version updates for @svenvw/fdm-data.
.changeset/funny-dancers-rush.md Introduced the new function updateFertilizerFromCatalogue for modifying custom fertilizer details.
fdm-app/** (components, routes, and types in farm and fertilizer modules) Enhanced UI components and forms (e.g., FarmHeader, DataTableColumnHeader, FertilizerForm, schema, and table) to support fertilizer selection, editing, and catalogue integration; new routes and actions allow both adding and updating fertilizer entries.
fdm-calculator/src/doses/get-dose-field.test.ts Modified test logic to derive p_id_catalogue using addFertilizerToCatalogue instead of random generation.
fdm-core/** (catalogues, fertilizer functions, tests, and db schema) Modularized catalogue synchronization (via syncFertilizerCatalogue and syncCultivationCatalogue), revised addFertilizerToCatalogue to include user and farm identifiers, introduced updateFertilizerFromCatalogue, and updated tests and schema constraints.
fdm-data/** (cultivations and fertilizers modules) Updated hashing logic by introducing dedicated hash functions (hashFertilizer and hashCultivation), adjusted interface properties to be optional, and removed dependency on previous hashing libraries.
fdm-app/package.json Added new dependency "@tanstack/react-table": "^8.21.2" for enhanced data table functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI as FertilizerForm
    participant Route as FertilizerAction
    participant Service as addFertilizerToCatalogue
    participant DB

    User->>UI: Fill and submit new fertilizer data
    UI->>Route: POST form data
    Route->>Service: Invoke addFertilizerToCatalogue(principal_id, b_id_farm, properties)
    Service->>Service: Compute hash (via hashFertilizer)
    Service->>DB: Insert new fertilizer record
    DB-->>Service: Return new fertilizer ID
    Service-->>Route: Forward fertilizer ID
    Route-->>UI: Send success response
    UI->>User: Display updated catalogue
Loading
sequenceDiagram
    participant User
    participant UI as FertilizerUpdateForm
    participant Route as UpdateAction
    participant Service as updateFertilizerFromCatalogue
    participant DB

    User->>UI: Submit updated fertilizer details
    UI->>Route: POST updated data
    Route->>Service: Invoke updateFertilizerFromCatalogue(principal_id, b_id_farm, p_id_catalogue, updatedProperties)
    Service->>Service: Generate new hash (via hashFertilizer)
    Service->>DB: Update fertilizer record
    DB-->>Service: Confirm update
    Service-->>Route: Return success status
    Route-->>UI: Deliver updated info
    UI->>User: Show updated fertilizer details
Loading

Possibly related PRs

  • Add fertilizer application #16: The changes in the main PR, which involve the adaptation of the addFertilizerToCatalogue function to include custom fertilizers, are related to the retrieved PR that introduces the FertilizerApplicationsForm, which also deals with fertilizer management and application processes. Both PRs modify functionalities related to fertilizers, indicating a direct connection at the code level.
  • Add field management and soil analysis features #30: The changes in the main PR, which involve the adaptation of the addFertilizerToCatalogue function to include custom fertilizers, are related to the retrieved PR, which also focuses on enhancements in the management of fertilizers, including the addition of soil analysis features that may interact with fertilizer management. Both PRs involve modifications to the handling of fertilizers within the application.
  • Update farm management routing and data model structure #45: The changes in the main PR, which involve the adaptation of the addFertilizerToCatalogue function to include custom fertilizers, are related to the retrieved PR as both involve modifications to the farm management system, specifically in how fertilizers are handled within the context of farm data management. The retrieved PR introduces a new function getFarms and updates the data model structure, which is directly relevant to the changes made in the main PR regarding fertilizer management.

Poem

I'm a little rabbit with code to share,
Hopping through functions with flair in the air.
Fertilizers bloom in fields so bright,
Custom updates make the system just right.
With every new hash and a table so neat,
I dance and twitch – coding is a treat!
🐇🌱 Happy updates to all, so clever and sweet!


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

@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 26, 2025

Codecov Report

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

Project coverage is 92.06%. Comparing base (b380de2) to head (5a3d4b5).
Report is 59 commits behind head on development.

Files with missing lines Patch % Lines
fdm-core/src/catalogues.ts 97.56% 2 Missing ⚠️
fdm-data/src/index.ts 0.00% 2 Missing ⚠️
Additional details and impacted files
@@               Coverage Diff               @@
##           development     #111      +/-   ##
===============================================
+ Coverage        91.83%   92.06%   +0.23%     
===============================================
  Files               40       43       +3     
  Lines             4299     4475     +176     
  Branches           422      440      +18     
===============================================
+ Hits              3948     4120     +172     
- Misses             350      354       +4     
  Partials             1        1              
Flag Coverage Δ
fdm-calculator 92.68% <ø> (ø)
fdm-core 91.95% <98.99%> (+0.20%) ⬆️
fdm-data 94.64% <96.92%> (+0.47%) ⬆️

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 and others added 2 commits March 31, 2025 13:07
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Sven Verweij <37927107+SvenVw@users.noreply.github.com>
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-core/src/fertilizer.ts (1)

453-458: Add farm ID to error context for better debugging.

The error context should include the farm ID to make debugging easier in case of failures.

        throw handleError(err, "Exception for updateFertilizerFromCatalogue", {
            p_id_catalogue,
+           b_id_farm,
            properties,
        })
🧰 Tools
🪛 GitHub Actions: Tests

[warning] 453-453: @rollup/plugin-typescript TS1128: Declaration or statement expected.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 942c211 and 10f34a3.

📒 Files selected for processing (1)
  • fdm-core/src/fertilizer.ts (9 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
fdm-core/src/fertilizer.ts (4)
fdm-core/src/authorization.d.ts (1)
  • PrincipalId (21-23)
fdm-core/src/db/schema.ts (2)
  • farmsTypeInsert (32-32)
  • fertilizersCatalogueTypeInsert (239-240)
fdm-core/src/authorization.ts (1)
  • checkPermission (155-239)
fdm-core/src/error.ts (1)
  • handleError (15-31)
🪛 Biome (1.9.4)
fdm-core/src/fertilizer.ts

[error] 399-400: Expected a property, or a signature but instead found '-'.

Expected a property, or a signature here.

(parse)


[error] 400-400: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 411-459: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.

(lint/complexity/noUselessLoneBlockStatements)

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

[warning] 400-400: @rollup/plugin-typescript TS1131: Property or signature expected.


[warning] 400-400: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 401-401: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 405-405: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 406-406: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 410-410: @rollup/plugin-typescript TS1128: Declaration or statement expected.


[warning] 410-410: @rollup/plugin-typescript TS1109: Expression expected.


[warning] 411-411: @rollup/plugin-typescript TS1109: Expression expected.


[warning] 412-412: @rollup/plugin-typescript TS1005: ':' expected.


[warning] 413-413: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 415-415: @rollup/plugin-typescript TS1003: Identifier expected.


[warning] 415-415: @rollup/plugin-typescript TS1138: Parameter declaration expected.


[warning] 416-416: @rollup/plugin-typescript TS1003: Identifier expected.


[warning] 416-416: @rollup/plugin-typescript TS1138: Parameter declaration expected.


[warning] 419-419: @rollup/plugin-typescript TS1003: Identifier expected.


[warning] 419-419: @rollup/plugin-typescript TS1138: Parameter declaration expected.


[warning] 422-422: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 434-434: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 434-434: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 434-434: @rollup/plugin-typescript TS1136: Property assignment expected.


[warning] 453-453: @rollup/plugin-typescript TS1128: Declaration or statement expected.


[warning] 459-459: @rollup/plugin-typescript TS1128: Declaration or statement expected.


[error] 228-228: RollupError: Expression expected (Note that you need plugins to import files that are not JavaScript)

🔇 Additional comments (6)
fdm-core/src/fertilizer.ts (6)

1-1: Import changes look good.

Added imports for and from drizzle-orm and hashFertilizer from @svenvw/fdm-data match the functional changes in the code.

Also applies to: 13-13


75-85: Function signature updates are appropriate.

The updated JSDoc comments and function signature now properly include the principal_id and b_id_farm parameters, which align with the implementation changes that follow.

Also applies to: 86-90


138-161: Implementation of addFertilizerToCatalogue looks good.

The function now:

  1. Correctly performs permission checks
  2. Returns the ID of the added fertilizer
  3. Uses the hashFertilizer function to generate a hash for the fertilizer properties
  4. Sets the farm ID as the source

These changes improve security and traceability of fertilizer catalog entries.


264-266: New fields added to getFertilizer and getFertilizers.

Adding fields like p_id_catalogue, p_source, p_dm, p_density, and type information (p_type_manure, etc.) to the query results enables more detailed fertilizer information in the UI and client applications.

Also applies to: 273-285, 313-315, 493-495, 502-514, 542-544


399-401: Fixed parameter naming inconsistencies.

The naming inconsistencies in the properties list have been correctly addressed:

  1. pr_cr_rtp_cr_rt
  2. p_cl_rt referencing p_cl_crp_cl_rt referencing p_cl_rt

This fixes the syntax errors flagged by the static analysis tools.

Also applies to: 405-406

🧰 Tools
🪛 Biome (1.9.4)

[error] 399-400: Expected a property, or a signature but instead found '-'.

Expected a property, or a signature here.

(parse)


[error] 400-400: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)

🪛 GitHub Actions: Tests

[warning] 400-400: @rollup/plugin-typescript TS1131: Property or signature expected.


[warning] 400-400: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 401-401: @rollup/plugin-typescript TS1005: ';' expected.


344-459: New updateFertilizerFromCatalogue function looks good.

The function properly implements the update operation with appropriate permission checks, existence validation, and hash recalculation. The and condition in the where clause for both the select and update operations correctly ensures that users can only update fertilizers associated with their farm.

🧰 Tools
🪛 Biome (1.9.4)

[error] 399-400: Expected a property, or a signature but instead found '-'.

Expected a property, or a signature here.

(parse)


[error] 400-400: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 411-459: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.

(lint/complexity/noUselessLoneBlockStatements)

🪛 GitHub Actions: Tests

[warning] 400-400: @rollup/plugin-typescript TS1131: Property or signature expected.


[warning] 400-400: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 401-401: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 405-405: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 406-406: @rollup/plugin-typescript TS1005: ';' expected.


[warning] 410-410: @rollup/plugin-typescript TS1128: Declaration or statement expected.


[warning] 410-410: @rollup/plugin-typescript TS1109: Expression expected.


[warning] 411-411: @rollup/plugin-typescript TS1109: Expression expected.


[warning] 412-412: @rollup/plugin-typescript TS1005: ':' expected.


[warning] 413-413: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 415-415: @rollup/plugin-typescript TS1003: Identifier expected.


[warning] 415-415: @rollup/plugin-typescript TS1138: Parameter declaration expected.


[warning] 416-416: @rollup/plugin-typescript TS1003: Identifier expected.


[warning] 416-416: @rollup/plugin-typescript TS1138: Parameter declaration expected.


[warning] 419-419: @rollup/plugin-typescript TS1003: Identifier expected.


[warning] 419-419: @rollup/plugin-typescript TS1138: Parameter declaration expected.


[warning] 422-422: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 434-434: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 434-434: @rollup/plugin-typescript TS1005: ',' expected.


[warning] 434-434: @rollup/plugin-typescript TS1136: Property assignment expected.


[warning] 453-453: @rollup/plugin-typescript TS1128: Declaration or statement expected.


[warning] 459-459: @rollup/plugin-typescript TS1128: Declaration or statement expected.

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 (2)
fdm-app/app/components/custom/fertilizer/columns.tsx (2)

32-35: Consider removing commented code

There's a commented-out column definition for the "p_id" field. If this is intentionally excluded from the UI, consider removing the commented code entirely to keep the codebase clean.

-    // {
-    //     accessorKey: "p_id",
-    //     header: "ID",
-    // },

64-98: Consider using a derived accessor for the Type column

The "Type" column uses "Type" as the accessorKey, but there's no corresponding property in the Fertilizer type. Consider using an accessor function to make this relationship more explicit:

    {
-        accessorKey: "Type",
+        id: "type",
+        accessorFn: (row) => ({
+            manure: row.p_type_manure,
+            compost: row.p_type_compost,
+            mineral: row.p_type_mineral
+        }),
        cell: ({ row }) => {
            const fertilizer = row.original

            return (
                <span className="flex items-center gap-2">
                    {fertilizer.p_type_manure ? (
                        <Badge
                            className="bg-amber-600 text-white hover:bg-amber-700"
                            variant="default"
                        >
                            Mest
                        </Badge>
                    ) : null}
                    {fertilizer.p_type_compost ? (
                        <Badge
                            className="bg-green-600 text-white hover:bg-green-700"
                            variant="default"
                        >
                            Compost
                        </Badge>
                    ) : null}
                    {fertilizer.p_type_mineral ? (
                        <Badge
                            className="bg-blue-600 text-white hover:bg-blue-700"
                            variant="default"
                        >
                            Kunstmest
                        </Badge>
                    ) : null}
                </span>
            )
        },
    },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 10f34a3 and 7ffafcf.

📒 Files selected for processing (1)
  • fdm-app/app/components/custom/fertilizer/columns.tsx (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
fdm-app/app/components/custom/fertilizer/columns.tsx (1)
fdm-app/app/components/custom/fertilizer/column-header.tsx (1)
  • DataTableColumnHeader (20-66)
🔇 Additional comments (3)
fdm-app/app/components/custom/fertilizer/columns.tsx (3)

1-11: Import section looks good

The imports are properly structured and include all necessary components. The NavLink is correctly imported from "react-router-dom", addressing the issue mentioned in a previous review.


13-29: Type definition is complete and well-structured

The Fertilizer type definition now includes all required properties mentioned in previous reviews. Properties are appropriately marked as optional with proper type definitions, ensuring type safety throughout the component.


99-117: Details column implementation is good

The "Details" column provides a good user experience with a tooltip and navigation link. The implementation is clean and follows best practices.

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

🔭 Outside diff range comments (1)
fdm-core/src/catalogues.test.ts (1)

664-719: ⚠️ Potential issue

Apply same fix to cultivation test.

The cultivation catalog test likely has the same issue as the fertilizer test. It selects a random item from the database rather than one that's guaranteed to be in the BRP catalog.

Modify the test using the same approach:

 it("should update cultivation catalogue", async () => {
     await syncCatalogues(fdm)
 
-    // Update a catalogue item
-    const item = await fdm
-        .select({
-            b_lu_catalogue: schema.cultivationsCatalogue.b_lu_catalogue,
-            hash: schema.cultivationsCatalogue.hash,
-        })
-        .from(schema.cultivationsCatalogue)
-        .where(isNotNull(schema.cultivationsCatalogue.hash))
-        .limit(1)
-    expect(item[0].b_lu_catalogue).toBeDefined()
+    // Start with a cultivation from the BRP catalogue
+    const brpCatalogue = await getCultivationCatalogue("brp")
+    const originalCatalogItem = brpCatalogue[0] // Use the first item
+    expect(originalCatalogItem).toBeDefined()
+    expect(originalCatalogItem.b_lu_catalogue).toBeDefined()
+
+    // Find this item in the database
+    const item = await fdm
+        .select({
+            b_lu_catalogue: schema.cultivationsCatalogue.b_lu_catalogue,
+            hash: schema.cultivationsCatalogue.hash,
+        })
+        .from(schema.cultivationsCatalogue)
+        .where(eq(schema.cultivationsCatalogue.b_lu_catalogue, originalCatalogItem.b_lu_catalogue))
+        .limit(1)
+    expect(item[0].b_lu_catalogue).toBeDefined()
🧹 Nitpick comments (6)
fdm-core/src/catalogues.ts (1)

377-422: Consider extracting common catalogue sync logic.

Both syncFertilizerCatalogue and syncCultivationCatalogue share very similar logic structures. Consider extracting the common pattern into a higher-order function to reduce duplication.

Here's a suggested implementation:

async function syncGenericCatalogue<T, K extends keyof T>(
    fdm: FdmType,
    getCatalogue: () => Promise<T[]>,
    hashItem: (item: T) => Promise<string>,
    table: any,
    idField: K,
    errorMessage: string
) {
    const catalogue = await getCatalogue();
    await fdm.transaction(async (tx) => {
        try {
            for (const item of catalogue) {
                const hash = await hashItem(item);
                const existing = await tx
                    .select({ hash: table.hash })
                    .from(table)
                    .where(eq(table[idField as string], item[idField]))
                    .limit(1);
                
                if (existing.length === 0) {
                    await tx.insert(table).values({
                        ...item,
                        hash: hash,
                    });
                } else if (
                    existing[0].hash === null ||
                    existing[0].hash === undefined ||
                    existing[0].hash !== hash
                ) {
                    await tx
                        .update(table)
                        .set({ hash: hash })
                        .where(eq(table[idField as string], item[idField]));
                }
            }
        } catch (error) {
            throw handleError(error, errorMessage);
        }
    });
}

// Usage:
async function syncFertilizerCatalogue(fdm: FdmType) {
    await syncGenericCatalogue(
        fdm,
        () => getFertilizersCatalogue("srm"),
        hashFertilizer,
        schema.fertilizersCatalogue,
        'p_id_catalogue',
        "Exception for syncFertilizerCatalogue"
    );
}

Also applies to: 424-470

fdm-data/src/cultivations/index.ts (1)

4-22: Update JSDoc to reflect async nature.

The JSDoc comments should be updated to reflect that this function is now asynchronous and returns a Promise.

Update the JSDoc:

 * @returns An array of `CatalogueCultivationItem` objects representing the
 *          requested cultivation catalogue.
+* @returns A Promise that resolves to an array of `CatalogueCultivationItem` objects.
 * @throws {Error} Throws an error if the provided `catalogueName` is not
 *                 recognized or supported.
 *
 *
 * @example
 * ```typescript
-* const brpCatalogue = getCultivationCatalogue("brp");
+* const brpCatalogue = await getCultivationCatalogue("brp");
 * console.log(brpCatalogue);
 * ```
fdm-data/src/fertilizers/index.ts (1)

4-22: Update JSDoc to reflect async nature.

The JSDoc comments should be updated to reflect that this function is now asynchronous and returns a Promise.

Update the JSDoc:

 * @returns An array of `CatalogueFertilizerItem` objects representing the
 *          requested fertilizer catalogue.
+* @returns A Promise that resolves to an array of `CatalogueFertilizerItem` objects.
 * @throws {Error} Throws an error if the provided `catalogueName` is not
 *                 recognized or supported.
 *
 *
 * @example
 * ```typescript
-* const srmCatalogue = getFertilizersCatalogue("srm");
+* const srmCatalogue = await getFertilizersCatalogue("srm");
 * console.log(srmCatalogue);
 * ```
fdm-data/src/fertilizers/hash.test.ts (1)

65-172: Comprehensive test coverage, but could be refactored

The test coverage is thorough, successfully verifying that:

  • Different fertilizer items produce different hashes
  • Identical items yield the same hash
  • Changes to boolean, numerical, and string values result in different hashes

However, there's significant repetition of large fertilizer objects across tests.

Consider using a factory function to reduce repetition:

+ function createTestFertilizer(overrides = {}): CatalogueFertilizerItem {
+   return {
+     p_id_catalogue: "test-id-1",
+     p_source: "test-source",
+     p_name_nl: "Test Fertilizer 1",
+     p_name_en: "Test Fertilizer (EN)",
+     p_description: "This is a test fertilizer",
+     p_dm: 37,
+     // ... rest of default properties
+     ...overrides
+   };
+ }

  it("should generate different hashes when a string value changes", async () => {
-     const fertilizer1: CatalogueFertilizerItem = {
-       p_id_catalogue: "test-id-1",
-       // ... many repeated properties
-     }
+     const fertilizer1 = createTestFertilizer();
      
-     const fertilizer2: CatalogueFertilizerItem = {
-       ...fertilizer1,
-       p_name_nl: "Updated Test Fertilizer Name",
-     }
+     const fertilizer2 = createTestFertilizer({ 
+       p_name_nl: "Updated Test Fertilizer Name" 
+     });

Also applies to: 174-234, 236-297, 298-359, 360-421

fdm-data/src/fertilizers/index.test.ts (1)

33-33: Unusual async usage in describe block.

The describe function doesn't typically take an async callback. While this may not cause immediate issues, it's unconventional and could lead to unexpected behavior as the Promise returned by the async function is not being awaited or handled in any way.

-describe("getCatalogueSrm", async () => {
+describe("getCatalogueSrm", () => {
fdm-core/src/fertilizer.ts (1)

431-434: Consider adding more specific error messaging.

The error message "Fertilizer does not exist in catalogue" could be more informative by including the fertilizer ID and farm ID to help with troubleshooting.

-            throw new Error("Fertilizer does not exist in catalogue")
+            throw new Error(`Fertilizer with ID ${p_id_catalogue} does not exist in catalogue for farm ${b_id_farm}`)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c2b2614 and 657e10f.

⛔ Files ignored due to path filters (3)
  • fdm-core/src/db/migrations/0002_kind_cardiac.sql is excluded by !fdm-core/src/db/migrations/**
  • fdm-core/src/db/migrations/meta/0002_snapshot.json is excluded by !fdm-core/src/db/migrations/**
  • fdm-core/src/db/migrations/meta/_journal.json is excluded by !fdm-core/src/db/migrations/**
📒 Files selected for processing (12)
  • .changeset/chubby-bushes-burn.md (1 hunks)
  • fdm-core/src/catalogues.test.ts (1 hunks)
  • fdm-core/src/catalogues.ts (2 hunks)
  • fdm-core/src/db/schema.ts (2 hunks)
  • fdm-core/src/fertilizer.ts (9 hunks)
  • fdm-data/src/cultivations/catalogues/brp.ts (3 hunks)
  • fdm-data/src/cultivations/index.test.ts (3 hunks)
  • fdm-data/src/cultivations/index.ts (1 hunks)
  • fdm-data/src/fertilizers/catalogues/srm.ts (3 hunks)
  • fdm-data/src/fertilizers/hash.test.ts (1 hunks)
  • fdm-data/src/fertilizers/index.test.ts (2 hunks)
  • fdm-data/src/fertilizers/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/chubby-bushes-burn.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • fdm-core/src/db/schema.ts
🧰 Additional context used
🧬 Code Definitions (8)
fdm-data/src/cultivations/index.ts (2)
fdm-data/src/cultivations/d.ts (2)
  • CatalogueCultivationName (1-1)
  • CatalogueCultivation (14-14)
fdm-data/src/cultivations/catalogues/brp.ts (1)
  • getCatalogueBrp (15-48)
fdm-data/src/cultivations/catalogues/brp.ts (2)
fdm-data/src/cultivations/d.ts (1)
  • CatalogueCultivation (14-14)
fdm-data/src/cultivations/hash.ts (1)
  • hashCultivation (4-25)
fdm-data/src/fertilizers/hash.test.ts (1)
fdm-data/src/fertilizers/hash.ts (1)
  • hashFertilizer (4-25)
fdm-data/src/fertilizers/index.ts (2)
fdm-data/src/fertilizers/d.ts (2)
  • CatalogueFertilizerName (1-1)
  • CatalogueFertilizer (55-55)
fdm-data/src/fertilizers/catalogues/srm.ts (1)
  • getCatalogueSrm (15-83)
fdm-core/src/catalogues.ts (4)
fdm-data/src/fertilizers/index.ts (1)
  • getFertilizersCatalogue (23-31)
fdm-data/src/fertilizers/hash.ts (1)
  • hashFertilizer (4-25)
fdm-data/src/cultivations/index.ts (1)
  • getCultivationCatalogue (23-32)
fdm-data/src/cultivations/hash.ts (1)
  • hashCultivation (4-25)
fdm-data/src/cultivations/index.test.ts (2)
fdm-data/src/cultivations/catalogues/brp.ts (1)
  • getCatalogueBrp (15-48)
fdm-data/src/cultivations/index.ts (1)
  • getCultivationCatalogue (23-32)
fdm-data/src/fertilizers/index.test.ts (2)
fdm-data/src/fertilizers/catalogues/srm.ts (1)
  • getCatalogueSrm (15-83)
fdm-data/src/fertilizers/index.ts (1)
  • getFertilizersCatalogue (23-31)
fdm-core/src/fertilizer.ts (4)
fdm-core/src/authorization.d.ts (1)
  • PrincipalId (21-23)
fdm-core/src/db/schema.ts (3)
  • farmsTypeInsert (32-32)
  • fertilizersCatalogueTypeInsert (239-240)
  • fertilizersCatalogueTypeSelect (237-238)
fdm-core/src/authorization.ts (1)
  • checkPermission (155-239)
fdm-core/src/error.ts (1)
  • handleError (15-31)
🪛 GitHub Actions: Tests
fdm-core/src/catalogues.test.ts

[error] 661-661: AssertionError: expected 'Updated hash' to be 'fac006e5' // Object.is equality

🔇 Additional comments (24)
fdm-core/src/catalogues.ts (2)

372-375: Refactoring to modular design.

The refactoring of syncCatalogues to call two specialized functions improves code organization and readability. This modular approach makes maintenance easier and follows good software design principles.


405-415:

Details

✅ Verification successful

Verify hash update logic in catalog syncing.

The pipeline failure suggests issues with the hash update logic. When a database item differs from the catalog, ensure it's correctly matched and updated.


🏁 Script executed:

#!/bin/bash
# Check the SRM catalog structure and the sync implementation
echo "Examining the getFertilizersCatalogue implementation:"
cat fdm-data/src/fertilizers/catalogues/srm.ts | grep -A 15 "export async function getCatalogueSrm"

echo -e "\nChecking how hash comparisons are handled:"
cat fdm-core/src/catalogues.ts | grep -A 10 "existing\\[0\\].hash === null"

echo -e "\nLooking at relevant tests:"
cat fdm-core/src/catalogues.test.ts | grep -A 20 "should update fertilizer catalogue"

Length of output: 3227


Hash update logic verified as expected.
The condition for triggering the hash update—checking if the existing hash is null, undefined, or not matching the computed hash—appears to be correctly implemented for the fertilizers catalogue. The related tests in fdm-core/src/catalogues.test.ts confirm that the update behavior is triggered when the hash differs. Similarly, the analogous logic for the cultivations catalogue follows the same pattern.

No further modifications to the hash update logic are required based on this verification. However, please ensure that additional test cases cover scenarios where the hash remains unchanged to prevent unnecessary updates.

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

594-595: Correct usage of async function.

Good update to add the await keyword when calling the now-asynchronous getFertilizersCatalogue function.


602-603: Correct usage of async function.

Good update to add the await keyword when calling the now-asynchronous getCultivationCatalogue function.


606-662: ⚠️ Potential issue

Fix failing test for fertilizer catalog update.

The pipeline shows this test is failing because after syncCatalogues, the hash remains as "Updated hash" instead of reverting to the original value. This happens because the test selects a random item that may not be in the SRM catalog, so it isn't processed by syncFertilizerCatalogue.

Modify the test to use an item from the SRM catalog:

 it("should update fertilizer catalogue", async () => {
     await syncCatalogues(fdm)
 
-    // Update a catalogue item
-    const item = await fdm
-        .select({
-            p_id_catalogue: schema.fertilizersCatalogue.p_id_catalogue,
-            hash: schema.fertilizersCatalogue.hash,
-        })
-        .from(schema.fertilizersCatalogue)
-        .where(isNotNull(schema.fertilizersCatalogue.hash))
-        .limit(1)
-    expect(item[0].p_id_catalogue).toBeDefined()
+    // Start with a fertilizer from the SRM catalogue
+    const srmCatalogue = await getFertilizersCatalogue("srm")
+    const originalCatalogItem = srmCatalogue[0] // Use the first item
+    expect(originalCatalogItem).toBeDefined()
+    expect(originalCatalogItem.p_id_catalogue).toBeDefined()
+
+    // Find this item in the database
+    const item = await fdm
+        .select({
+            p_id_catalogue: schema.fertilizersCatalogue.p_id_catalogue,
+            hash: schema.fertilizersCatalogue.hash,
+        })
+        .from(schema.fertilizersCatalogue)
+        .where(eq(schema.fertilizersCatalogue.p_id_catalogue, originalCatalogItem.p_id_catalogue))
+        .limit(1)
+    expect(item[0].p_id_catalogue).toBeDefined()
🧰 Tools
🪛 GitHub Check: core (20)

[failure] 661-661: src/catalogues.test.ts > Catalogues syncing > should update fertilizer catalogue
AssertionError: expected 'Updated hash' to be 'fac006e5' // Object.is equality

Expected: "fac006e5"
Received: "Updated hash"

❯ src/catalogues.test.ts:661:36

🪛 GitHub Actions: Tests

[error] 661-661: AssertionError: expected 'Updated hash' to be 'fac006e5' // Object.is equality

fdm-data/src/cultivations/index.ts (1)

23-29: Proper conversion to async function.

Good update to make getCultivationCatalogue asynchronous, including the return type change to Promise<CatalogueCultivation> and the use of await when calling getCatalogueBrp().

fdm-data/src/fertilizers/index.ts (1)

23-29: Proper conversion to async function.

Good update to make getFertilizersCatalogue asynchronous, including the return type change to Promise<CatalogueFertilizer> and the use of await when calling getCatalogueSrm().

fdm-data/src/cultivations/catalogues/brp.ts (2)

2-2: Good addition of hashCultivation import

This import correctly supports the asynchronous hashing functionality that's being implemented.


15-16: Well-implemented async conversion

The function has been properly converted to an asynchronous implementation:

  • Function signature now includes async and returns Promise<CatalogueCultivation>
  • Correctly uses async/await with the hashCultivation function
  • Properly handles multiple concurrent operations with Promise.all

This change aligns with modern JavaScript/TypeScript practices for handling asynchronous operations, especially for potentially time-consuming operations like hashing.

Also applies to: 41-41, 46-46

fdm-data/src/fertilizers/hash.test.ts (1)

1-63: Well-structured test for hash generation

This test case thoroughly verifies that the hashFertilizer function generates a valid hash with the expected value.

fdm-data/src/cultivations/index.test.ts (3)

6-9: Properly updated async/await pattern

The test has been correctly updated to handle async operations:

  • Added async to the test function
  • Used await for both function calls
  • Maintains the same assertion logic

12-16: Correct implementation of async error testing

The error handling test has been properly updated to use the .rejects.toThrowError() pattern, which is the appropriate way to test for rejected promises in async/await code.


18-22: Well-structured async test conversions

All test cases have been correctly updated to handle the asynchronous nature of the functions being tested, while maintaining the same test behavior and assertions.

Also applies to: 24-29, 31-38, 42-56, 58-61

fdm-data/src/fertilizers/catalogues/srm.ts (2)

2-2: Properly implemented async pattern

The function has been correctly converted to an asynchronous implementation using the same pattern as in other files:

  • Added appropriate import for hashFertilizer
  • Updated function signature to return a Promise
  • Properly uses await with hashFertilizer
  • Correctly handles multiple promises with Promise.all

This ensures consistency across the codebase in how asynchronous operations are handled.

Also applies to: 15-16, 76-76, 81-82


68-68: Good property name consistency update

Renaming p_cl_cr to p_cl_rt improves consistency with the field naming throughout the codebase, making maintenance easier.

fdm-data/src/fertilizers/index.test.ts (2)

6-9: Good conversion to async/await pattern.

The conversion of test cases to properly use async/await syntax is well-implemented. This ensures that promises are correctly resolved before assertions are made, preventing potential race conditions or false positives in tests.

Also applies to: 12-16, 19-20, 25-26, 35-36, 92-93


84-84: Property name update consistent with schema changes.

The change from checking p_cl_cr to p_cl_rt aligns with the recent renaming in the schema definition files, ensuring consistency across the codebase.

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

129-129: ⚠️ Potential issue

Fix parameter name inconsistency.

There's a typo in the property name, which should be p_cr_rt instead of pr_cr_rt to maintain naming consistency with other properties.

-        pr_cr_rt: schema.fertilizersCatalogueTypeInsert["p_cr_rt"]
+        p_cr_rt: schema.fertilizersCatalogueTypeInsert["p_cr_rt"]

133-133: Correctly updated parameter type reference.

The property definition has been corrected to use the proper schema type p_cl_rt instead of p_cl_cr, which aligns with the schema changes and ensures type consistency.


86-138: Improved function signature with proper security checks.

The function now correctly requires principal_id and b_id_farm parameters to enforce permission checks, and returns the created fertilizer ID. This enhances security and improves reusability by allowing callers to easily reference the newly created entity.


149-157: Well-implemented hash generation flow.

The code properly builds the input object, sets the hash to null initially, then uses the imported hashFertilizer function to generate a hash based on the complete object. This approach ensures data integrity and consistent hashing.


356-460: Well-designed update function with proper security.

The new updateFertilizerFromCatalogue function is well-implemented with:

  1. Proper permission checks
  2. Verification that the fertilizer exists
  3. Secure filtering by both catalogue ID and farm ID (source)
  4. Proper hash regeneration after updates

This ensures data integrity and prevents unauthorized modifications.


1-13: Good import organization.

The imports are well-organized with appropriate grouping and include the new dependencies needed for enhanced functionality (and from drizzle-orm and hashFertilizer from the data package).


410-454: Consistent error handling pattern.

The function follows the established pattern for error handling in the codebase, using the handleError helper function with specific error messages and context. This maintains consistency and provides useful debugging information.

Comment thread fdm-core/src/catalogues.ts
Comment thread fdm-core/src/catalogues.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: 0

🧹 Nitpick comments (1)
fdm-data/src/cultivations/index.ts (1)

12-14: Remove the duplicate @returns tag

There are two @returns tags in the JSDoc documentation. The original tag on lines 12-13 should be removed to avoid confusion, leaving only the new Promise-based description.

 * @param catalogueName - The name of the desired cultivation catalogue.
 *                        Currently supported names are: "brp".
- * @returns An array of `CatalogueCultivationItem` objects representing the
- *          requested cultivation catalogue.
 * @returns A Promise that resolves to an array of `CatalogueCultivationItem` objects.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9051ddc and 1240a14.

📒 Files selected for processing (4)
  • fdm-core/src/catalogues.test.ts (3 hunks)
  • fdm-core/src/catalogues.ts (2 hunks)
  • fdm-data/src/cultivations/index.ts (1 hunks)
  • fdm-data/src/fertilizers/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • fdm-core/src/catalogues.test.ts
🧰 Additional context used
🧬 Code Definitions (3)
fdm-data/src/fertilizers/index.ts (2)
fdm-data/src/fertilizers/d.ts (2)
  • CatalogueFertilizerName (1-1)
  • CatalogueFertilizer (55-55)
fdm-data/src/fertilizers/catalogues/srm.ts (1)
  • getCatalogueSrm (15-83)
fdm-core/src/catalogues.ts (4)
fdm-data/src/fertilizers/index.ts (1)
  • getFertilizersCatalogue (24-32)
fdm-data/src/fertilizers/hash.ts (1)
  • hashFertilizer (4-25)
fdm-data/src/cultivations/index.ts (1)
  • getCultivationCatalogue (24-33)
fdm-data/src/cultivations/hash.ts (1)
  • hashCultivation (4-25)
fdm-data/src/cultivations/index.ts (2)
fdm-data/src/cultivations/d.ts (2)
  • CatalogueCultivationName (1-1)
  • CatalogueCultivation (14-14)
fdm-data/src/cultivations/catalogues/brp.ts (1)
  • getCatalogueBrp (15-48)
🪛 GitHub Check: codecov/patch
fdm-core/src/catalogues.ts

[warning] 419-419: fdm-core/src/catalogues.ts#L419
Added line #L419 was not covered by tests


[warning] 467-467: fdm-core/src/catalogues.ts#L467
Added line #L467 was not covered by tests

🔇 Additional comments (13)
fdm-data/src/fertilizers/index.ts (2)

14-14: Documentation updates correctly reflect async changes

The updated JSDoc comments now correctly indicate that the function returns a Promise and the example shows proper usage with the await keyword.

Also applies to: 20-20


24-26:

Details

✅ Verification successful

Function correctly converted to async pattern

The function signature has been properly updated with the async keyword and the correct return type of Promise<CatalogueFertilizer>. The implementation correctly uses await when calling getCatalogueSrm().

Note that this is a breaking change for consumers of this API. All callers of getFertilizersCatalogue will need to be updated to handle the Promise return type.

Also applies to: 29-29


🏁 Script executed:

#!/bin/bash
# Search for instances where getFertilizersCatalogue is called to ensure they're properly awaited
rg -A 2 -B 2 "getFertilizersCatalogue" --glob "*.{ts,tsx,js,jsx}" --no-filename

Length of output: 2358


Async Conversion Verified – No Further Updates Required

The getFertilizersCatalogue function in fdm-data/src/fertilizers/index.ts has been correctly updated to an asynchronous pattern with the proper return type. Verification across test cases confirms all invocations use await appropriately. Please note that this change is breaking for API consumers, so all external calls must be updated accordingly.

  • Function signature correctly uses async and returns a Promise<CatalogueFertilizer>.
  • Test files and example usages now await the function call as expected.
  • Reminder: Update any external consumers if not already handled.
fdm-data/src/cultivations/index.ts (3)

20-20: LGTM: Example updated correctly

The example has been properly updated to include the await keyword, reflecting the function's new asynchronous nature.


29-29: LGTM: Proper await usage

The await keyword has been correctly added to properly handle the Promise returned by getCatalogueBrp().


24-26:

Details

❓ Verification inconclusive

LGTM: Function signature updated properly

The function signature has been correctly updated to be asynchronous, matching the implementation in getCatalogueBrp().


🏁 Script executed:

#!/bin/bash
# Check for any usage of getCultivationCatalogue without await to identify potential breaking changes
echo "Checking for usages of getCultivationCatalogue..."
rg "getCultivationCatalogue\\((?!.*await)" --type ts

Length of output: 427


Action Required: Re-verify Asynchronous Usage with Updated Regex Options

The asynchronous function signature in fdm-data/src/cultivations/index.ts has been correctly updated to align with getCatalogueBrp(). However, our initial automated check for direct invocations of getCultivationCatalogue without using await failed due to unsupported lookahead in the regex engine. To proceed, please re-run the verification using the PCRE2 flag. For example:

#!/bin/bash
echo "Checking for usages of getCultivationCatalogue..."
rg --pcre2 "getCultivationCatalogue\\((?!.*await)" --type ts

Once you confirm that all usages correctly handle the asynchronous call, this change can be approved.

fdm-core/src/catalogues.ts (8)

10-11: LGTM! Required imports added.

The new imports for hashCultivation and hashFertilizer are correctly added to support the functionality introduced in the new synchronization functions.


373-375: Excellent refactoring of the syncCatalogues function.

The refactoring improves code organization by separating concerns into dedicated functions. This makes the code more maintainable and easier to understand.


377-422: The implementation of syncFertilizerCatalogue looks good.

The function correctly:

  1. Fetches the SRM fertilizer catalogue
  2. Processes items within a transaction
  3. Updates or inserts catalogue items with proper hash calculations
  4. Properly implements error propagation as requested in a previous review

A test for the hash update logic was already provided in a previous review comment. Please ensure these tests are implemented to cover this code path, particularly line 419 which is flagged by code coverage tools.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 419-419: fdm-core/src/catalogues.ts#L419
Added line #L419 was not covered by tests


424-470: Well-implemented syncCultivationCatalogue function.

The function follows the same pattern as syncFertilizerCatalogue with appropriate adaptations for cultivation data. The error handling is properly implemented as requested in a previous review.

Similar to syncFertilizerCatalogue, please ensure test coverage for the hash update logic and error handling path (line 467) which is flagged by code coverage tools.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 467-467: fdm-core/src/catalogues.ts#L467
Added line #L467 was not covered by tests


404-405: Hash update logic is well-implemented.

The logic correctly identifies when a hash needs to be updated (null, undefined, or different) and updates only when necessary. This optimization avoids unnecessary database operations.

Also applies to: 407-411


450-453: Consistent hash update implementation across catalogue types.

The hash update logic for cultivation catalogue follows the same pattern as for fertilizers, maintaining consistency across the codebase. This is a good practice for maintainability.

Also applies to: 455-462


467-467:

Details

❓ Verification inconclusive

Error handling properly implemented for cultivation catalogue sync.

The error handling now correctly throws the handled error, consistent with the approach in syncFertilizerCatalogue.

Run the following script to verify test coverage for this error path:


🏁 Script executed:

#!/bin/bash
# Check if there are tests that cover the error handling path
rg -A 2 -B 2 "test.*syncCultivationCatalogue.*error" --type=ts fdm-core/src

Length of output: 77


SyncCultivationCatalogue Error Handling – Manual Test Coverage Verification Needed

The error handling implementation (i.e. throwing the handled error using throw handleError(error, "Exception for syncCultivationCatalogue")) is consistent with the approach in syncFertilizerCatalogue. However, our automated search for tests covering this error path did not produce any results. Please manually verify that tests exist for this code path or consider adding appropriate tests if they are missing.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 467-467: fdm-core/src/catalogues.ts#L467
Added line #L467 was not covered by tests


419-419:

Details

❓ Verification inconclusive

Error handling correctly propagates errors.

The function now properly throws the handled error, allowing it to be caught and handled by calling functions.

Run the following script to verify test coverage for this error path:


🏁 Script executed:

#!/bin/bash
# Check if there are tests that cover the error handling path
rg -A 2 -B 2 "test.*syncFertilizerCatalogue.*error" --type=ts fdm-core/src

Length of output: 76


Error handling in syncFertilizerCatalogue appears correct as the handled error is properly thrown; however, our automated search did not uncover any tests covering this specific error path in fdm-core/src/catalogues.ts (line 419). Please manually verify whether there are existing tests for this error scenario or add tests as needed.

  • Confirm that tests exercise the error handling for syncFertilizerCatalogue (look for any tests triggering an error and verifying it is correctly thrown).
  • If no tests exist, consider adding them to ensure robust error propagation.
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 419-419: fdm-core/src/catalogues.ts#L419
Added line #L419 was not covered by tests

@SvenVw SvenVw requested a review from gerardhros March 31, 2025 14:20
p_mg_rt: 180,
p_ca_rt: 190,
p_ne: 200,
p_s_rt: 210,
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

p_ne is a correct name?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It stands for Neutralising effect of product with the unit g CaO/kg

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.

LGTM

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enable users to add custom fertilizers

2 participants