Skip to content

Conversation

@mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Feb 25, 2025

Description

添加演示页面:部门管理

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features
    • Launched a comprehensive department management module allowing users to create, edit, and delete departments via an interactive grid and modal forms.
    • Enhanced table display with dynamic cell renderers for status tags and action buttons.
    • Expanded navigation with new routes for streamlined system management.
    • Broadened localization support with additional language strings for both English and Chinese.
    • Introduced a new icon to enrich the visual interface.
    • Added a new API for managing department data, including fetching, creating, updating, and deleting departments.
  • Bug Fixes
    • Improved form validation and state management in department creation and editing modals.

@mynetfan mynetfan requested review from a team, anncwb and vince292007 as code owners February 25, 2025 11:16
@changeset-bot
Copy link

changeset-bot bot commented Feb 25, 2025

⚠️ No Changeset found

Latest commit: c0bb035

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

This update introduces several new API endpoints and event handlers for department management in the backend mock service, including token verification and simulated delays. It also updates middleware to handle asynchronous requests. In addition, new icons and extended localization strings (both in English and Chinese) have been added. On the frontend, a new system API is defined for department operations, along with updates to table renderers, route definitions, and Vue components for displaying and editing department data.

Changes

Files Change Summary
apps/backend-mock/api/system/dept/*.ts (including .post.ts, [id].delete.ts, [id].put.ts) Added new asynchronous event handlers that verify access tokens, incorporate sleep delays, and return appropriate success or unauthorized responses.
apps/backend-mock/api/system/dept/list.ts New event handler generating mock department data with authentication and delay before responding successfully.
apps/backend-mock/middleware/1.api.ts Updated the event handler signature to asynchronous and added conditional sleep delays with forbidden response for specific HTTP methods.
packages/@core/base/icons/src/lucide.ts Added the Plus icon export to the icons set.
packages/locales/src/index.ts Introduced a new constant $te to support additional translation methods, expanding the export list.
packages/locales/src/langs/en-US/common.json
packages/locales/src/langs/en-US/ui.json
packages/locales/src/langs/zh-CN/common.json
packages/locales/src/langs/zh-CN/ui.json
Added new key-value pairs and sections to enhance localization support for common and UI messages in both English (US) and Chinese (CN).
playground/src/adapter/vxe-table.ts Enhanced table rendering with new cell renderers (CellTag and CellOperation), updated proxy configuration, and added new type definitions for action click handling.
playground/src/api/system/dept.ts New TypeScript API implementation for system department operations with endpoints for list, create, update, and delete.
playground/src/locales/langs/en-US/system.json
playground/src/locales/langs/zh-CN/system.json
New JSON localization files for system management, providing labels and descriptors for department-related fields.
playground/src/router/routes/modules/system.ts New route definitions for the system module with a child route for department management, using dynamic component imports and localization.
playground/src/views/system/dept/data.ts
playground/src/views/system/dept/list.vue
playground/src/views/system/dept/modules/form.vue
New Vue components and utility functions for managing department data, including form schema, grid columns, modal interactions, and CRUD operation handlers.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Handler
  participant Auth as verifyAccessToken
  participant Delay as sleep
  participant ResponseSuccess as useResponseSuccess
  participant Unauth as unAuthorizedResponse
  
  Client->>Handler: Send request (POST/PUT/DELETE)
  Handler->>Auth: Verify access token
  alt Token invalid
    Auth-->>Handler: Falsy userinfo
    Handler->>Unauth: Return unauthorized response
    Unauth-->>Client: Unauthorized response
  else Token valid
    Auth-->>Handler: Valid userinfo
    Handler->>Delay: Sleep (600-2000ms)
    Delay-->>Handler: Wait complete
    Handler->>ResponseSuccess: Return success response
    ResponseSuccess-->>Client: Success data
  end
Loading
sequenceDiagram
  participant User
  participant Grid as DeptListComponent
  participant Modal as FormModal
  participant API as SystemDeptApi
  
  User->>Grid: Request department data/actions
  Grid->>API: Call getDeptList / createDept / updateDept / deleteDept
  API-->>Grid: Send department data or operation result
  Grid-->>User: Display updated grid
  
  User->>Grid: Trigger create/edit action
  Grid->>Modal: Open modal with form (useSchema)
  Modal->>User: Collect department data
  User->>Modal: Submit form
  Modal->>API: Process create/update request
  API-->>Modal: Return operation result
  Modal->>Grid: Call refreshGrid
  Grid-->>User: Updated department list displayed
Loading

Suggested reviewers

  • vince292007
  • anncwb

Poem

O hopping code, so swift and bright,
I scurry through each byte tonight.
New endpoints bloom by day and night,
With tokens checked and forms in flight.
In fields of code, I munch with glee—
A rabbit’s joy in every API!
🐰✨


📜 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 5819a6a and c0bb035.

📒 Files selected for processing (5)
  • apps/backend-mock/api/system/dept/.post.ts (1 hunks)
  • apps/backend-mock/api/system/dept/[id].delete.ts (1 hunks)
  • apps/backend-mock/api/system/dept/[id].put.ts (1 hunks)
  • apps/backend-mock/api/system/dept/list.ts (1 hunks)
  • apps/backend-mock/middleware/1.api.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/backend-mock/api/system/dept/.post.ts
  • apps/backend-mock/api/system/dept/[id].put.ts
  • apps/backend-mock/api/system/dept/list.ts
  • apps/backend-mock/api/system/dept/[id].delete.ts
  • apps/backend-mock/middleware/1.api.ts
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)

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. (Beta)
  • @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
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: 6

🧹 Nitpick comments (18)
apps/backend-mock/api/system/dept/[id].put.ts (1)

9-9: Consider consistent delay times across similar endpoints.

This endpoint has a 2000ms delay, while the POST endpoint uses 600ms. Unless there's a specific reason for the longer delay on updates, consider using consistent delay times across similar endpoints for a more predictable mock API behavior.

apps/backend-mock/api/system/dept/[id].delete.ts (1)

4-11: Consider adding error handling for the delete operation

The event handler currently handles token verification but lacks a try/catch block to manage potential errors during the delete operation.

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }
-  await sleep(1000);
-  return useResponseSuccess(null);
+  try {
+    await sleep(1000);
+    return useResponseSuccess(null);
+  } catch (error) {
+    return createError({
+      statusCode: 500,
+      message: 'Failed to delete department',
+    });
+  }
});
apps/backend-mock/middleware/1.api.ts (1)

10-16: Consider internationalizing the error message

The error message "演示环境,禁止修改" (which means "Demo environment, modification is prohibited") is hardcoded in Chinese. Consider using an internationalization approach for better user experience across different locales.

packages/locales/src/langs/en-US/common.json (1)

19-19: Add trailing comma for consistency

Consider adding a trailing comma after the "create" translation key for consistency with other entries and to make future additions cleaner in the diff.

-  "create": "Create"
+  "create": "Create",
playground/src/views/system/dept/data.ts (4)

16-27: Refine user feedback on validation.
The form rules for name look good. However, consider providing more user-friendly messages or localized strings for the minimum/maximum length validation to help guide end-users more effectively.


42-54: Use a typed enum or constant for status.
Defining status values as numeric literals can lead to confusion. Extract them into an enum or constant for better clarity and maintainability.

- { label: $t('common.enabled'), value: 1 },
- { label: $t('common.disabled'), value: 0 },
+ import { DEPT_STATUS } from '../constants';

+ { label: $t('common.enabled'), value: DEPT_STATUS.ENABLED },
+ { label: $t('common.disabled'), value: DEPT_STATUS.DISABLED },

56-68: Add minimal length validation for remarks.
Although remark is optional, you might want to ensure at least some comments are still meaningful, possibly with a minimal length if desired.


80-135: Review delete restrictions for nested departments.
The current logic disables delete if the department has children, which is appropriate. However, consider whether a recursive deletion or a user confirmation for bulk deletion might be desirable.

playground/src/views/system/dept/modules/form.vue (2)

35-50: Add error feedback for create or update failures.
Inside the try block, there's no error-specific handling. You may want to catch exceptions and display an appropriate notification or message to inform the user of potential errors (e.g., network or validation errors).

try {
  await (formData.value?.id
    ? updateDept(formData.value.id, data)
    : createDept(data)
  );
  modalApi.close();
  emit('success');
} catch (err) {
+ // Notify user about the specific error
+ console.error(err);
+ // Add an error notification or UI feedback
} finally {
  modalApi.lock(false);
}

72-78: Provide a more descriptive "Reset" label or confirm its meaning.
“Reset” might be slightly ambiguous to some users. Consider a label like “Clear Form” or “Revert” for better clarity, if suitable to your UX guidelines.

playground/src/api/system/dept.ts (2)

14-21: Add potential caching strategy for getDeptList.
If department data is frequently requested and rarely changes, a simple caching mechanism (in-memory or local) could reduce network overhead and speed up subsequent requests.


23-52: Centralize error handling for all CRUD operations.
Each function simply returns the request client promise. Consider adding a wrapper or interceptor to handle and log errors consistently across all department endpoints.

playground/src/adapter/vxe-table.ts (2)

77-95: Enable dynamic or extended Tag states.
Currently, CellTag only distinguishes between enabled/disabled. For future maintainability, you might anticipate more statuses (e.g., pending, archived). Consider extending the tag options or making them configurable via props.


100-223: Enhance operation button feedback.
The Popconfirm for delete is great, but there's no indication of success or error after the delete action. Adding visual or textual feedback could improve user clarity.

playground/src/views/system/dept/list.vue (4)

52-69: Enhance error handling in the delete operation.

The delete operation has a catch block that only hides the loading message without displaying an error message to the user. This might lead to confusion if the deletion fails.

Consider adding an error message to inform the user when deletion fails:

    .catch(() => {
      hideLoading();
+     message.error({
+       content: $t('ui.actionMessage.deleteFailed', [row.name]),
+       key: 'action_process_msg',
+     });
    });

134-134: Consider using localization for the table title.

The table title "部门列表" is hardcoded in Chinese, which could create inconsistency in a multilingual application.

Replace the hardcoded text with a localized string:

-    <Grid table-title="部门列表">
+    <Grid :table-title="$t('system.dept.list')">

97-97: Consider memoizing the columns configuration.

The columns configuration is recreated on each render with useColumns(onActionClick), which might impact performance for complex tables.

Consider using useMemo or a similar approach to memoize the columns:

+ import { useMemo } from 'vue';

// elsewhere in your component setup
+ const columns = useMemo(() => useColumns(onActionClick), []);

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents: {},
  gridOptions: {
-    columns: useColumns(onActionClick),
+    columns: columns.value,
    // rest of the configuration...
  } as VxeTableGridOptions,
});

105-107: Consider adding error handling for API query.

The query function lacks error handling for the API call, which could lead to unhandled promise rejections if the API request fails.

Add try-catch block for better error handling:

query: async (_params) => {
-  return await getDeptList();
+  try {
+    return await getDeptList();
+  } catch (error) {
+    message.error($t('system.dept.fetchFailed'));
+    return [];
+  }
},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7041c6a and 5819a6a.

📒 Files selected for processing (19)
  • apps/backend-mock/api/system/dept/.post.ts (1 hunks)
  • apps/backend-mock/api/system/dept/[id].delete.ts (1 hunks)
  • apps/backend-mock/api/system/dept/[id].put.ts (1 hunks)
  • apps/backend-mock/api/system/dept/list.ts (1 hunks)
  • apps/backend-mock/middleware/1.api.ts (2 hunks)
  • packages/@core/base/icons/src/lucide.ts (1 hunks)
  • packages/locales/src/index.ts (1 hunks)
  • packages/locales/src/langs/en-US/common.json (1 hunks)
  • packages/locales/src/langs/en-US/ui.json (1 hunks)
  • packages/locales/src/langs/zh-CN/common.json (1 hunks)
  • packages/locales/src/langs/zh-CN/ui.json (1 hunks)
  • playground/src/adapter/vxe-table.ts (4 hunks)
  • playground/src/api/system/dept.ts (1 hunks)
  • playground/src/locales/langs/en-US/system.json (1 hunks)
  • playground/src/locales/langs/zh-CN/system.json (1 hunks)
  • playground/src/router/routes/modules/system.ts (1 hunks)
  • playground/src/views/system/dept/data.ts (1 hunks)
  • playground/src/views/system/dept/list.vue (1 hunks)
  • playground/src/views/system/dept/modules/form.vue (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • playground/src/locales/langs/en-US/system.json
  • playground/src/locales/langs/zh-CN/system.json
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Check (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
🔇 Additional comments (22)
packages/@core/base/icons/src/lucide.ts (1)

52-52: Added Plus icon to exports.

The Plus icon is now available for import, which will be useful for the department management UI components, particularly for actions like adding new departments.

packages/locales/src/index.ts (1)

10-10: Enhanced i18n support with $te method.

The addition of the $te constant (which maps to i18n.global.te) provides a way to check if a translation key exists, complementing the existing $t function which retrieves the actual translations. This is a good addition that will help improve localization handling in the department management UI.

Also applies to: 14-14

apps/backend-mock/api/system/dept/.post.ts (1)

4-11: POST handler implementation for department creation.

The implementation follows the standard pattern for the project's API handlers with proper access token verification. The 600ms delay simulates network latency which is appropriate for a mock API.

apps/backend-mock/api/system/dept/[id].put.ts (1)

4-11: PUT handler implementation for department updates.

The implementation follows the standard pattern for the project's API handlers with proper access token verification, which is good.

apps/backend-mock/middleware/1.api.ts (1)

1-1: Function signature changed to async

Good change - this allows for the use of awaited operations in the middleware.

playground/src/router/routes/modules/system.ts (1)

1-28: LGTM! Well-structured route configuration

The route configuration for the System module is well-organized and follows best practices:

  • Clean imports and exports
  • Proper use of internationalization with $t
  • Appropriate metadata including icons and ordering
  • Lazy-loading of components for better performance

The hierarchical structure with parent/child routes is also well-implemented.

packages/locales/src/langs/en-US/common.json (1)

9-19: LGTM! Good additions to localization keys

The new localization keys are well-chosen and provide necessary translations for common UI actions that will be used in the department management interface.

packages/locales/src/langs/zh-CN/common.json (1)

9-9: Localization entries look good for department management features.

The added translation entries for common UI actions (reset, enabled, disabled, edit, delete, create) provide necessary localization support for the new department management demo page. These entries correctly match the English counterparts mentioned in the summary.

Also applies to: 15-19

apps/backend-mock/api/system/dept/list.ts (2)

5-13: Date formatter implementation looks good.

The Intl.DateTimeFormat implementation for Chinese locale is correctly configured with appropriate options for formatting date and time.


15-48: Mock data generation function is well-structured.

The generateMockDataList function creates a realistic hierarchical department structure with proper parent-child relationships. It uses faker appropriately to generate random but meaningful data for each department.

packages/locales/src/langs/zh-CN/ui.json (3)

5-7: Form validation rule translations look good.

The added validation messages for minLength, maxLength, and length constraints are appropriate and consistent with the English translations.


9-14: Action title translations are properly implemented.

The actionTitle section with translations for edit, create, delete, and view operations is well-structured and includes proper placeholder formatting with {0} for dynamic content.


15-21: Action message translations are consistent and complete.

The actionMessage section provides appropriate translations for delete confirmations, operation status messages, and uses consistent placeholder formatting.

packages/locales/src/langs/en-US/ui.json (3)

5-7: Form validation rule translations look good.

The English validation messages for minLength, maxLength, and length constraints are clear and use proper grammar with placeholders.


9-14: Action title translations are well-implemented.

The actionTitle section is properly implemented with clear English translations. Note that "edit" is translated as "Modify" which is a slight semantic difference from the Chinese version, but still acceptable.


15-20: Action message translations are consistent with Chinese version.

The actionMessage section provides clear English translations that maintain the same meaning as their Chinese counterparts. The placeholder usage is consistent across languages.

playground/src/views/system/dept/data.ts (1)

29-40: Verify large data performance for ApiTreeSelect.
The getDeptList API could return a large dataset. If the number of departments grows significantly, using ApiTreeSelect without pagination or lazy loading might cause performance bottlenecks.

Would you like a script to search for usage patterns and confirm the typical data size for getDeptList?

playground/src/views/system/dept/modules/form.vue (1)

52-63: Clarify top-level department logic.
You convert pid from 0 to undefined to represent top-level departments. Ensure that any consuming API endpoints or business logic also treat undefined and 0 equivalently to avoid inconsistent data.

playground/src/adapter/vxe-table.ts (1)

37-37: Confirm the impact of clearing proxyConfig.list.
You replaced "list": "items" with an empty string, which may break the table’s internal data fetching if it relies on the list key. Ensure that the relevant usage is updated accordingly to avoid unexpected rendering.

playground/src/views/system/dept/list.vue (3)

94-122: Well-structured grid configuration with appropriate tree settings.

The grid configuration is well-defined with proper tree settings for hierarchical department data. The parentField and rowField settings correctly map to the data structure.


20-23: Good modal implementation with proper cleanup.

Using destroyOnClose: true ensures that the modal component is properly cleaned up after closing, which helps prevent memory leaks and state persistence issues.


131-143: Clean and well-structured template.

The template follows good practices with proper component nesting and clear separation of concerns. Using the Page component with auto-content-height provides a responsive layout.

@mynetfan mynetfan merged commit d33261d into vbenjs:main Feb 25, 2025
14 checks passed
@mynetfan mynetfan deleted the feat/system-managment branch February 25, 2025 11:47
@coderabbitai coderabbitai bot mentioned this pull request Feb 26, 2025
16 tasks
@github-actions github-actions bot locked and limited conversation to collaborators Mar 28, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant