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(web): Add campaign monitor email signup service #16240

Merged
merged 12 commits into from
Oct 4, 2024

Conversation

mannipje
Copy link
Member

@mannipje mannipje commented Oct 2, 2024

Add campaign monitor email signup service

Why

  • Vinnueftirlitið is using campaign monitor to control their email signup

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced Campaign Monitor integration for email signups, allowing users to subscribe to mailing lists.
    • Enhanced localization for error and success messages in the email signup component, supporting both Icelandic and English.
    • Added a new service for managing email signups through the Campaign Monitor API.
  • Bug Fixes

    • Improved error handling and feedback for email signup submissions.
  • Configuration Updates

    • Added a new environment variable for Campaign Monitor API key across multiple services.
    • Adjusted health check paths and resource configurations for better service management.
    • Expanded the email signup model to include a new signup type for Campaign Monitor.

@mannipje mannipje added the automerge Merge this PR as soon as all checks pass label Oct 2, 2024
@mannipje mannipje requested review from a team as code owners October 2, 2024 15:02
Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Walkthrough

The pull request introduces multiple changes across various files, primarily focusing on the addition of a new environment variable VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY for campaign monitoring. This variable is incorporated into several configurations, including the API service and email signup module. Additionally, localization enhancements are made to user feedback in the email signup component. New services and configurations are defined to support the campaign monitoring functionality, while some existing provider setups are removed.

Changes

File Path Change Summary
apps/api/infra/api.ts Added environment variable VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY to serviceSetup function.
apps/api/src/app/app.module.ts Added CampaignMonitorSignupConfig to EmailSignupModule and updated ConfigModule.forRoot.
apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx Enhanced localization of error messages and user feedback using useI18n hook.
charts/islandis/values.dev.yaml Added VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY under global section; modified health checks and HPA settings.
charts/islandis/values.prod.yaml Added VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY; updated health checks, resource configurations, and ingress settings.
charts/islandis/values.staging.yaml Added VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY under api service's secrets section; adjusted resource limits.
libs/api/domains/email-signup/src/index.ts Added export for campaignMonitor.config.
libs/api/domains/email-signup/src/lib/emailSignup.config.ts Added vinnueftirlitidCampaignMonitorApiKey to schema and updated load function for environment variable retrieval.
libs/api/domains/email-signup/src/lib/emailSignup.module.ts Introduced CampaignMonitorSignupService in EmailSignupModule.
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts Introduced new campaignMonitor.config.ts with schema validation for vinnueftirlitidCampaignMonitorApiKey.
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts Added CampaignMonitorSignupService class with subscribeToMailingList method for API interactions.
libs/api/domains/email-signup/src/lib/services/zenter/zenter.service.ts Removed console log statement from subscribeToMailingList method.
libs/cms/src/lib/models/emailSignup.model.ts Updated signupType field to include 'campaign monitor' as an option.

Possibly related PRs

Suggested reviewers

  • albinagu
  • rafnarnason
  • kksteini

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

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

gitguardian bot commented Oct 2, 2024

️✅ There are no secrets present in this pull request anymore.

If these secrets were true positive and are still valid, we highly recommend you to revoke them.
Once a secret has been leaked into a git repository, you should consider it compromised, even if it was deleted immediately.
Find here more information about risks.


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

Copy link
Member

@RunarVestmann RunarVestmann left a comment

Choose a reason for hiding this comment

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

Looks good to me

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: 3

🧹 Outside diff range and nitpick comments (13)
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts (1)

8-18: Configuration structure is good, but consider using a more generic environment variable name.

The use of defineConfig and the overall structure of the configuration export aligns well with the coding guidelines for reusability. The load function correctly ensures that the required environment variable is provided.

However, for better reusability across different NextJS apps, consider using a more generic environment variable name.

Here's a suggested change:

 export const CampaignMonitorSignupConfig = defineConfig({
   name: 'CampaignMonitorSignup',
   schema,
   load(env) {
     return {
-      vinnueftirlitirdCampaignMonitorApiKey: env.required(
-        'VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY',
+      campaignMonitorApiKey: env.required(
+        'CAMPAIGN_MONITOR_API_KEY',
       ),
     }
   },
 })

This change would make the configuration more reusable for other projects that might use Campaign Monitor.

libs/api/domains/email-signup/src/lib/emailSignup.module.ts (1)

16-16: LGTM: Service correctly added to providers. Consider grouping similar services.

The CampaignMonitorSignupService is correctly added to the providers array, making it available for dependency injection within the module. This addition aligns with the module's purpose of managing email signup services.

As a minor suggestion for improved code organization, consider grouping all email signup services together in the providers array. This could enhance readability and maintain a logical structure as the number of services grows.

Here's a suggested refactor to group the services:

 @Module({
   imports: [CmsModule],
   providers: [
+    // Email signup services
     ZenterSignupService,
     MailchimpSignupService,
     CampaignMonitorSignupService,
+    // Other services
     EmailSignupService,
     EmailSignupResolver,
   ],
 })
libs/api/domains/email-signup/src/lib/emailSignup.config.ts (1)

Line range hint 1-28: Consider exporting the configuration type for improved reusability.

While the code adheres well to the coding guidelines for libs/**/* files, consider exporting the inferred type of the configuration object. This would enhance reusability and type safety when this configuration is used in other parts of the application.

You can add the following export at the end of the file:

export type EmailSignupConfigType = z.infer<typeof schema>;

This allows other parts of the application to import and use the type, improving type safety and developer experience.

libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (5)

1-14: LGTM! Consider enhancing type safety for the configuration.

The imports, class declaration, and dependency injection are well-structured and follow NestJS conventions. The use of LazyDuringDevScope aligns with the coding guidelines for reusability across different NextJS apps.

To further improve type safety, consider explicitly typing the injected configuration:

constructor(
  @Inject(CampaignMonitorSignupConfig.KEY)
  private readonly config: ConfigType<typeof CampaignMonitorSignupConfig>,
) {}

This ensures that the configuration object strictly adheres to the expected structure.


16-25: LGTM! Consider enhancing API key security.

The method signature and initial setup are well-structured. The use of TypeScript for defining props and the async nature of the method align with the coding guidelines.

To enhance security, consider using a more secure method for handling the API key:

  1. Use environment variables for storing sensitive information.
  2. Implement a secure key management system for production environments.

Example refactor:

const API_KEY = process.env.CAMPAIGN_MONITOR_API_KEY || this.config.vinnueftirlitirdCampaignMonitorApiKey;

if (!API_KEY) {
  throw new Error('Campaign Monitor API key is not configured');
}

This approach provides an additional layer of security and flexibility in different environments.


26-35: LGTM! Consider enhancing code readability.

The data preparation for the API request is well-structured and flexible. The use of a Map for organizing data and the iteration over input fields allow for easy extensibility.

To improve code readability and maintainability, consider extracting the default values and field mapping into separate functions:

const getDefaultValues = () => new Map([
  ['ConsentToTrack', 'Yes'],
  ['Resubscribe', true]
]);

const mapInputFields = (inputFields: EmailSignupInput['inputFields']) => 
  inputFields.reduce((map, field) => map.set(field.name, field.value), new Map());

const map = new Map([...getDefaultValues(), ...mapInputFields(inputFields)]);
const obj = Object.fromEntries(map);

This approach separates concerns and makes the code more modular and easier to test.


37-47: LGTM! Consider refining response handling and error management.

The API request and response handling are structured well, ensuring consistent return values. However, there are opportunities for improvement in error handling and response processing.

  1. Simplify the response handling as suggested by the static analysis tool:
return {
  subscribed: response?.data?.result !== 'error'
};
  1. Enhance error handling to provide more context:
.catch((error) => {
  console.error('Error subscribing to mailing list:', error.message);
  return { subscribed: false, error: error.message };
});
  1. Consider adding more detailed error information in the return object to help with debugging:
return {
  subscribed: response?.data?.result !== 'error',
  details: response?.data
};

These changes will improve the code's readability, error handling, and debugging capabilities while maintaining the consistent return structure.

🧰 Tools
🪛 Biome

[error] 41-41: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)


1-48: Overall, good implementation with room for enhancement.

The CampaignMonitorSignupService is well-structured and adheres to most of the coding guidelines for the libs directory. It uses TypeScript effectively and is designed for reusability across different NextJS apps.

Key strengths:

  1. Proper use of dependency injection and configuration management.
  2. TypeScript usage for defining props and exporting types.
  3. Asynchronous handling of API requests.

Areas for improvement:

  1. Enhance security practices, especially around API key management.
  2. Refine error handling and logging for better debugging.
  3. Improve code organization by extracting some logic into separate functions.

Consider the following architectural improvements:

  1. Implement a retry mechanism for failed API requests to improve reliability.
  2. Add unit tests to validate the functionality and edge cases of the service.
  3. Consider implementing a more robust error handling strategy, possibly using custom error classes.

These enhancements will further improve the service's reliability, maintainability, and adherence to best practices.

🧰 Tools
🪛 Biome

[error] 41-41: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

libs/api/domains/email-signup/src/lib/emailSignup.service.ts (1)

Line range hint 1-56: Overall assessment: Changes align well with coding guidelines

The introduced changes to support the Campaign Monitor email signup service adhere well to the existing patterns and structure of the file. The modifications demonstrate good reusability, as adding new signup services can be done with minimal changes to the existing code. TypeScript is used appropriately for type definitions, and the changes don't introduce any obvious issues with tree-shaking or bundling practices.

To further improve the code:

  1. Consider introducing an enum for signup types as suggested earlier.
  2. Ensure that any new types or interfaces related to the Campaign Monitor service are exported if they might be needed by other parts of the application.
  3. If not already done, consider adding unit tests for the new Campaign Monitor signup functionality.
apps/api/infra/api.ts (1)

Line range hint 1-390: Consider refactoring for improved maintainability

While the current change is small and correct, I've noticed that this configuration file is quite large and complex. To improve maintainability and readability, consider the following suggestions:

  1. Split the configuration into smaller, logical modules (e.g., by service or functionality).
  2. Use a configuration management library to handle environment-specific values more elegantly.
  3. Implement a type-safe configuration solution to catch potential errors early in the development process.

These changes could make the codebase more maintainable and easier to update in the future.

Would you like assistance in planning or implementing any of these refactoring suggestions?

apps/api/src/app/app.module.ts (1)

32-32: Summary: Integration of CampaignMonitorSignupConfig

The changes in this file are minimal and focused on integrating the CampaignMonitorSignupConfig. The implementation follows existing patterns and is consistent with the file structure. These changes align well with the PR objective of adding a campaign monitor email signup service for Vinnueftirlitið.

However, it's worth noting that according to the PR description, the author has not yet updated the documentation or added tests for this new feature. Consider addressing these points to ensure comprehensive implementation and maintainability.

To improve the overall quality of this PR, consider:

  1. Updating relevant documentation to reflect the addition of the Campaign Monitor email signup service.
  2. Adding appropriate tests to validate the functionality of the new feature.

Also applies to: 394-394

charts/islandis/values.staging.yaml (1)

548-548: Approved: New environment variable added for Vinnueftirlitið campaign monitor

The addition of the VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY environment variable is in line with the PR objectives for integrating a campaign monitor email signup service for Vinnueftirlitið. This change looks good.

Consider updating the relevant documentation to reflect this new integration and the purpose of this API key.

apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx (1)

Line range hint 133-139: Avoid using @ts-ignore and resolve TypeScript errors

Using @ts-ignore suppresses TypeScript errors, which can hide potential issues and reduce type safety. It's important to address the underlying type errors to ensure code reliability.

Consider defining or updating the types for field and field.name so that TypeScript correctly recognizes the properties without the need for @ts-ignore. For example, ensure that all optional chaining and type checks are correctly implemented to satisfy TypeScript's requirements.

Also applies to: 152-154, 197-199, 223-225, 247-249, 275-277

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0e45aa5 and abfe717.

📒 Files selected for processing (13)
  • apps/api/infra/api.ts (1 hunks)
  • apps/api/src/app/app.module.ts (2 hunks)
  • apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx (9 hunks)
  • charts/islandis/values.dev.yaml (1 hunks)
  • charts/islandis/values.prod.yaml (1 hunks)
  • charts/islandis/values.staging.yaml (1 hunks)
  • libs/api/domains/email-signup/src/index.ts (1 hunks)
  • libs/api/domains/email-signup/src/lib/emailSignup.config.ts (2 hunks)
  • libs/api/domains/email-signup/src/lib/emailSignup.module.ts (1 hunks)
  • libs/api/domains/email-signup/src/lib/emailSignup.service.ts (2 hunks)
  • libs/api/domains/email-signup/src/lib/serviceProvider.ts (0 hunks)
  • libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts (1 hunks)
  • libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • libs/api/domains/email-signup/src/lib/serviceProvider.ts
🧰 Additional context used
📓 Path-based instructions (9)
apps/api/infra/api.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/api/src/app/app.module.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/api/domains/email-signup/src/index.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/email-signup/src/lib/emailSignup.config.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/email-signup/src/lib/emailSignup.module.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/email-signup/src/lib/emailSignup.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts

[error] 41-41: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (20)
libs/api/domains/email-signup/src/index.ts (1)

4-4: Verify the necessity of exporting the Campaign Monitor config

The addition of the Campaign Monitor config export aligns with the PR objective of integrating a campaign monitor email signup service. This export enhances reusability across NextJS apps and supports effective tree-shaking, which is great.

However, please consider the following points:

  1. Ensure that exporting the entire config is intentional and necessary for the public API of this module.
  2. Update the documentation to reflect this new export, as mentioned in your PR checklist.
  3. Add appropriate tests to validate the functionality of the Campaign Monitor integration, also noted in your checklist.

To ensure the config export is being used appropriately, please run the following script:

This will help verify that the export is necessary and being utilized correctly in other parts of the codebase.

libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts (2)

1-2: Imports look good and follow best practices.

The use of @island.is/nest/config and zod aligns with the coding guidelines for reusability and type safety across different NextJS apps.


1-18: Overall good implementation, but tests are missing and reusability could be improved.

The configuration file is well-structured and follows most of the coding guidelines. It uses TypeScript effectively, defines exports properly, and is set up for effective tree-shaking and bundling. However, there are two main points to address:

  1. Reusability: As mentioned in previous comments, consider using more generic names for the configuration property and environment variable to improve reusability across different NextJS apps.

  2. Testing: According to the PR objectives, tests have not been added for this new feature. It's important to add tests to validate the functionality of this configuration.

To check for existing tests, you can run the following command:

If this command doesn't return any results, it confirms that tests are missing for this new feature.

Would you like assistance in generating test cases for this configuration file?

libs/api/domains/email-signup/src/lib/emailSignup.module.ts (1)

9-9: LGTM: Import statement is correct and follows conventions.

The import statement for CampaignMonitorSignupService is properly structured and follows the established naming conventions. The service is imported from a dedicated directory, which aligns with good practices for code organization.

libs/api/domains/email-signup/src/lib/emailSignup.config.ts (2)

9-9: LGTM: Schema addition is correct and consistent.

The new vinnueftirlitirdCampaignMonitorApiKey property has been correctly added to the schema as a required string. This addition aligns with the PR objective and maintains consistency with the existing schema structure.


23-25: LGTM: Environment variable loading is implemented correctly.

The vinnueftirlitirdCampaignMonitorApiKey is properly loaded from the 'VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY' environment variable. The use of env.required() ensures that this crucial configuration is present before the application starts.

libs/api/domains/email-signup/src/lib/emailSignup.service.ts (3)

7-7: LGTM: Import statement for CampaignMonitorSignupService

The import statement for CampaignMonitorSignupService is correctly added and follows the established pattern for service imports in this file.


15-15: LGTM: Constructor injection for CampaignMonitorSignupService

The CampaignMonitorSignupService is correctly injected into the constructor as a private readonly property, following the established dependency injection pattern in this class.


47-52: LGTM: Addition of campaign monitor signup handling

The new conditional block for handling the 'campaign monitor' signup type is correctly implemented. It follows the established pattern in the method and uses the injected campaignMonitorSignupService appropriately.

apps/api/infra/api.ts (2)

389-390: LGTM: New secret added for Vinnueftirlitið's Campaign Monitor API key

The addition of the VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY secret is consistent with the existing code structure and naming conventions. This change allows for secure storage and access of the Campaign Monitor API key for Vinnueftirlitið.

To ensure the security of this new API key, please run the following script to verify that it's not accidentally exposed in any other part of the codebase:

#!/bin/bash
# Description: Check for potential exposure of the Vinnueftirlitið Campaign Monitor API key

# Test: Search for any hardcoded references to the API key
rg -i "VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY" --type ts --type js --type json

389-390: Consider updating documentation and related components

While the addition of the VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY secret is straightforward, it suggests a new integration with Campaign Monitor for Vinnueftirlitið. To ensure a smooth implementation:

  1. Update relevant documentation to reflect this new integration.
  2. Verify that any components or services that will use this API key are properly implemented and follow best practices for secret management.
  3. Consider adding unit tests for any new functionality related to this integration.

To identify potential usage of this new secret and ensure proper implementation, run the following script:

✅ Verification successful

Verification Successful: Secret Integration Confirmed

The VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY is properly integrated across the relevant services and configurations. Ensure that associated documentation is updated and appropriate unit tests are in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find potential usage of the new Vinnueftirlitið Campaign Monitor API key

# Test: Search for references to the new environment variable
rg "process\.env\.VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY" --type ts --type js

# Test: Look for new Campaign Monitor related imports or usage
rg -i "campaign.?monitor" --type ts --type js

Length of output: 3134

apps/api/src/app/app.module.ts (2)

32-32: LGTM: Import of CampaignMonitorSignupConfig

The import of CampaignMonitorSignupConfig is correctly added to the existing import statement from '@island.is/api/domains/email-signup'. This change aligns with the PR objective of integrating a campaign monitor email signup service.


394-394: LGTM: Addition of CampaignMonitorSignupConfig to ConfigModule

The CampaignMonitorSignupConfig is correctly added to the load array in ConfigModule.forRoot. This change is consistent with the import added earlier and aligns with the PR objective of integrating a campaign monitor email signup service.

Please verify if any additional configuration or setup is required for the CampaignMonitorSignupConfig. Run the following script to check for any related configuration files or environment variables:

✅ Verification successful

Verified: CampaignMonitorSignupConfig Integration

The CampaignMonitorSignupConfig has been successfully integrated into the ConfigModule.forRoot without relying on any related environment variables. No additional configuration or setup is required.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for CampaignMonitorSignupConfig related files and environment variables

# Search for CampaignMonitorSignupConfig in configuration files
echo "Searching for CampaignMonitorSignupConfig in configuration files:"
rg -i "CampaignMonitorSignupConfig" --type ts --type js --type json

# Check for related environment variables
echo "Checking for related environment variables:"
rg -i "CAMPAIGN_MONITOR" .env* 2>/dev/null || echo "No .env files found or no matches"

Length of output: 1166

charts/islandis/values.prod.yaml (1)

540-540: New environment variable added for Vinnueftirlitið campaign monitor

A new environment variable VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY has been added to the api service. This addition aligns with the PR objective of integrating a campaign monitor email signup service for Vinnueftirlitið.

To ensure the new environment variable is properly set and accessible, please run the following verification script:

✅ Verification successful

Environment variable VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY is properly set in values.prod.yaml

The VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY environment variable is present in charts/islandis/values.prod.yaml, confirming it has been correctly added for the api service.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new environment variable is set in the api deployment

# Test: Check if the environment variable is present in the api deployment
kubectl get deployment web-api -n islandis -o jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY")]}' | grep VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY

# Expected output: Should display the environment variable if it's set correctly

Length of output: 276


Script:

#!/bin/bash
# Description: Verify the presence of the new environment variable in the values.prod.yaml file

# Search for the environment variable in charts/islandis/values.prod.yaml
rg 'VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY' charts/islandis/values.prod.yaml

Length of output: 176

charts/islandis/values.dev.yaml (3)

550-550: Approved: Good addition of Campaign Monitor API key for Vinnueftirlitið

The new environment variable VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY has been correctly added to the global environment section. It's good to see that the value is being fetched from a Kubernetes secret, which is a secure practice for handling sensitive information like API keys.

[security]
Consider setting an explicit expiration date for this secret and implement a rotation policy to enhance security further.


550-550: Summary: Approved changes with minor suggestions

The addition of the VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY environment variable to the global configuration is approved. This change aligns with the PR objective of integrating a campaign monitor email signup service for Vinnueftirlitið. The implementation follows good security practices by using a Kubernetes secret.

To ensure a smooth integration and maintain system security, please consider the following suggestions:

  1. Update relevant documentation to reflect this new integration.
  2. Implement a secret rotation policy for the API key.
  3. Verify the usage of this environment variable across the system.

Overall, this change is straightforward and well-implemented. Once the suggested actions are addressed, this PR should be ready for merging.


550-550: Suggestion: Update documentation and verify usage

While the addition of the VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY is straightforward and correctly implemented, it's important to ensure that this change is properly documented and its usage is verified across the system.

  1. Update relevant documentation to reflect this new integration with Campaign Monitor for Vinnueftirlitið.
  2. Verify which services or applications will be using this API key and ensure they are configured to access this global environment variable correctly.

To help identify potential usage of this new environment variable, you can run the following command to search for references to it in the codebase:

This will help ensure that the integration is properly implemented across the system.

✅ Verification successful

Verification Successful: Environment Variable Usage Confirmed

The VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY is consistently used across relevant configuration and service files.

  • Documentation Updates:

    • Document the addition of VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY in all relevant sections, including:
      • libs/api/domains/email-signup/src/lib/emailSignup.config.ts
      • libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts
      • apps/api/infra/api.ts
      • charts/islandis/values.dev.yaml
      • charts/islandis/values.staging.yaml
      • charts/islandis/values.prod.yaml
  • Configuration Verification:

    • Ensure that all services and applications referencing the API key are correctly configured to access the global environment variable.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential usage of the new environment variable
rg "VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY" --type yaml --type javascript --type typescript

Length of output: 128


Script:

#!/bin/bash
# Search for potential usage of the new environment variable with corrected file types
rg "VINNUEFTIRLITID_CAMPAIGN_MONITOR_API_KEY" --type yaml --type js --type ts

Length of output: 878

apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx (3)

22-22: Importing useI18n for localization

The import of useI18n is appropriate for implementing localization in the component.


27-27: Importing FormFieldType

The import of FormFieldType is necessary for handling different form field types and is correctly imported.


54-54: Destructuring activeLocale from useI18n

Using activeLocale from useI18n to determine the current locale is appropriate.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 2, 2024

Datadog Report

All test runs 419cba7 🔗

11 Total Test Services: 0 Failed, 10 Passed
➡️ Test Sessions change in coverage: 29 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.72s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 12.32s 1 no change Link
api-domains-communications 0 0 0 5 0 28.7s 1 no change Link
api-domains-license-service 0 0 0 0 0 664.1ms 1 no change Link
application-system-api 0 0 0 120 2 3m 6.2s 1 no change Link
application-template-api-modules 0 0 0 135 0 2m 7.93s 1 no change Link
cms-translations 0 0 0 3 0 30.26s 1 no change Link
judicial-system-api 0 0 0 57 0 7.93s 1 no change Link
judicial-system-backend 0 0 0 21023 0 20m 16.49s 1 no change Link
services-user-notification 0 0 0 51 0 1m 29.73s 1 no change Link

Copy link
Member

@svanaeinars svanaeinars left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link

codecov bot commented Oct 2, 2024

Codecov Report

Attention: Patch coverage is 5.26316% with 18 lines in your changes missing coverage. Please review.

Project coverage is 36.91%. Comparing base (e66d89b) to head (6e33f86).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...nts/Organization/Slice/EmailSignup/EmailSignup.tsx 0.00% 18 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16240      +/-   ##
==========================================
- Coverage   36.92%   36.91%   -0.01%     
==========================================
  Files        6781     6781              
  Lines      140035   140053      +18     
  Branches    39817    39834      +17     
==========================================
  Hits        51705    51705              
- Misses      88330    88348      +18     
Flag Coverage Δ
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (ø)
api-domains-auth-admin 48.77% <ø> (ø)
api-domains-communications 39.92% <100.00%> (ø)
application-api-files 57.91% <ø> (ø)
application-core 71.62% <ø> (+0.32%) ⬆️
application-system-api 41.63% <100.00%> (ø)
application-template-api-modules 24.40% <ø> (ø)
application-templates-accident-notification 29.44% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.63% <ø> (ø)
application-templates-driving-license 18.63% <ø> (ø)
application-templates-estate 12.32% <ø> (ø)
application-templates-example-payment 25.41% <ø> (ø)
application-templates-financial-aid 14.34% <ø> (ø)
application-templates-general-petition 23.68% <ø> (ø)
application-templates-health-insurance 26.62% <ø> (ø)
application-templates-inheritance-report 6.45% <ø> (ø)
application-templates-marriage-conditions 15.23% <ø> (ø)
application-templates-mortgage-certificate 43.96% <ø> (ø)
application-templates-parental-leave 30.15% <ø> (+0.12%) ⬆️
application-types 6.71% <ø> (ø)
application-ui-components 1.28% <ø> (ø)
application-ui-shell 21.27% <ø> (ø)
auth-react 22.77% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
cms 0.43% <0.00%> (ø)
cms-translations 39.04% <100.00%> (ø)
contentful-apps 5.57% <ø> (ø)
financial-aid-backend 56.53% <ø> (ø)
financial-aid-shared 19.03% <ø> (ø)
island-ui-core 28.44% <ø> (ø)
judicial-system-api 18.30% <ø> (ø)
judicial-system-backend 55.24% <100.00%> (ø)
judicial-system-web 28.10% <ø> (ø)
portals-admin-regulations-admin 1.88% <ø> (ø)
portals-core 16.15% <ø> (ø)
services-auth-personal-representative 45.55% <ø> (ø)
services-user-notification 47.06% <100.00%> (-0.01%) ⬇️
shared-components 27.65% <ø> (ø)
shared-form-fields 31.59% <ø> (ø)
web 1.83% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
apps/api/src/app/app.module.ts 0.00% <ø> (ø)
libs/cms/src/lib/models/emailSignup.model.ts 54.16% <100.00%> (ø)
...nts/Organization/Slice/EmailSignup/EmailSignup.tsx 0.00% <0.00%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e66d89b...6e33f86. Read the comment docs.

Copy link
Member

@baering baering left a comment

Choose a reason for hiding this comment

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

Core file LGTM

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

🧹 Outside diff range and nitpick comments (1)
libs/api/domains/email-signup/src/lib/emailSignup.service.ts (1)

39-39: LGTM with a minor suggestion for consistency

The subscribeToMailingList method has been correctly updated to handle the new CampaignMonitor signup type. The use of the SignupType enum in conditional checks improves type safety.

For consistency, consider updating the other conditional checks to use the SignupType enum as well:

if (emailSignupModel.signupType === SignupType.Mailchimp) {
  // ...
}

if (emailSignupModel.signupType === SignupType.Zenter) {
  // ...
}

This change would make the code more uniform and leverage the full benefits of the enum.

Also applies to: 46-46, 53-58

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between abfe717 and 72c2a21.

📒 Files selected for processing (2)
  • apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx (9 hunks)
  • libs/api/domains/email-signup/src/lib/emailSignup.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/components/Organization/Slice/EmailSignup/EmailSignup.tsx
🧰 Additional context used
📓 Path-based instructions (1)
libs/api/domains/email-signup/src/lib/emailSignup.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (4)
libs/api/domains/email-signup/src/lib/emailSignup.service.ts (4)

7-7: LGTM: Import statement is correctly added

The import for CampaignMonitorSignupService is properly placed and follows the existing import pattern for services.


10-14: Great job implementing the enum for signup types!

The introduction of the SignupType enum improves type safety and maintainability, as suggested in a previous review. It's well-placed and includes all necessary types.


21-21: LGTM: Constructor properly updated

The CampaignMonitorSignupService is correctly injected into the constructor, following the existing pattern for service injection.


Line range hint 1-62: Overall, excellent changes that adhere to coding guidelines

The modifications to the EmailSignupService effectively integrate the new CampaignMonitor signup type while maintaining good coding practices:

  1. Reusability: The service extension allows for easy integration of new signup types.
  2. TypeScript usage: The introduction of the SignupType enum improves type safety and code clarity.
  3. Bundling and tree-shaking: The changes are localized and should not negatively impact these aspects.

Great job on implementing these changes in a clean and maintainable way!

@mannipje mannipje requested a review from a team as a code owner October 4, 2024 10:23
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: 4

🧹 Outside diff range and nitpick comments (1)
libs/cms/src/lib/models/emailSignup.model.ts (1)

Line range hint 1-45: Enhance documentation for better reusability and maintainability.

The file adheres well to the coding guidelines, using TypeScript effectively and providing reusable components. To further improve it:

  1. Add JSDoc comments to the EmailSignup class and its fields, explaining their purpose and usage.
  2. Document the mapEmailSignup function, describing its parameters and return value.
  3. Consider adding a brief file-level comment explaining the purpose of this model in the broader context of the CMS library.

These additions will enhance the reusability of this code across different NextJS apps by providing clear documentation for developers.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 72c2a21 and faba5ef.

⛔ Files ignored due to path filters (1)
  • libs/cms/src/lib/generated/contentfulTypes.d.ts is excluded by !**/generated/**
📒 Files selected for processing (3)
  • libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (3 hunks)
  • libs/api/domains/email-signup/src/lib/services/zenter/zenter.service.ts (1 hunks)
  • libs/cms/src/lib/models/emailSignup.model.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • libs/api/domains/email-signup/src/lib/services/zenter/zenter.service.ts
🧰 Additional context used
📓 Path-based instructions (2)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/cms/src/lib/models/emailSignup.model.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (1)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

9-9: Imported CampaignMonitorSignupService Correctly

The import statement for CampaignMonitorSignupService is correct and necessary for testing its functionality.

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

🧹 Outside diff range and nitpick comments (5)
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (3)

1-14: LGTM! Consider enhancing type safety for the configuration.

The imports, class declaration, and dependency injection are well-structured and follow NestJS conventions. The use of LazyDuringDevScope aligns with the coding guidelines for reusability across different NextJS apps.

To further improve type safety, consider explicitly typing the injected configuration:

constructor(
  @Inject(CampaignMonitorSignupConfig.KEY)
  private readonly config: ConfigType<typeof CampaignMonitorSignupConfig>,
) {}

This ensures that the configuration object strictly adheres to the expected structure.


16-25: LGTM! Consider adding error handling for missing API key.

The method signature and initial setup are well-structured, using TypeScript types and following security best practices by retrieving the API key from the injected configuration.

Consider adding a check for the API key's presence:

const API_KEY = this.config.vinnueftirlitidCampaignMonitorApiKey
if (!API_KEY) {
  throw new Error('Campaign Monitor API key is not configured')
}

This ensures that the service fails fast if the API key is missing, preventing potential runtime errors.


26-35: LGTM! Consider using object literal for initial map values.

The data preparation for the API request is well-structured, using a Map for flexible data organization and properly handling the input fields.

To improve readability, consider using an object literal for the initial map values:

const initialValues = {
  ConsentToTrack: 'Yes',
  Resubscribe: true,
};
const map = new Map(Object.entries(initialValues));

for (const field of inputFields) {
  map.set(field.name, field.value);
}

This approach makes the initial values more explicit and easier to maintain.

libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (2)

33-41: Provider configuration looks good, but check the property name

The provider for CampaignMonitorSignupService is correctly added to the testing module and follows the existing pattern of using a factory function. However, there's a potential typo in the configuration property name.

On line 37, vinnueftirlitidCampaignMonitorApiKey might be a typo. Please verify if it should be vinnueftirlitiðCampaignMonitorApiKey instead.

-              vinnueftirlitidCampaignMonitorApiKey: '',
+              vinnueftirlitiðCampaignMonitorApiKey: '',

Line range hint 1-239: Overall changes look good, minor suggestion for consistency

The addition of the Campaign Monitor test suite completes the coverage for all signup services. The overall structure and testing approach is consistent across all test suites.

For consistency, consider adding a test case in the 'subscribeToCampaignMonitor' suite to check for subscription failure, similar to the one in the 'subscribeMailchimp' suite (lines 92-106). This would ensure uniform error handling across all signup services.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between faba5ef and 3c98d28.

📒 Files selected for processing (4)
  • libs/api/domains/email-signup/src/lib/emailSignup.config.ts (2 hunks)
  • libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (3 hunks)
  • libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts (1 hunks)
  • libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • libs/api/domains/email-signup/src/lib/emailSignup.config.ts
  • libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.config.ts
🧰 Additional context used
📓 Path-based instructions (2)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🪛 Biome
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts

[error] 41-41: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

🔇 Additional comments (2)
libs/api/domains/email-signup/src/lib/services/campaignMonitor/campaignMonitor.service.ts (1)

37-47: ⚠️ Potential issue

Improve response processing and error handling.

While the API request is correctly implemented using axios, there are opportunities to enhance the response processing and error handling.

  1. Simplify the response processing:
return axios
  .post(url, obj, { headers: { Authorization: authHeader } })
  .then((response) => ({
    subscribed: response?.data?.result !== 'error'
  }))
  .catch((error) => {
    console.error('Error subscribing to mailing list:', error.message);
    return { subscribed: false };
  });
  1. Consider adding more detailed error information:
.catch((error) => {
  console.error('Error subscribing to mailing list:', error.message);
  return {
    subscribed: false,
    error: error.response?.data?.Message || 'An unknown error occurred'
  };
});

These changes will improve code readability and provide more informative error handling, which can be useful for debugging and user feedback.

To ensure that the error handling is consistent across the codebase, let's check for similar patterns:

🧰 Tools
🪛 Biome

[error] 41-41: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

9-9: LGTM: Import statement for CampaignMonitorSignupService

The import statement for CampaignMonitorSignupService is correctly added and follows the existing import style in the file.

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: 2

🧹 Outside diff range and nitpick comments (2)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (2)

183-265: Approve test suite structure with suggestions for improvement

The new test suite for subscribeToCampaignMonitor is well-structured and follows the existing testing patterns. It correctly mocks the necessary services and API calls, covering key scenarios such as invalid input, error handling, and successful subscription.

To further improve the robustness of your test suite, consider adding the following test cases:

  1. Test with missing required fields in the input.
  2. Test with an empty email address.
  3. Test the behavior when CmsContentfulService returns null.
  4. Test with various error responses from the Campaign Monitor API.
  5. Test with different configurations (e.g., when isConfigured is false).

These additional test cases will help ensure comprehensive coverage of the new functionality.


195-207: Approve test case with suggestion for clarity

The test case for handling invalid email input is well-structured and correctly verifies the expected behavior.

To improve clarity, consider updating the test description to be more specific about what constitutes an "invalid email". For example:

- it('should handle invalid email', async () => {
+ it('should handle subscription failure for invalid email format', async () => {

This change would make the test's purpose more explicit and help other developers understand the specific scenario being tested.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3c98d28 and 50c9582.

📒 Files selected for processing (1)
  • libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (1)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

9-9: LGTM: Import statement for CampaignMonitorSignupService

The import statement for CampaignMonitorSignupService is correctly placed and follows the project's import structure. This import is necessary for the new tests being added for the Campaign Monitor email signup service.

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: 2

🧹 Outside diff range and nitpick comments (1)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

235-255: LGTM: Successful subscription test case with suggestion

The successful subscription test case for subscribeToCampaignMonitor is well-implemented:

  • It correctly mocks the CMS service and axios post request.
  • The test properly simulates a successful API response scenario.
  • The assertion verifies that the subscription succeeds as expected.

Suggestion for improvement:
Consider enhancing the axios.post mock to more closely simulate the actual API response. For example:

jest.spyOn(axios, 'post').mockImplementation((_url, data) => {
  const { EmailAddress } = data as { EmailAddress: string };
  return Promise.resolve({
    data: {
      SubscriberState: EmailAddress === testInput.inputFields[0].value ? 'Active' : 'Unsubscribed',
      Result: 'Success',
    },
  });
});

This change would make the test more resilient to changes in the actual API response structure.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 50c9582 and f6ba10b.

📒 Files selected for processing (1)
  • libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (3)
libs/api/domains/email-signup/src/lib/emailSignup.resolver.spec.ts (3)

9-9: LGTM: Import statement for CampaignMonitorSignupService

The import statement for CampaignMonitorSignupService is correctly placed and follows the project's import conventions.


183-256: LGTM: Test suite structure and coverage

The test suite for subscribeToCampaignMonitor is well-structured and covers important scenarios:

  1. Error handling from the subscription API
  2. Successful subscription with valid input

The test cases follow the existing patterns in the file and provide good coverage for the new functionality.


218-233: LGTM: Error handling test case

The error handling test case for subscribeToCampaignMonitor is well-implemented:

  • It correctly mocks the CMS service and axios post request.
  • The test properly simulates an API error scenario.
  • The assertion verifies that the subscription fails as expected when an error occurs.

This test case enhances the robustness of the email signup functionality.

@kodiakhq kodiakhq bot merged commit 1482e07 into main Oct 4, 2024
138 checks passed
@kodiakhq kodiakhq bot deleted the feature/add-campaign-monitor-to-email-signup branch October 4, 2024 16:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants