Skip to content
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

Feat/set recipientname as messsage recipient #696

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

axely123
Copy link
Contributor

@axely123 axely123 commented Feb 12, 2025

Description

The recipientName in the notification templates should be the name of the message recipient and not the notification recipient. This PR adds logic that replaces the recipientName in the notification content to the message recipient.

The limitation that RecipientOverride does not work with email or phone number when using notification template or a custom template that uses recipientName is now removed. This limitation existed because the recipientName could not be looked up for an email or a phone number of which the notification recipient could be. The recipientName is now the message recipient, which is always either an organization or person so no limitation is needed.

This PR also changes the notification template texts to reflect the change that recipientName is now the message recipient and not the notification recipient.

User documentation update PR: Altinn/altinn-studio-docs#2008

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

    • Notifications now automatically include personalized recipient names in message content.
  • Bug Fixes

    • Improved handling of valid phone number and email inputs for custom recipient configurations, ensuring notifications process successfully.
  • Chores

    • Updated notification templates for improved consistency across multiple languages.
    • Streamlined internal validation processes to enhance overall notification delivery performance.
    • Removed outdated error messages related to recipient overrides for better clarity in error handling.

Ytterås added 5 commits February 12, 2025 12:56
…oes not work with notification templates or with custom templates that use $recipientName$
…ecipientName$ is now the message recipient and not the notification recipient.
…tOverride limitations for email and number
Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

📝 Walkthrough

Walkthrough

This pull request updates the correspondence notification system by modifying test expectations, revising error codes, and altering recipient override validations. The tests now expect successful (HTTP 200) responses with valid data. Additionally, asynchronous handling and personalization of notification content have been introduced. A new migration updates the database schema and notification template configurations.

Changes

File Change Summary
Test/Altinn.Correspondence.Tests/.../CorrespondenceNotificationTests.cs Renamed test methods and updated assertions from expecting BadRequest to OK; inline data now uses valid phone numbers/email inputs.
src/Altinn.Correspondence.Application/Errors.cs Removed three error declarations and reassigned the error code for MissingRecipientsForRecipientOverride from 3017 to 3015.
src/Altinn.Correspondence.Application/Helpers/InitializeCorrespondenceHelper.cs Removed recipient override validation checks related to custom notification templates and recipient name tags.
src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs Updated CreateNotifications to be asynchronous with a CancellationToken and added SetRecipientNameOnNotificationContent to personalize notification content.
src/.../Migrations/20250214083302_ChangedNotificationTemplate.{Designer,cs} Introduced a new migration that updates notification template schema and content, including SQL updates for multi-language fields.

Possibly related PRs

Suggested labels

kind/enhancement, kind/feature-request

Suggested reviewers

  • Ceredron

📜 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 bddefee and ab99b82.

📒 Files selected for processing (3)
  • Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceNotificationTests.cs (3 hunks)
  • src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs (4 hunks)
  • src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.cs
  • src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (4)
Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceNotificationTests.cs (4)

598-599: LGTM! Valid phone number format used in test data.

The test data now uses a properly formatted phone number with country code.


631-632: LGTM! Valid phone number format used in test data.

The test data now uses a properly formatted phone number with country code.


627-627: LGTM! Test expectations updated to match new behavior.

The assertions now correctly expect HTTP 200 OK responses, reflecting that phone numbers and email addresses are now valid for recipient overrides.

Also applies to: 663-663


659-661:

❓ Verification inconclusive

Test coverage added for message recipient name in templates.

The test now verifies that the notification templates can use $correspondenceRecipientName$ tag, which aligns with the PR objective to use message recipient's name instead of notification recipient's name.

Let's verify if this is the only place where the tag is used:


🏁 Script executed:

#!/bin/bash
# Search for other usages of the correspondenceRecipientName tag
rg -i 'correspondenceRecipientName'

Length of output: 5230


Token Usage Consistency in Notification Templates

The added test effectively verifies that when either number or email is provided, the notification template correctly incorporates the $correspondenceRecipientName$ tag. This aligns with the PR objective to use the message recipient’s name rather than the notification recipient’s name.

Additional searches confirm that this token is also used in:

  • The production substitution logic within src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs
  • The migration templates in src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.cs

Please ensure that any future changes to the token or its handling remain synchronized across these areas.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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. (Beta)
  • @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.

@axely123 axely123 linked an issue Feb 12, 2025 that may be closed by this pull request
2 tasks
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceNotificationTests.cs (1)

666-861: Add test coverage for recipient name content verification.

While the current tests comprehensively cover the recipient lookup scenarios, consider adding test cases to verify that the correct recipient name is actually used in the notification content. This would directly validate the main objective of this PR.

Example test case to add:

+[Fact]
+public async Task Correspondence_CustomRecipient_UsesCorrectRecipientNameInNotification()
+{
+    // Arrange
+    var recipient = $"{UrnConstants.OrganizationNumberAttribute}:991825827";
+    var expectedRecipientName = "Test Recipient";
+    var customRecipients = new List<CustomNotificationRecipientExt>()
+    {
+        new CustomNotificationRecipientExt()
+        {
+            RecipientToOverride = recipient,
+            Recipients = new List<NotificationRecipientExt>()
+            {
+                new NotificationRecipientExt()
+                {
+                    EmailAddress = "[email protected]",
+                    Name = expectedRecipientName
+                }
+            }
+        }
+    };
+    
+    var payload = new CorrespondenceBuilder()
+        .CreateCorrespondence()
+        .WithRecipients([recipient])
+        .WithNotificationTemplate(NotificationTemplateExt.CustomMessage)
+        .WithNotificationChannel(NotificationChannelExt.Email)
+        .WithEmailContent()
+        .WithCustomNotificationRecipients(customRecipients)
+        .Build();
+
+    // Capture the actual notification content
+    NotificationOrderRequest? capturedRequest = null;
+    var mockNotificationService = new Mock<IAltinnNotificationService>();
+    mockNotificationService
+        .Setup(x => x.CreateNotification(It.IsAny<NotificationOrderRequest>(), It.IsAny<CancellationToken>()))
+        .Callback<NotificationOrderRequest, CancellationToken>((req, _) => capturedRequest = req)
+        .ReturnsAsync(new NotificationOrderRequestResponse { OrderId = Guid.NewGuid() });
+
+    var testFactory = new UnitWebApplicationFactory(services =>
+    {
+        services.AddSingleton(mockNotificationService.Object);
+    });
+    var senderClient = testFactory.CreateSenderClient();
+
+    // Act
+    var response = await senderClient.PostAsJsonAsync("correspondence/api/v1/correspondence", payload, _responseSerializerOptions);
+
+    // Assert
+    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+    Assert.NotNull(capturedRequest);
+    Assert.Contains(expectedRecipientName, capturedRequest.NotificationContent);
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7a3664 and eb39a1b.

📒 Files selected for processing (6)
  • Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceNotificationTests.cs (3 hunks)
  • src/Altinn.Correspondence.Application/Errors.cs (1 hunks)
  • src/Altinn.Correspondence.Application/Helpers/InitializeCorrespondenceHelper.cs (0 hunks)
  • src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs (4 hunks)
  • src/Altinn.Correspondence.Persistence/Migrations/20240927122054_add_Notification_templates.cs (1 hunks)
  • src/Altinn.Correspondence.Persistence/Migrations/20250129072844_update_notification_templates.cs (1 hunks)
💤 Files with no reviewable changes (1)
  • src/Altinn.Correspondence.Application/Helpers/InitializeCorrespondenceHelper.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (6)
src/Altinn.Correspondence.Persistence/Migrations/20250129072844_update_notification_templates.cs (1)

13-40: LGTM! The notification templates have been updated consistently across all languages.

The changes correctly implement the new format using $recipientName$ placeholder and maintain consistency in punctuation and phrasing across all languages.

Run the following script to verify the notification templates:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Description: Verify the notification templates in the database.

# Test: Check if the notification templates have been updated correctly.
# Expect: All templates should use the $recipientName$ placeholder.
psql -d correspondence -c "SELECT \"Language\", \"EmailBody\", \"ReminderEmailBody\", \"SmsBody\", \"ReminderSmsBody\" FROM correspondence.\"NotificationTemplates\" WHERE \"Template\" = 1;"

Length of output: 272


Reminder: Manual Verification Required for Database Notification Templates

The shell script output indicates that the psql command was not found in the current environment, so we couldn’t verify the database content automatically. Please manually run the query in an environment where PostgreSQL’s CLI is available to ensure that all notification templates correctly use the $recipientName$ placeholder.

src/Altinn.Correspondence.Persistence/Migrations/20240927122054_add_Notification_templates.cs (1)

36-115: LGTM! The notification templates table is created with correct structure and initial data.

The changes correctly:

  • Create the table with all necessary columns
  • Insert templates for different languages (no, en, nn) and recipient types
  • Use consistent placeholders ($recipientName$, $sendersName$) across all templates
src/Altinn.Correspondence.Application/Errors.cs (1)

71-71: LGTM! Error declarations have been updated to reflect the new validation requirements.

The changes correctly:

  • Remove unnecessary error declarations for recipient override validations
  • Reuse error code 3015 for MissingRecipientsForRecipientOverride
src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs (1)

218-218: LGTM! The method has been correctly made asynchronous.

The change correctly awaits the asynchronous CreateNotifications call.

Test/Altinn.Correspondence.Tests/TestingController/Correspondence/CorrespondenceNotificationTests.cs (2)

597-628: LGTM! Test correctly validates custom recipient scenarios.

The test method now properly validates that custom recipients with valid phone numbers or email addresses are accepted, which aligns with the PR objectives.


630-664: LGTM! Test properly validates recipient name tag in notifications.

The test method correctly validates:

  1. Custom recipients with valid contact information
  2. Usage of $recipientName$ tag in notification bodies

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between eb39a1b and fd35a40.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs (1)
Learnt from: CelineTrammi
PR: Altinn/altinn-correspondence#550
File: src/Altinn.Correspondence.API/Mappers/InitializeCorrespondenceNotificationMapper.cs:36-37
Timestamp: 2024-12-10T10:51:48.001Z
Learning: Null checking of `CustomNotificationRecipients` is performed within the `MapExternalRecipientsToRequest` method in the `NotificationMapper` class, so additional checks in the `InitializeCorrespondenceNotificationMapper` class are unnecessary.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (1)
src/Altinn.Correspondence.Application/InitializeCorrespondences/InitializeCorrespondencesHandler.cs (1)

270-352: LGTM! The changes to CreateNotifications method look good.

The method has been correctly updated to support asynchronous operations and properly propagates the cancellation token. The logic for handling both organization and person recipients, as well as custom notification recipients, is well-implemented.

Copy link
Collaborator

@Andreass2 Andreass2 left a comment

Choose a reason for hiding this comment

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

Changes to the database has to be done in a new migration.

Roar can show you tomorrow, or I can show you on friday

@Andreass2
Copy link
Collaborator

I`,m a bit unsure if we should change the keyword name, as it is the same one used by Altinn Notification to get the name of the notification recipient.

How do we avoid confusion?

Ytterås added 2 commits February 14, 2025 10:09
…t the $recipientName$ is now the message recipient and not the notification recipient."

This reverts commit 92e1785.
Copy link
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)
src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.cs (2)

13-46: Ensure safe usage of the placeholder values and consider parameterized migrations.
The raw SQL statements are fine for targeted updates. However, if $recipientName$ or $sendersName$ will be replaced by user input at runtime, be cautious about potential injection risks. Normally for migrations, this is low-risk. Using parameters instead of inline string concatenation can further safeguard against unexpected characters or future expansions.


49-53: Consider implementing a corresponding rollback.
The Down method is empty, so these updates cannot be reverted if needed. Implementing a partial rollback (e.g., resetting templates to default values) is often a good practice, especially in production systems requiring robust rollbacks.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fd35a40 and bddefee.

📒 Files selected for processing (2)
  • src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.Designer.cs (1 hunks)
  • src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (csharp)
🔇 Additional comments (1)
src/Altinn.Correspondence.Persistence/Migrations/20250214083302_ChangedNotificationTemplate.Designer.cs (1)

1-522: No manual changes needed.
Because this file is auto-generated by EF Core migration tooling, modifications should generally be avoided unless there's a strong requirement. The file structure and model definitions appear consistent with typical Entity Framework conventions.

…entName$ to $correspondenceRecpientName$ to avoid using the same keyword that is used to replace notification recipient name on notifications
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.

Endre RecipientName i varslingsmaler til å være mottaker av MELDINGEN
2 participants