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

delete dialog when publish goes wrong #682

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

Conversation

Andreass2
Copy link
Collaborator

@Andreass2 Andreass2 commented Feb 5, 2025

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 the correspondence publishing process: The system now automatically clears outdated dialogs when a publishing attempt fails and enriches successful publishes with additional activity updates.
  • Tests

    • Added new tests to verify that the dialog clearing behavior is reliably triggered on failure.

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a new test method in the DialogportenTests class to verify that a failed publication correctly triggers a dialog purge. Additionally, the PublishCorrespondenceHandler is updated to include a new dependency on IDialogportenService and to call its PurgeCorrespondenceDialog method within its error handling logic. The IDialogportenService interface now includes the purge method, and two integration classes (DialogportenDevService and DialogportenService) have been updated with corresponding implementations.

Changes

File(s) Change Summary
Test/.../DialogportenTests.cs Added new test method FailedPublish_DialogIsPurged with necessary using directives and mock setups to verify that the dialog is purged on publish failure.
src/.../PublishCorrespondenceHandler.cs Updated constructor to include IDialogportenService; modified Process to call PurgeCorrespondenceDialog during error handling and enqueue an info activity.
src/.../IDialogportenService.cs Added new method signature: Task PurgeCorrespondenceDialog(Guid correspondenceId).
src/.../DialogportenDevService.cs, src/.../DialogportenService.cs Implemented PurgeCorrespondenceDialog: Dev service returns Task.CompletedTask, while Service implements full async purge logic with error handling.

Possibly related PRs

  • LegacyController: PurgeCorrespondence #480: The changes in this PR are related to the addition of the PurgeCorrespondenceDialog method in the IDialogportenService, which is invoked in the PublishCorrespondenceHandler during error handling, while the retrieved PR introduces a new endpoint for purging correspondence in the LegacyCorrespondenceController, indicating a direct connection in functionality related to purging correspondence.
  • Fix: Ensure correspondence is fetched before updating to Read or Confirmed #427: The changes in this PR, which involve adding a test for the PurgeCorrespondenceDialog method in the DialogportenTests class, are related to the modifications in the retrieved PR that also involve the PurgeCorrespondenceDialog method, specifically its implementation in the IDialogportenService interface and its usage in the PublishCorrespondenceHandler.
  • Add unit tests for legacy controller #467: The changes in this PR, which involve adding a test method that verifies the invocation of the PurgeCorrespondenceDialog method, are related to the modifications in the retrieved PR, as both involve testing functionalities that interact with the IDialogportenService and its methods.

Suggested labels

kind/bug

Suggested reviewers

  • CelineTrammi
  • Andreass2

📜 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 f5cbb7d and e4e118f.

📒 Files selected for processing (1)
  • src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenService.cs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenService.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (csharp)

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.

@Ceredron
Copy link
Collaborator

Added test and tested manually locally.

@Ceredron Ceredron marked this pull request as ready for review February 13, 2025 18:22
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/TestingFeature/DialogportenTests.cs (1)

102-145: Enhance test robustness and clarity.

While the test verifies the dialog purge behavior, consider these improvements:

  1. Add explicit setup to trigger the publish failure (e.g., mock a service to throw an exception).
  2. Verify the correspondence status after failure.
  3. Add test data cleanup.

Here's a suggested implementation:

 [Fact]
 public async Task FailedPublish_DialogIsPurged() {
     // Arrange
     var hangfireBackgroundJobClient = new Mock<IBackgroundJobClient>();
     var contactReservationRegistry = new Mock<IContactReservationRegistryService>();
+    var publishService = new Mock<IPublishService>();
+    publishService.Setup(x => x.PublishCorrespondence(It.IsAny<Guid>(), It.IsAny<CancellationToken>()))
+        .ThrowsAsync(new Exception("Simulated publish failure"));
     contactReservationRegistry.Setup(contactReservationRegistry => contactReservationRegistry.IsPersonReserved(It.IsAny<string>())).ReturnsAsync(true);
     contactReservationRegistry.Setup(contactReservationRegistry => contactReservationRegistry.GetReservedRecipients(It.IsAny<List<string>>())).ReturnsAsync(new List<string>());
     var testFactory = new UnitWebApplicationFactory((IServiceCollection services) =>
     {
         services.AddSingleton(hangfireBackgroundJobClient.Object);
         services.AddSingleton(contactReservationRegistry.Object);
+        services.AddSingleton(publishService.Object);
     });

     var correspondence = new CorrespondenceBuilder().CreateCorrespondence().Build();
     var testClient = testFactory.CreateSenderClient();
+    Guid? correspondenceId = null;

     try {
         // Act
         using var scope = testFactory.Services.CreateScope();
         var correspondenceRepository = scope.ServiceProvider.GetRequiredService<ICorrespondenceRepository>();
         var initializedCorrespondence = await correspondenceRepository.CreateCorrespondence(new Core.Models.Entities.CorrespondenceEntity()
         {
             Created = DateTimeOffset.UtcNow,
             Recipient = correspondence.Recipients[0],
             RequestedPublishTime = DateTimeOffset.UtcNow,
             ResourceId = correspondence.Correspondence.ResourceId,
             Sender = correspondence.Correspondence.Sender,
             SendersReference = correspondence.Correspondence.SendersReference,
             Statuses = new List<Core.Models.Entities.CorrespondenceStatusEntity>()
             {
                 new Core.Models.Entities.CorrespondenceStatusEntity()
                 {
                     Status = Core.Models.Enums.CorrespondenceStatus.Initialized,
                     StatusChanged = DateTimeOffset.UtcNow
                 }
             }
         }, CancellationToken.None);
         correspondenceId = initializedCorrespondence.Id;
         Assert.NotNull(correspondenceId);
         var handler = scope.ServiceProvider.GetRequiredService<PublishCorrespondenceHandler>();
         await handler.Process(correspondenceId.Value, null, CancellationToken.None);

         // Assert
         Assert.True(hangfireBackgroundJobClient.Invocations.Any(invocation => invocation.Arguments[0].ToString() == "IDialogportenService.PurgeCorrespondenceDialog"));
+        var updatedCorrespondence = await correspondenceRepository.GetCorrespondenceById(correspondenceId.Value, false, false, CancellationToken.None);
+        Assert.Equal(Core.Models.Enums.CorrespondenceStatus.Failed, updatedCorrespondence.Statuses.OrderByDescending(s => s.StatusChanged).First().Status);
     } finally {
+        if (correspondenceId.HasValue) {
+            using var scope = testFactory.Services.CreateScope();
+            var correspondenceRepository = scope.ServiceProvider.GetRequiredService<ICorrespondenceRepository>();
+            await correspondenceRepository.DeleteCorrespondence(correspondenceId.Value, CancellationToken.None);
+        }
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 57eeb7e and e8694dc.

📒 Files selected for processing (5)
  • Test/Altinn.Correspondence.Tests/TestingFeature/DialogportenTests.cs (2 hunks)
  • src/Altinn.Correspondence.Application/PublishCorrespondence/PublishCorrespondenceHandler.cs (2 hunks)
  • src/Altinn.Correspondence.Core/Services/IDialogportenService.cs (1 hunks)
  • src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenDevService.cs (1 hunks)
  • src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenService.cs (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Test application
src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenService.cs

[failure] 75-75:
The name '_logger' does not exist in the current context


[failure] 75-75:
The name '_logger' does not exist in the current context

🪛 GitHub Actions: Test application
src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenService.cs

[error] 75-75: The name '_logger' does not exist in the current context.

🔇 Additional comments (5)
src/Altinn.Correspondence.Core/Services/IDialogportenService.cs (1)

10-11: LGTM! Clean interface extension.

The new PurgeCorrespondenceDialog method follows the existing interface patterns and naming conventions.

src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenDevService.cs (1)

17-21: LGTM! Appropriate dev implementation.

The implementation follows the pattern of other methods in the development service, using Task.CompletedTask for non-production scenarios.

src/Altinn.Correspondence.Integrations/Dialogporten/DialogportenService.cs (1)

63-84: LGTM! Robust implementation with proper error handling.

The implementation follows the established patterns:

  • Validates correspondence existence
  • Checks for dialog ID
  • Handles HTTP response errors
🧰 Tools
🪛 GitHub Check: Test application

[failure] 75-75:
The name '_logger' does not exist in the current context


[failure] 75-75:
The name '_logger' does not exist in the current context

🪛 GitHub Actions: Test application

[error] 75-75: The name '_logger' does not exist in the current context.

src/Altinn.Correspondence.Application/PublishCorrespondence/PublishCorrespondenceHandler.cs (1)

25-25: LGTM! Well-integrated error handling.

The changes properly integrate dialog purging:

  • Correctly injected IDialogportenService
  • Appropriately scheduled dialog purge in the error path using Hangfire
  • Consistent with existing background job patterns

Also applies to: 86-86

Test/Altinn.Correspondence.Tests/TestingFeature/DialogportenTests.cs (1)

2-3: LGTM!

The added using directives are necessary for the new test and follow the existing organization pattern.

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