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(policy editor): app policy summary component #14757

Merged
merged 13 commits into from
Mar 4, 2025

Conversation

nkylstad
Copy link
Member

@nkylstad nkylstad commented Feb 20, 2025

Description

Created a summary component for app policy, that can be used to create an overview of the roles, actions and resources set in the policy.

Example with the default app policy:
Screenshot 2025-02-20 at 15 36 35

Implementing the component in the policy editor will be done in a separate PR.

Verification

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

Summary by CodeRabbit

  • New Features

    • Introduced new components in the policy editor that deliver a comprehensive, tabulated view of policy rules, subjects, and their associated actions.
    • Added localization support with new entries for clearer navigation and understanding of roles and access within the application.
    • Added a new test suite for the PolicyRuleSubjectSummary and PolicySummary components to ensure proper rendering and functionality.
  • Style

    • Enhanced layout styling to ensure consistent spacing and improved visual alignment within policy summary elements.
    • Added new CSS classes for better handling of layout in the PolicyRuleSubjectSummary and PolicyRuleSummary components.

Copy link
Contributor

coderabbitai bot commented Feb 20, 2025

Warning

Rate limit exceeded

@nkylstad has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 21 minutes and 40 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 8e2e2d4 and 7a1d9a8.

📒 Files selected for processing (2)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (1 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts (1 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces several enhancements across the policy editor module. It adds new CSS classes, multiple React components for summarizing policy rules and subjects, and corresponding types. Additionally, new test files have been created to validate these components. The changes also include an expanded set of utility functions and constants for managing policy rules, along with comprehensive unit tests. These updates extend functionality and improve test coverage for policy management in the UI.

Changes

File(s) Change summary
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSubjectSummary/PolicyRuleSubjectSummary.module.css Added a new CSS class (.limitationsCell) for layout styling.
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx, frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.test.tsx Implemented the PolicyRuleSubjectSummary React component with its prop type and created tests to verify rendering and functionality.
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.tsx Introduced the new PolicyRuleSummary component and its associated prop type to summarize policy rules, detailing subjects and localized actions in a table row.
frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.tsx, frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.test.tsx Added the PolicySummary component that provides an overview of policy rules in a table layout along with tests to verify correct rendering and behavior.
frontend/packages/policy-editor/src/types/index.ts Introduced new type declarations: AppPolicyActionMap and AppSubResourceDefaultLimitationType for enhanced type safety in policy handling.
frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts, frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts, frontend/packages/policy-editor/src/utils/AppPolicyUtils/index.ts Added multiple utility functions and constants for policy management (e.g., extracting unique actions/subjects, filtering rules, mapping actions) with comprehensive unit tests and updated module exports.
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.module.css Added a new CSS class (.subjectCell) for layout styling in the PolicyRuleSummary component.
frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.ts, frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.test.ts Introduced new utility methods (toString, getArrayFromString) in ArrayUtils with corresponding tests to enhance functionality and coverage.

Suggested reviewers

  • Jondyr
  • mlqn

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @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.

@github-actions github-actions bot added solution/studio/designer Issues related to the Altinn Studio Designer solution. area/authorization Area: Issues related to roles and rights on apps, such as who can instantiate, sign etc. frontend labels Feb 20, 2025
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

🧹 Nitpick comments (8)
frontend/packages/policy-editor/src/types/index.ts (1)

5-5: Consider adding JSDoc comments for the URN type.

The AppSubResourceDefaultLimitationType type would benefit from documentation explaining the significance of these URN values.

+/** URN type for defining the scope of sub-resource limitations in app policies */
 export type AppSubResourceDefaultLimitationType = 'urn:altinn:org' | 'urn:altinn:app';
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx (1)

31-47: Consider memoizing the action mapping logic.

The action mapping and rendering logic could benefit from memoization to prevent unnecessary re-renders.

+const MemoizedActionCell = React.memo(({ action, actionsForRole }: { action: string; actionsForRole: AppPolicyActionMap }) => (
+  <StudioTable.Cell>
+    <div className={classes.limitationsCell}>
+      {actionsForRole[action]
+        ? actionsForRole[action].split(', ').map((r, i) => (
+          <StudioTag size='small' key={i} color='info'>
+            {r}
+          </StudioTag>
+        ))
+        : '-'}
+    </div>
+  </StudioTable.Cell>
+));

 {actions.map((action, index) => (
-  <StudioTable.Cell key={index}>
-    <div className={classes.limitationsCell}>
-      {actionsForRole[action]
-        ? actionsForRole[action].split(', ').map((r, i) => {
-            return (
-              <StudioTag size='small' key={i} color='info'>
-                {r}
-              </StudioTag>
-            );
-          })
-        : '-'}
-    </div>
-  </StudioTable.Cell>
+  <MemoizedActionCell key={action} action={action} actionsForRole={actionsForRole} />
 ))}
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.tsx (1)

37-46: Move inline styles to CSS modules.

For better maintainability and consistency, move the inline styles to a CSS module.

+// PolicyRuleSummary.module.css
+.subjectContainer {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 4px;
+}

-<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
+<div className={classes.subjectContainer}>
frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.tsx (1)

8-54: Consider memoizing extracted values.

The extractAllUniqueActions and extractAllUniqueSubjects functions are called multiple times. Consider memoizing their results.

 export function PolicySummary() {
   const { policyRules } = usePolicyEditorContext();
   const { t } = useTranslation();
 
+  const uniqueActions = React.useMemo(() => extractAllUniqueActions(policyRules), [policyRules]);
+  const uniqueSubjects = React.useMemo(() => extractAllUniqueSubjects(policyRules), [policyRules]);
+
   return (
     // ... existing JSX
-    {extractAllUniqueActions(policyRules).map((action) => (
+    {uniqueActions.map((action) => (
       // ... action rendering
     ))}
     // ... more JSX
-    {extractAllUniqueSubjects(policyRules).map((subject) => (
+    {uniqueSubjects.map((subject) => (
       <PolicyRuleSubjectSummary
         subject={subject}
-        actions={extractAllUniqueActions(policyRules)}
+        actions={uniqueActions}
       />
     ))}
     // ... remaining JSX
   );
 }
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.test.tsx (1)

54-62: Improve test coverage for PolicyRuleSubjectSummary component.

The current test suite only verifies basic rendering. Consider adding test cases for:

  • Different subject types (role codes, organizations)
  • Various action combinations
  • Error states and edge cases
frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.test.tsx (1)

12-25: Consider extracting mock data to a shared test utility.

The mock subjects are duplicated across test files. Consider moving them to a shared test utility file, similar to how mockAction1, mockAction2 are imported from policyActionMocks.

frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts (2)

68-78: Consider memoizing the extracted subjects list.

The extractAllUniqueSubjects function processes the rules array on every call. Consider memoizing the result to improve performance when the rules haven't changed.

+import { useMemo } from 'react';

-export const extractAllUniqueSubjects = (rules: PolicyRuleCard[]): string[] => {
+export const useExtractAllUniqueSubjects = (rules: PolicyRuleCard[]): string[] => {
+  return useMemo(() => {
     const subjects: string[] = [];
     rules.forEach((rule) => {
       rule.subject.forEach((s) => {
         if (!subjects.includes(s.toLowerCase())) {
           subjects.push(s.toLowerCase());
         }
       });
     });
     return subjects;
+  }, [rules]);
 };

146-167: Consider using a more type-safe approach for action mapping.

The mapActionsForRole function uses a plain object for the result. Consider using a Map or defining a strict type for better type safety.

-  const result = {};
+  const result = new Map<string, string>();

   filterRulesWithSubject(policyRules, subject).forEach((rule) => {
     const covers = rule.resources
       .map((r) => getSubResourceDisplayText(r, usageType, t).concat(` (${rule.ruleId})`))
       .join(', ');

     rule.actions.forEach((action) => {
-      if (!result[action]) {
-        result[action] = `${covers}`;
+      if (!result.has(action)) {
+        result.set(action, covers);
       } else {
-        result[action] += `, ${covers}`;
+        result.set(action, `${result.get(action)}, ${covers}`);
       }
     });
   });
   return result;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 41c86ad and a2ecf84.

📒 Files selected for processing (10)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.module.css (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.test.tsx (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.tsx (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.test.tsx (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.tsx (1 hunks)
  • frontend/packages/policy-editor/src/types/index.ts (1 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (1 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts (1 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.module.css
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Testing
  • GitHub Check: CodeQL
  • GitHub Check: Build environment and run e2e test
🔇 Additional comments (2)
frontend/packages/policy-editor/src/types/index.ts (1)

1-3: LGTM! Well-defined type for action mapping.

The AppPolicyActionMap type provides a flexible structure for mapping policy actions.

frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (1)

13-491: Well-structured and comprehensive test suite!

The test suite provides excellent coverage with:

  • Clear test descriptions
  • Good edge case coverage
  • Thorough validation of functionality

Copy link

codecov bot commented Feb 21, 2025

Codecov Report

Attention: Patch coverage is 98.93617% with 1 line in your changes missing coverage. Please review.

Project coverage is 95.80%. Comparing base (d404250) to head (7a1d9a8).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...ary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx 93.33% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14757      +/-   ##
==========================================
+ Coverage   95.79%   95.80%   +0.01%     
==========================================
  Files        1928     1932       +4     
  Lines       25141    25235      +94     
  Branches     2868     2877       +9     
==========================================
+ Hits        24083    24176      +93     
  Misses        798      798              
- Partials      260      261       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (3)

59-85: Make the test description more descriptive.

Consider renaming the test description to better describe the scenario being tested, e.g., "should return an empty list when searching for a non-existent subject".

-    it('should return an empty list if no rules have the provided subject', () => {
+    it('should return an empty list when searching for a non-existent subject', () => {

169-173: Make the test description more descriptive.

Consider renaming the test description to better describe the scenario being tested, e.g., "should return an empty list when given an empty list of policy rules".

-    it('should return an empty list if the list of policy rules is empty', () => {
+    it('should return an empty list when given an empty list of policy rules', () => {

307-372: Add error cases for invalid inputs.

The mapActionsForRole function's test suite could benefit from additional test cases for invalid inputs:

  1. Invalid resource types
  2. Malformed resource arrays
  3. Empty or invalid actions

Consider adding these test cases:

it('should handle invalid resource types gracefully', () => {
  const rules: PolicyRuleCard[] = [{
    ruleId: '1',
    actions: ['read'],
    resources: [[{ type: 'invalid:type', id: 'test' }]],
    subject: ['subject1'],
    description: 'test'
  }];
  const mappedActions = mapActionsForRole(rules, 'subject1', 'app', textMock);
  expect(mappedActions).toEqual({});
});

it('should handle empty actions gracefully', () => {
  const rules: PolicyRuleCard[] = [{
    ruleId: '1',
    actions: [],
    resources: [[{ type: 'urn:altinn:app', id: '[app]' }]],
    subject: ['subject1'],
    description: 'test'
  }];
  const mappedActions = mapActionsForRole(rules, 'subject1', 'app', textMock);
  expect(mappedActions).toEqual({});
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2ecf84 and d269a23.

📒 Files selected for processing (4)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.test.tsx (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.tsx (1 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicySummary.tsx
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.test.tsx
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
  • GitHub Check: CodeQL
🔇 Additional comments (2)
frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (2)

212-265: Well-structured test cases with good coverage!

The test cases for getSubResourceDisplayText are well-structured and cover various scenarios:

  1. No limitations
  2. App sub-resource with limitations
  3. Generic sub-resource with limitations

The test descriptions are clear, and the assertions are specific and meaningful.


493-569: Excellent test coverage for case-insensitive subject matching!

The test cases for getSubjectDisplayName are comprehensive and cover important scenarios:

  1. Regular subject lookup
  2. Non-existent subject fallback
  3. Service owner special case
  4. Case-insensitive matching

The test descriptions are clear, and the assertions verify the expected behavior thoroughly.

Copy link
Collaborator

@framitdavid framitdavid left a comment

Choose a reason for hiding this comment

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

Nice works! 🎆 Added a few comments and nits 👏

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.ts (2)

79-86: Fix inconsistency in JSDoc documentation.

The JSDoc description for the delimiter parameter (line 82) mentions that it "Defaults to ', '" (with a space after the comma), but the actual implementation in code (line 85) uses just ',' without a space as the default value.

Update the JSDoc to match the actual implementation:

-   * @param delimiter The delimiter to use between items. Defaults to ', '.
+   * @param delimiter The delimiter to use between items. Defaults to ','.

88-97: Fix incorrect parameter name in JSDoc documentation.

The JSDoc has an incorrect parameter name. The first parameter is named "array" in the documentation but it should be "string" to match the actual parameter name.

Update the parameter name in the JSDoc:

-   * @param array The array of interest.
+   * @param string The string to split into an array.
frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.test.ts (2)

338-350: Add test case for whitespace trimming functionality.

The getArrayFromString implementation in ArrayUtils.ts trims whitespace from each item, but there's no test case specifically verifying this behavior.

Add a test case to verify that whitespace is properly trimmed:

  it('returns an empty array when the input string is empty', () => {
    expect(ArrayUtils.getArrayFromString('')).toEqual([]);
  });
+
+  it('trims whitespace from each item in the array', () => {
+    expect(ArrayUtils.getArrayFromString(' a , b , c ')).toEqual(['a', 'b', 'c']);
+  });

343-345: Test case description could be more precise.

The test description states "returns an array with the input string as the only element when no separator is found", but this might be slightly misleading. The string doesn't have to be "not found" - it's more that no splitting occurs because the delimiter doesn't exist in the input.

Consider rephrasing the test description for clarity:

-  it('returns an array with the input string as the only element when no separator is found', () => {
+  it('returns an array with the input string as the only element when the delimiter is not present in the string', () => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d269a23 and d699c63.

📒 Files selected for processing (4)
  • frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.test.ts (1 hunks)
  • frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.ts (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.module.css (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.module.css
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSummary.tsx
🔇 Additional comments (1)
frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.test.ts (1)

324-336: The test suite covers all essential scenarios well.

The test cases for the toString method cover the primary use cases: default delimiter behavior, empty array handling, and custom delimiter support.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx (2)

18-26: Consider memoizing the actionsForRole mapping.

The mapActionsForRole operation is potentially expensive and is being recalculated on every render. Since it depends only on the context and props, consider using React.useMemo to optimize performance.

- const actionsForRole = mapActionsForRole(policyRules, subject, usageType, t);
+ const actionsForRole = React.useMemo(
+   () => mapActionsForRole(policyRules, subject, usageType, t),
+   [policyRules, subject, usageType, t]
+ );

36-44: Implement safe access to actionsForRole using optional chaining.

Direct property access with actionsForRole[action] could potentially cause errors if the action key doesn't exist in the object. Using optional chaining would make the code more robust.

- {actionsForRole[action]
+ {actionsForRole?.[action]
   ? ArrayUtils.getArrayFromString(actionsForRole[action]).map((subResource) => {
       // ...

Also consider adding a null check for the second reference to actionsForRole[action] within the map function:

- ? ArrayUtils.getArrayFromString(actionsForRole[action]).map((subResource) => {
+ ? ArrayUtils.getArrayFromString(actionsForRole?.[action] || '').map((subResource) => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d699c63 and 348c5ec.

📒 Files selected for processing (2)
  • frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.test.ts (1 hunks)
  • frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Typechecking and linting
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: CodeQL
  • GitHub Check: Testing
🔇 Additional comments (4)
frontend/libs/studio-pure-functions/src/ArrayUtils/ArrayUtils.test.ts (2)

324-336: Tests look comprehensive and well-written.

The test cases for the toString method cover the essential scenarios including default delimiter behavior, empty array handling, and custom delimiter usage.


338-354: Good coverage of edge cases for the getArrayFromString method.

The test suite for getArrayFromString covers all important scenarios including basic parsing, handling single items without separators, empty strings, and whitespace trimming. This ensures the utility function behaves as expected in various conditions.

frontend/packages/policy-editor/src/components/PolicySummary/PolicyRuleSummary/PolicyRuleSubjectSummary.tsx (2)

13-16: Props interface is clean and focused.

The type definition is concise and clearly represents the data required for this component.


32-48: Use unique keys for array items.

Using array indices as keys can lead to rendering issues. Consider using a more stable unique identifier.

But I see you're now using key={action} for the StudioTable.Cell which is good. However, ensure action values are indeed unique in your application context to avoid potential key collisions.

@nkylstad
Copy link
Member Author

nkylstad commented Mar 4, 2025

Skipping manual test because these components are not actually implemented anywhere yet.

@nkylstad nkylstad added skip-manual-testing PRs that do not need to be tested manually skip-releasenotes Issues that do not make sense to list in our release notes labels Mar 4, 2025
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

🧹 Nitpick comments (5)
frontend/language/src/nb.json (1)

731-736: Review and Minor Correction for Summary Component Translations
The new keys for the policy summary component are implemented as follows:

  • "policy_editor.summary_heading": "Oversikt over tilganger som er satt opp for appen"
  • "policy_editor.summary_info_about": "I tabellen under kan du se en oversikt over hvilke roller som er gitt tilganger i appens tilgangspolicy, oghvilke rettigheter som er satt for de ulike rollene. Rettigheter kan settes for hele tjenesten, eller for spesifikke deler av tjenesten, som en oppgave i prosessen. Regelen som rettigheten er satt på vises i parentes."
  • "policy_editor.summary_info_edit": "Gå til fanen \"Rediger regler\" for å se detaljer om de enkelte reglene, og for å legge til eller fjerne regler."
  • "policy_editor.summary_table.header_rolecategory": "Kategori"
  • "policy_editor.summary_table.header_rolecode": "Kode"
  • "policy_editor.summary_table.header_rolename": "Navn"

There is a minor typographical error in "policy_editor.summary_info_about": the word "oghvilke" should be "og hvilke".

Please consider applying the following diff to correct this minor issue:

-"policy_editor.summary_info_about": "I tabellen under kan du se en oversikt over hvilke roller som er gitt tilganger i appens tilgangspolicy, oghvilke rettigheter som er satt for de ulike rollene. Rettigheter kan settes for hele tjenesten, eller for spesifikke deler av tjenesten, som en oppgave i prosessen. Regelen som rettigheten er satt på vises i parentes.",
+"policy_editor.summary_info_about": "I tabellen under kan du se en oversikt over hvilke roller som er gitt tilganger i appens tilgangspolicy, og hvilke rettigheter som er satt for de ulike rollene. Rettigheter kan settes for hele tjenesten, eller for spesifikke deler av tjenesten, som en oppgave i prosessen. Regelen som rettigheten er satt på vises i parentes.",
frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts (4)

38-45: Consider using .some() to avoid creating intermediate arrays.
Instead of mapping each subject to lowercase and then checking .includes(...), you could streamline the check:

-return rules.filter((rule) =>
-  rule.subject.map((s) => s.toLowerCase()).includes(subject.toLowerCase()),
-);
+return rules.filter((rule) =>
+  rule.subject.some((s) => s.toLowerCase() === subject.toLowerCase()),
+);

This avoids allocating a new array for each rule, though performance gains may be minor unless dealing with very large rule sets.


68-78: Optimize subject extraction using a Set.
Using a Set would simplify uniqueness checks and improve efficiency:

-export const extractAllUniqueSubjects = (rules: PolicyRuleCard[]): string[] => {
-  const subjects: string[] = [];
-  rules.forEach((rule) => {
-    rule.subject.forEach((s) => {
-      if (!subjects.includes(s.toLowerCase())) {
-        subjects.push(s.toLowerCase());
-      }
-    });
-  });
-  return subjects;
+export const extractAllUniqueSubjects = (rules: PolicyRuleCard[]): string[] => {
+  const foundSubjects = new Set<string>();
+  rules.forEach((rule) => {
+    rule.subject.forEach((s) => foundSubjects.add(s.toLowerCase()));
+  });
+  return Array.from(foundSubjects);
 };

85-95: Extract actions more cleanly using a Set.
This can mirror the approach suggested for subjects:

-export const extractAllUniqueActions = (rules: PolicyRuleCard[]): string[] => {
-  const actions: string[] = [];
-  rules.forEach((rule) => {
-    rule.actions.forEach((a) => {
-      if (!actions.includes(a)) {
-        actions.push(a);
-      }
-    });
-  });
-  return actions;
+export const extractAllUniqueActions = (rules: PolicyRuleCard[]): string[] => {
+  const foundActions = new Set<string>();
+  rules.forEach((rule) => {
+    rule.actions.forEach((a) => foundActions.add(a));
+  });
+  return Array.from(foundActions);
 };

139-167: Consider storing action coverage in a more structured format.
Currently, each action stores a comma-separated list of resource coverage strings. For future extensibility (e.g., sorting or filtering resources), you might store them in a data structure, then generate a string at the presentation layer.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 348c5ec and 8e2e2d4.

📒 Files selected for processing (3)
  • frontend/language/src/nb.json (3 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts (1 hunks)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build environment and run e2e test
  • GitHub Check: Testing
🔇 Additional comments (5)
frontend/language/src/nb.json (3)

660-660: New Translation Entry for Whole Service
The new key "policy_editor._subresource_covers.whole_service": "Hele tjenesten", is clearly added to support the policy summary component. The translation is concise and consistent with similar entries.


708-710: Review of Role Category Translations
The keys related to role categories are defined as follows:

  • "policy_editor.role_category.altinn_org": "Organisasjon"
  • "policy_editor.role_category.altinn_rolecode": "Rolle"
  • "policy_editor.role_category.unknown": "Ukjent"

These translations are clear and appropriate for their intended context in the policy editor.


725-726: Validation of Rule Editor Keys
The keys "policy_editor.rules_edit": "Regler" and "policy_editor.rules_summary": "Oversikt" are succinctly set. Please confirm that these brief terms fully capture their intended actions without causing confusion in the UI. Overall, they seem consistent with the rest of the localization entries.

frontend/packages/policy-editor/src/utils/AppPolicyUtils/AppPolicyUtils.ts (2)

9-14: Constants look good.
The default limitations and subject code/name constants are straightforward and seem appropriate for labeling service owners in the policy editor context.


22-30: Implementation of getSubjectDisplayName is clear and intuitive.
Using case-insensitive matching for subject IDs is a solid approach, and falling back to the subject if none is found provides robust handling of unexpected cases.

@nkylstad nkylstad merged commit 38052e5 into main Mar 4, 2025
9 of 10 checks passed
@nkylstad nkylstad deleted the feat(policy-editor)/app-policy-summary branch March 4, 2025 13:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/authorization Area: Issues related to roles and rights on apps, such as who can instantiate, sign etc. frontend skip-manual-testing PRs that do not need to be tested manually skip-releasenotes Issues that do not make sense to list in our release notes solution/studio/designer Issues related to the Altinn Studio Designer solution.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants