Skip to content

Refactor(permission,test)#398

Merged
kanyxmo merged 3 commits into
masterfrom
refactor(permission,test)
Oct 31, 2024
Merged

Refactor(permission,test)#398
kanyxmo merged 3 commits into
masterfrom
refactor(permission,test)

Conversation

@kanyxmo

@kanyxmo kanyxmo commented Oct 31, 2024

Copy link
Copy Markdown
Member

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new utility function for extracting specific keys from nested objects.
    • Added a database seeder to update menu entries.
  • Improvements

    • Updated permission codes for user and role management actions to reflect a more consistent naming convention.
    • Enhanced the delete operation in the user management interface for better synchronization.
  • Bug Fixes

    • Adjusted permission checks in tests to align with updated permission codes.
  • Chores

    • Commented out a console warning in the route store to streamline error reporting.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Oct 31, 2024
@coderabbitai

coderabbitai Bot commented Oct 31, 2024

Copy link
Copy Markdown

Walkthrough

The pull request includes modifications to permission codes in the RoleController and UserController, updating them to reflect a more consistent naming scheme. A new database seeder class is introduced to update menu entries, and various test files are adjusted to align with the new permission codes. Additionally, changes are made to the getTableColumns function and user-related components to enhance their functionality. A new utility function for extracting keys from nested objects is added, and minor adjustments to error reporting in the route store are included.

Changes

File Path Change Summary
app/Http/Admin/Controller/Permission/RoleController.php Updated permission codes in getRolePermissionForRole and batchGrantPermissionsForRole methods.
app/Http/Admin/Controller/Permission/UserController.php Updated permission codes in getUserRole and batchGrantRolesForUser methods.
databases/seeders/menu_update_20241031.php Added MenuUpdate20241031 seeder class with methods to update menu entries in the database.
tests/Feature/Admin/Permission/RoleControllerTest.php Modified assertions in testBatchGrantPermissionsForRole to reflect updated permission codes.
tests/Feature/Admin/Permission/UserControllerTest.php Updated permission checks in testBatchGrantRolesForUser to use new permission strings.
web/src/modules/base/views/permission/role/data/getTableColumns.tsx Changed setPermission action's show property to check multiple permission strings instead of one.
web/src/modules/base/views/permission/user/index.vue Updated handleDelete to await proTableRef.value.refresh() after deletion.
web/src/store/modules/useRouteStore.ts Commented out a console warning for missing route components in menuToRoutes.
web/src/store/modules/useUserStore.ts Added import for recursionGetKey and updated requestUserInfo method to use this utility function for collecting route names.
web/src/utils/recursionGetKey.ts Added a new utility function recursionGetKey for extracting specific keys from nested arrays.

Possibly related PRs

🐇 In the code, we hop and play,
Permissions change, a brand new way.
With menus updated, tests align,
A sprinkle of code, all works fine!
So let’s celebrate, with joy and cheer,
For every change brings us near! 🎉


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.

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.

@dosubot dosubot Bot added the enhancement label Oct 31, 2024

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (6)
web/src/utils/recursionGetKey.ts (1)

1-21: Add JSDoc documentation for better code clarity

While the file header provides project information, the function itself lacks documentation explaining its purpose, parameters, and return value.

Add function documentation:

+/**
+ * Recursively extracts values for a specified key from a nested array of objects
+ * @template T - Type of objects in the array
+ * @param {T[]} arr - Array of objects to process
+ * @param {keyof T} key - Key to extract from each object
+ * @returns {unknown[]} Array of extracted values
+ */
 export function recursionGetKey<T extends Record<string, unknown>>(arr: T[], key: keyof T): unknown[] {
databases/seeders/menu_update_20241031.php (1)

43-51: Add documentation for permission mapping structure.

Consider adding PHPDoc comments explaining:

  • The structure and format of permission codes
  • The reasoning behind the permission name changes
  • Any implications for existing code using these permissions
+    /**
+     * Returns the mapping of old permission codes to new ones.
+     * Format: 'old:permission:code' => 'new:permission:code'
+     *
+     * @return array<string, string> Array of permission mappings
+     */
     public function data(): array
app/Http/Admin/Controller/Permission/RoleController.php (1)

Line range hint 159-165: Consider enhancing error handling with more specific messages.

While the current error handling catches non-existent roles, consider these improvements:

  1. Add a specific error message to help identify the problematic role ID
  2. Validate permission IDs before applying them to prevent potential issues with invalid permissions

Here's a suggested improvement:

 if (! $this->service->existsById($id)) {
-    throw new BusinessException(code: ResultCode::NOT_FOUND);
+    throw new BusinessException(
+        sprintf('Role with ID %d not found', $id),
+        ResultCode::NOT_FOUND
+    );
 }
 $permissionIds = Arr::get($request->validated(), 'permissions', []);
+if (! empty($permissionIds)) {
+    // Validate that all permission IDs exist before applying
+    $validPermissions = Menu::whereIn('id', $permissionIds)->pluck('id')->toArray();
+    $invalidPermissions = array_diff($permissionIds, $validPermissions);
+    if (! empty($invalidPermissions)) {
+        throw new BusinessException(
+            sprintf('Invalid permission IDs: %s', implode(', ', $invalidPermissions)),
+            ResultCode::INVALID_PARAMS
+        );
+    }
+}
 $this->service->batchGrantPermissionsForRole($id, $permissionIds);
web/src/modules/base/views/permission/user/index.vue (1)

133-133: Good addition of await for proper async handling!

The addition of await ensures that the table refresh operation completes before proceeding, which is a good practice to prevent potential race conditions.

Consider adding error handling for the refresh operation:

- await proTableRef.value.refresh()
+ try {
+   await proTableRef.value.refresh()
+ } catch (error) {
+   msg.error(t('crud.refreshError'))
+ }
app/Http/Admin/Controller/Permission/UserController.php (2)

175-175: LGTM! Consider updating API documentation.

The permission code change aligns with the new standardized format. Since this is a breaking change in permission codes, ensure that the API documentation and client applications are updated accordingly.

Consider adding a comment in the API documentation to highlight this permission code change for API consumers.


Line range hint 157-175: Consider providing a migration guide for the permission code changes.

The permission code refactoring introduces a more structured format (permission:entity:action), which improves maintainability. However, this is a breaking change that affects multiple components.

Consider:

  1. Adding a migration guide in the documentation
  2. Implementing a temporary backward compatibility layer
  3. Providing a script to help users identify and update affected configurations
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 44ce6e3 and be166d1.

📒 Files selected for processing (10)
  • app/Http/Admin/Controller/Permission/RoleController.php (2 hunks)
  • app/Http/Admin/Controller/Permission/UserController.php (2 hunks)
  • databases/seeders/menu_update_20241031.php (1 hunks)
  • tests/Feature/Admin/Permission/RoleControllerTest.php (1 hunks)
  • tests/Feature/Admin/Permission/UserControllerTest.php (1 hunks)
  • web/src/modules/base/views/permission/role/data/getTableColumns.tsx (1 hunks)
  • web/src/modules/base/views/permission/user/index.vue (1 hunks)
  • web/src/store/modules/useRouteStore.ts (1 hunks)
  • web/src/store/modules/useUserStore.ts (2 hunks)
  • web/src/utils/recursionGetKey.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • web/src/store/modules/useRouteStore.ts
🔇 Additional comments (11)
web/src/utils/recursionGetKey.ts (1)

10-21: Verify the impact on route processing

Since this function is used for processing route names in useUserStore.ts, we should verify that it handles all possible route configurations correctly.

Let's check the route configurations:

✅ Verification successful

Let me gather more information about the menu structure and route configurations.


Based on the analysis of the codebase, I can now provide a final response:

The recursionGetKey function correctly handles route configurations

The function is used in useUserStore.ts to extract route names from the menu structure for permission checking. The analysis shows that:

  1. The menu structure follows a consistent pattern with optional children arrays and required name properties
  2. The recursive traversal matches the hierarchical menu structure used throughout the application
  3. The function is only used for permission code extraction, not for actual route processing
  4. The route configurations are properly handled separately by the router system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check route configurations to ensure they match the expected structure
# Expected structure: Objects with optional 'children' array and the key being extracted

# Search for route definitions
rg -l 'routes?\s*=|routes?:\s*\[' --type ts --type vue

# Search for usage of recursionGetKey
rg 'recursionGetKey' -A 5 -B 5

Length of output: 2769


Script:

#!/bin/bash
# Check the menu structure and route configurations

# Look for menu type definitions and interfaces
ast-grep --pattern 'interface $_Menu {
  $$$
}'

# Search for menu-related code and route configurations
rg -t ts "(menu.*=|route.*=|interface.*Menu)" -A 5 -B 2

# Look specifically for the getMenu implementation
ast-grep --pattern 'function getMenu() {
  $$$
}'

Length of output: 58977

databases/seeders/menu_update_20241031.php (2)

1-16: LGTM! Well-structured file header with proper imports.

The file includes appropriate strict typing, comprehensive documentation headers, and necessary imports.


19-27: Verify the usage of BASE_DATA constant.

The BASE_DATA constant appears to be unused in the implementation. If it's intended for future use or documentation purposes, consider adding a comment explaining its purpose. Otherwise, consider removing it to avoid confusion.

web/src/modules/base/views/permission/role/data/getTableColumns.tsx (1)

57-57: Permission check update looks good but needs verification.

The change from a single permission to an array of permissions aligns with the backend changes. However, let's verify the permission consistency across the stack.

✅ Verification successful

Permission changes are consistent across the stack

The verification shows that:

  • Backend controller methods are properly decorated with the new permissions permission:role:getMenu and permission:role:setMenu
  • A database seeder maps old permissions to these new ones
  • Tests validate both permissions are working correctly
  • Similar pattern is used in other parts of the codebase (e.g., user management)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify permission consistency across frontend and backend
# Expected: Permission strings should match in both frontend and backend

# Check frontend permission usage
echo "Frontend permission usage:"
rg -A 2 "permission:role:(getMenu|setMenu|permission)" --type ts --type tsx

# Check backend permission definitions
echo "Backend permission definitions:"
rg -A 2 "permission:role:(getMenu|setMenu|permission)" --type php

Length of output: 2566


Script:

#!/bin/bash
# Let's try again with correct file type for tsx/ts files and expand the search
echo "Frontend permission usage:"
rg -A 2 "permission:role:(getMenu|setMenu|permission)" 

# Also check for any other related permission checks in the codebase
echo -e "\nRelated permission checks:"
ast-grep --pattern 'showBtn($$$)'

Length of output: 3961

app/Http/Admin/Controller/Permission/RoleController.php (2)

157-157: Permission code change maintains consistency with the new naming scheme.

The updated permission code permission:role:setMenu aligns with the standardized format and pairs logically with the corresponding getMenu permission.

Let's verify the permission code consistency and related changes:

#!/bin/bash
# Search for any remaining old permission code
rg "permission:set:role"

# Search for the new permission code format
rg "permission:role:setMenu"

# Look for related test updates to ensure test coverage is maintained
rg -t php "role:setMenu" "tests/"

138-138: Permission code change aligns with the new naming convention.

The updated permission code permission:role:getMenu better reflects the method's purpose and follows the new standardized format permission:{entity}:{action}.

Let's verify the consistency of this permission code change across the codebase:

✅ Verification successful

Permission code change is consistent with the codebase-wide refactoring

The verification confirms that:

  • The old permission code permission:get:role is being systematically replaced with permission:role:getMenu as part of a broader permission naming standardization
  • The change is properly reflected in:
    • Database seeders (menu_update_20241031.php contains the mapping)
    • Tests (RoleControllerTest.php has updated assertions)
    • Frontend code (getTableColumns.tsx uses the new permission)
  • The new format follows the consistent pattern permission:{entity}:{action} across the codebase, as evidenced by similar changes in UserController (permission:user:getRole, permission:user:setRole)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining old permission code format
rg "permission:get:role"

# Search for the new permission code format to verify consistent usage
rg "permission:role:getMenu"

# Search for similar permission patterns to verify naming convention
rg "permission:[a-z]+:(get|set)[A-Z][a-zA-Z]+"

Length of output: 1425


Script:

#!/bin/bash
# Search for the new permission code format to verify consistent usage
rg "permission:role:getMenu"

# Search for similar permission patterns in PHP files
rg -t php "permission:[a-z]+:(get|set)[A-Z][a-zA-Z]+"

# Check menu seeders for permission mappings
rg -A 5 "permission:get:role|permission:role:getMenu" databases/seeders/

Length of output: 5057

app/Http/Admin/Controller/Permission/UserController.php (1)

157-157: LGTM! Verify test coverage for the updated permission code.

The permission code change follows the new standardized format permission:entity:action, which improves consistency across the codebase.

✅ Verification successful

Test coverage exists for the updated permission code

The test file tests/Feature/Admin/Permission/UserControllerTest.php contains comprehensive test coverage for the updated permission code permission:user:getRole. The test verifies:

  • Permission check before access
  • Permission grant functionality
  • Actual role retrieval with the new permission code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test coverage for the updated permission code
# Test: Search for test cases covering the new permission code
rg -l 'permission:user:getRole' --type php '*Test.php'

Length of output: 104


Script:

#!/bin/bash
# Let's try a more comprehensive search for test files
fd "Test\.php$" | while read -r file; do
    echo "=== $file ==="
    rg -A 5 "permission:user:getRole|'user:get:roles'" "$file" || true
done

# Also search for the controller test specifically
fd "UserControllerTest\.php$" | while read -r file; do
    echo "=== $file ==="
    cat "$file"
done

Length of output: 20066

web/src/store/modules/useUserStore.ts (2)

16-16: LGTM: Clean import statement

The import statement follows proper TypeScript conventions and uses appropriate module aliasing.


135-137: 🛠️ Refactor suggestion

Verify menu structure and add type safety

The new permission collection logic has changed from route-based to menu-based, which could have security implications. Consider the following improvements:

  1. Validate menu structure before recursion
  2. Add type checking for the menu items
  3. Handle potential undefined 'name' properties

Let's verify the menu structure and usage:

Consider adding type safety and validation:

-        const codes: string[] = recursionGetKey(getMenu(), 'name')
+        const menu = getMenu()
+        if (!menu || !Array.isArray(menu)) {
+          throw new Error('Invalid menu structure')
+        }
+        const codes: string[] = recursionGetKey(menu, 'name')
+        // Filter out undefined/null values
+        .filter(Boolean)
tests/Feature/Admin/Permission/RoleControllerTest.php (1)

231-237: Verify permission code changes across the codebase.

The permission codes have been updated from permission:set:role and permission:get:role to permission:role:setMenu and permission:role:getMenu. Let's ensure these changes are consistent across the codebase.

✅ Verification successful

Permission code changes are consistent across the codebase

The permission code changes from permission:get:role and permission:set:role to permission:role:getMenu and permission:role:setMenu are properly migrated across the codebase:

  1. The migration is handled by MenuUpdate20241031 seeder which explicitly maps the old codes to new ones:
'permission:get:role' => 'permission:role:getMenu',
'permission:set:role' => 'permission:role:setMenu',
  1. The new permission codes are correctly used in:
  • RoleController.php annotations (@Permission)
  • Frontend code in getTableColumns.tsx
  • Test file (RoleControllerTest.php)

The changes are consistent and complete across all relevant parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for old and new permission codes to ensure complete migration

echo "Checking for old permission codes..."
rg -l "permission:(set|get):role"

echo -e "\nChecking for new permission codes..."
rg -l "permission:role:(setMenu|getMenu)"

echo -e "\nChecking RoleController for permission annotations..."
rg -A 5 "@Permission" "app/Http/Admin/Controller/Permission/RoleController.php"

Length of output: 759


Script:

#!/bin/bash
# Let's examine the content of the files that contain permission codes

echo "Content of menu_update_20241031.php:"
cat databases/seeders/menu_update_20241031.php

echo -e "\nContent of menu_seeder_20240926.php:"
cat databases/seeders/menu_seeder_20240926.php

echo -e "\nContent of RoleController.php:"
cat app/Http/Admin/Controller/Permission/RoleController.php

echo -e "\nContent of getTableColumns.tsx:"
cat web/src/modules/base/views/permission/role/data/getTableColumns.tsx

Length of output: 32420

tests/Feature/Admin/Permission/UserControllerTest.php (1)

267-273: Permission naming convention updates look good!

The permission string updates follow the new standardized format:

  • Added 'permission:' prefix
  • Using camelCase for actions
  • Following entity-action pattern

Let's verify the permission string updates are consistent across the codebase:

✅ Verification successful

Permission updates are correctly implemented with proper migration path

The verification shows a well-managed permission update:

  • The new format permission:user:getRole and permission:user:setRole is consistently implemented in:
    • UserControllerTest.php (test cases)
    • UserController.php (controller annotations)
    • Frontend components (table columns)
  • Old format occurrences (user:get:roles, user:set:roles) only appear in:
    • menu_seeder_20240926.php (historical seeder)
    • menu_update_20241031.php (migration mapping old to new permissions)

The presence of the mapping in menu_update_20241031.php indicates a proper migration path for the permission changes, ensuring backward compatibility during the transition.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining old-style permission strings and verify new permission format adoption

# Check for old permission format
echo "Checking for old permission format..."
rg -l "user:(get|set):roles?"

# Verify new permission format usage
echo "Verifying new permission format..."
rg -l "permission:user:(get|set)Role"

# Check permission strings in route/middleware definitions
echo "Checking permission definitions in routes..."
rg -l "middleware.*permission:" -g "routes/*"

Length of output: 838


Script:

#!/bin/bash
# Let's check the specific content of files that still contain old permission format
echo "Content of files with old permission format:"
rg "user:(get|set):roles?" databases/seeders/menu_seeder_20240926.php databases/seeders/menu_update_20241031.php -B 2 -A 2

# Let's also check route definitions more broadly
echo -e "\nChecking route definitions:"
fd "routes" --type f --exec rg "permission:" {} -B 1 -A 1

# Let's verify the complete implementation in UserController
echo -e "\nChecking UserController implementation:"
rg "permission:user:(get|set)Role" app/Http/Admin/Controller/Permission/UserController.php -B 2 -A 2

Length of output: 2366

Comment thread web/src/utils/recursionGetKey.ts
Comment thread web/src/utils/recursionGetKey.ts
Comment thread databases/seeders/menu_update_20241031.php
Comment thread databases/seeders/menu_update_20241031.php
Comment thread web/src/modules/base/views/permission/role/data/getTableColumns.tsx
Comment thread tests/Feature/Admin/Permission/RoleControllerTest.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant