Skip to content

PR Incident Filters UI Component #658

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

Merged
merged 12 commits into from
May 30, 2025

Conversation

Kamlesh72
Copy link
Contributor

@Kamlesh72 Kamlesh72 commented May 22, 2025

Linked Issue(s)

Ref #557

Further Comments

This is a stacked PR on top of #656

Proposed changes (including videos or screenshots)

Incident.PR.Filters.UI.Video.mp4

Summary by CodeRabbit

  • New Features
    • Introduced a user interface for configuring regex-based incident pull request (PR) filters at the team level, including options to add, edit, or remove filters and to include or exclude reverted PRs.
    • Added a modal in team settings to manage incident PR filters.
    • Added API endpoints to fetch and update incident PR filter settings per team.
  • Enhancements
    • Incident PR filter settings now affect Dora metrics calculations and reporting.
    • Improved feedback with success and error notifications when updating filter settings.

Copy link

coderabbitai bot commented May 22, 2025

Walkthrough

This change introduces support for configuring and managing incident pull request (PR) filters at the team level. It adds a new API endpoint, Redux state management, TypeScript types, UI components, and updates utility functions to handle incident PR filter settings, enabling teams to customize how incident PRs are identified and processed.

Changes

File(s) Change Summary
web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts Added new API route for GET/PUT of team incident PR filter settings, including Yup validation and internal endpoint integration.
web-server/src/components/DoraMetricsConfigurationSettings.tsx Enhanced settings component to support and display configuration UI for incident PR filters, including modal logic and Redux dispatches.
web-server/src/components/TeamIncidentPRsFilter.tsx Added new React component for configuring incident PR filters, with dynamic fields, validation, state management, and save logic.
web-server/src/slices/team.ts Introduced Redux state, async thunks, and reducers for fetching and updating team incident PR filter settings.
web-server/src/types/resources.ts Added new TypeScript types for incident PR filter settings and API responses.
web-server/src/utils/cockpitMetricUtils.ts Updated utility function to accept and apply incident PR filter parameters in metric API requests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DoraSettings as DoraMetricsConfigurationSettings
    participant Modal as TeamIncidentPRsFilter Modal
    participant Redux
    participant API
    participant Backend

    User->>DoraSettings: Click "Incident PR Filter" menu item
    DoraSettings->>Modal: Open TeamIncidentPRsFilter modal
    Modal->>Redux: Dispatch fetchTeamIncidentPRsFilter (team_id)
    Redux->>API: GET /internal/team/{team_id}/incident_prs_filter
    API->>Backend: Fetch incident PR filter settings
    Backend-->>API: Return settings
    API-->>Redux: Return settings
    Redux-->>Modal: Provide incident PR filter settings

    User->>Modal: Edit and save filters
    Modal->>Redux: Dispatch updateTeamIncidentPRsFilter (team_id, setting)
    Redux->>API: PUT /internal/team/{team_id}/incident_prs_filter
    API->>Backend: Update settings
    Backend-->>API: Return updated settings
    API-->>Redux: Return updated settings
    Redux-->>Modal: Confirm update
    Modal->>Redux: Dispatch fetchDoraMetrics (with updated filters)
Loading

Possibly related PRs

  • middlewarehq/middleware#650: Implements backend support for IncidentPrsSetting, including data model and filtering logic for revert PRs, directly complementing the frontend and API changes here.
  • middlewarehq/middleware#656: Adds backend logic for applying incident PR filters to analytics and metrics, which aligns with the client-side and API interface introduced in this PR.

Poem

🐇
A filter for incidents, precise and neat,
Now teams can tailor which PRs they meet.
Regex and toggles, all wrapped in a form,
With modals and metrics, it’s far from the norm!
Settings are saved, the state is refreshed—
In the garden of code, our features have meshed.

— A rabbit, hopping through PRs


📜 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 a02603a and 2f35ad4.

📒 Files selected for processing (2)
  • web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts (1 hunks)
  • web-server/src/components/TeamIncidentPRsFilter.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts
  • web-server/src/components/TeamIncidentPRsFilter.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: All file linting
✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 10

🧹 Nitpick comments (7)
backend/analytics_server/mhq/service/code/pr_filter.py (1)

106-107: Change if to elif for setting type check

The current implementation uses if for both setting type checks, which means both conditions will be checked independently. Since these are mutually exclusive settings, using elif would be more appropriate and slightly more efficient.

if setting_type == SettingType.EXCLUDED_PRS_SETTING:
    self._apply_excluded_pr_ids_setting(setting=setting)
-if setting_type == SettingType.INCIDENT_PRS_SETTING:
+elif setting_type == SettingType.INCIDENT_PRS_SETTING:
    self._apply_incident_prs_setting(setting=setting)
web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts (1)

1-60: Consider adding error handling for specific error scenarios.

While the current implementation leverages the global error handling from handleRequest, consider adding specific error handling for common scenarios like not found or validation failures specific to this endpoint.

 endpoint.handle.GET(getSchema, async (req, res) => {
   const { team_id } = req.payload;
-  const { setting } = await handleRequest<TeamIncidentPRsSettingApiResponse>(
-    `/teams/${team_id}/settings`,
-    {
-      method: 'GET',
-      params: {
-        setting_type: 'INCIDENT_PRS_SETTING'
-      }
-    }
-  );
-  return res.send({ setting } as TeamIncidentPRsSettingsResponse);
+  try {
+    const { setting } = await handleRequest<TeamIncidentPRsSettingApiResponse>(
+      `/teams/${team_id}/settings`,
+      {
+        method: 'GET',
+        params: {
+          setting_type: 'INCIDENT_PRS_SETTING'
+        }
+      }
+    );
+    return res.send({ setting } as TeamIncidentPRsSettingsResponse);
+  } catch (error) {
+    // Handle specific error cases
+    if (error.response?.status === 404) {
+      return res.status(404).send({ 
+        error: 'Incident PR settings not found for this team' 
+      });
+    }
+    throw error; // Let the global error handler deal with other errors
+  }
 });
web-server/src/slices/team.ts (1)

272-295: Consider adding error handling for more resilient API interactions.

While the current implementation leverages the default error handling from handleApi, consider adding specific error handling to provide more meaningful feedback to users.

export const fetchTeamIncidentPRsFilter = createAsyncThunk(
  'teams/fetchTeamIncidentPRsFilter',
  async (params: { team_id: ID }) => {
-    return await handleApi<TeamIncidentPRsSettingsResponse>(
-      `/internal/team/${params.team_id}/incident_prs_filter`,
-      {
-        method: 'GET'
-      }
-    );
+    try {
+      return await handleApi<TeamIncidentPRsSettingsResponse>(
+        `/internal/team/${params.team_id}/incident_prs_filter`,
+        {
+          method: 'GET'
+        }
+      );
+    } catch (error) {
+      // Handle specific error cases, such as 404 or 500
+      console.error('Failed to fetch incident PR filters:', error);
+      throw error; // Rethrow to let Redux handle it
+    }
  }
);
web-server/src/components/TeamIncidentPRsFilter.tsx (1)

238-252: Autocomplete value is updated only on blur – use onChange to keep the form reactive

Relying solely on onBlur means that selecting an option with a mouse click updates the store only when the input loses focus, leading to surprising UX and possible validation mismatches (the user might press “Save” before blurring).

<Autocomplete
  freeSolo
  options={regexOptions.map((option) => option.value)}
  value={filter.value}
- onBlur={(e: any) => {
-   setValue(`setting.filters.${idx}.value`, e.target.value, {
-     shouldValidate: true,
-     shouldDirty: true
-   });
- }}
+ onChange={(_, newVal) =>
+   setValue(`setting.filters.${idx}.value`, newVal ?? '', {
+     shouldValidate: true,
+     shouldDirty: true,
+   })
+ }
+ onBlur={(e) =>
+   setValue(`setting.filters.${idx}.value`, e.target.value, {
+     shouldValidate: true,
+     shouldDirty: true,
+   })
+ }

Using both onChange and onBlur ensures the field stays in sync with user interactions.

backend/analytics_server/mhq/service/settings/configuration_settings.py (1)

264-270: Serialising dataclasses back to JSON should use asdict for symmetry

_adapt_incident_prs_setting_json_data re-assembles the dict manually. If IncidentPRsSetting gains new attributes (e.g., match_case), this function will silently drop them. Prefer:

-        return {
-            "include_revert_prs": specific_setting.include_revert_prs,
-            "filters": specific_setting.filters,
-        }
+        from dataclasses import asdict
+        return asdict(specific_setting)

Keeps the adapter future-proof and eliminates duplication.

backend/analytics_server/mhq/service/incidents/incidents.py (1)

165-174: Regex extraction helper could short-circuit on invalid patterns

check_regex presumably validates patterns; if it returns False we still call re.search, leading to re.error. Add an early bail-out:

-        if check_regex(regex_pattern):
-            match = re.search(regex_pattern, text)
+        if not check_regex(regex_pattern):
+            return None
+        match = re.search(regex_pattern, text)

Avoids unexpected exceptions.

backend/analytics_server/mhq/api/incidents.py (1)

122-131: Potential runtime type confusion – ensure pr_filter is always a dict before casting

pr_filter arrives as Optional[str] coerced through json.loads, but could still be None.
apply_pr_filter handles None, yet later layers (asdict(pr_filter) in incidents.py) assume a dataclass. Guard early:

pr_filter_data = pr_filter or {}
pr_filter: PRFilter = apply_pr_filter(
    pr_filter_data,
    EntityType.TEAM,
    team_id,
    [...]
)

Prevents accidental TypeError if JSON parsing fails and pr_filter becomes an unexpected type.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6920e76 and 3f32baa.

📒 Files selected for processing (22)
  • backend/analytics_server/mhq/api/incidents.py (7 hunks)
  • backend/analytics_server/mhq/api/resources/settings_resource.py (2 hunks)
  • backend/analytics_server/mhq/service/code/pr_filter.py (3 hunks)
  • backend/analytics_server/mhq/service/incidents/incident_filter.py (2 hunks)
  • backend/analytics_server/mhq/service/incidents/incidents.py (4 hunks)
  • backend/analytics_server/mhq/service/incidents/models/adapter.py (1 hunks)
  • backend/analytics_server/mhq/service/settings/configuration_settings.py (7 hunks)
  • backend/analytics_server/mhq/service/settings/default_settings_data.py (1 hunks)
  • backend/analytics_server/mhq/service/settings/models.py (1 hunks)
  • backend/analytics_server/mhq/service/settings/setting_type_validator.py (1 hunks)
  • backend/analytics_server/mhq/store/models/code/filter.py (2 hunks)
  • backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1 hunks)
  • backend/analytics_server/mhq/store/repos/code.py (1 hunks)
  • backend/analytics_server/tests/service/Incidents/test_incident_types_setting.py (1 hunks)
  • backend/analytics_server/tests/service/Incidents/test_mean_time_to_recovery.py (1 hunks)
  • backend/analytics_server/tests/service/Incidents/test_team_pr_incidents.py (1 hunks)
  • web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts (1 hunks)
  • web-server/src/components/DoraMetricsConfigurationSettings.tsx (4 hunks)
  • web-server/src/components/TeamIncidentPRsFilter.tsx (1 hunks)
  • web-server/src/slices/team.ts (5 hunks)
  • web-server/src/types/resources.ts (1 hunks)
  • web-server/src/utils/cockpitMetricUtils.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (12)
backend/analytics_server/mhq/api/resources/settings_resource.py (1)
backend/analytics_server/mhq/service/settings/models.py (1)
  • IncidentPRsSetting (56-58)
backend/analytics_server/mhq/service/settings/setting_type_validator.py (1)
backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)
  • SettingType (14-22)
backend/analytics_server/mhq/service/settings/default_settings_data.py (1)
backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)
  • SettingType (14-22)
web-server/src/components/DoraMetricsConfigurationSettings.tsx (2)
web-server/src/slices/team.ts (1)
  • fetchTeamIncidentPRsFilter (272-282)
web-server/src/components/TeamIncidentPRsFilter.tsx (1)
  • TeamIncidentPRsFilter (92-377)
backend/analytics_server/mhq/service/incidents/incident_filter.py (3)
backend/analytics_server/mhq/service/settings/models.py (1)
  • IncidentPRsSetting (56-58)
backend/analytics_server/mhq/store/models/incidents/enums.py (1)
  • IncidentType (29-32)
backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)
  • SettingType (14-22)
backend/analytics_server/mhq/store/models/code/filter.py (1)
backend/analytics_server/mhq/store/models/code/pull_requests.py (1)
  • PullRequest (12-76)
backend/analytics_server/mhq/service/incidents/models/adapter.py (2)
backend/analytics_server/mhq/store/models/code/pull_requests.py (1)
  • PullRequest (12-76)
backend/analytics_server/mhq/store/models/incidents/enums.py (2)
  • IncidentStatus (23-26)
  • IncidentType (29-32)
web-server/src/utils/cockpitMetricUtils.ts (2)
web-server/src/api-helpers/axios.ts (1)
  • handleRequest (86-96)
web-server/src/types/resources.ts (2)
  • MeanTimeToRestoreApiResponse (538-541)
  • MeanTimeToRestoreApiTrendsResponse (543-546)
backend/analytics_server/mhq/service/code/pr_filter.py (2)
backend/analytics_server/mhq/service/settings/models.py (2)
  • ExcludedPRsSetting (30-31)
  • IncidentPRsSetting (56-58)
backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)
  • SettingType (14-22)
web-server/src/slices/team.ts (1)
web-server/src/types/resources.ts (2)
  • TeamIncidentPRsSettingsResponse (638-640)
  • IncidentPRsSettings (623-629)
backend/analytics_server/mhq/service/settings/configuration_settings.py (2)
backend/analytics_server/mhq/service/settings/models.py (1)
  • IncidentPRsSetting (56-58)
backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)
  • SettingType (14-22)
backend/analytics_server/tests/service/Incidents/test_incident_types_setting.py (4)
backend/analytics_server/mhq/service/incidents/incident_filter.py (3)
  • ConfigurationsIncidentFilterProcessor (65-126)
  • apply (32-42)
  • apply (80-89)
backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)
  • SettingType (14-22)
backend/analytics_server/mhq/service/settings/models.py (2)
  • IncidentTypesSetting (35-36)
  • IncidentPRsSetting (56-58)
backend/analytics_server/mhq/store/models/incidents/enums.py (1)
  • IncidentType (29-32)
🪛 Biome (1.9.4)
web-server/src/components/TeamIncidentPRsFilter.tsx

[error] 185-185: 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)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: All file linting
🔇 Additional comments (34)
backend/analytics_server/mhq/store/repos/code.py (1)

310-327: Implementation looks clean and follows established patterns.

The new method get_prs_merged_in_interval_by_numbers is well-structured and consistent with other similar methods in the class. It properly reuses existing filtering methods and adds specific filtering by PR numbers. The method signature includes appropriate type hints and follows the repository's pattern of using the @rollback_on_exc decorator for error handling.

backend/analytics_server/mhq/store/models/settings/configuration_settings.py (1)

20-20: LGTM - Addition follows enum pattern.

The new INCIDENT_PRS_SETTING enum value is correctly added to the SettingType enum, following the established naming convention.

backend/analytics_server/mhq/service/settings/default_settings_data.py (1)

32-36: Default configuration is appropriately structured.

The default configuration for the incident PR settings initializes with sensible defaults - not including revert PRs and starting with an empty filters list. This follows the pattern established for other setting types in this function.

backend/analytics_server/mhq/service/settings/setting_type_validator.py (1)

22-23: Validator implementation is consistent with existing pattern.

The addition of validation support for the INCIDENT_PRS_SETTING type follows the established pattern in the function and ensures proper handling of the new setting type.

backend/analytics_server/tests/service/Incidents/test_mean_time_to_recovery.py (1)

19-19: Updated constructor call for compatibility with new dependencies.

The test has been correctly updated to reflect the new IncidentService constructor signature, which now requires three arguments instead of two. This change aligns with the extended service dependency on CodeRepoService for incident PR filtering functionality.

Also applies to: 27-27

backend/analytics_server/mhq/api/resources/settings_resource.py (2)

8-8: Added import for new IncidentPRsSetting class.

The import statement has been added correctly to support the new incident PR filtering functionality.


59-64: Support added for IncidentPRsSetting in API response serialization.

The implementation correctly adds the include_revert_prs boolean and filters list to the response when handling instances of IncidentPRsSetting. This follows the established pattern for other setting types in this file.

web-server/src/components/DoraMetricsConfigurationSettings.tsx (5)

6-6: Import added for TeamIncidentPRsFilter component.

The import statement has been correctly added to support the new UI for configuring incident PR filters.


13-16: Updated imports for team-related actions.

The imports have been refactored to use named imports in a cleaner format, adding the new action for fetching incident PR filters.


27-27: Added dispatch to fetch incident PR filter settings.

This dispatch ensures that incident PR filter settings are loaded when the component mounts, similar to the existing pattern for production branches.


40-47: Added callback for opening the incident PR filter modal.

The implementation correctly follows the existing pattern for modal creation, providing a consistent user experience with other configuration modals.


90-97: Added menu item for configuring incident PR filters.

The new menu item is correctly implemented, following the same pattern as the existing menu item for production branches.

backend/analytics_server/mhq/service/settings/models.py (2)

49-53: New dataclass IncidentPRFilter defined.

This dataclass is well-structured for representing a key-value pair for regex filters, with appropriate field types for string values.


55-58: New dataclass IncidentPRsSetting defined.

This setting class extends BaseSetting and includes appropriate fields for managing incident PR filtering options, with proper typing for the boolean flag and list of filters.

backend/analytics_server/mhq/store/models/code/filter.py (2)

16-16: Addition of incident_pr_filters looks good

The new attribute allows for storing a list of dictionaries that will be used for filtering PRs related to incidents.


102-102: LGTM - Adding incident_pr_filters to conditions dictionary

Properly adds the new query condition to the existing conditions dictionary.

backend/analytics_server/mhq/service/incidents/incident_filter.py (3)

7-7: LGTM - Imported IncidentPRsSetting correctly

Appropriate import added for the new setting type that will be used in the filter processing.


10-10: LGTM - Imported IncidentType for filtering logic

Added the necessary import for the enum that will be used in the filtering logic.


112-125: LGTM - Good implementation of revert PR filtering based on settings

The implementation correctly filters out the REVERT_PR incident type when the include_revert_prs flag is set to False in the IncidentPRsSetting. The code also properly handles type checking to ensure the setting is of the expected type.

backend/analytics_server/mhq/service/code/pr_filter.py (2)

4-4: LGTM - Added import for new IncidentPRsSetting

Correctly added import for the new setting type.


117-120: LGTM - Proper implementation of applying incident PR filters

The method correctly appends the filters from the setting to the PR filter's incident_pr_filters list, initializing it if it was previously None.

web-server/src/types/resources.ts (3)

623-629: Well-structured type definition for incident PR filters.

The IncidentPRsSettings type is well-defined with clear fields that capture both the inclusion of revert PRs and custom filters with field/value pairs.


631-636: Type follows API response pattern consistently.

The API response type includes standard fields (timestamps, team_id) alongside the settings payload, maintaining consistency with other similar response types in the codebase.


638-640: Simplified response type looks good.

This simplified response type focuses only on the settings data, appropriate for frontend consumption after API processing.

web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts (3)

10-25: Strong validation schemas for API inputs.

The Yup schemas effectively validate both the path parameters and request body, ensuring proper data structure and types. The nested schema for filters ensures each filter has required field and value properties.


27-41: GET handler implementation is clean and follows best practices.

The implementation properly extracts the team_id from the validated request payload, makes an appropriate backend request with setting_type parameter, and returns a well-structured response.


43-58: PUT handler follows consistent pattern for settings updates.

The implementation correctly extracts both team_id and setting from the validated request payload, makes the appropriate backend request with setting_type and setting_data, and returns a properly structured response.

web-server/src/utils/cockpitMetricUtils.ts (2)

114-115: Successfully integrated PR filters into MTTR metrics.

The changes correctly incorporate the PR filter parameter into all mean time to restore API requests, ensuring consistent filtering across current/previous stats and trends. This maintains consistency with how filters are applied to other metrics in the file.

Also applies to: 120-123, 129-130, 136-137


101-102: Consistent parameter extraction for PR filter.

The PR filter is correctly extracted from the parameters alongside the existing time objects.

web-server/src/slices/team.ts (4)

17-19: Added new types for PR filter functionality.

Imports have been properly updated to include the necessary types for incident PR filters.


37-37: State management extended for incident PR filters.

The state definition and initial state values have been properly updated to support the new incident PR filters feature.

Also applies to: 53-53


121-136: Redux reducers follow established patterns.

The implementation adds new reducer cases for incident PR filter operations following the existing pattern with addFetchCasesToReducer, maintaining consistency.


272-295: Well-implemented thunks for incident PR filter operations.

The thunks for fetching and updating incident PR filters follow Redux best practices and maintain consistency with existing code patterns.

backend/analytics_server/mhq/service/incidents/incidents.py (1)

148-151: pr_filter vs resolution_prs_filter – verify intent

You compute resolution_prs_filter (which already merges EXCLUDED_PRS_SETTING & INCIDENT_PRS_SETTING) but then pass the original pr_filter to get_prs_merged_in_interval_by_numbers.
If the original came from the API it lacks INCIDENT_PRS_SETTING, producing asymmetric results.

Please confirm which filter should be applied and adjust accordingly.

@adnanhashmi09
Copy link
Contributor

@coderabbitai full review

Copy link

coderabbitai bot commented May 25, 2025

✅ Actions performed

Full review triggered.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (4)
web-server/src/components/TeamIncidentPRsFilter.tsx (4)

247-256: Use onChange instead of onInputChange for better control.

The onInputChange fires on every keystroke including when navigating options. For better control and consistency, use onChange:

                     <Autocomplete
                       freeSolo
                       options={regexOptions.map((option) => option.value)}
                       value={filter.value}
-                      onInputChange={(_, value) => {
+                      onChange={(_, value) => {
-                        setValue(`setting.filters.${idx}.value`, value, {
+                        setValue(`setting.filters.${idx}.value`, value || '', {
                           shouldValidate: true,
                           shouldDirty: true
                         });
                       }}

291-295: Avoid using all: 'unset' style reset.

Using style={{ all: 'unset' }} removes all default styles which could break accessibility and expected behavior. Consider using MUI's styling system:

                         return (
                           <ListItem
                             {...props}
                             key={option}
-                            style={{ all: 'unset' }}
+                            disablePadding
+                            sx={{ display: 'block' }}
                           >

367-375: Extract complex disabled logic for better readability.

The button's disabled condition is complex and hard to parse. Consider extracting it:

+          const isEmptyFilter = settings.filters.length === 1 &&
+            !settings.filters[0].field &&
+            !settings.filters[0].value;
+          const isSaveDisabled = !isDirty || (!isValid && !isEmptyFilter);
+
           <LoadingButton
             type="submit"
             variant="outlined"
             color="primary"
-            disabled={
-              !isDirty ||
-              !(
-                isValid ||
-                (settings.filters.length === 1 &&
-                  !settings.filters[0].field &&
-                  !settings.filters[0].value)
-              )
-            }
+            disabled={isSaveDisabled}
             loading={isSaving.value}

92-390: Consider adding unit tests for regex validation logic.

This component introduces critical business logic for incident PR filtering. Consider adding comprehensive unit tests to cover:

  • Regex validation edge cases
  • Form state management
  • Save/update flow
  • Error scenarios

Would you like me to help generate unit tests for this component or open an issue to track this task?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 65b1873 and a02603a.

📒 Files selected for processing (6)
  • web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts (1 hunks)
  • web-server/src/components/DoraMetricsConfigurationSettings.tsx (4 hunks)
  • web-server/src/components/TeamIncidentPRsFilter.tsx (1 hunks)
  • web-server/src/slices/team.ts (5 hunks)
  • web-server/src/types/resources.ts (1 hunks)
  • web-server/src/utils/cockpitMetricUtils.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
web-server/src/slices/team.ts (1)
web-server/src/types/resources.ts (2)
  • TeamIncidentPRsSettingsResponse (638-640)
  • IncidentPRsSettings (623-629)
web-server/src/utils/cockpitMetricUtils.ts (2)
web-server/src/api-helpers/axios.ts (1)
  • handleRequest (86-96)
web-server/src/types/resources.ts (2)
  • MeanTimeToRestoreApiResponse (538-541)
  • MeanTimeToRestoreApiTrendsResponse (543-546)
🔇 Additional comments (19)
web-server/src/components/DoraMetricsConfigurationSettings.tsx (5)

6-6: LGTM! Clean component import.

The import follows the established pattern and integrates well with the existing codebase structure.


13-16: LGTM! Consistent import pattern.

The import structure maintains consistency with the existing fetchTeamReposProductionBranches import pattern.


27-27: LGTM! Proper integration in useEffect.

The dispatch call is correctly placed alongside the existing production branches fetch, ensuring both configurations are loaded when the component mounts.


40-46: LGTM! Consistent modal implementation.

The callback follows the exact same pattern as openProductionBranchSelectorModal, maintaining code consistency and reusability.


90-97: LGTM! Well-structured menu item.

The menu item implementation is consistent with the existing production branch configuration item, following the same click handler pattern.

web-server/src/types/resources.ts (3)

623-629: LGTM! Well-designed settings type.

The IncidentPRsSettings type is well-structured with clear field names and appropriate types. The filters array design allows for flexible field-value pair filtering.


631-636: LGTM! Consistent API response type.

The TeamIncidentPRsSettingApiResponse follows the established pattern of other team setting API response types in the file, maintaining consistency.


638-640: LGTM! Clean response type.

The simplified TeamIncidentPRsSettingsResponse type appropriately extracts only the setting data, following good API design principles.

web-server/pages/api/internal/team/[team_id]/incident_prs_filter.ts (4)

10-13: LGTM! Proper path validation.

The UUID validation for team_id is crucial for security and prevents injection attacks. Good use of Yup's built-in UUID validator.


15-25: LGTM! Comprehensive PUT schema validation.

The schema properly validates the setting structure including:

  • Boolean validation for include_revert_prs
  • Array validation for filters
  • Required string validation for field and value

This ensures data integrity and prevents malformed requests.


29-41: LGTM! Clean GET handler implementation.

The GET handler properly:

  • Extracts team_id from validated payload
  • Uses appropriate setting_type parameter
  • Returns consistent response structure

43-58: LGTM! Proper PUT handler implementation.

The PUT handler correctly:

  • Extracts both team_id and setting from payload
  • Sends setting_data to internal API
  • Returns consistent response structure matching the type definitions
web-server/src/utils/cockpitMetricUtils.ts (5)

101-103: LGTM! Proper parameter integration.

The prFilter parameter is correctly extracted from the function parameters and will be properly applied to the API requests.


114-114: LGTM! Consistent filter application.

The prFilter is properly spread into the request parameters, ensuring incident PR filters are applied to the current stats request.


121-123: LGTM! Complete filter integration.

Both prevStatsTimeObject and prFilter are correctly spread into the parameters for the previous stats request, maintaining consistency.


129-129: LGTM! Trends filtering applied correctly.

The prFilter is properly included in the current trends request parameters.


136-138: LGTM! Complete trends filter integration.

Both time object and PR filter are correctly applied to the previous trends request, ensuring all API calls in the function respect the incident PR filters.

web-server/src/slices/team.ts (1)

17-295: Redux implementation looks good!

The incident PR filters feature is well-integrated into the team slice:

  • New state field and types are properly added
  • Async thunks follow the established patterns
  • API endpoints are consistent with the naming convention
  • Error handling is managed through the existing addFetchCasesToReducer utility
web-server/src/components/TeamIncidentPRsFilter.tsx (1)

37-62: Well-designed schema validation!

The Yup schema correctly validates that regex patterns contain exactly one (\d+) capture group, which ensures the backend can reliably extract PR numbers from matched strings.

Copy link
Contributor

@jayantbh jayantbh left a comment

Choose a reason for hiding this comment

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

Good stuff, just minor things left.

@adnanhashmi09 adnanhashmi09 merged commit c42476c into middlewarehq:main May 30, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants