Skip to content

[Gel] - Add trigger to create financial/narrative reports upon project creation #3279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

bryanjnelson
Copy link
Contributor

@bryanjnelson bryanjnelson commented Aug 16, 2024

Monday Story

Monday Task

Description

This adds a createPeriodicReportsOnInsert trigger to create the appropriate number of both narrative and financial reports when a project is created, based upon the financialReportPeriod in the project.

Open items for discussion/modification:

  • Should the create_periodic_report_ranges function be made more generic to handle other use cases? (Probably not.)
  • Is the create_periodic_report_ranges function located in the best place? It could be moved to the common.esdl, but if this is the only place it will be used then no. It could also potentially be moved to the periodic-report.esdl?
  • It's possible the EdgeQL in create_periodic_report_ranges could be written a bit more cleanly
  • It's currently problematic that the mouStart, mouEnd, and financialReportPeriod fields are not required on a Project; this will obviously prevent any reports from being generated correctly. We'll need to figure out the best way to handle that. Make them required? Update the trigger to also run on update when all 3 are finally populated?
  • Handle TODO in the FinancialReport insert; I'm unclear what that project level field is used for

@bryanjnelson bryanjnelson requested a review from CarsonF as a code owner August 16, 2024 17:43
Copy link
Member

@CarsonF CarsonF left a comment

Choose a reason for hiding this comment

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

Wow love the initiative!

For this to be fully out of app code, we also need to handle:

  • Date range expanding (on update), which would add new periods.
    Jan-March -> Jan-July
  • Date range shrinking (on update), which would delete empty periods
    Jan-May -> Jan-March
    But we only want to delete reports that don't have a file uploaded or a progress report started
  • On financial reporting frequency change create new and delete old empty periods.
    Monthly (Jan, Feb, March) -> Quarterly (Jan-March)

Honestly "on insert" will never be hit by users since they don't define the date ranges when they create the project.
May be useful for migration though?

Should the create_periodic_report_ranges function be made more generic to handle other use cases? (Probably not.)

Probably not

Is the create_periodic_report_ranges function located in the best place? It could be moved to the common.esdl, but if this is the only place it will be used then no. It could also potentially be moved to the periodic-report.esdl?

Probably their own files for each concrete report. They all have distinct use-cases / logic.

It's currently problematic that the mouStart, mouEnd, and financialReportPeriod fields are not required on a Project; this will obviously prevent any reports from being generated correctly. We'll need to figure out the best way to handle that. Make them required? Update the trigger to also run on update when all 3 are finally populated?

That's what we do in app code. If all 3 are given, synchronize.

@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from cf4bbc4 to c6d7120 Compare September 11, 2024 18:37
@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from 436412b to f594e65 Compare May 8, 2025 17:08
Copy link

coderabbitai bot commented May 8, 2025

📝 Walkthrough

Walkthrough

This update introduces triggers and functions on the Project type to automate creation, updating, and removal of periodic financial, narrative, and progress reports based on MOU start/end dates and financial reporting periods. It also adds a constraint on PeriodicReport to ensure valid date ranges.

Changes

File(s) Change Summary
dbschema/project.gel Added triggers createPeriodicReports (after insert) and addRemovePeriodicReports (after update) on Project to manage periodic reports. Added functions create_periodic_report_ranges, determine_requested_report_periods, insert_narrative_and_progress_reports, and insert_financial_reports to generate report date ranges, identify missing report periods, and insert corresponding financial, narrative, and progress reports. Implemented logic to delete reports without files when relevant project dates or reporting periods change.
dbschema/periodic-report.gel Added a constraint expression on the abstract type PeriodicReport to enforce that the computed end date is always greater than or equal to the computed start date, ensuring valid report period ranges.

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@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: 5

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 42d326f and f594e65.

📒 Files selected for processing (1)
  • dbschema/project.gel (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: Generate (head)
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: Generate (base)
  • GitHub Check: Clean
  • GitHub Check: Unit
  • GitHub Check: lint
  • GitHub Check: Analyze (javascript)

@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from f594e65 to e0b8c5d Compare May 12, 2025 20:10
@bryanjnelson bryanjnelson changed the title [EdgeDB] - Add trigger to appropriately create financial/narrative report upon project creation [EdgeDB] - Add trigger to create financial/narrative reports upon project creation May 12, 2025
@bryanjnelson bryanjnelson changed the title [EdgeDB] - Add trigger to create financial/narrative reports upon project creation [Gel] - Add trigger to create financial/narrative reports upon project creation May 12, 2025
Copy link

@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 (2)
dbschema/project.gel (2)

125-157: ⚠️ Potential issue

Missing guard for NULL MOU / period values

The trigger could fail at runtime if any of the required fields (mouStart, mouEnd, financialReportPeriod) are NULL, as the function create_periodic_report_ranges will attempt to cast them to cal::local_date.

Apply this diff to add a guard clause:

-trigger createPeriodicReports after insert for each do (
+trigger createPeriodicReports after insert for each
+  when (
+    exists __new__.mouStart
+    and exists __new__.mouEnd
+    and exists __new__.financialReportPeriod
+  )
+  do (

This will make the insert path safe and allow you to decide later if you want an additional trigger to create reports once these fields are populated.


307-323: ⚠️ Potential issue

Off-by-one error: upper bound of range is exclusive

In EdgeDB, range(lower, upper) is inclusive on the lower bound and exclusive on the upper bound [lower, upper). The current implementation would exclude the last day of each period.

Apply this diff to correct the range calculation:

-              firstDayOfNextMonth := (select firstDayOfMonth + <cal::relative_duration>(monthInterval ++ ' month')),
-              lastDayOfMonth := firstDayOfNextMonth - <cal::relative_duration>'1 day'
-            select range(<cal::local_date>firstDayOfMonth, <cal::local_date>lastDayOfMonth)
+              firstDayOfNextPeriod := (
+                select firstDayOfMonth + <cal::relative_duration>(monthInterval ++ ' month')
+              )
+            select range(
+              <cal::local_date>firstDayOfMonth,
+              <cal::local_date>firstDayOfNextPeriod
+            )

This will create a range from the first day of the period to the first day of the next period, which correctly includes all days in the period.

🧹 Nitpick comments (1)
dbschema/project.gel (1)

187-206: Be consistent with parentheses for clarity

The code logic is complex with nested conditionals. Consistent parentheses would make it easier to understand the structure.

Add parentheses around conditional expressions:

-      else if __old__.financialReportPeriod ?!= __new__.financialReportPeriod
-        or (__new__.mouStart > __old__.mouStart) ?? false 
-        or (__new__.mouEnd < __old__.mouEnd) ?? false then (
+      else if (
+        __old__.financialReportPeriod ?!= __new__.financialReportPeriod
+        or (__new__.mouStart > __old__.mouStart) ?? false 
+        or (__new__.mouEnd < __old__.mouEnd) ?? false
+      ) then (
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f594e65 and e0b8c5d.

📒 Files selected for processing (1)
  • dbschema/project.gel (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: Generate (head)
  • GitHub Check: Unit
  • GitHub Check: Generate (base)
  • GitHub Check: Clean
  • GitHub Check: lint
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
dbschema/project.gel (3)

325-366: Function reuses requestedReportPeriodsForInsertion logic properly

Good job implementing the insertion logic in a separate function that correctly filters out periods that already have reports, addressing potential duplication issues.


159-218: Comprehensive trigger for handling report lifecycle

The trigger properly handles:

  1. Removing reports when MOU dates are removed
  2. Removing and adding reports when financial report period changes
  3. Adding new reports when MOU dates change

The code uses the correct filter .container.id = __old__.id to prevent deleting reports from other projects.


202-204:

✅ Verification successful

Ensure deletion is scoped to current project

The delete report operation appears properly scoped to the current project through the initial filter on existingReports, but it's good practice to double-check at deletion time too.


🏁 Script executed:

#!/bin/bash
# Verify that delete operation properly scopes to the current project
# Looking for any similar trigger that has an explicit container check at deletion time

rg -A 5 "delete.*filter.*container"

Length of output: 37


🏁 Script executed:

#!/bin/bash
# Show context around the delete report operation to verify project scoping
rg -n "delete report" -A10 -B10 dbschema/project.gel

Length of output: 1352


🏁 Script executed:

#!/bin/bash
# Locate the definition of existingReports to confirm project scoping
rg -n "existingReports" -A10 -B10 dbschema/project.gel

Length of output: 3693


Deletion correctly scoped to current project
The existingReports selection (lines 171–174) already filters by .container.id = __old__.id, so all entries in reportsForDeletion (and the subsequent delete report calls) are inherently limited to the current project. No additional container filter is needed.

@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from e0b8c5d to 5be235c Compare May 22, 2025 13:28
Copy link

@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

♻️ Duplicate comments (2)
dbschema/project.gel (2)

125-157: ⚠️ Potential issue

Missing null-checks may cause runtime failures in createPeriodicReports trigger

The trigger attempts to use mouStart, mouEnd, and financialReportPeriod without checking if these optional fields are populated. This could cause runtime errors when inserting projects with incomplete data.

As mentioned in a previous review comment, add a when condition to prevent runtime errors:

-trigger createPeriodicReports after insert for each do (
+trigger createPeriodicReports after insert for each
+  when (
+    exists __new__.mouStart
+    and exists __new__.mouEnd
+    and exists __new__.financialReportPeriod
+  )
+  do (

319-321: ⚠️ Potential issue

Off-by-one error: upper bound of the range is exclusive

The current implementation builds [firstDayOfMonth, lastDayOfMonth) which omits the last day of the period.

As suggested in a previous review, use the next period's first day as the exclusive upper bound:

-              firstDayOfNextMonth := (select firstDayOfMonth + <cal::relative_duration>(monthInterval ++ ' month')),
-              lastDayOfMonth := firstDayOfNextMonth - <cal::relative_duration>'1 day'
-            select range(<cal::local_date>firstDayOfMonth, <cal::local_date>lastDayOfMonth)
+              firstDayOfNextPeriod := (
+                select firstDayOfMonth + <cal::relative_duration>(monthInterval ++ ' month')
+              )
+            select range(
+              <cal::local_date>firstDayOfMonth,
+              <cal::local_date>firstDayOfNextPeriod
+            )
🧹 Nitpick comments (4)
dbschema/project.gel (4)

165-218: Trigger branch handling could be improved with early returns

The current implementation uses a sequence of if/else if branches with nested CTEs that makes the code difficult to follow. Consider restructuring the logic for better readability.

-      select if not exists __new__.mouStart or not exists __new__.mouEnd then (
+      # Handle MOU date removal first
+      select if not exists __new__.mouStart or not exists __new__.mouEnd then (
         for report in reportsForDeletion 
         union (
           delete report 
         )
       )
-      else if __old__.financialReportPeriod ?!= __new__.financialReportPeriod
-        or (__new__.mouStart > __old__.mouStart) ?? false 
-        or (__new__.mouEnd < __old__.mouEnd) ?? false then (
+      # Handle period type change or MOU period shrinking
+      else if __old__.financialReportPeriod ?!= __new__.financialReportPeriod or
+        (__new__.mouStart > __old__.mouStart) ?? false or
+        (__new__.mouEnd < __old__.mouEnd) ?? false then (

339-351: Consider refactoring duplicate report insertion logic

There's significant code duplication between financial and narrative report insertion. While EdgeQL has limitations for dynamic typing, the code could still be more maintainable.

While the previous attempt to combine loops didn't work due to EdgeQL limitations (as noted in past review comments), you could at least extract common properties into a CTE:

+        commonReportProps := {
+          createdAt := datetime_of_statement(),
+          modifiedAt := datetime_of_statement(),
+          createdBy := assert_exists(global default::currentActor),
+          modifiedBy := assert_exists(global default::currentActor),
+          project := newProject,
+          projectContext := newProject.projectContext,
+          container := newProject,
+        },
         financialReports := (for reportPeriod in requestedReportPeriodsForInsertion
         union (
           insert default::FinancialReport {
-            createdAt := datetime_of_statement(),
-            modifiedAt := datetime_of_statement(),
-            createdBy := assert_exists(global default::currentActor),
-            modifiedBy := assert_exists(global default::currentActor),
-            project := newProject,
-            projectContext := newProject.projectContext,
-            container := newProject,
+            commonReportProps,
             period := reportPeriod,
           }

Also applies to: 352-364


309-311: Document function usage and expected behavior

The function lacks documentation that explains expected behavior and valid input parameters.

  # creates the ranges for the given start and end dates based upon the given month interval
+ # Parameters:
+ #   startDate: The start date of the MOU period
+ #   endDate: The end date of the MOU period
+ #   monthInterval: Either '1' for monthly or '3' for quarterly reporting
+ # Returns:
+ #   A set of date ranges covering the MOU period, each representing a reporting period
  function create_periodic_report_ranges(startDate: cal::local_date, endDate: cal::local_date, 
    monthInterval: str) -> set of range<cal::local_date>

126-129: Hardcoded interval mapping may be better expressed in a function

The mapping of ReportPeriod.Monthly to '1' and other values to '3' is hardcoded in multiple places and could be extracted to a utility function.

+    # Helper function to get month interval string from ReportPeriod
+    function report_period_to_month_interval(period: default::ReportPeriod) -> str
+      using (
+        if period = default::ReportPeriod.Monthly then '1' else '3'
+      );
+
     trigger createPeriodicReports after insert for each do (
       with
-        interval := (select 
-          if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3'),
+        interval := Project::report_period_to_month_interval(__new__.financialReportPeriod),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0b8c5d and 5be235c.

📒 Files selected for processing (1)
  • dbschema/project.gel (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: Generate (head)
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Generate (base)
  • GitHub Check: lint
  • GitHub Check: Clean
  • GitHub Check: Unit
🔇 Additional comments (1)
dbschema/project.gel (1)

130-133:

❓ Verification inconclusive

Add error handling for production concerns

While the current implementation handles core functionality, it doesn't account for potential edge cases that could occur in production.

Please consider these cases:

  1. What happens if a project is created without MOU dates or financial report period, and these are added later?
  2. What happens if a project's MOU dates or financial report period are updated frequently?
  3. How will the system handle extremely long MOU periods that would generate hundreds of reports?

Also applies to: 341-350, 354-363


🏁 Script executed:

#!/bin/bash
# Check for existing reports to understand the typical number of periods
rg -A 3 "FinancialReport|NarrativeReport" --type edgeql | grep "period"

# Look for existing date range handling elsewhere in the codebase
rg "range<cal::local_date>" --type edgeql

Length of output: 177


Add production-grade error handling for MOU and reporting date ranges

The existing code around generating reports (e.g. mouStart, mouEnd, interval) doesn’t guard against several real-world scenarios. I wasn’t able to locate any existing date-range validation in .gel files (the rg --type edgeql scan failed on unrecognized file type), so please manually verify or extend the logic to cover:

  • Missing dates
    • What if mouStart, mouEnd or report period aren’t set at creation and are added later?
  • Frequent updates
    • How does the system behave if those dates are changed often? Are old reports cleaned up/re-generated?
  • Very long periods
    • A multi-year MOU could spawn hundreds of report intervals—do you cap, batch or page those?

Also review the same patterns at lines 341–350 and 354–363 to ensure consistent error checking and performance guards.

@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from 5be235c to faef758 Compare May 23, 2025 15:11
Copy link

@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)
dbschema/project.gel (1)

303-320: ⚠️ Potential issue

Address the off-by-one error and add input validation

Two issues need attention:

  1. Off-by-one error still present: The range calculation on lines 314-316 uses lastDayOfMonth := firstDayOfNextMonth - <cal::relative_duration>'1 day' which creates [firstDay, lastDay) that excludes the last day of the period.

  2. Missing input validation: The function lacks validation for input parameters.

Apply this diff to fix the off-by-one error:

-              firstDayOfNextMonth := (select firstDayOfMonth + <cal::relative_duration>(monthInterval ++ ' month')),
-              lastDayOfMonth := firstDayOfNextMonth - <cal::relative_duration>'1 day'
-            select range(<cal::local_date>firstDayOfMonth, <cal::local_date>lastDayOfMonth)
+              firstDayOfNextPeriod := (
+                select firstDayOfMonth + <cal::relative_duration>(monthInterval ++ ' month')
+              )
+            select range(
+              <cal::local_date>firstDayOfMonth,
+              <cal::local_date>firstDayOfNextPeriod
+            )

And add input validation at the beginning:

  function create_periodic_report_ranges(startDate: cal::local_date, endDate: cal::local_date, 
    monthInterval: str) -> set of range<cal::local_date>
    using (
+     # Validate input parameters
+     assert(startDate <= endDate, 
+       message := "Start date must be before or equal to end date"),
+     assert(monthInterval = '1' or monthInterval = '3',
+       message := "Month interval must be '1' or '3'"),
      with
🧹 Nitpick comments (1)
dbschema/project.gel (1)

145-214: LGTM! Comprehensive update logic with proper scoping

The trigger correctly handles multiple update scenarios and properly scopes operations to the specific project (line 159: filter .container.id = __old__.id). The conditional logic appropriately handles:

  • Field deletions → cleanup reports without files
  • Period/range changes → selective deletion and insertion
  • Date-only changes → insertion of missing reports

The complexity is justified by the comprehensive business logic requirements.

Consider adding inline comments to document the different scenarios handled by each conditional branch for future maintainability:

      select
+     # Scenario 1: Required fields were deleted - cleanup empty reports
      if not exists __new__.mouStart
        or not exists __new__.mouEnd
        or not exists __new__.financialReportPeriod then (
...
+     # Scenario 2: Period type changed or date range shrunk - selective update
      else if __old__.financialReportPeriod ?!= __new__.financialReportPeriod
...
+     # Scenario 3: Date range expanded or shifted - add missing reports  
      else if newMouStart ?!= oldMouStart 
...
+     # Scenario 4: No relevant changes - no action needed
      ) else (
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5be235c and faef758.

📒 Files selected for processing (1)
  • dbschema/project.gel (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: Generate (head)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Clean
  • GitHub Check: lint
  • GitHub Check: Unit
  • GitHub Check: Generate (base)
🔇 Additional comments (3)
dbschema/project.gel (3)

126-143: LGTM! Proper NULL guard implementation

The trigger correctly implements the when clause to guard against NULL values for required fields, addressing the previous concern about runtime failures. The logic flow is clean and uses the helper functions appropriately.


322-335: LGTM! Proper duplicate prevention logic

The function correctly implements duplicate prevention by filtering out requested periods that already have existing reports. The use of distinct and array_unpack properly handles the array operations.


337-368: LGTM! Clean report insertion implementation

The function properly creates both financial and narrative reports with correct metadata and relationships. The use of datetime_of_statement() ensures consistency, and the union pattern cleanly combines both report types.

@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from faef758 to 68d60d7 Compare May 23, 2025 16:19
@bryanjnelson bryanjnelson linked an issue May 29, 2025 that may be closed by this pull request
@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from 68d60d7 to ac6823b Compare May 30, 2025 02:46
Copy link

@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: 5

♻️ Duplicate comments (2)
dbschema/project.gel (2)

204-208: Fix inconsistent function naming (duplicate occurrence)

Same naming inconsistency appears again in this branch.


304-306: 🛠️ Refactor suggestion

Add input validation for create_periodic_report_ranges function

The function should validate that monthInterval is a supported value and that the date parameters are valid.

  function create_periodic_report_ranges(startDate: cal::local_date, endDate: cal::local_date, 
    monthInterval: str) -> set of range<cal::local_date>
    using (
+     assert(startDate <= endDate, message := "Start date must be before or equal to end date"),
+     assert(monthInterval in {'1', '3'}, message := "Month interval must be '1' (monthly) or '3' (quarterly)"),
      with
🧹 Nitpick comments (2)
dbschema/project.gel (2)

343-368: Consider reducing code duplication in report creation

The financial and narrative report creation loops are nearly identical. While EdgeQL limitations may prevent full unification, consider extracting common metadata into a shared expression.

      with
+        commonMetadata := (
+          createdAt := datetime_of_statement(),
+          modifiedAt := datetime_of_statement(),
+          createdBy := assert_exists(global default::currentActor),
+          modifiedBy := assert_exists(global default::currentActor),
+          project := newProject,
+          projectContext := newProject.projectContext,
+          container := newProject,
+        ),
        financialReports := (for reportPeriod in array_unpack(requestedReportPeriodsForInsertion)
        union (
          insert default::FinancialReport {
-            createdAt := datetime_of_statement(),
-            modifiedAt := datetime_of_statement(),
-            createdBy := assert_exists(global default::currentActor),
-            modifiedBy := assert_exists(global default::currentActor),
-            project := newProject,
-            projectContext := newProject.projectContext,
-            container := newProject,
+            commonMetadata,
            period := reportPeriod,
          }
        )),
        narrativeReports := (for reportPeriod in array_unpack(requestedReportPeriodsForInsertion)
        union (
          insert default::NarrativeReport {
-            createdAt := datetime_of_statement(),
-            modifiedAt := datetime_of_statement(),
-            createdBy := assert_exists(global default::currentActor),
-            modifiedBy := assert_exists(global default::currentActor),
-            project := newProject,
-            projectContext := newProject.projectContext,
-            container := newProject,
+            commonMetadata,
            period := reportPeriod,
          }
        ))

193-197: Optimize deletion filter for better performance

The deletion logic filters reports by checking if their period is not in requestedReportPeriods. For large sets, this could be inefficient. Consider using a more direct approach.

-          deletedReports := (for report in reportsForDeletion 
-          union (
-            delete report
-            filter report.period not in requestedReportPeriods
-          ))
+          deletedReports := (
+            delete reportsForDeletion
+            filter reportsForDeletion.period not in requestedReportPeriods
+          )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 68d60d7 and ac6823b.

📒 Files selected for processing (2)
  • dbschema/periodic-report.gel (1 hunks)
  • dbschema/project.gel (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dbschema/periodic-report.gel
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: Analyze (javascript)

Comment on lines 134 to 135
interval := (select
if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3'),
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for financialReportPeriod values

The interval calculation assumes only Monthly (mapped to '1') or Quarterly (mapped to '3') values, but there's no validation that other enum values won't cause unexpected behavior.

-        interval := (select 
-          if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3'),
+        interval := (select 
+          if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' 
+          else if __new__.financialReportPeriod = default::ReportPeriod.Quarterly then '3'
+          else (assert(false, message := "Unsupported financial report period: " ++ <str>__new__.financialReportPeriod))),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interval := (select
if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3'),
interval := (
select
if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1'
else if __new__.financialReportPeriod = default::ReportPeriod.Quarterly then '3'
else (
assert(
false,
message := "Unsupported financial report period: " ++
<str>__new__.financialReportPeriod
)
)
),
🤖 Prompt for AI Agents
In dbschema/project.gel around lines 134 to 135, the interval calculation
assumes financialReportPeriod is either Monthly or Quarterly without validating
other enum values. Add validation logic to explicitly check if
financialReportPeriod is one of the expected values (Monthly or Quarterly) and
handle or reject any other values to prevent unexpected behavior. This can be
done by adding a conditional check or a validation step before the interval
assignment.

Comment on lines +318 to +343
additionalReportPeriodRange := (
select range(<cal::local_date>endDate, <cal::local_date>endDate, inc_upper := true)
)
select reportPeriodRanges union additionalReportPeriodRange
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unnecessary additional report period range

The additionalReportPeriodRange creates a zero-length range from endDate to endDate which serves no purpose and could cause confusion.

-        additionalReportPeriodRange := (
-          select range(<cal::local_date>endDate, <cal::local_date>endDate, inc_upper := true)
-        )
-      select reportPeriodRanges union additionalReportPeriodRange
+      select reportPeriodRanges
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
additionalReportPeriodRange := (
select range(<cal::local_date>endDate, <cal::local_date>endDate, inc_upper := true)
)
select reportPeriodRanges union additionalReportPeriodRange
select reportPeriodRanges
🤖 Prompt for AI Agents
In dbschema/project.gel around lines 318 to 321, remove the definition and usage
of additionalReportPeriodRange since it creates a zero-length range from endDate
to endDate that is unnecessary. Update the code to directly select
reportPeriodRanges without unioning the redundant additionalReportPeriodRange.

Comment on lines 161 to 162
interval := (
select (if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3')
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent conditional logic for interval calculation

The interval calculation logic differs between the insert and update triggers - the update trigger doesn't handle the case where financialReportPeriod might be null after the when clause conditions.

-        interval := (
-          select (if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3')
-        ),
+        interval := (
+          select (
+            if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' 
+            else if __new__.financialReportPeriod = default::ReportPeriod.Quarterly then '3'
+            else (assert(false, message := "Unsupported financial report period: " ++ <str>__new__.financialReportPeriod))
+          )
+        ),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interval := (
select (if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1' else '3')
interval := (
select (
if __new__.financialReportPeriod = default::ReportPeriod.Monthly then '1'
else if __new__.financialReportPeriod = default::ReportPeriod.Quarterly then '3'
else (assert(false, message := "Unsupported financial report period: " ++ <str>__new__.financialReportPeriod))
)
),
🤖 Prompt for AI Agents
In dbschema/project.gel around lines 161 to 162, the interval calculation uses
conditional logic that is inconsistent between insert and update triggers and
does not handle null values for financialReportPeriod in the update trigger.
Modify the update trigger's interval calculation to include a null check for
financialReportPeriod and ensure it matches the insert trigger's logic by
explicitly handling the null case and setting a default interval value
accordingly.

@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from ac6823b to 60348cd Compare May 30, 2025 02:54
- Handles periodic report date ranges expanding and shrinking
- Handles periodic report frequency changing
@bryanjnelson bryanjnelson force-pushed the 0933-periodic-report-trigger branch from 60348cd to 2f2b513 Compare June 6, 2025 20:22
Copy link

@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

♻️ Duplicate comments (1)
dbschema/project.gel (1)

340-343: Remove unnecessary additional report period range

The additionalReportPeriodRange creates a zero-length range from endDate to endDate which serves no purpose and could cause confusion.

Apply this diff:

-        additionalReportPeriodRange := (
-          select range(<cal::local_date>endDate, <cal::local_date>endDate, inc_upper := true)
-        )
-      select reportPeriodRanges union additionalReportPeriodRange
+      select reportPeriodRanges
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 60348cd and 2f2b513.

📒 Files selected for processing (2)
  • dbschema/periodic-report.gel (1 hunks)
  • dbschema/project.gel (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dbschema/periodic-report.gel
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: E2E Tests (neo4j 4/6)
  • GitHub Check: E2E Tests (neo4j 1/6)
  • GitHub Check: E2E Tests (neo4j 3/6)
  • GitHub Check: E2E Tests (neo4j 5/6)
  • GitHub Check: E2E Tests (neo4j 2/6)
  • GitHub Check: E2E Tests (neo4j 6/6)
  • GitHub Check: Unit
  • GitHub Check: Generate (head)
  • GitHub Check: Generate (base)
  • GitHub Check: lint
  • GitHub Check: Clean
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
dbschema/project.gel (4)

156-235: Complex but well-structured trigger logic

The update trigger correctly handles all the different scenarios for MOU date and financial report period changes. The conditional logic properly manages report lifecycle and the function calls match the defined signatures.


346-359: Clean implementation for avoiding duplicate reports

The function correctly identifies which report periods need to be created by filtering out existing ones. The use of distinct and proper filtering logic ensures no duplicates.


361-397: Well-implemented report insertion function

The function correctly handles the creation of both narrative and progress reports, properly avoiding duplicates and setting all required fields.


399-432: Correct implementation for financial report insertion

The function properly handles both monthly and quarterly financial report creation based on the project's financialReportPeriod setting. The conditional logic and field assignments are correct.

Comment on lines +144 to +152
financialReports := Project::insert_financial_reports(array_agg(financialReportRanges), __new__)
select financialReports
) else if __new__.financialReportPeriod = default::ReportPeriod.Quarterly then (
select Project::insert_financial_reports(array_agg(reportRanges), __new__)
) else (
select <default::FinancialReport>{}
)
),
insertedNarrativeAndProgressReports := Project::insert_narrative_and_progress_reports(array_agg(reportRanges), __new__)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Function signature mismatch will cause runtime errors

The function calls in this trigger don't match the defined function signatures:

  • insert_financial_reports is called with 2 parameters but defined to expect 4
  • insert_narrative_and_progress_reports is called with 2 parameters but defined to expect 3

Apply this diff to fix the function calls:

-            financialReports := Project::insert_financial_reports(array_agg(financialReportRanges), __new__)
+            financialReports := Project::insert_financial_reports(__new__, (select <default::FinancialReport>{}), array_agg(financialReportRanges), (select <range<cal::local_date>>{}))
-            select Project::insert_financial_reports(array_agg(reportRanges), __new__)
+            select Project::insert_financial_reports(__new__, (select <default::FinancialReport>{}), (select <range<cal::local_date>>{}), array_agg(reportRanges))
-        insertedNarrativeAndProgressReports := Project::insert_narrative_and_progress_reports(array_agg(reportRanges), __new__)
+        insertedNarrativeAndProgressReports := Project::insert_narrative_and_progress_reports(__new__, array_agg(reportRanges), (select <default::PeriodicReport>{}))

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In dbschema/project.gel around lines 144 to 152, the calls to
insert_financial_reports and insert_narrative_and_progress_reports have
incorrect argument counts that do not match their function definitions, causing
runtime errors. Update the insert_financial_reports calls to pass four
parameters as defined, and modify the insert_narrative_and_progress_reports call
to include the required third argument, ensuring all function calls match their
signatures exactly.

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.

Gel - PeriodicReport - Triggers
2 participants