Skip to content

Feature/784 new trigger endpoint #795

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 23 commits into
base: main
Choose a base branch
from

Conversation

eskebab
Copy link
Contributor

@eskebab eskebab commented Apr 9, 2025

This will introduce the new trigger endpoint which should be called via cronjob in Kubernetes, scheduled to be called every minute of the hour, without exclusion.

Description

The database function that gets new sms notifications with status 'New' must now filter its result based on the order's sending time policy set. The existing trigger endpoint will get results having null or Daytime value, while the new endpoint will get sms notifications related to orders with sending time policy anytime

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features
    • Enhanced SMS notification scheduling with configurable sending time policies, enabling dispatch during designated daytime or anytime periods.
    • Added new endpoints allowing users to trigger SMS notifications for specific sending time policies, providing greater control over message timing.
  • Bug Fixes
    • Improved filtering of SMS notifications to respect the specified sending time policy.
  • Tests
    • Expanded test coverage for SMS notification retrieval and sending, including scenarios for different sending time policies.

Copy link

coderabbitai bot commented Apr 9, 2025

📝 Walkthrough

Walkthrough

This pull request updates multiple components of the SMS notification system to support sending time policies. The changes introduce a new parameter, sendingTimePolicy, with a default value of SendingTimePolicy.Daytime, into various method signatures in interfaces, service classes, and repository implementations. Additionally, the SQL migration scripts have been modified to filter results based on the sending time policy, and the API endpoints have been updated to offer distinct routes for daytime and anytime notifications. Test cases and utility methods have also been adapted to accommodate the new parameter.

Changes

File(s) Change Summary
src/Altinn.Notifications.Core/Persistence/ISmsNotificationRepository.cs
src/Altinn.Notifications.Core/Services/Interfaces/ISmsNotificationService.cs
src/Altinn.Notifications.Core/Services/SmsNotificationService.cs
src/Altinn.Notifications.Persistence/Repository/SmsNotificationRepository.cs
Updated method signatures to include the sendingTimePolicy parameter (defaulting to SendingTimePolicy.Daytime). Repository methods now pass this parameter in SQL queries to filter SMS notifications accordingly.
src/Altinn.Notifications/Controllers/TriggerController.cs Renamed existing SMS notification endpoint to Trigger_SendSmsNotificationsDaytime with route sendsmsdaytime and added a new endpoint Trigger_SendSmsNotificationsAnytime with route sendsmsanytime, both passing the appropriate sending time policy to the service.
src/Altinn.Notifications.Persistence/Migration/FunctionsAndProcedures/getsmsstatusnewupdatestatus.sql
src/Altinn.Notifications.Persistence/Migration/v0.40/01-functions-and-procedures.sql
Modified the SQL function notifications.getsms_statusnew_updatestatus to accept a new integer parameter _sendingtimepolicy for filtering SMS notifications by sending time policy. The migration script also adds multiple functions and procedures for notification management, including order cancellation, recipient retrieval, status updates, and insertion procedures.
test/Altinn.Notifications.IntegrationTests/Notifications.Persistence/SmsNotificationRepositoryTests.cs
test/Altinn.Notifications.IntegrationTests/Utils/PostgreUtil.cs
test/Altinn.Notifications.IntegrationTests/Utils/TestdataUtil.cs
test/Altinn.Notifications.Tests/Notifications.Core/TestingServices/SmsNotificationServiceTests.cs
test/Altinn.Notifications.Tests/Notifications/TestingControllers/TriggerControllerTests.cs
Added a new integration test for retrieving SMS notifications with a sending time policy. Updated utility methods to support the sending time policy parameter. Modified unit tests for the SMS notification service and trigger controller to accommodate the updated method signatures with the sending time policy parameter.

Possibly related PRs

  • Feature/783 add sendingtimepolicy column #785: The changes in the main PR, which involve modifying the GetNewNotifications method to include a sendingTimePolicy parameter, are related to the retrieved PR as both involve the SendingTimePolicy concept, specifically in how it is integrated into notification handling, including the addition of a property in the IBaseNotificationOrder interface.

Suggested reviewers

  • tba76
  • Ahmed-Ghanam
  • SandGrainOne

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4cfa9f7 and 9f8d9c4.

📒 Files selected for processing (1)
  • src/Altinn.Notifications.Persistence/Repository/SmsNotificationRepository.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Altinn.Notifications.Persistence/Repository/SmsNotificationRepository.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (csharp)
  • GitHub Check: Build, test & analyze

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

@eskebab eskebab marked this pull request as ready for review April 9, 2025 11:13
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

🧹 Nitpick comments (3)
src/Altinn.Notifications.Persistence/Migration/FunctionsAndProcedures/getsmsstatusnewupdatestatus.sql (1)

25-65: LGTM: SQL function correctly extended with SendingTimePolicy filtering.

The new function overload properly implements the filtering based on sending time policy with appropriate handling of NULL values. The detailed comment at the end is helpful for future maintainers.

Note that the original function without parameters is kept, which may be intentional for backward compatibility, but consider adding a deprecation comment if it should no longer be used.

Consider adding a deprecation comment to the original function if it should no longer be used:

+-- This function is kept for backward compatibility and may be removed in future versions.
+-- Use notifications.getsms_statusnew_updatestatus(integer) instead.
 CREATE OR REPLACE FUNCTION notifications.getsms_statusnew_updatestatus()
test/Altinn.Notifications.IntegrationTests/Utils/TestdataUtil.cs (2)

39-57: Method name contains a typo.

The method name GeOrderAndSmsAnytimeNotification is missing a 't' and should be GetOrderAndSmsAnytimeNotification.

-public static (NotificationOrder Order, SmsNotification Notification) GeOrderAndSmsAnytimeNotification()
+public static (NotificationOrder Order, SmsNotification Notification) GetOrderAndSmsAnytimeNotification()

39-57: Consider refactoring to reduce code duplication.

There's significant duplication between GeOrderAndSmsAnytimeNotification and GetOrderAndSmsNotification. Consider refactoring to have the first method call the second with appropriate parameters.

-public static (NotificationOrder Order, SmsNotification Notification) GeOrderAndSmsAnytimeNotification()
+public static (NotificationOrder Order, SmsNotification Notification) GetOrderAndSmsAnytimeNotification()
 {
-    NotificationOrder order = NotificationOrder_SmsTemplate_OneRecipient();
-    order.Id = Guid.NewGuid();
-    var recipient = order.Recipients[0];
-    SmsAddressPoint? addressPoint = recipient.AddressInfo.Find(a => a.AddressType == AddressType.Sms) as SmsAddressPoint;
-    var smsNotification = new SmsNotification()
-    {
-        Id = Guid.NewGuid(),
-        OrderId = order.Id,
-        RequestedSendTime = DateTime.UtcNow,
-        Recipient = new()
-        {
-            MobileNumber = addressPoint!.MobileNumber,
-        },
-        SendResult = new(SmsNotificationResultType.New, DateTime.UtcNow)
-    };
-    return (order, smsNotification);
+    var (order, notification) = GetOrderAndSmsNotification(SendingTimePolicy.Anytime);
+    notification.RequestedSendTime = DateTime.UtcNow;
+    return (order, notification);
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b46365 and 8fcfb3e.

📒 Files selected for processing (12)
  • src/Altinn.Notifications.Core/Persistence/ISmsNotificationRepository.cs (1 hunks)
  • src/Altinn.Notifications.Core/Services/Interfaces/ISmsNotificationService.cs (2 hunks)
  • src/Altinn.Notifications.Core/Services/SmsNotificationService.cs (1 hunks)
  • src/Altinn.Notifications.Persistence/Migration/FunctionsAndProcedures/getsmsstatusnewupdatestatus.sql (1 hunks)
  • src/Altinn.Notifications.Persistence/Migration/v0.40/01-functions-and-procedures.sql (1 hunks)
  • src/Altinn.Notifications.Persistence/Repository/SmsNotificationRepository.cs (2 hunks)
  • src/Altinn.Notifications/Controllers/TriggerController.cs (1 hunks)
  • test/Altinn.Notifications.IntegrationTests/Notifications.Persistence/SmsNotificationRepositoryTests.cs (1 hunks)
  • test/Altinn.Notifications.IntegrationTests/Utils/PostgreUtil.cs (2 hunks)
  • test/Altinn.Notifications.IntegrationTests/Utils/TestdataUtil.cs (2 hunks)
  • test/Altinn.Notifications.Tests/Notifications.Core/TestingServices/SmsNotificationServiceTests.cs (2 hunks)
  • test/Altinn.Notifications.Tests/Notifications/TestingControllers/TriggerControllerTests.cs (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
test/Altinn.Notifications.IntegrationTests/Utils/TestdataUtil.cs (2)
src/Altinn.Notifications.Core/Models/Orders/NotificationOrder.cs (4)
  • NotificationOrder (11-133)
  • NotificationOrder (56-80)
  • NotificationOrder (85-88)
  • NotificationOrder (101-104)
src/Altinn.Notifications.Core/Models/Notification/SmsNotification.cs (1)
  • SmsNotification (9-41)
src/Altinn.Notifications.Persistence/Repository/SmsNotificationRepository.cs (2)
src/Altinn.Notifications.Core/Persistence/ISmsNotificationRepository.cs (4)
  • Task (20-20)
  • Task (27-27)
  • Task (34-34)
  • Task (43-43)
src/Altinn.Notifications.Core/Services/SmsNotificationService.cs (4)
  • Task (44-63)
  • Task (66-77)
  • Task (80-83)
  • Task (94-106)
test/Altinn.Notifications.IntegrationTests/Utils/PostgreUtil.cs (3)
src/Altinn.Notifications.Core/Persistence/ISmsNotificationRepository.cs (4)
  • Task (20-20)
  • Task (27-27)
  • Task (34-34)
  • Task (43-43)
test/Altinn.Notifications.IntegrationTests/Utils/TestdataUtil.cs (6)
  • NotificationOrder (12-37)
  • NotificationOrder (39-57)
  • NotificationOrder (59-79)
  • NotificationOrder (84-118)
  • NotificationOrder (123-155)
  • TestdataUtil (10-156)
src/Altinn.Notifications.Core/Models/Orders/NotificationOrder.cs (4)
  • NotificationOrder (11-133)
  • NotificationOrder (56-80)
  • NotificationOrder (85-88)
  • NotificationOrder (101-104)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build, test & analyze
🔇 Additional comments (28)
src/Altinn.Notifications.Core/Services/Interfaces/ISmsNotificationService.cs (2)

1-1: Appropriate import addition for the SendingTimePolicy enum.

The import statement for the Enums namespace is needed for the SendingTimePolicy parameter.


29-29: Interface method updated to support filtering by sending time policy.

The method signature has been updated to include a SendingTimePolicy parameter, which aligns with the PR objective of creating a separate trigger endpoint for SMS notifications with different sending time policies.

test/Altinn.Notifications.Tests/Notifications.Core/TestingServices/SmsNotificationServiceTests.cs (4)

190-191: Updated mock to account for the new SendingTimePolicy parameter.

The mock setup correctly uses It.IsAny() to accommodate the interface change.


212-213: Updated mock setup for the SendingTimePolicy parameter.

The mock setup correctly uses It.IsAny() to match the updated interface.


225-225: Test method doesn't specify SendingTimePolicy parameter.

Similar to the previous test, this calls SendNotifications() without parameters but should work with the default parameter value.


200-200:

✅ Verification successful

Test method doesn't specify SendingTimePolicy parameter.

The test calls SendNotifications() without parameters, but should still work as the implementation provides a default value of SendingTimePolicy.Daytime.


🏁 Script executed:

#!/bin/bash
# Check SmsNotificationService implementation to confirm default parameter exists
grep -A3 "public async Task SendNotifications" src/Altinn.Notifications.Core/Services/SmsNotificationService.cs

Length of output: 341


Defaults Verified – No Test Change Required

The implementation of SendNotifications in SmsNotificationService confirms that the default parameter (SendingTimePolicy.Daytime) is provided. Calling the method without parameters, as done in the test, is correct.

src/Altinn.Notifications.Core/Services/SmsNotificationService.cs (2)

66-66: Method implementation updated with SendingTimePolicy parameter and default value.

The method now accepts a SendingTimePolicy parameter with a default value of SendingTimePolicy.Daytime, ensuring backward compatibility with existing code calling this method without parameters.


68-68: Repository call updated to pass the SendingTimePolicy parameter.

The GetNewNotifications call now correctly passes the sendingTimePolicy parameter to the repository layer.

test/Altinn.Notifications.Tests/Notifications/TestingControllers/TriggerControllerTests.cs (6)

5-5: Added import for SendingTimePolicy enum.

The import statement for the Enums namespace is correctly added to support the SendingTimePolicy parameter in the tests.


25-25: Updated mock setup to include SendingTimePolicy parameter.

The mock setup for the SmsNotificationService now correctly uses It.IsAny() to match the updated interface.


43-43: Method name changed from Trigger_SendSmsNotifications to Trigger_SendSmsNotificationsDaytime.

The test now calls a different controller method that likely filters notifications by daytime policy, which aligns with the PR objective.


46-46: Verification updated to include SendingTimePolicy parameter.

The verification now correctly checks the call to SendNotifications with It.IsAny().


58-58: Updated method call to Trigger_SendSmsNotificationsDaytime.

Consistent with the change in the first test, this test also calls the updated controller method.


61-61: Verification updated to include SendingTimePolicy parameter.

The verification correctly checks the call to SendNotifications with It.IsAny().

test/Altinn.Notifications.IntegrationTests/Utils/PostgreUtil.cs (2)

1-1: LGTM: Required using directive added for SendingTimePolicy enum.

The new using directive is correctly added to support the SendingTimePolicy enum parameter in the modified method.


97-99: LGTM: Method correctly enhanced to support SendingTimePolicy filtering.

The method signature has been appropriately updated to accept an optional SendingTimePolicy parameter, and the parameter is correctly passed to TestdataUtil.GetOrderAndSmsNotification, allowing tests to create orders with specific sending time policies.

test/Altinn.Notifications.IntegrationTests/Notifications.Persistence/SmsNotificationRepositoryTests.cs (1)

94-110: LGTM: Well-structured test for the new SendingTimePolicy.Anytime functionality.

The new test method follows the same pattern as existing tests and properly verifies that the SmsNotificationRepository correctly retrieves notifications when filtering by the SendingTimePolicy.Anytime value.

src/Altinn.Notifications.Core/Persistence/ISmsNotificationRepository.cs (1)

25-27: LGTM: Method signature and documentation updated correctly.

The GetNewNotifications method has been properly enhanced to accept a SendingTimePolicy parameter with a sensible default value of SendingTimePolicy.Daytime. The XML documentation clearly explains the parameter's purpose.

src/Altinn.Notifications.Persistence/Repository/SmsNotificationRepository.cs (3)

21-21: SQL constant name accurately represents its purpose.

The constant name _getNewSmsNoticationsSqlWithSendingTimePolicyParameter clearly indicates that it expects a sending time policy parameter. The SQL query itself uses a parameter placeholder ($1) for filtering, which aligns with the PR objectives.


91-97: Well-documented method parameters and purpose.

The method documentation clearly explains the purpose of the method, the meaning of the new parameter, and what it returns. This makes the code more maintainable and helps other developers understand how to use the method.


100-102: Proper implementation of parameterized query.

The code correctly uses the updated SQL constant and properly adds the sending time policy parameter to the query. This ensures that notifications are filtered based on the specified sending time policy as required.

src/Altinn.Notifications/Controllers/TriggerController.cs (3)

59-67: Route duplication maintains backward compatibility.

The method now has two route attributes: the original sendsms and the new, more descriptive sendsmsdaytime. This approach ensures backward compatibility while also providing a more descriptive route for new API consumers.


74-76: Explicit sending time policy parameter.

The code now explicitly passes Core.Enums.SendingTimePolicy.Daytime to the service method, clarifying the intent of this endpoint and implementing the requirement to filter based on sending time policy.


78-89: New endpoint for anytime SMS notifications.

The new endpoint Trigger_SendSmsNotificationsAnytime with route sendsmsanytime properly implements the requirement to provide a separate endpoint for SMS notifications that can be sent at any time. The implementation correctly passes Core.Enums.SendingTimePolicy.Anytime to the service method.

test/Altinn.Notifications.IntegrationTests/Utils/TestdataUtil.cs (1)

12-37: Method enhancement to support sending time policy.

The GetOrderAndSmsNotification method has been correctly enhanced to accept an optional sending time policy parameter, allowing for more flexible test data creation. The implementation properly assigns the policy to the order when provided.

src/Altinn.Notifications.Persistence/Migration/v0.40/01-functions-and-procedures.sql (3)

432-464: Well-implemented SQL function to support sending time policy filtering.

The SQL function getsms_statusnew_updatestatus has been properly implemented to accept a sending time policy parameter. The function correctly filters records based on the provided policy and handles the case where the policy is null by treating it as the default Daytime policy (value 2).


466-471: Clear documentation of SQL function behavior.

The comment on the function clearly explains its purpose, parameters, and behavior, including important information about how null values are treated. This documentation is valuable for maintaining the code in the future.


582-606: Function overloading provides flexibility while maintaining backward compatibility.

The overloaded insertorder function allows for specifying a sending time policy while maintaining backward compatibility with existing code that doesn't provide this parameter. This is a good approach for extending functionality.

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

🧹 Nitpick comments (3)
src/Altinn.Notifications.Persistence/Migration/v0.40/01-functions-and-procedures.sql (3)

407-432: Legacy SMS Status Update in notifications.getsms_statusnew_updatestatus
This legacy function is maintained for backward compatibility. Consider adding clear documentation and possibly a deprecation note if you plan to remove it in a future release.


434-467: New SMS Status Update with Sending Time Policy in notifications.getsms_statusnew_updatestatus(integer)
This new function extends the SMS status update by accepting a _sendingtimepolicy parameter. The logic at line 463—using the condition
  WHERE o.sendingtimepolicy = _sendingtimepolicy OR (o.sendingtimepolicy IS NULL AND _sendingtimepolicy = 2)—ensures that if the order’s policy is null, it defaults to the ‘Daytime’ setting (assumed to be represented by 2).

Suggestions:
• Add inline documentation (or a comment block) at the beginning of the function to clearly define the expected integer values and their meaning (e.g., which value represents Daytime vs. Anytime).
• Consider whether additional input validation is needed for _sendingtimepolicy to prevent unexpected behavior if an invalid value is passed.


584-608: Overloaded Order Insertion with Sending Time Policy in notifications.insertorder
The new overloaded version now captures an additional _sendingtimepolicy parameter and inserts it into the orders table. This supports the new functionality for filtering notifications by sending time policy.

Suggestions:
• Verify that all callers of the insertorder function are updated to supply the _sendingtimepolicy parameter as needed.
• Consider adding input validation or a defaulting mechanism (if applicable) to handle cases where the sending time policy is not explicitly provided.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 907fc8b and 01b104e.

📒 Files selected for processing (2)
  • src/Altinn.Notifications.Persistence/Migration/FunctionsAndProcedures/getsmsstatusnewupdatestatus.sql (2 hunks)
  • src/Altinn.Notifications.Persistence/Migration/v0.40/01-functions-and-procedures.sql (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Altinn.Notifications.Persistence/Migration/FunctionsAndProcedures/getsmsstatusnewupdatestatus.sql
🔇 Additional comments (16)
src/Altinn.Notifications.Persistence/Migration/v0.40/01-functions-and-procedures.sql (16)

3-64: Cancellation Logic and Order Retrieval in notifications.cancelorder
The function correctly retrieves the order record and handles the “not found” case. However, note the condition on line 48 where the check combines the requested send time and processed status with an OR. Please verify that this logic (i.e. allowing cancellation to be denied when either the order’s send time is too near or its status is not 'Registered') exactly matches the intended business rules.


67-85: Email Recipients Retrieval in notifications.getemailrecipients_v2
This function straightforwardly retrieves email recipient details using a subquery to obtain the internal order id. The implementation is clear and consistent.


87-139: Email Status Update in notifications.getemails_statusnew_updatestatus
The function manages the email timeout and resets it if needed before updating emails marked as ‘New’ to ‘Sending’. The use of a conditional RETURN QUERY and subsequent update is well structured.


142-173: Email Summary Retrieval in notifications.getemailsummary_v2
This function returns a summary of email notifications using a primary query followed by a fallback query if no rows are found. Please double-check that the use of two RETURN QUERY blocks (and the IF NOT FOUND check) behaves as expected in your PL/pgSQL context.


174-205: Metrics Aggregation in notifications.getmetrics
The aggregation of order, email, and SMS metrics is implemented correctly. For optimal performance on large datasets, ensure that appropriate indexes exist on the date/time columns (e.g. requestedsendtime).


207-283: Order Status and Notification Counts in notifications.getorder_includestatus_v4
The function effectively aggregates both email and SMS counts while retrieving order details. Conversion of JSON fields and conditional null handling for IgnoreReservation is appropriate.


285-347: Order Chain Tracking in notifications.get_orders_chain_tracking
The function checks for the existence of a matching order chain before returning tracking details. The error handling (i.e. returning an empty result) is a good practice for idempotency.


369-386: Updating Past Send Time in notifications.getorders_pastsendtime_updatestatus
The query updates orders that have reached or passed their send time (with a one-minute interval) and limits the update to 50 rows. Please confirm that this fixed limit is appropriate and that any remaining orders are handled by subsequent invocations of the trigger.


387-406: SMS Recipients Retrieval in notifications.getsmsrecipients_v2
A simple, clear extraction of SMS recipient information based on the order identifier. The variable naming and use of subquery for order id are consistent with the rest of the codebase.


476-507: SMS Summary Retrieval in notifications.getsmssummary_v2
This function mirrors the approach used in the email summary by first attempting a join and then providing a fallback query if no results are found. The structure is clear and should work as intended provided that the order and creator parameters are correctly set.


508-556: Inserting Email Notifications in notifications.insertemailnotification
The procedure takes all necessary parameters and performs an INSERT into the email notifications table with proper type casting. The use of a subquery to retrieve the order id is consistent with earlier functions.


557-565: Inserting Email Text in notifications.insertemailtext
The implementation is straightforward and correctly inserts email content into the designated table.


568-583: Basic Order Insertion in notifications.insertorder (First Overload)
This function handles order insertion and returns the generated order id. The implementation follows standard practices and appears correct.


611-640: Order Chain Insertion in notifications.insertorderchain
This procedure correctly inserts a new order chain into the database. The column mapping and ordering are correct.


642-689: Inserting SMS Notifications in notifications.insertsmsnotification
The procedure performs an INSERT into the SMS notifications table with proper data type conversions. The implementation is consistent with similar procedures in this script.


691-700: Email Status Update in notifications.updateemailstatus
This procedure is responsible for updating the status, result time, and operation id of email notifications. The SQL is clear and adheres to expected standards.

Comment on lines 91 to 97
/// <summary>
/// Retrieves and updates status on all sms that have the status new
/// Calls database function with sendingTimePolicy parameter to filter result based on sending schedule of choice
/// </summary>
/// <param name="sendingTimePolicy">Filtered by the sending time policy set on the order related to the notification row</param>
/// <returns>List of rows read and updated from the database</returns>
public async Task<List<Sms>> GetNewNotifications(SendingTimePolicy sendingTimePolicy = SendingTimePolicy.Daytime)
Copy link
Contributor

Choose a reason for hiding this comment

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

We use /// <inheritdoc/> to reduce duplication, improve maintainability, keep documentation consistent and reduce code size

@@ -18,7 +18,7 @@ public class SmsNotificationRepository : ISmsNotificationRepository
{
private readonly NpgsqlDataSource _dataSource;

private const string _getNewSmsNotificationsSql = "select * from notifications.getsms_statusnew_updatestatus()";
private const string _getNewSmsNoticationsSqlWithSendingTimePolicyParameter = "select * from notifications.getsms_statusnew_updatestatus($1)"; // (_sendingtimepolicy)
Copy link
Contributor

Choose a reason for hiding this comment

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

This is a verbose name, and we could keep using the name _getNewSmsNotificationsSql. Anyway it is up to you to decide which one to use.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I did this because I'm now calling an overload function. Which I think is important to keep in mind. But it could have been an extra comment.

Comment on lines +49 to +57
SELECT u.alternateid,
st.sendernumber,
u.mobilenumber,
CASE WHEN u.customizedbody IS NOT NULL AND u.customizedbody <> '' THEN u.customizedbody ELSE st.body END AS body
FROM updated u
JOIN notifications.smstexts st ON u._orderid = st._orderid
JOIN notifications.orders o ON st._orderid = o._id
-- sendingTimePolicy = 2 is equal to daytime, the default choice when null
WHERE o.sendingtimepolicy = _sendingtimepolicy OR (o.sendingtimepolicy IS NULL AND _sendingtimepolicy = 2);
Copy link
Contributor

Choose a reason for hiding this comment

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

We can use the following for clearer intent:

SELECT u.alternateid, 
       st.sendernumber, 
       u.mobilenumber, 
       CASE WHEN u.customizedbody IS NOT NULL AND u.customizedbody <> '' THEN u.customizedbody ELSE st.body END AS body
FROM updated u
JOIN notifications.smstexts st ON u._orderid = st._orderid
JOIN notifications.orders o ON st._orderid = o._id 
WHERE
    CASE
        WHEN _sendingtimepolicy = 1 THEN
            o.sendingtimepolicy = 1
        WHEN _sendingtimepolicy = 2 THEN
            (o.sendingtimepolicy = 2 OR o.sendingtimepolicy IS NULL)
    END;

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.

2 participants