-
Notifications
You must be signed in to change notification settings - Fork 8.4k
chore: demo page for system/department #5611
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
Conversation
|
WalkthroughThis 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
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
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
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (5)
⏰ Context from checks skipped due to timeout of 90000ms (8)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 operationThe 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 messageThe 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 consistencyConsider 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 fornamelook 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.
Definingstatusvalues 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 thetryblock, 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 forgetDeptList.
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,CellTagonly 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.
ThePopconfirmfor 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
useMemoor 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
📒 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
$teconstant (which maps toi18n.global.te) provides a way to check if a translation key exists, complementing the existing$tfunction 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 asyncGood 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 configurationThe 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 keysThe 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
generateMockDataListfunction 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 forApiTreeSelect.
ThegetDeptListAPI could return a large dataset. If the number of departments grows significantly, usingApiTreeSelectwithout 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 convertpidfrom0toundefinedto represent top-level departments. Ensure that any consuming API endpoints or business logic also treatundefinedand0equivalently to avoid inconsistent data.playground/src/adapter/vxe-table.ts (1)
37-37: Confirm the impact of clearingproxyConfig.list.
You replaced"list": "items"with an empty string, which may break the table’s internal data fetching if it relies on thelistkey. 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: trueensures 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.
Description
添加演示页面:部门管理
Type of change
Please delete options that are not relevant.
pnpm-lock.yamlunless you introduce a new test example.Checklist
pnpm run docs:devcommand.pnpm test.feat:,fix:,perf:,docs:, orchore:.Summary by CodeRabbit