Skip to content

feat(menu): 更新菜单权限并添加数据中心相关权限#388

Merged
kanyxmo merged 1 commit into
masterfrom
fix-add-attachment-menu-seeder
Oct 30, 2024
Merged

feat(menu): 更新菜单权限并添加数据中心相关权限#388
kanyxmo merged 1 commit into
masterfrom
fix-add-attachment-menu-seeder

Conversation

@people-sea

@people-sea people-sea commented Oct 29, 2024

Copy link
Copy Markdown
Member
  • 修改附件管理相关权限代码,增加 dataCenter前缀
  • 添加数据中心菜单及其子菜单项
  • 更新相关测试用例以匹配新的权限代码

Summary by CodeRabbit

  • New Features

    • Updated permission codes for attachment management methods to better categorize permissions.
    • Introduced a new database seeder for populating menu-related data, including hierarchical menu structure.
  • Bug Fixes

    • Adjusted test cases to reflect updated permission codes for attachment actions, ensuring accurate authorization checks.

- 修改附件管理相关权限代码,增加 dataCenter前缀
- 添加数据中心菜单及其子菜单项
- 更新相关测试用例以匹配新的权限代码
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Oct 29, 2024
@people-sea
people-sea requested a review from zds-s October 29, 2024 18:20
@coderabbitai

coderabbitai Bot commented Oct 29, 2024

Copy link
Copy Markdown

Walkthrough

The changes in this pull request involve updates to permission codes in the AttachmentController class, adding a dataCenter: prefix to the existing codes for the list, upload, and delete methods. Additionally, a new database seeder class, MenuUpdate20241029, is introduced to populate the database with a hierarchical menu structure, including menu items related to attachments. Corresponding updates to the AttachmentControllerTest class reflect these permission code changes to ensure consistency in testing.

Changes

File Path Change Summary
app/Http/Admin/Controller/AttachmentController.php Updated permission codes for list, upload, and delete methods from attachment:* to dataCenter:attachment:*.
databases/seeders/menu_update_20241029.php Added MenuUpdate20241029 seeder class with methods to populate the database with hierarchical menu data.
tests/Feature/Admin/DataCenter/AttachmentControllerTest.php Updated permission codes in tests for testPageList and testDelete methods to match the new format.

Possibly related PRs

Poem

🐇 In the garden where data blooms,
New permissions dance in digital rooms.
Attachments now have a clearer way,
With seeding menus brightening the day.
Hop along, let the changes sing,
For a better structure, we joyfully spring! 🌼


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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0859e44 and a434922.

📒 Files selected for processing (3)
  • app/Http/Admin/Controller/AttachmentController.php (3 hunks)
  • databases/seeders/menu_update_20241029.php (1 hunks)
  • tests/Feature/Admin/DataCenter/AttachmentControllerTest.php (2 hunks)
🔇 Additional comments (8)
tests/Feature/Admin/DataCenter/AttachmentControllerTest.php (3)

31-31: LGTM! Permission code update aligns with requirements.

The updated permission code dataCenter:attachment:list correctly reflects the new hierarchical permission structure, and the test comprehensively verifies all access scenarios.


71-71: LGTM! Permission code update maintains test integrity.

The updated permission code dataCenter:attachment:delete correctly reflects the new structure while maintaining comprehensive test coverage, including proper setup, authorization checks, and deletion verification.


Line range hint 1-91: Consider adding test coverage for upload operation.

The test file covers list and delete operations, but appears to be missing test coverage for the upload operation that should use the dataCenter:attachment:upload permission code. Consider adding a testUpload method to ensure complete test coverage of all attachment operations.

Would you like me to help generate a test method for the upload operation?

app/Http/Admin/Controller/AttachmentController.php (3)

51-51: LGTM! Permission code update aligns with data center categorization.

The permission code change properly reflects the method's categorization under the data center module, maintaining consistency with the Swagger documentation.


72-72: LGTM! Permission code update maintains consistency.

The permission code change follows the same pattern as other methods, maintaining a consistent permission hierarchy within the data center module.


89-89: LGTM! Permission code update is consistent. Verify related components.

The permission code change maintains consistency with the data center module structure.

Let's verify that all related components (tests, seeders, frontend) have been updated to use the new permission codes:

✅ Verification successful

Permission code changes are properly synchronized across all components

All related files have been updated to use the new dataCenter:attachment:* permission codes:

  • Controller: All three permissions (list, upload, delete) use the new format
  • Database seeder: Menu permissions are correctly defined with the new format
  • Test file: Test cases use the updated permission codes

The changes are consistent and no remnants of the old permission format were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining old permission codes that might need updating
rg -l 'attachment:(list|upload|delete)' --type php

# Search for the new permission codes to ensure they're properly referenced
rg -l 'dataCenter:attachment:(list|upload|delete)' --type php

Length of output: 424


Script:

#!/bin/bash
# Let's check the actual content of these files to verify the permission codes
echo "=== AttachmentController.php ==="
rg 'attachment:(list|upload|delete)|dataCenter:attachment:(list|upload|delete)' app/Http/Admin/Controller/AttachmentController.php

echo -e "\n=== menu_update_20241029.php ==="
rg 'attachment:(list|upload|delete)|dataCenter:attachment:(list|upload|delete)' databases/seeders/menu_update_20241029.php

echo -e "\n=== AttachmentControllerTest.php ==="
rg 'attachment:(list|upload|delete)|dataCenter:attachment:(list|upload|delete)' tests/Feature/Admin/DataCenter/AttachmentControllerTest.php

Length of output: 1124

databases/seeders/menu_update_20241029.php (2)

1-28: LGTM! Well-structured class declaration with proper documentation.

The file follows PHP best practices with strict typing, proper documentation, and clear constant definition.


82-104: Verify permission code alignment with controllers.

The permission codes (dataCenter:attachment:list, dataCenter:attachment:upload, dataCenter:attachment:delete) should match the permission checks in the AttachmentController. Let's verify this alignment.

✅ Verification successful

Permission codes perfectly align with controller annotations

The permission codes in the menu seeder exactly match the Permission attribute annotations in AttachmentController.php:

  • dataCenter:attachment:list
  • dataCenter:attachment:upload
  • dataCenter:attachment:delete
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for permission checks in AttachmentController
rg -A 2 "Permission\(['\"]dataCenter:attachment:" app/

Length of output: 58


Script:

#!/bin/bash
# Let's try a broader search for the controller and permission checks
# First, find the attachment controller
fd -e php "AttachmentController"

# Also search for any permission checks related to attachments
rg -i "permission.*attach" app/

Length of output: 496

Comment on lines +43 to +110
public function data(): array
{
return [
[
'name' => 'dataCenter',
'path' => '/dataCenter',
'meta' => new Meta([
'title' => '数据中心',
'i18n' => 'baseMenu.dataCenter.index',
'icon' => 'ri:database-line',
'type' => 'M',
'hidden' => 1,
'componentPath' => 'modules/',
'componentSuffix' => '.vue',
'breadcrumbEnable' => 1,
'copyright' => 1,
'cache' => 1,
'affix' => 0,
]),
'children' => [
[
'name' => 'dataCenter:attachment',
'path' => '/dataCenter/attachment',
'component' => 'base/views/dataCenter/attachment/index',
'meta' => new Meta([
'title' => '附件管理',
'type' => 'M',
'hidden' => 1,
'icon' => 'ri:attachment-line',
'i18n' => 'baseMenu.dataCenter.attachment',
'componentPath' => 'modules/',
'componentSuffix' => '.vue',
'breadcrumbEnable' => 1,
'copyright' => 1,
'cache' => 1,
'affix' => 0,
]),
'children' => [
[
'name' => 'dataCenter:attachment:list',
'meta' => new Meta([
'title' => '附件列表',
'i18n' => 'baseMenu.dataCenter.attachmentList',
'type' => 'B',
]),
],
[
'name' => 'dataCenter:attachment:upload',
'meta' => new Meta([
'title' => '上传附件',
'i18n' => 'baseMenu.dataCenter.attachmentUpload',
'type' => 'B',
]),
],
[
'name' => 'dataCenter:attachment:delete',
'meta' => new Meta([
'title' => '删除附件',
'i18n' => 'baseMenu.dataCenter.attachmentDelete',
'type' => 'B',
]),
],
],
],
],
],
];
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using constants for menu types and common values.

The menu structure is well-organized, but could benefit from these improvements:

  1. Define constants for menu types ('M', 'B')
  2. Consider creating an enum for menu types
  3. Consider validating i18n keys format

Example implementation:

class MenuType
{
    public const MENU = 'M';
    public const BUTTON = 'B';
}

// Usage in data():
'type' => MenuType::MENU

Comment on lines +112 to +125
public function create(array $data, int $parent_id = 0): void
{
foreach ($data as $v) {
$_v = $v;
if (isset($v['children'])) {
unset($_v['children']);
}
$_v['parent_id'] = $parent_id;
$menu = Menu::create(array_merge(self::BASE_DATA, $_v));
if (isset($v['children']) && count($v['children'])) {
$this->create($v['children'], $menu->id);
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding validation and optimizing performance.

The recursive creation logic works but could be improved:

  1. Add validation for required fields before creation
  2. Consider adding a max depth limit to prevent stack overflow
  3. Consider using batch inserts for better performance

Here's a suggested implementation:

+ private const MAX_DEPTH = 5;  // Prevent excessive nesting

- public function create(array $data, int $parent_id = 0): void
+ public function create(array $data, int $parent_id = 0, int $depth = 0): void
 {
+    if ($depth >= self::MAX_DEPTH) {
+        throw new \RuntimeException('Maximum menu depth exceeded');
+    }
+
+    $batch = [];
     foreach ($data as $v) {
         $_v = $v;
+        // Validate required fields
+        if (empty($_v['name'])) {
+            throw new \InvalidArgumentException('Menu name is required');
+        }
+
         if (isset($v['children'])) {
             unset($_v['children']);
         }
         $_v['parent_id'] = $parent_id;
-        $menu = Menu::create(array_merge(self::BASE_DATA, $_v));
+        $batch[] = array_merge(self::BASE_DATA, $_v);
     }
+    
+    // Batch insert menus
+    $menus = Menu::insert($batch);
+    
+    // Process children
+    foreach ($data as $k => $v) {
         if (isset($v['children']) && count($v['children'])) {
-            $this->create($v['children'], $menu->id);
+            $this->create($v['children'], $menus[$k]->id, $depth + 1);
         }
     }
 }

Committable suggestion was skipped due to low confidence.

Comment on lines +32 to +41
public function run(): void
{
if (env('DB_DRIVER') === 'odbc-sql-server') {
Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] ON;');
}
$this->create($this->data());
if (env('DB_DRIVER') === 'odbc-sql-server') {
Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] OFF;');
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding transaction and error handling.

While the SQL Server identity insert handling is good, consider these improvements for better reliability:

  1. Wrap the seeding operation in a transaction
  2. Add try-catch block for error handling

Here's a suggested implementation:

 public function run(): void
 {
+    try {
+        Db::beginTransaction();
         if (env('DB_DRIVER') === 'odbc-sql-server') {
             Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] ON;');
         }
         $this->create($this->data());
         if (env('DB_DRIVER') === 'odbc-sql-server') {
             Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] OFF;');
         }
+        Db::commit();
+    } catch (\Throwable $e) {
+        Db::rollBack();
+        throw $e;
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public function run(): void
{
if (env('DB_DRIVER') === 'odbc-sql-server') {
Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] ON;');
}
$this->create($this->data());
if (env('DB_DRIVER') === 'odbc-sql-server') {
Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] OFF;');
}
}
public function run(): void
{
try {
Db::beginTransaction();
if (env('DB_DRIVER') === 'odbc-sql-server') {
Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] ON;');
}
$this->create($this->data());
if (env('DB_DRIVER') === 'odbc-sql-server') {
Db::unprepared('SET IDENTITY_INSERT [' . Menu::getModel()->getTable() . '] OFF;');
}
Db::commit();
} catch (\Throwable $e) {
Db::rollBack();
throw $e;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

2 participants