From bca3f3ff243cd76a179870ecad807e7b6bf904b0 Mon Sep 17 00:00:00 2001 From: XiaoDaiGua-Ray <51957438+XiaoDaiGua-Ray@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:21:59 +0800 Subject: [PATCH] feat(admin): add user management and HTTP mock APIs Add user CRUD, account-scoped navigation history and favorites. Unify HTTP mocks, backend contracts and route configuration. Reuse existing scrolling components and add Harness reuse guidance. --- README.md | 10 +- README.zh-CN.md | 8 +- __test__/app/user-management.spec.ts | 58 + __test__/axios/admin-headers.spec.ts | 39 + __test__/hooks/useSiderBar.spec.ts | 4 +- __test__/layout/global-search.spec.ts | 146 + __test__/layout/navigation-history.spec.ts | 86 + __test__/mock/admin-api.spec.ts | 204 ++ __test__/mock/connection.spec.ts | 38 + __test__/mock/demo-http.spec.ts | 71 + __test__/mock/openapi.spec.ts | 38 + __test__/setup-api.ts | 15 + apps/admin/mock/demo/person.mock.ts | 19 - apps/admin/package.json | 17 +- apps/admin/public/contracts/admin-api.json | 3247 +++++++++++++++++ apps/admin/public/mockServiceWorker.js | 349 ++ apps/admin/src/api/admin/client.ts | 82 + apps/admin/src/api/admin/contracts.ts | 153 + apps/admin/src/api/admin/index.ts | 68 + apps/admin/src/api/admin/openapi.ts | 238 ++ apps/admin/src/api/demo/contracts.ts | 60 + apps/admin/src/api/demo/data.ts | 38 + apps/admin/src/api/demo/mock/person.ts | 26 +- apps/admin/src/api/demo/test.ts | 7 +- .../request/plugins/request-headers.ts | 65 +- apps/admin/src/axios/instance.ts | 8 + apps/admin/src/documentation-example.tsx | 8 + apps/admin/src/hooks/template/index.ts | 1 + apps/admin/src/hooks/template/useAccess.ts | 17 + .../components/Search/GlobalSearch/index.scss | 167 +- .../components/Search/GlobalSearch/index.tsx | 515 +-- .../src/locales/lang/en-US/demoDetails.json | 3 +- apps/admin/src/locales/lang/en-US/menu.json | 4 +- .../locales/lang/en-US/navigationSearch.json | 16 + .../locales/lang/en-US/routeManagement.json | 18 +- .../locales/lang/en-US/userManagement.json | 85 + .../locales/lang/en-US/views/login/index.json | 4 +- .../src/locales/lang/zh-CN/demoDetails.json | 3 +- apps/admin/src/locales/lang/zh-CN/menu.json | 4 +- .../locales/lang/zh-CN/navigationSearch.json | 16 + .../locales/lang/zh-CN/routeManagement.json | 18 +- .../locales/lang/zh-CN/userManagement.json | 85 + .../locales/lang/zh-CN/views/login/index.json | 4 +- apps/admin/src/main.ts | 9 + apps/admin/src/mocks/browser.ts | 61 + apps/admin/src/mocks/connection.ts | 21 + apps/admin/src/mocks/data/charts.json | 45 + apps/admin/src/mocks/data/orders.ts | 104 + .../examples => src/mocks/data}/request.json | 6 +- apps/admin/src/mocks/data/routes.json | 488 +++ apps/admin/src/mocks/data/users.ts | 69 + apps/admin/src/mocks/database.ts | 383 ++ apps/admin/src/mocks/handlers.ts | 213 ++ apps/admin/src/router/README.md | 7 +- apps/admin/src/router/app-route-modules.ts | 6 +- apps/admin/src/router/config/source.ts | 21 +- apps/admin/src/router/config/views.ts | 4 + apps/admin/src/router/modules/dashboard.ts | 16 - apps/admin/src/router/modules/demo/assets.ts | 37 - .../src/router/modules/demo/components.ts | 82 - apps/admin/src/router/modules/demo/doc.ts | 14 - .../src/router/modules/demo/interaction.ts | 53 - .../src/router/modules/demo/navigation.ts | 111 - apps/admin/src/router/modules/demo/tables.ts | 101 - .../src/router/modules/demo/utilities.ts | 48 - .../router/utils/combine-raw-route-modules.ts | 39 - apps/admin/src/router/utils/index.ts | 1 - apps/admin/src/store/README.md | 4 + .../store/hooks/useNavigationHistoryStore.ts | 18 + apps/admin/src/store/hooks/useSigningStore.ts | 6 +- apps/admin/src/store/index.ts | 1 + apps/admin/src/store/modules/menu/index.ts | 10 + .../store/modules/navigation-history/index.ts | 117 + apps/admin/src/store/modules/signing/index.ts | 91 +- apps/admin/src/store/modules/signing/types.ts | 2 + apps/admin/src/views/demo/axios/index.tsx | 9 +- apps/admin/src/views/demo/echart/index.tsx | 139 +- .../src/views/demo/tables/auto-height.tsx | 18 +- apps/admin/src/views/demo/tables/basic.tsx | 18 +- apps/admin/src/views/demo/tables/columns.tsx | 7 +- .../src/views/demo/tables/controlled.tsx | 19 +- apps/admin/src/views/demo/tables/custom.tsx | 7 +- .../src/views/demo/tables/hooks-output.tsx | 7 +- .../src/views/demo/tables/hooks-selection.tsx | 7 +- apps/admin/src/views/demo/tables/printing.tsx | 7 +- apps/admin/src/views/demo/tables/remote.tsx | 2 +- .../src/views/demo/tables/search-fixtures.ts | 110 +- apps/admin/src/views/demo/tables/search.tsx | 94 +- .../src/views/demo/tables/usePeopleData.ts | 40 + .../views/login/components/Signing/index.tsx | 16 +- .../src/views/route-management/index.tsx | 24 +- .../src/views/route-management/visual.tsx | 35 +- .../src/views/user-management/UserEditor.tsx | 337 ++ .../src/views/user-management/index.scss | 134 + .../admin/src/views/user-management/index.tsx | 576 +++ apps/docs/.vitepress/sidebar.mts | 1 + apps/docs/guide/backend.md | 130 + apps/docs/guide/first-page.md | 32 +- apps/docs/guide/layout.md | 6 + apps/docs/guide/requests.md | 10 +- apps/docs/guide/routing.md | 10 +- apps/docs/public/contracts/admin-api.json | 3247 +++++++++++++++++ apps/docs/reference/store/signing.md | 15 +- docs/architecture.md | 16 +- docs/docs-handoff.md | 2 +- docs/toolchain-upgrade.md | 12 +- harness/README.md | 1 + harness/context/api.md | 4 +- harness/context/routing.md | 2 +- harness/context/ui.md | 2 + package.json | 33 +- pnpm-lock.yaml | 671 ++-- pnpm-workspace.yaml | 2 + scripts/admin-api.mjs | 44 + tsconfig.base.json | 4 +- tsconfig.node.json | 2 +- vite.custom.config.ts | 2 +- vite.plugin.config.ts | 10 - vitest.config.ts | 1 + 119 files changed, 12446 insertions(+), 1669 deletions(-) create mode 100644 __test__/app/user-management.spec.ts create mode 100644 __test__/axios/admin-headers.spec.ts create mode 100644 __test__/layout/global-search.spec.ts create mode 100644 __test__/layout/navigation-history.spec.ts create mode 100644 __test__/mock/admin-api.spec.ts create mode 100644 __test__/mock/connection.spec.ts create mode 100644 __test__/mock/demo-http.spec.ts create mode 100644 __test__/mock/openapi.spec.ts create mode 100644 __test__/setup-api.ts delete mode 100644 apps/admin/mock/demo/person.mock.ts create mode 100644 apps/admin/public/contracts/admin-api.json create mode 100644 apps/admin/public/mockServiceWorker.js create mode 100644 apps/admin/src/api/admin/client.ts create mode 100644 apps/admin/src/api/admin/contracts.ts create mode 100644 apps/admin/src/api/admin/index.ts create mode 100644 apps/admin/src/api/admin/openapi.ts create mode 100644 apps/admin/src/api/demo/contracts.ts create mode 100644 apps/admin/src/api/demo/data.ts create mode 100644 apps/admin/src/hooks/template/useAccess.ts create mode 100644 apps/admin/src/locales/lang/en-US/navigationSearch.json create mode 100644 apps/admin/src/locales/lang/en-US/userManagement.json create mode 100644 apps/admin/src/locales/lang/zh-CN/navigationSearch.json create mode 100644 apps/admin/src/locales/lang/zh-CN/userManagement.json create mode 100644 apps/admin/src/mocks/browser.ts create mode 100644 apps/admin/src/mocks/connection.ts create mode 100644 apps/admin/src/mocks/data/charts.json create mode 100644 apps/admin/src/mocks/data/orders.ts rename apps/admin/{public/examples => src/mocks/data}/request.json (65%) create mode 100644 apps/admin/src/mocks/data/routes.json create mode 100644 apps/admin/src/mocks/data/users.ts create mode 100644 apps/admin/src/mocks/database.ts create mode 100644 apps/admin/src/mocks/handlers.ts delete mode 100644 apps/admin/src/router/modules/dashboard.ts delete mode 100644 apps/admin/src/router/modules/demo/assets.ts delete mode 100644 apps/admin/src/router/modules/demo/components.ts delete mode 100644 apps/admin/src/router/modules/demo/doc.ts delete mode 100644 apps/admin/src/router/modules/demo/interaction.ts delete mode 100644 apps/admin/src/router/modules/demo/navigation.ts delete mode 100644 apps/admin/src/router/modules/demo/tables.ts delete mode 100644 apps/admin/src/router/modules/demo/utilities.ts delete mode 100644 apps/admin/src/router/utils/combine-raw-route-modules.ts create mode 100644 apps/admin/src/store/hooks/useNavigationHistoryStore.ts create mode 100644 apps/admin/src/store/modules/navigation-history/index.ts create mode 100644 apps/admin/src/views/demo/tables/usePeopleData.ts create mode 100644 apps/admin/src/views/user-management/UserEditor.tsx create mode 100644 apps/admin/src/views/user-management/index.scss create mode 100644 apps/admin/src/views/user-management/index.tsx create mode 100644 apps/docs/guide/backend.md create mode 100644 apps/docs/public/contracts/admin-api.json create mode 100644 scripts/admin-api.mjs diff --git a/README.md b/README.md index ddbc556a..f76dc408 100644 --- a/README.md +++ b/README.md @@ -34,11 +34,11 @@ Page tabs keep multiple tasks open, and breadcrumbs show where you are. Find men [Layout playground source](apps/admin/src/views/demo/layout-demo.tsx) · [Layout configuration and slots](apps/admin/src/layout/README.md) -### Route modules connect pages, menus, and permissions +### HTTP route configuration connects pages, menus, and permissions -Declare a page in `apps/admin/src/router/modules` to generate its navigation and breadcrumbs. Route metadata controls menu labels and icons, roles, visibility, and `keepAlive`. Detail pages can extend the breadcrumb while keeping the current menu and tab. Role checks cover both menu filtering and direct navigation. Connect your backend to validate sessions and authorize API requests. +Register the page component ID in `apps/admin/src/router/config/views.ts`, then return its route record from the API to generate navigation and breadcrumbs. Initial demo records live in `apps/admin/src/mocks/data/routes.json`. Route metadata controls menu labels and icons, roles, visibility, and `keepAlive`. Detail pages can extend the breadcrumb while keeping the current menu and tab. Role checks cover both menu filtering and direct navigation. Connect your backend to validate sessions and authorize API requests. -[Routing guide](apps/admin/src/router/README.md) · [Nested navigation and caching example](apps/admin/src/router/modules/demo/navigation.ts) +[Routing guide](apps/admin/src/router/README.md) · [Nested navigation and caching example](apps/admin/src/mocks/data/routes.json) ### Reusable components, composables, and SVG icons @@ -115,8 +115,8 @@ export default defineComponent({ ``` 1. **Build the view.** Add a page in `apps/admin/src/views`. The [remote table example](apps/admin/src/views/demo/tables/remote.tsx) shows sorting, row selection, and toolbar actions. -2. **Connect navigation.** Add a route in `apps/admin/src/router/modules` and give its menu entry English and Simplified Chinese labels. Follow the [routing guide](apps/admin/src/router/README.md) when setting up page caching. -3. **Connect your data.** Define your API in `apps/admin/src/api`, use `apps/admin/src/axios` for interceptors and request cancellation, and connect your real sign-in and session. The people directory uses a mock HTTP endpoint in development and sample data in the static preview. [Request layer guide](apps/admin/src/axios/README.md) +2. **Connect navigation.** Register the page component ID and add its route to the Mock JSON or your backend response, with English and Simplified Chinese menu labels. Follow the [routing guide](apps/admin/src/router/README.md) when setting up page caching. +3. **Connect your data.** Define your API in `apps/admin/src/api`, use `apps/admin/src/axios` for interceptors and request cancellation, and connect your real sign-in and session. Development and static previews use the same HTTP Mock API. The [backend contract](apps/docs/guide/backend.md) includes authentication, permission codes, users, routes, and a generated OpenAPI specification. [Request layer guide](apps/admin/src/axios/README.md) ## Checks, builds, and deployment diff --git a/README.zh-CN.md b/README.zh-CN.md index 6200e13d..2ee80007 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -36,9 +36,9 @@ Ray Template 是一套**开箱即用的中后台前端模板**,适合搭建管 ### 路由模块:把页面、菜单与权限放在同一处配置 -在 `apps/admin/src/router/modules` 声明页面,模板按路由配置生成菜单和面包屑。路由 `meta` 可以配置菜单文案与图标、角色、显示条件和 `keepAlive`。从列表进入详情时,可以保留当前菜单和标签页,只在面包屑中补充详情层级。角色配置同时用于菜单过滤和直接导航时的守卫。接入业务时,由后端校验会话与接口权限。 +先在 `apps/admin/src/router/config/views.ts` 登记页面组件 ID,再由接口返回路由记录,模板据此生成菜单和面包屑。Mock 初始记录位于 `apps/admin/src/mocks/data/routes.json`。路由 `meta` 可以配置菜单文案与图标、角色、显示条件和 `keepAlive`。从列表进入详情时,可以保留当前菜单和标签页,只在面包屑中补充详情层级。角色配置同时用于菜单过滤和直接导航时的守卫。接入业务时,由后端校验会话与接口权限。 -[路由与菜单约定](apps/admin/src/router/README.md) · [多级菜单与缓存示例](apps/admin/src/router/modules/demo/navigation.ts) +[路由与菜单约定](apps/admin/src/router/README.md) · [多级菜单与缓存示例](apps/admin/src/mocks/data/routes.json) ### 组件、Hooks 与图标:从可运行的示例里复用 @@ -115,8 +115,8 @@ export default defineComponent({ ``` 1. **写页面**。在 `apps/admin/src/views` 新建页面,参考[远端查询示例](apps/admin/src/views/demo/tables/remote.tsx)加入排序、行选择和工具栏。 -2. **接入导航**。在 `apps/admin/src/router/modules` 添加路由,给菜单配置中英文文案。页面需要缓存时,参考[路由约定](apps/admin/src/router/README.md)配置路由与组件名称。 -3. **替换演示数据**。从 `apps/admin/src/api` 接入业务接口,通过 `apps/admin/src/axios` 统一处理拦截与取消,再接入实际登录和会话。人员列表示例在开发时走 Mock HTTP,静态预览使用本地样例数据。[请求层说明](apps/admin/src/axios/README.md) +2. **接入导航**。登记页面组件 ID,在 Mock JSON 或后端响应中添加路由,给菜单配置中英文文案。页面需要缓存时,参考[路由约定](apps/admin/src/router/README.md)配置路由与组件名称。 +3. **替换演示数据**。从 `apps/admin/src/api` 接入业务接口,通过 `apps/admin/src/axios` 统一处理拦截与取消,再接入实际登录和会话。开发和静态预览共用 HTTP Mock。[服务端契约](apps/docs/guide/backend.md) 提供会话、权限码、用户和路由接口及可下载的 OpenAPI。[请求层说明](apps/admin/src/axios/README.md) ## 检查、构建与部署 diff --git a/__test__/app/user-management.spec.ts b/__test__/app/user-management.spec.ts new file mode 100644 index 00000000..fd7d095b --- /dev/null +++ b/__test__/app/user-management.spec.ts @@ -0,0 +1,58 @@ +import * as adminApi from '@/api/admin' +import { router } from '@/router' +import { piniaSigningStore } from '@/store/modules/signing' +import UserManagement from '@/views/user-management' +import { flushPromises, mount } from '@vue/test-utils' +import setupMiniApp from '../utils/setupMiniApp' + +it('keeps the current list and selection context when opening and closing an editor', async () => { + localStorage.clear() + const { app } = await setupMiniApp() + + await piniaSigningStore().signing({ name: 'admin', pwd: '123456' }) + const fetchUsers = vi.spyOn(adminApi, 'getUsers') + const message = window.$message + + window.$message = { + error: vi.fn(), + success: vi.fn(), + } as unknown as Window['$message'] + const wrapper = mount(UserManagement, { + attachTo: document.body, + global: { + plugins: [router], + stubs: { + Modal: { inheritAttrs: false, template: '
' }, + RIcon: { inheritAttrs: false, template: '' }, + }, + }, + }) + + try { + await vi.waitFor(() => expect(wrapper.text()).toContain('Alex Chen'), { + timeout: 3000, + }) + expect(fetchUsers).toHaveBeenCalledTimes(1) + await wrapper + .findAll('button') + .find((button) => button.text().trim() === '新增用户')! + .trigger('click') + await flushPromises() + expect(wrapper.find('input[name="username"]').exists()).toBe(true) + expect(wrapper.text()).toContain('Alex Chen') + expect(fetchUsers).toHaveBeenCalledTimes(1) + await wrapper + .findAll('button') + .find((button) => button.text().trim() === '取消')! + .trigger('click') + await flushPromises() + expect(wrapper.text()).toContain('Alex Chen') + expect(fetchUsers).toHaveBeenCalledTimes(1) + } finally { + wrapper.unmount() + app.unmount() + window.$message = message + localStorage.clear() + vi.restoreAllMocks() + } +}) diff --git a/__test__/axios/admin-headers.spec.ts b/__test__/axios/admin-headers.spec.ts new file mode 100644 index 00000000..6c2fb6f6 --- /dev/null +++ b/__test__/axios/admin-headers.spec.ts @@ -0,0 +1,39 @@ +import { APP_CATCH_KEY } from '@/app-config' +import { injectRequestHeaders } from '@/axios/axios-interceptor/request/plugins/request-headers' +import type { RequestInterceptorConfig } from '@/axios/types' +import { setStorage } from '@/utils/cache' +import { AxiosHeaders } from 'axios' + +afterEach(() => { + localStorage.clear() + vi.unstubAllEnvs() +}) + +it('sends Bearer credentials only to the configured API origin and path', () => { + vi.stubEnv('VITE_API_BASE_URL', 'https://api.example.test/v1/') + setStorage(APP_CATCH_KEY.token, 'test-token', 'localStorage') + const config = (url: string): RequestInterceptorConfig => ({ + url, + headers: new AxiosHeaders(), + }) + const owned = config('https://api.example.test/v1/admin/users') + + injectRequestHeaders(owned, '') + expect(owned.headers?.Authorization).toBe('Bearer test-token') + + for (const url of [ + 'https://other.example.test/v1/admin/users', + 'https://api.example.test/v10/admin/users', + ]) { + const foreign = config(url) + + injectRequestHeaders(foreign, '') + expect(foreign.headers?.Authorization).toBeUndefined() + } + + const explicit = config('https://api.example.test/v1/admin/users') + + explicit.headers = { authorization: 'Bearer supplied-token' } + injectRequestHeaders(explicit, '') + expect(explicit.headers.authorization).toBe('Bearer supplied-token') +}) diff --git a/__test__/hooks/useSiderBar.spec.ts b/__test__/hooks/useSiderBar.spec.ts index 044cdd39..26524e51 100644 --- a/__test__/hooks/useSiderBar.spec.ts +++ b/__test__/hooks/useSiderBar.spec.ts @@ -1,6 +1,7 @@ import { useAppRoot } from '../../apps/admin/src/hooks/template/useAppRoot' import { useSiderBar } from '../../apps/admin/src/hooks/template/useSiderBar' import { useVueRouter } from '../../apps/admin/src/hooks/web/useVueRouter' +import { firstMenuLeaf } from '../../apps/admin/src/layout/navigation' import { useMenuActions, useMenuGetters } from '../../apps/admin/src/store' import type { AppMenuOption, @@ -142,7 +143,8 @@ describe('useSiderBar', async () => { updateMenuTagOptions() const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [f, s] = getMenuOptions.value + const [f, group] = getMenuOptions.value + const s = firstMenuLeaf(group)! closeRight(f.fullPath) diff --git a/__test__/layout/global-search.spec.ts b/__test__/layout/global-search.spec.ts new file mode 100644 index 00000000..3e6ada28 --- /dev/null +++ b/__test__/layout/global-search.spec.ts @@ -0,0 +1,146 @@ +import GlobalSearch from '@/layout/components/Search/GlobalSearch' +import { router } from '@/router' +import { piniaMenuStore } from '@/store/modules/menu' +import { piniaNavigationHistoryStore } from '@/store/modules/navigation-history' +import { piniaSigningStore } from '@/store/modules/signing' +import type { AppMenuOption } from '@/types' +import { flushPromises, mount } from '@vue/test-utils' +import setupMiniApp from '../utils/setupMiniApp' + +const option = (path: string, label: string, show = true): AppMenuOption => ({ + path, + fullPath: path, + key: path, + name: path, + breadcrumbLabel: label, + label, + show, + meta: {}, +}) + +it('filters cached entries by current menu visibility and keeps favorite toggles separate from navigation', async () => { + vi.stubGlobal('innerWidth', 1440) + const { app } = await setupMiniApp() + + piniaSigningStore().signingCallback = { + id: 'search-user', + name: 'Search User', + role: 'admin', + } + const menu = piniaMenuStore() + + menu.options = [ + option('/visible', 'Visible page'), + option('/hidden', 'Hidden page', false), + ] + const history = piniaNavigationHistoryStore() + + history.recordVisit('/visible') + history.toggleFavorite('/hidden') + history.toggleFavorite('/removed') + const navigate = vi + .spyOn(menu, 'changeMenuModelValue') + .mockImplementation(() => void 0) + const wrapper = mount(GlobalSearch, { + attachTo: document.body, + props: { show: true }, + global: { + plugins: [router], + stubs: { + teleport: true, + Modal: { inheritAttrs: false, template: '
' }, + RIcon: { inheritAttrs: false, template: '' }, + }, + }, + }) + + try { + await flushPromises() + expect(wrapper.find('.global-search').text()).toContain('Visible page') + expect(wrapper.find('.global-search').text()).not.toContain('Hidden page') + const star = wrapper.find('.global-search__favorite') + .element as HTMLButtonElement + + star.click() + await flushPromises() + expect(history.favoritePaths).toContain('/visible') + expect(navigate).not.toHaveBeenCalled() + menu.options = [] + await flushPromises() + expect(wrapper.find('.global-search__destination').exists()).toBe(false) + } finally { + wrapper.unmount() + app.unmount() + vi.unstubAllGlobals() + } +}) + +it('does not navigate while composing and supports keyboard result focus and Enter', async () => { + vi.stubGlobal('innerWidth', 1440) + const { app } = await setupMiniApp() + + piniaSigningStore().signingCallback = { + id: 'keyboard-user', + name: 'Keyboard User', + role: 'admin', + } + const menu = piniaMenuStore() + + menu.options = [option('/visible', 'Visible page')] + const navigate = vi + .spyOn(menu, 'changeMenuModelValue') + .mockImplementation(() => void 0) + const wrapper = mount(GlobalSearch, { + attachTo: document.body, + props: { show: true }, + global: { + plugins: [router], + stubs: { + teleport: true, + Modal: { inheritAttrs: false, template: '
' }, + RIcon: { inheritAttrs: false, template: '' }, + }, + }, + }) + + try { + await flushPromises() + const input = wrapper.find('input').element as HTMLInputElement + + input.value = 'Visible' + input.dispatchEvent(new Event('input', { bubbles: true })) + await flushPromises() + expect(wrapper.findAll('.global-search__destination')).toHaveLength(1) + input.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'Enter', + isComposing: true, + bubbles: true, + }), + ) + expect(navigate).not.toHaveBeenCalled() + input.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'ArrowDown', + bubbles: true, + cancelable: true, + }), + ) + expect( + document.activeElement?.classList.contains('global-search__destination'), + ).toBe(true) + input.dispatchEvent( + new KeyboardEvent('keydown', { + key: 'Enter', + bubbles: true, + cancelable: true, + }), + ) + await flushPromises() + expect(navigate).toHaveBeenCalledTimes(1) + } finally { + wrapper.unmount() + app.unmount() + vi.unstubAllGlobals() + } +}) diff --git a/__test__/layout/navigation-history.spec.ts b/__test__/layout/navigation-history.spec.ts new file mode 100644 index 00000000..bdf29bf5 --- /dev/null +++ b/__test__/layout/navigation-history.spec.ts @@ -0,0 +1,86 @@ +import { APP_CATCH_KEY } from '@/app-config' +import { piniaNavigationHistoryStore } from '@/store/modules/navigation-history' +import { piniaSigningStore } from '@/store/modules/signing' +import { createPinia, disposePinia, setActivePinia } from 'pinia' + +let pinia: ReturnType + +beforeEach(() => { + localStorage.clear() + pinia = createPinia() + setActivePinia(pinia) +}) +afterEach(() => { + disposePinia(pinia) + localStorage.clear() +}) +const account = (id: string) => { + piniaSigningStore().signingCallback = { id, name: id, role: 'admin' } +} + +it('restores recent pages in order, deduplicates them and clears history independently of favorites', () => { + account('one') + const store = piniaNavigationHistoryStore() + + for (let index = 0; index < 15; index++) store.recordVisit(`/page-${index}`) + + store.recordVisit('/page-10') + store.toggleFavorite('/page-10') + expect(store.recentPaths).toHaveLength(10) + expect(store.recentPaths[0]).toBe('/page-10') + disposePinia(pinia) + pinia = createPinia() + setActivePinia(pinia) + account('one') + const restored = piniaNavigationHistoryStore() + + expect(restored.recentPaths[0]).toBe('/page-10') + expect(restored.favoritePaths).toEqual(['/page-10']) + restored.clearRecent() + expect(restored.recentPaths).toEqual([]) + expect(restored.favoritePaths).toEqual(['/page-10']) +}) + +it('isolates accounts and restores each account without storing titles or URL parameters', () => { + account('one') + const store = piniaNavigationHistoryStore() + + store.recordVisit('/system/users') + store.recordVisit('/search?private=value') + store.toggleFavorite('/system/users') + account('two') + expect(store.recentPaths).toEqual([]) + expect(store.favoritePaths).toEqual([]) + store.toggleFavorite('/dashboard') + account('one') + expect(store.favoritePaths).toEqual(['/system/users']) + expect( + JSON.parse( + localStorage.getItem(`${APP_CATCH_KEY.appGlobalSearchOptions}:v1:one`)!, + ), + ).toEqual({ + version: 1, + recent: ['/system/users'], + favorites: ['/system/users'], + }) + account('') + expect(store.favoritePaths).toEqual([]) +}) + +it('recovers from malformed cached data and filters external or parameterized paths', () => { + localStorage.setItem( + `${APP_CATCH_KEY.appGlobalSearchOptions}:v1:one`, + JSON.stringify({ + version: 1, + recent: ['/ok', '//example.com', '/:id', '/ok', 42], + favorites: 'invalid', + }), + ) + account('one') + const store = piniaNavigationHistoryStore() + + expect(store.recentPaths).toEqual(['/ok']) + expect(store.favoritePaths).toEqual([]) + store.toggleFavorite('https://example.com') + expect(store.favoritePaths).toEqual([]) +}) diff --git a/__test__/mock/admin-api.spec.ts b/__test__/mock/admin-api.spec.ts new file mode 100644 index 00000000..b5141044 --- /dev/null +++ b/__test__/mock/admin-api.spec.ts @@ -0,0 +1,204 @@ +import { + createUser, + deleteUsers, + getAdminRoutes, + getAdminSession, + getUser, + getUserOptions, + getUsers, + loginAdmin, + logoutAdmin, + resetDemoUsers, + updateAdminRoutes, + updateUser, + updateUserStatus, +} from '@/api/admin' +import { AdminApiError } from '@/api/admin/client' +import type { UserInput } from '@/api/admin/contracts' +import { APP_CATCH_KEY } from '@/app-config' +import { createAdminDatabase } from '@/mocks/database' +import { getStorage, setStorage } from '@/utils/cache' + +const input: UserInput = { + username: 'integration-user', + name: 'Integration User', + email: 'integration@example.com', + phone: '', + departmentId: 'platform', + role: 'member', + status: 'enabled', + remark: 'Test account', +} +const signIn = async (username = 'admin') => { + const result = await loginAdmin(username, '123456') + + setStorage(APP_CATCH_KEY.token, result.accessToken, 'localStorage') + + return result +} + +beforeEach(async () => { + localStorage.clear() + await signIn() + await resetDemoUsers() +}) +afterEach(() => localStorage.clear()) + +it('runs create, query, detail, update, status and delete through the HTTP contract', async () => { + const options = await getUserOptions() + + expect(options.departments.some((item) => item.id === 'platform')).toBe(true) + const created = await createUser(input) + + expect(await getUser(created.id)).toMatchObject(input) + expect( + await getUsers({ + name: 'Integration', + departmentId: 'engineering', + page: 1, + pageSize: 1, + }), + ).toMatchObject({ total: 1, data: [{ id: created.id }] }) + const edited = await updateUser(created.id, { + ...input, + name: 'Updated User', + }) + + expect(edited.id).toBe(created.id) + expect(edited.createdAt).toBe(created.createdAt) + await updateUserStatus([created.id], 'disabled') + expect((await getUser(created.id)).status).toBe('disabled') + await deleteUsers([created.id]) + expect(await getUsers({ username: input.username })).toEqual({ + data: [], + total: 0, + }) +}) + +it('rejects duplicate or malformed writes and preserves the existing record', async () => { + const user = await createUser(input) + + await expect( + createUser({ + ...input, + username: input.username.toUpperCase(), + email: 'other@example.com', + }), + ).rejects.toMatchObject({ code: 409, key: 'duplicateUsername' }) + await expect( + updateUser(user.id, { ...input, departmentId: 'missing' }), + ).rejects.toMatchObject({ code: 400, key: 'invalid' }) + expect(await getUser(user.id)).toMatchObject(input) + await expect(getUsers({ page: 0 })).rejects.toMatchObject({ code: 400 }) +}) + +it('enforces read-only permissions at the Mock API boundary', async () => { + await signIn('member') + expect((await getAdminSession()).permissions).toContain('users:read') + expect((await getUsers({ page: 1, pageSize: 10 })).data).toHaveLength(10) + await expect(createUser(input)).rejects.toMatchObject({ + code: 403, + key: 'forbidden', + }) + await expect(deleteUsers(['demo-user-3'])).rejects.toMatchObject({ + code: 403, + }) + await expect(updateAdminRoutes(await getAdminRoutes())).rejects.toMatchObject( + { code: 403 }, + ) +}) + +it('prevents manager privilege escalation and protects the current account', async () => { + const session = await signIn('manager') + + await expect(createUser({ ...input, role: 'admin' })).rejects.toMatchObject({ + code: 403, + }) + await expect( + updateUserStatus([session.user.id], 'disabled'), + ).rejects.toMatchObject({ code: 409, key: 'selfProtected' }) + const admin = await signIn() + + await expect( + deleteUsers(['demo-user-3', admin.user.id]), + ).rejects.toMatchObject({ code: 409, key: 'selfProtected' }) + expect((await getUser('demo-user-3')).id).toBe('demo-user-3') +}) + +it('saves route configuration through PUT and rejects unknown executable components', async () => { + const original = await getAdminRoutes() + const next = { + ...original, + routes: [ + ...original.routes, + { + path: '/api-contract-page', + component: 'dashboard', + meta: { noLocalTitle: 'API contract page' }, + }, + ], + } + + try { + await updateAdminRoutes(next) + expect((await getAdminRoutes()).routes.at(-1)?.path).toBe( + '/api-contract-page', + ) + await expect( + updateAdminRoutes({ + version: 1, + routes: [ + { + path: '/unsafe', + component: 'https://example.com/code.js', + meta: {}, + }, + ], + }), + ).rejects.toMatchObject({ code: 400, key: 'invalidRoutes' }) + expect((await getAdminRoutes()).routes.at(-1)?.path).toBe( + '/api-contract-page', + ) + } finally { + await updateAdminRoutes(original) + } +}) + +it('invalidates the server-side Mock session on logout', async () => { + expect(getStorage(APP_CATCH_KEY.token, 'localStorage')).toEqual( + expect.any(String), + ) + await logoutAdmin() + await expect(getAdminSession()).rejects.toBeInstanceOf(AdminApiError) + await expect(getUsers({})).rejects.toMatchObject({ code: 401 }) +}) + +it('restores Mock writes and active sessions after recreating the database', () => { + localStorage.clear() + const first = createAdminDatabase(localStorage) + const session = first.login({ username: 'admin', password: '123456' }) + const user = first.saveUser(input, session.accessToken) + const second = createAdminDatabase(localStorage) + + expect(second.getUser(user.id, session.accessToken)).toMatchObject(input) + expect(second.authorize(session.accessToken).user.id).toBe(session.user.id) +}) + +it('keeps writes atomic when persistence fails', () => { + const storage: Storage = { + length: 0, + key: () => null, + clear() {}, + removeItem() {}, + getItem: () => null, + setItem: vi.fn(), + } + const database = createAdminDatabase(storage) + const session = database.login({ username: 'admin', password: '123456' }) + + vi.mocked(storage.setItem).mockImplementation(() => { + throw new Error('Quota exceeded') + }) + expect(() => database.saveUser(input, session.accessToken)).toThrow('storage') + expect(database.listUsers({}, session.accessToken).total).toBe(24) +}) diff --git a/__test__/mock/connection.spec.ts b/__test__/mock/connection.spec.ts new file mode 100644 index 00000000..8aadb545 --- /dev/null +++ b/__test__/mock/connection.spec.ts @@ -0,0 +1,38 @@ +import { createMockConnection } from '@/mocks/connection' + +it('does not restart a healthy worker', async () => { + const restart = vi.fn(async () => {}) + + await createMockConnection(async () => true, restart)() + expect(restart).not.toHaveBeenCalled() +}) + +it('recovers once for concurrent requests after the worker loses its client state', async () => { + let ready = false + const restart = vi.fn(async () => { + ready = true + }) + const ensure = createMockConnection(async () => ready, restart) + + await Promise.all([ensure(), ensure(), ensure()]) + expect(restart).toHaveBeenCalledTimes(1) + await ensure() + expect(restart).toHaveBeenCalledTimes(1) +}) + +it('blocks business traffic when recovery fails, then allows a later retry', async () => { + let available = false + const ensure = createMockConnection( + async () => available, + async () => {}, + ) + const write = vi.fn() + + await expect(ensure().then(write)).rejects.toThrow( + 'Mock connection could not be restored', + ) + expect(write).not.toHaveBeenCalled() + available = true + await ensure().then(write) + expect(write).toHaveBeenCalledTimes(1) +}) diff --git a/__test__/mock/demo-http.spec.ts b/__test__/mock/demo-http.spec.ts new file mode 100644 index 00000000..bc43b2a7 --- /dev/null +++ b/__test__/mock/demo-http.spec.ts @@ -0,0 +1,71 @@ +import { + getDemoCharts, + getSearchOrders, + getSearchOwners, +} from '@/api/demo/data' +import { getPersonList } from '@/api/demo/mock/person' +import { getRequestFixture, getWeather } from '@/api/demo/test' + +it('loads all table fixtures through the same paginated HTTP API', async () => { + const first = await getPersonList({ page: 1, pageSize: 10 }) + const second = await getPersonList({ page: 2, pageSize: 10 }) + + expect(first.total).toBe(100) + expect( + new Set([...first.data, ...second.data].map((row) => row.id)).size, + ).toBe(20) + expect( + (await getPersonList({ email: first.data[0].email })).data, + ).toContainEqual(first.data[0]) +}) + +it('queries advanced search on the Mock server and localizes the returned labels', async () => { + const result = await getSearchOrders( + { status: ['pending'], page: 1, pageSize: 5 }, + 'en-US', + ) + + expect(result.items).toHaveLength(5) + expect(result.items.every((row) => row.status === 'pending')).toBe(true) + expect(result.total).toBe(32) + expect( + (await getSearchOrders({ keyword: 'no matching order' }, 'zh-CN')).total, + ).toBe(0) + const owners = await getSearchOwners( + 'north', + '', + 'en-US', + new AbortController().signal, + ) + + expect(owners.map((item) => item.value)).toEqual(['n1', 'n2']) + await expect( + getSearchOrders({}, 'en-US', void 0, true), + ).rejects.toMatchObject({ code: 503 }) +}) + +it('aborts an in-flight HTTP search instead of applying stale results', async () => { + const controller = new AbortController() + const promise = getSearchOwners('north', '', 'en-US', controller.signal) + + controller.abort() + await expect(promise).rejects.toMatchObject({ code: 'ERR_CANCELED' }) +}) + +it('loads chart datasets, refreshes them through HTTP and keeps request examples working', async () => { + const first = await getDemoCharts() + const next = await getDemoCharts(true) + + expect(first.days).toHaveLength(7) + expect(next.lines.map((item) => item.name)).toEqual( + first.lines.map((item) => item.name), + ) + expect(next.lines.every((item) => item.values.length === 7)).toBe(true) + const fixture = await getRequestFixture() + + expect(fixture.ticket.id).toEqual(expect.any(String)) + expect(await getWeather('Hangzhou')).toMatchObject({ + city: 'Hangzhou', + temperature: expect.any(Number), + }) +}) diff --git a/__test__/mock/openapi.spec.ts b/__test__/mock/openapi.spec.ts new file mode 100644 index 00000000..4c82946b --- /dev/null +++ b/__test__/mock/openapi.spec.ts @@ -0,0 +1,38 @@ +import { getAdminOpenApi } from '@/api/admin/openapi' + +it('keeps every generated schema reference resolvable from the OpenAPI document', () => { + const document = getAdminOpenApi() + const refs: string[] = [] + const visit = (value: unknown) => { + if (!value || typeof value !== 'object') return + + for (const [key, child] of Object.entries(value)) { + if (key === '$ref') refs.push(String(child)) + else visit(child) + } + } + + visit(document) + expect(refs.some((ref) => ref.includes('/RouteConfig/$defs/'))).toBe(true) + + for (const ref of refs) { + expect(ref).toMatch(/^#\//) + const target = ref + .slice(2) + .split('/') + .map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~')) + .reduce( + (value, key) => + value && typeof value === 'object' + ? (value as Record)[key] + : void 0, + document, + ) + + expect(target, ref).toBeDefined() + } + + expect(document.components.schemas.RouteConfig.$schema).toBe( + 'https://json-schema.org/draft/2020-12/schema', + ) +}) diff --git a/__test__/setup-api.ts b/__test__/setup-api.ts new file mode 100644 index 00000000..ee5b5799 --- /dev/null +++ b/__test__/setup-api.ts @@ -0,0 +1,15 @@ +import { setupServer } from 'msw/node' +import { apiUrl } from '../apps/admin/src/api/admin/client' +import { createAdminDatabase } from '../apps/admin/src/mocks/database' +import { createAdminHandlers } from '../apps/admin/src/mocks/handlers' + +if (typeof document !== 'undefined') { + const server = setupServer( + ...createAdminHandlers(createAdminDatabase(), apiUrl('')), + ) + + // 部分旧 Hook 用例在 describe 收集阶段启动应用,拦截必须先于该阶段就绪。 + server.listen({ onUnhandledRequest: 'bypass' }) + afterEach(() => server.resetHandlers()) + afterAll(() => server.close()) +} diff --git a/apps/admin/mock/demo/person.mock.ts b/apps/admin/mock/demo/person.mock.ts deleted file mode 100644 index 5fa8363b..00000000 --- a/apps/admin/mock/demo/person.mock.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { listPeople } from '@/demo-data/people' -import { defineMock } from 'vite-plugin-mock-dev-server' - -export default defineMock({ - url: '/api/list', - method: 'GET', - delay: 250, - body: ({ query }) => - listPeople({ - page: Number(query.page), - pageSize: Number(query.pageSize), - email: typeof query.email === 'string' ? query.email : void 0, - name: typeof query.name === 'string' ? query.name : void 0, - sortAge: - query.sortAge === 'ascend' || query.sortAge === 'descend' - ? query.sortAge - : void 0, - }), -}) diff --git a/apps/admin/package.json b/apps/admin/package.json index c70493be..2d15a9cd 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -7,6 +7,13 @@ "@faker-js/faker": "10.6.0", "@logicflow/core": "2.2.5", "@logicflow/extension": "2.3.1", + "@ray-template/admin-shell": "workspace:*", + "@ray-template/composables": "workspace:*", + "@ray-template/directives": "workspace:*", + "@ray-template/http": "workspace:*", + "@ray-template/icons": "workspace:*", + "@ray-template/routing": "workspace:*", + "@ray-template/ui": "workspace:*", "@ray-template/utils": "workspace:*", "@valibot/to-json-schema": "1.8.0", "@vueuse/core": "15.0.0", @@ -19,6 +26,7 @@ "interactjs": "1.10.28", "jsbarcode": "3.12.3", "lodash-es": "4.18.1", + "msw": "2.11.6", "naive-ui": "2.45.3", "pinia": "4.1.0", "pinia-plugin-persistedstate": "4.7.1", @@ -29,13 +37,6 @@ "vue-hooks-plus": "2.4.3", "vue-i18n": "11.4.17", "vue-router": "5.4.0", - "vue3-next-qrcode": "4.1.1", - "@ray-template/ui": "workspace:*", - "@ray-template/composables": "workspace:*", - "@ray-template/directives": "workspace:*", - "@ray-template/icons": "workspace:*", - "@ray-template/routing": "workspace:*", - "@ray-template/http": "workspace:*", - "@ray-template/admin-shell": "workspace:*" + "vue3-next-qrcode": "4.1.1" } } diff --git a/apps/admin/public/contracts/admin-api.json b/apps/admin/public/contracts/admin-api.json new file mode 100644 index 00000000..27789158 --- /dev/null +++ b/apps/admin/public/contracts/admin-api.json @@ -0,0 +1,3247 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Ray Admin API", + "version": "1.0.0", + "description": "Mock and real backends share this contract. Route component values are identifiers from the frontend view catalog, never executable code." + }, + "servers": [ + { + "url": "/ray-template/api", + "description": "Default demo base. Replace with VITE_API_BASE_URL for your backend." + } + ], + "components": { + "schemas": { + "UserInput": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 32, + "minLength": 2, + "pattern": "^\\S+$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "email": { + "type": "string", + "maxLength": 120, + "format": "email" + }, + "phone": { + "type": "string", + "maxLength": 24, + "pattern": "^[+\\d ()-]*$" + }, + "departmentId": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "role": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + }, + "remark": { + "type": "string", + "maxLength": 300 + } + }, + "required": [ + "username", + "name", + "email", + "phone", + "departmentId", + "role", + "status", + "remark" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "User": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 32, + "minLength": 2, + "pattern": "^\\S+$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "email": { + "type": "string", + "maxLength": 120, + "format": "email" + }, + "phone": { + "type": "string", + "maxLength": 24, + "pattern": "^[+\\d ()-]*$" + }, + "departmentId": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "role": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + }, + "remark": { + "type": "string", + "maxLength": 300 + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "username", + "name", + "email", + "phone", + "departmentId", + "role", + "status", + "remark", + "id", + "createdAt" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "UserList": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 32, + "minLength": 2, + "pattern": "^\\S+$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "email": { + "type": "string", + "maxLength": 120, + "format": "email" + }, + "phone": { + "type": "string", + "maxLength": 24, + "pattern": "^[+\\d ()-]*$" + }, + "departmentId": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "role": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + }, + "remark": { + "type": "string", + "maxLength": 300 + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "username", + "name", + "email", + "phone", + "departmentId", + "role", + "status", + "remark", + "id", + "createdAt" + ] + } + }, + "total": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "items", + "total" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "UserOptions": { + "type": "object", + "properties": { + "departments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "parentId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string" + }, + "labelKey": { + "type": "string" + } + }, + "required": [ + "id", + "parentId", + "name" + ] + } + }, + "roles": { + "type": "array", + "items": { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "label": { + "type": "string" + }, + "labelKey": { + "type": "string" + }, + "disabled": { + "type": "boolean" + } + }, + "required": [ + "value", + "label" + ] + } + } + }, + "required": [ + "departments", + "roles" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "LoginInput": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "password": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "required": [ + "username", + "password" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "LoginResult": { + "type": "object", + "properties": { + "user": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "username": { + "type": "string" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "avatar": { + "type": "string" + } + }, + "required": [ + "id", + "username", + "name", + "role" + ] + }, + "permissions": { + "type": "array", + "items": { + "type": "string" + } + }, + "accessToken": { + "type": "string", + "minLength": 1 + }, + "expiresAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "user", + "permissions", + "accessToken", + "expiresAt" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Session": { + "type": "object", + "properties": { + "user": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "username": { + "type": "string" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "avatar": { + "type": "string" + } + }, + "required": [ + "id", + "username", + "name", + "role" + ] + }, + "permissions": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "user", + "permissions" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Ids": { + "type": "object", + "properties": { + "ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "maxItems": 500 + } + }, + "required": [ + "ids" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "StatusInput": { + "type": "object", + "properties": { + "ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "maxItems": 500 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + } + }, + "required": [ + "ids", + "status" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Changed": { + "type": "object", + "properties": { + "affected": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "affected" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "RouteConfig": { + "type": "object", + "properties": { + "version": { + "const": 1 + }, + "routes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/?(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute or relative child path. Supports named and optional parameters." + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[A-Za-z_][\\w.-]*$", + "description": "Unique Vue Router name. Required for keepAlive." + }, + "component": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered view ID. Use layout for a menu group." + }, + "alias": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + "minItems": 1, + "maxItems": 16 + } + ], + "description": "Absolute alternative path(s) for a leaf." + }, + "redirect": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute path of another configured page." + }, + "props": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "object", + "propertyNames": { + "not": { + "pattern": "^(?:[oO][nN]|innerHTML$|outerHTML$|srcdoc$|__proto__$|constructor$|prototype$)" + } + }, + "additionalProperties": {} + } + ], + "description": "Pass route params (true) or a JSON object to the view." + }, + "meta": { + "type": "object", + "properties": { + "i18nKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Translation key for the menu title." + }, + "noLocalTitle": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ], + "description": "Literal title if i18nKey is absent." + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$", + "description": "IconName from src/icons/manifest.ts." + }, + "role": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "maxItems": 32, + "description": "Allowed roles. Omitted or empty means any authenticated role." + }, + "hidden": { + "type": "boolean", + "description": "Hide from the menu. Direct navigation still uses the role guard." + }, + "sameLevel": { + "type": "boolean", + "description": "Append a breadcrumb without replacing the current tab." + }, + "order": { + "type": "number", + "description": "Menu sort order at the top level." + }, + "env": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "maxItems": 16 + } + ], + "description": "Vite mode(s) in which the menu item is visible." + }, + "windowOpen": { + "type": "string", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?:\\/\\/", + "description": "Open this HTTP(S) URL in a new tab." + }, + "ignoreAutoResetScroll": { + "type": "boolean", + "description": "Keep the content scroll position on navigation." + }, + "keepAlive": { + "type": "boolean", + "description": "Keep the view mounted. name must match the registered view name." + }, + "extra": { + "type": "object", + "properties": { + "label": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "i18nLabel": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$" + }, + "show": { + "type": "boolean" + }, + "type": { + "enum": [ + "default", + "primary", + "info", + "success", + "warning", + "error" + ], + "type": "string" + } + }, + "required": [], + "additionalProperties": false, + "description": "Optional menu badge." + } + }, + "required": [], + "additionalProperties": false + }, + "children": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RouteConfig/$defs/0" + }, + "minItems": 1, + "maxItems": 300 + } + }, + "required": [ + "path", + "meta" + ], + "additionalProperties": false + }, + "maxItems": 300 + } + }, + "required": [ + "version", + "routes" + ], + "additionalProperties": false, + "title": "Ray Template route configuration", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "0": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/?(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute or relative child path. Supports named and optional parameters." + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[A-Za-z_][\\w.-]*$", + "description": "Unique Vue Router name. Required for keepAlive." + }, + "component": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered view ID. Use layout for a menu group." + }, + "alias": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + "minItems": 1, + "maxItems": 16 + } + ], + "description": "Absolute alternative path(s) for a leaf." + }, + "redirect": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute path of another configured page." + }, + "props": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "object", + "propertyNames": { + "not": { + "pattern": "^(?:[oO][nN]|innerHTML$|outerHTML$|srcdoc$|__proto__$|constructor$|prototype$)" + } + }, + "additionalProperties": {} + } + ], + "description": "Pass route params (true) or a JSON object to the view." + }, + "meta": { + "type": "object", + "properties": { + "i18nKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Translation key for the menu title." + }, + "noLocalTitle": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ], + "description": "Literal title if i18nKey is absent." + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$", + "description": "IconName from src/icons/manifest.ts." + }, + "role": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "maxItems": 32, + "description": "Allowed roles. Omitted or empty means any authenticated role." + }, + "hidden": { + "type": "boolean", + "description": "Hide from the menu. Direct navigation still uses the role guard." + }, + "sameLevel": { + "type": "boolean", + "description": "Append a breadcrumb without replacing the current tab." + }, + "order": { + "type": "number", + "description": "Menu sort order at the top level." + }, + "env": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "maxItems": 16 + } + ], + "description": "Vite mode(s) in which the menu item is visible." + }, + "windowOpen": { + "type": "string", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?:\\/\\/", + "description": "Open this HTTP(S) URL in a new tab." + }, + "ignoreAutoResetScroll": { + "type": "boolean", + "description": "Keep the content scroll position on navigation." + }, + "keepAlive": { + "type": "boolean", + "description": "Keep the view mounted. name must match the registered view name." + }, + "extra": { + "type": "object", + "properties": { + "label": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "i18nLabel": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$" + }, + "show": { + "type": "boolean" + }, + "type": { + "enum": [ + "default", + "primary", + "info", + "success", + "warning", + "error" + ], + "type": "string" + } + }, + "required": [], + "additionalProperties": false, + "description": "Optional menu badge." + } + }, + "required": [], + "additionalProperties": false + }, + "children": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RouteConfig/$defs/0" + }, + "minItems": 1, + "maxItems": 300 + } + }, + "required": [ + "path", + "meta" + ], + "additionalProperties": false + } + } + }, + "DemoCharts": { + "type": "object", + "properties": { + "days": { + "type": "array", + "items": { + "type": "string" + } + }, + "orders": { + "type": "array", + "items": { + "type": "number" + } + }, + "visits": { + "type": "array", + "items": { + "type": "number" + } + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "key", + "value" + ] + } + }, + "lines": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "values": { + "type": "array", + "items": { + "type": "number" + } + } + }, + "required": [ + "name", + "values" + ] + } + } + }, + "required": [ + "days", + "orders", + "visits", + "sources", + "lines" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoPeople": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "age": { + "type": "number" + }, + "address": { + "type": "string" + }, + "createDate": { + "type": "string" + }, + "email": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "age", + "address", + "createDate", + "email" + ] + } + }, + "total": { + "type": "number" + } + }, + "required": [ + "items", + "total" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoRequest": { + "type": "object", + "properties": { + "ticket": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "status": { + "type": "string" + } + }, + "required": [ + "id", + "title", + "status" + ] + }, + "cities": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "temperature": { + "type": "number" + }, + "humidity": { + "type": "number" + } + }, + "required": [ + "temperature", + "humidity" + ] + } + } + }, + "required": [ + "ticket", + "cities" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOrders": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "number" + }, + "orderNo": { + "type": "string" + }, + "productIndex": { + "type": "number" + }, + "productId": { + "type": "string" + }, + "statusIndex": { + "type": "number" + }, + "status": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "orgId": { + "type": "string" + }, + "ownerId": { + "type": "string" + }, + "ownerIndex": { + "type": "number" + }, + "warehouseIndex": { + "type": "number" + }, + "warehouseId": { + "type": "string" + }, + "amount": { + "type": "number" + }, + "invoiced": { + "type": "boolean" + }, + "delivery": { + "type": "string" + }, + "deliveryAt": { + "type": "number" + }, + "deliveryTime": { + "type": "string" + }, + "product": { + "type": "string" + }, + "statusLabel": { + "type": "string" + }, + "organization": { + "type": "string" + }, + "owner": { + "type": "string" + } + }, + "required": [ + "id", + "orderNo", + "productIndex", + "productId", + "statusIndex", + "status", + "createdAt", + "orgId", + "ownerId", + "ownerIndex", + "warehouseIndex", + "warehouseId", + "amount", + "invoiced", + "delivery", + "deliveryAt", + "deliveryTime", + "product", + "statusLabel", + "organization", + "owner" + ] + } + }, + "total": { + "type": "number" + } + }, + "required": [ + "items", + "total" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOwners": { + "type": "array", + "items": { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "value", + "label" + ] + }, + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOrderQuery": { + "type": "object", + "properties": { + "query": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "locale": { + "type": "string" + }, + "fail": { + "type": "boolean" + } + }, + "required": [ + "query", + "locale" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOwnerQuery": { + "type": "object", + "properties": { + "orgId": { + "type": "string" + }, + "keyword": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "fail": { + "type": "boolean" + } + }, + "required": [ + "orgId", + "keyword", + "locale" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Error": { + "type": "object", + "properties": { + "code": { + "type": "number" + }, + "msg": { + "type": "string" + }, + "data": { + "type": "null" + }, + "error": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "fields": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "key" + ] + } + }, + "required": [ + "code", + "msg", + "data" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + } + }, + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer" + } + } + }, + "paths": { + "/admin/demo/people": { + "get": { + "operationId": "getDemoPeople", + "summary": "getDemoPeople", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoPeople" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/request": { + "get": { + "operationId": "getRequestFixture", + "summary": "getRequestFixture", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoRequest" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/charts": { + "get": { + "operationId": "getDemoCharts", + "summary": "getDemoCharts", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoCharts" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/orders/search": { + "post": { + "operationId": "searchDemoOrders", + "summary": "searchDemoOrders", + "description": "Session or public bootstrap endpoint.", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DemoOrderQuery" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoOrders" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/owners/search": { + "post": { + "operationId": "searchDemoOwners", + "summary": "searchDemoOwners", + "description": "Session or public bootstrap endpoint.", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DemoOwnerQuery" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoOwners" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/auth/login": { + "post": { + "operationId": "login", + "summary": "login", + "description": "Session or public bootstrap endpoint.", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/LoginResult" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/auth/session": { + "get": { + "operationId": "getSession", + "summary": "getSession", + "description": "Session or public bootstrap endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Session" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/auth/logout": { + "post": { + "operationId": "logout", + "summary": "logout", + "description": "Session or public bootstrap endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "type": "null" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/route-config": { + "get": { + "operationId": "getRouteConfig", + "summary": "getRouteConfig", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/RouteConfig" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateRouteConfig", + "summary": "updateRouteConfig", + "description": "Required permission: routes:write.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RouteConfig" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/RouteConfig" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/options": { + "get": { + "operationId": "getUserOptions", + "summary": "getUserOptions", + "description": "Required permission: users:read.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/UserOptions" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users": { + "get": { + "operationId": "listUsers", + "summary": "listUsers", + "description": "Required permission: users:read.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/UserList" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "page", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "default": 1 + } + }, + { + "name": "pageSize", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 10 + } + }, + { + "name": "name", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "username", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "email", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "departmentId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "role", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "status", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "enabled", + "disabled" + ] + } + } + ] + }, + "post": { + "operationId": "createUser", + "summary": "createUser", + "description": "Required permission: users:create.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/User" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "get": { + "operationId": "getUser", + "summary": "getUser", + "description": "Required permission: users:read.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/User" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateUser", + "summary": "updateUser", + "description": "Required permission: users:update.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/User" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/batch-delete": { + "post": { + "operationId": "deleteUsers", + "summary": "deleteUsers", + "description": "Required permission: users:delete.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ids" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Changed" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/status": { + "patch": { + "operationId": "updateUserStatus", + "summary": "updateUserStatus", + "description": "Required permission: users:status.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StatusInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Changed" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/reset": { + "post": { + "operationId": "resetDemoUsers", + "summary": "resetDemoUsers", + "description": "Required permission: users:reset.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Changed" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + } + } +} diff --git a/apps/admin/public/mockServiceWorker.js b/apps/admin/public/mockServiceWorker.js new file mode 100644 index 00000000..2f658e91 --- /dev/null +++ b/apps/admin/public/mockServiceWorker.js @@ -0,0 +1,349 @@ +/* eslint-disable */ +/* tslint:disable */ + +/** + * Mock Service Worker. + * @see https://github.com/mswjs/msw + * - Please do NOT modify this file. + */ + +const PACKAGE_VERSION = '2.11.6' +const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82' +const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') +const activeClientIds = new Set() + +addEventListener('install', function () { + self.skipWaiting() +}) + +addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()) +}) + +addEventListener('message', async function (event) { + const clientId = Reflect.get(event.source || {}, 'id') + + if (!clientId || !self.clients) { + return + } + + const client = await self.clients.get(clientId) + + if (!client) { + return + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + switch (event.data) { + case 'KEEPALIVE_REQUEST': { + sendToClient(client, { + type: 'KEEPALIVE_RESPONSE', + }) + break + } + + case 'INTEGRITY_CHECK_REQUEST': { + sendToClient(client, { + type: 'INTEGRITY_CHECK_RESPONSE', + payload: { + packageVersion: PACKAGE_VERSION, + checksum: INTEGRITY_CHECKSUM, + }, + }) + break + } + + case 'MOCK_ACTIVATE': { + activeClientIds.add(clientId) + + sendToClient(client, { + type: 'MOCKING_ENABLED', + payload: { + client: { + id: client.id, + frameType: client.frameType, + }, + }, + }) + break + } + + case 'CLIENT_CLOSED': { + activeClientIds.delete(clientId) + + const remainingClients = allClients.filter((client) => { + return client.id !== clientId + }) + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister() + } + + break + } + } +}) + +addEventListener('fetch', function (event) { + const requestInterceptedAt = Date.now() + + // Bypass navigation requests. + if (event.request.mode === 'navigate') { + return + } + + // Opening the DevTools triggers the "only-if-cached" request + // that cannot be handled by the worker. Bypass such requests. + if ( + event.request.cache === 'only-if-cached' && + event.request.mode !== 'same-origin' + ) { + return + } + + // Bypass all requests when there are no active clients. + // Prevents the self-unregistered worked from handling requests + // after it's been terminated (still remains active until the next reload). + if (activeClientIds.size === 0) { + return + } + + const requestId = crypto.randomUUID() + event.respondWith(handleRequest(event, requestId, requestInterceptedAt)) +}) + +/** + * @param {FetchEvent} event + * @param {string} requestId + * @param {number} requestInterceptedAt + */ +async function handleRequest(event, requestId, requestInterceptedAt) { + const client = await resolveMainClient(event) + const requestCloneForEvents = event.request.clone() + const response = await getResponse( + event, + client, + requestId, + requestInterceptedAt, + ) + + // Send back the response clone for the "response:*" life-cycle events. + // Ensure MSW is active and ready to handle the message, otherwise + // this message will pend indefinitely. + if (client && activeClientIds.has(client.id)) { + const serializedRequest = await serializeRequest(requestCloneForEvents) + + // Clone the response so both the client and the library could consume it. + const responseClone = response.clone() + + sendToClient( + client, + { + type: 'RESPONSE', + payload: { + isMockedResponse: IS_MOCKED_RESPONSE in response, + request: { + id: requestId, + ...serializedRequest, + }, + response: { + type: responseClone.type, + status: responseClone.status, + statusText: responseClone.statusText, + headers: Object.fromEntries(responseClone.headers.entries()), + body: responseClone.body, + }, + }, + }, + responseClone.body ? [serializedRequest.body, responseClone.body] : [], + ) + } + + return response +} + +/** + * Resolve the main client for the given event. + * Client that issues a request doesn't necessarily equal the client + * that registered the worker. It's with the latter the worker should + * communicate with during the response resolving phase. + * @param {FetchEvent} event + * @returns {Promise} + */ +async function resolveMainClient(event) { + const client = await self.clients.get(event.clientId) + + if (activeClientIds.has(event.clientId)) { + return client + } + + if (client?.frameType === 'top-level') { + return client + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + return allClients + .filter((client) => { + // Get only those clients that are currently visible. + return client.visibilityState === 'visible' + }) + .find((client) => { + // Find the client ID that's recorded in the + // set of clients that have registered the worker. + return activeClientIds.has(client.id) + }) +} + +/** + * @param {FetchEvent} event + * @param {Client | undefined} client + * @param {string} requestId + * @param {number} requestInterceptedAt + * @returns {Promise} + */ +async function getResponse(event, client, requestId, requestInterceptedAt) { + // Clone the request because it might've been already used + // (i.e. its body has been read and sent to the client). + const requestClone = event.request.clone() + + function passthrough() { + // Cast the request headers to a new Headers instance + // so the headers can be manipulated with. + const headers = new Headers(requestClone.headers) + + // Remove the "accept" header value that marked this request as passthrough. + // This prevents request alteration and also keeps it compliant with the + // user-defined CORS policies. + const acceptHeader = headers.get('accept') + if (acceptHeader) { + const values = acceptHeader.split(',').map((value) => value.trim()) + const filteredValues = values.filter( + (value) => value !== 'msw/passthrough', + ) + + if (filteredValues.length > 0) { + headers.set('accept', filteredValues.join(', ')) + } else { + headers.delete('accept') + } + } + + return fetch(requestClone, { headers }) + } + + // Bypass mocking when the client is not active. + if (!client) { + return passthrough() + } + + // Bypass initial page load requests (i.e. static assets). + // The absence of the immediate/parent client in the map of the active clients + // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet + // and is not ready to handle requests. + if (!activeClientIds.has(client.id)) { + return passthrough() + } + + // Notify the client that a request has been intercepted. + const serializedRequest = await serializeRequest(event.request) + const clientMessage = await sendToClient( + client, + { + type: 'REQUEST', + payload: { + id: requestId, + interceptedAt: requestInterceptedAt, + ...serializedRequest, + }, + }, + [serializedRequest.body], + ) + + switch (clientMessage.type) { + case 'MOCK_RESPONSE': { + return respondWithMock(clientMessage.data) + } + + case 'PASSTHROUGH': { + return passthrough() + } + } + + return passthrough() +} + +/** + * @param {Client} client + * @param {any} message + * @param {Array} transferrables + * @returns {Promise} + */ +function sendToClient(client, message, transferrables = []) { + return new Promise((resolve, reject) => { + const channel = new MessageChannel() + + channel.port1.onmessage = (event) => { + if (event.data && event.data.error) { + return reject(event.data.error) + } + + resolve(event.data) + } + + client.postMessage(message, [ + channel.port2, + ...transferrables.filter(Boolean), + ]) + }) +} + +/** + * @param {Response} response + * @returns {Response} + */ +function respondWithMock(response) { + // Setting response status code to 0 is a no-op. + // However, when responding with a "Response.error()", the produced Response + // instance will have status code set to 0. Since it's not possible to create + // a Response instance with status code 0, handle that use-case separately. + if (response.status === 0) { + return Response.error() + } + + const mockedResponse = new Response(response.body, response) + + Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { + value: true, + enumerable: true, + }) + + return mockedResponse +} + +/** + * @param {Request} request + */ +async function serializeRequest(request) { + return { + url: request.url, + mode: request.mode, + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + cache: request.cache, + credentials: request.credentials, + destination: request.destination, + integrity: request.integrity, + redirect: request.redirect, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + body: await request.arrayBuffer(), + keepalive: request.keepalive, + } +} diff --git a/apps/admin/src/api/admin/client.ts b/apps/admin/src/api/admin/client.ts new file mode 100644 index 00000000..c11b0a42 --- /dev/null +++ b/apps/admin/src/api/admin/client.ts @@ -0,0 +1,82 @@ +import { APP_CATCH_KEY } from '@/app-config' +import { request } from '@/axios' +import type { AppRawRequestConfig } from '@/axios/types' +import { getStorage } from '@/utils/cache' +import { isAxiosError } from 'axios' +import * as v from 'valibot' +import { envelopeSchema } from './contracts' + +export const apiMockEnabled = + import.meta.env.VITE_API_MOCK === 'true' || + (import.meta.env.VITE_API_MOCK !== 'false' && + !import.meta.env.VITE_API_BASE_URL?.trim()) + +export const apiUrl = (path: string) => { + const base = + import.meta.env.VITE_API_BASE_URL?.trim() || + `${import.meta.env.BASE_URL}api/` + + return new URL( + path.replace(/^\//u, ''), + new URL(base.endsWith('/') ? base : `${base}/`, document.baseURI), + ).href +} + +export class AdminApiError extends Error { + constructor( + public readonly code: number, + public readonly key: string, + message: string, + public readonly fields?: Record, + ) { + super(message) + } +} + +export async function adminRequest( + path: string, + schema: Schema, + options: AppRawRequestConfig = {}, +): Promise> { + let body: unknown + + try { + const token = getStorage(APP_CATCH_KEY.token, 'localStorage') + + body = await request({ + ...options, + url: apiUrl(`admin/${path}`), + headers: { + ...(token ? { Authorization: `Bearer ${token}` } : {}), + ...options.headers, + }, + cancelConfig: { cancel: false }, + }) + } catch (error) { + if (!isAxiosError(error) || !error.response) throw error + + const result = v.safeParse(envelopeSchema, error.response.data) + + if (result.success) + throw new AdminApiError( + result.output.code, + result.output.error?.key ?? 'requestFailed', + result.output.msg, + result.output.error?.fields, + ) + + throw error + } + + const envelope = v.parse(envelopeSchema, body) + + if (envelope.code !== 200) + throw new AdminApiError( + envelope.code, + envelope.error?.key ?? 'requestFailed', + envelope.msg, + envelope.error?.fields, + ) + + return v.parse(schema, envelope.data) +} diff --git a/apps/admin/src/api/admin/contracts.ts b/apps/admin/src/api/admin/contracts.ts new file mode 100644 index 00000000..760fe8eb --- /dev/null +++ b/apps/admin/src/api/admin/contracts.ts @@ -0,0 +1,153 @@ +import * as v from 'valibot' + +const text = (max: number) => v.pipe(v.string(), v.trim(), v.maxLength(max)) + +export const userInputSchema = v.object({ + username: v.pipe(text(32), v.minLength(2), v.regex(/^\S+$/u)), + name: v.pipe(text(60), v.minLength(1)), + email: v.pipe(text(120), v.email()), + phone: v.pipe(text(24), v.regex(/^[+\d ()-]*$/u)), + departmentId: v.pipe(text(80), v.minLength(1)), + role: v.pipe(text(80), v.minLength(1)), + status: v.picklist(['enabled', 'disabled']), + remark: text(300), +}) +export type UserInput = v.InferOutput +export const userSchema = v.object({ + ...userInputSchema.entries, + id: v.pipe(v.string(), v.minLength(1), v.maxLength(80)), + createdAt: v.pipe(v.string(), v.isoTimestamp()), +}) +export type AdminUser = v.InferOutput +export type UserStatus = AdminUser['status'] + +export const departmentSchema = v.object({ + id: v.pipe(v.string(), v.minLength(1)), + parentId: v.nullable(v.string()), + name: v.string(), + labelKey: v.optional(v.string()), +}) +export type Department = v.InferOutput +export const roleOptionSchema = v.object({ + value: v.string(), + label: v.string(), + labelKey: v.optional(v.string()), + disabled: v.optional(v.boolean()), +}) +export const userOptionsSchema = v.pipe( + v.object({ + departments: v.array(departmentSchema), + roles: v.array(roleOptionSchema), + }), + v.check(({ departments, roles }) => { + const byId = new Map(departments.map((item) => [item.id, item])) + + if ( + byId.size !== departments.length || + new Set(roles.map((item) => item.value)).size !== roles.length + ) + return false + + return departments.every((item) => { + const seen = new Set() + let current: Department | undefined = item + + while (current) { + if (seen.has(current.id)) return false + + seen.add(current.id) + + if (current.parentId === null) return true + + current = byId.get(current.parentId) + } + + return false + }) + }, 'Departments must form a tree with unique identifiers.'), +) +export type UserOptions = v.InferOutput + +export const profileSchema = v.object({ + id: v.string(), + username: v.string(), + name: v.string(), + role: v.string(), + avatar: v.optional(v.string()), +}) +export const sessionSchema = v.object({ + user: profileSchema, + permissions: v.array(v.string()), +}) +export type SessionInfo = v.InferOutput +export const loginInputSchema = v.object({ + username: v.pipe(text(80), v.minLength(1)), + password: v.pipe(v.string(), v.minLength(1), v.maxLength(128)), +}) +export const loginResultSchema = v.object({ + ...sessionSchema.entries, + accessToken: v.pipe(v.string(), v.minLength(1)), + expiresAt: v.pipe(v.string(), v.isoTimestamp()), +}) +export type LoginResult = v.InferOutput + +export interface ApiResponse { + code: number + msg: string + data: T + error?: { key: string; fields?: Record } +} +export const envelopeSchema = v.object({ + code: v.number(), + msg: v.string(), + data: v.unknown(), + error: v.optional( + v.object({ + key: v.string(), + fields: v.optional(v.record(v.string(), v.string())), + }), + ), +}) +export const userListSchema = v.object({ + items: v.array(userSchema), + total: v.pipe(v.number(), v.integer(), v.minValue(0)), +}) +export const userListQuerySchema = v.object({ + page: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1))), + pageSize: v.optional( + v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100)), + ), + name: v.optional(text(60)), + username: v.optional(text(32)), + email: v.optional(text(120)), + departmentId: v.optional(text(80)), + status: v.optional(v.picklist(['enabled', 'disabled'])), + role: v.optional(text(80)), +}) +export type UserListParams = v.InferOutput +export const idsSchema = v.object({ + ids: v.pipe( + v.array(v.pipe(v.string(), v.minLength(1))), + v.minLength(1), + v.maxLength(500), + ), +}) +export const statusInputSchema = v.object({ + ...idsSchema.entries, + status: v.picklist(['enabled', 'disabled']), +}) +export const changedSchema = v.object({ + affected: v.pipe(v.number(), v.integer(), v.minValue(0)), +}) + +export const permissionCodes = [ + 'users:read', + 'users:create', + 'users:update', + 'users:delete', + 'users:status', + 'users:reset', + 'routes:read', + 'routes:write', +] as const +export type PermissionCode = (typeof permissionCodes)[number] diff --git a/apps/admin/src/api/admin/index.ts b/apps/admin/src/api/admin/index.ts new file mode 100644 index 00000000..a5b4d5c1 --- /dev/null +++ b/apps/admin/src/api/admin/index.ts @@ -0,0 +1,68 @@ +import type { RouteConfig } from '@/router/config/schema' +import { routeConfigSchema } from '@ray-template/routing/schema' +import * as v from 'valibot' +import { adminRequest } from './client' +import { + changedSchema, + loginResultSchema, + sessionSchema, + userListSchema, + userOptionsSchema, + userSchema, +} from './contracts' +import type { UserInput, UserListParams, UserStatus } from './contracts' + +export const loginAdmin = (username: string, password: string) => + adminRequest('auth/login', loginResultSchema, { + method: 'post', + data: { username, password }, + }) +export const getAdminSession = () => + adminRequest('auth/session', sessionSchema, { method: 'get' }) +export const logoutAdmin = () => + adminRequest('auth/logout', v.null(), { method: 'post' }) +export const getAdminRoutes = () => + adminRequest('route-config', routeConfigSchema, { method: 'get' }) +export const updateAdminRoutes = (config: RouteConfig) => + adminRequest('route-config', routeConfigSchema, { + method: 'put', + data: config, + }) +export const getUserOptions = (signal?: AbortSignal) => + adminRequest('users/options', userOptionsSchema, { method: 'get', signal }) +export const getUsers = async ( + params: UserListParams, + signal?: AbortSignal, +) => { + const { items, total } = await adminRequest('users', userListSchema, { + method: 'get', + params, + signal, + }) + + return { data: items, total } +} +export const getUser = (id: string, signal?: AbortSignal) => + adminRequest(`users/${encodeURIComponent(id)}`, userSchema, { + method: 'get', + signal, + }) +export const createUser = (data: UserInput) => + adminRequest('users', userSchema, { method: 'post', data }) +export const updateUser = (id: string, data: UserInput) => + adminRequest(`users/${encodeURIComponent(id)}`, userSchema, { + method: 'put', + data, + }) +export const deleteUsers = (ids: string[]) => + adminRequest('users/batch-delete', changedSchema, { + method: 'post', + data: { ids }, + }) +export const updateUserStatus = (ids: string[], status: UserStatus) => + adminRequest('users/status', changedSchema, { + method: 'patch', + data: { ids, status }, + }) +export const resetDemoUsers = () => + adminRequest('users/reset', changedSchema, { method: 'post' }) diff --git a/apps/admin/src/api/admin/openapi.ts b/apps/admin/src/api/admin/openapi.ts new file mode 100644 index 00000000..ac064cd9 --- /dev/null +++ b/apps/admin/src/api/admin/openapi.ts @@ -0,0 +1,238 @@ +import { routeConfigSchema } from '@ray-template/routing/schema' +import { toJsonSchema } from '@valibot/to-json-schema' +import * as v from 'valibot' +import { + chartsSchema, + ordersResultSchema, + ownerOptionsSchema, + peopleResultSchema, + requestFixtureSchema, +} from '../demo/contracts.ts' +import { + changedSchema, + envelopeSchema, + idsSchema, + loginInputSchema, + loginResultSchema, + sessionSchema, + statusInputSchema, + userInputSchema, + userListSchema, + userOptionsSchema, + userSchema, +} from './contracts.ts' + +export function getAdminOpenApi() { + const schemas = Object.fromEntries( + Object.entries({ + UserInput: userInputSchema, + User: userSchema, + UserList: userListSchema, + UserOptions: userOptionsSchema, + LoginInput: loginInputSchema, + LoginResult: loginResultSchema, + Session: sessionSchema, + Ids: idsSchema, + StatusInput: statusInputSchema, + Changed: changedSchema, + RouteConfig: routeConfigSchema, + DemoCharts: chartsSchema, + DemoPeople: peopleResultSchema, + DemoRequest: requestFixtureSchema, + DemoOrders: ordersResultSchema, + DemoOwners: ownerOptionsSchema, + DemoOrderQuery: v.object({ + query: v.record(v.string(), v.unknown()), + locale: v.string(), + fail: v.optional(v.boolean()), + }), + DemoOwnerQuery: v.object({ + orgId: v.string(), + keyword: v.string(), + locale: v.string(), + fail: v.optional(v.boolean()), + }), + Error: v.object({ ...envelopeSchema.entries, data: v.null() }), + }).map(([name, schema]) => [ + name, + toJsonSchema(schema, { + target: 'draft-2020-12', + errorMode: 'ignore', + // Schema 嵌入 OpenAPI 后,递归引用必须从整个文档定位到所属组件。 + overrideRef: ({ referenceId }) => + `#/components/schemas/${name}/$defs/${referenceId.replaceAll('~', '~0').replaceAll('/', '~1')}`, + }), + ]), + ) + const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` }) + const json = (schema: unknown) => ({ 'application/json': { schema } }) + const operation = ( + id: string, + result: string | null, + permission?: string, + input?: string, + publicEndpoint = false, + ) => ({ + operationId: id, + summary: id, + description: permission + ? `Required permission: ${permission}.` + : 'Session or public bootstrap endpoint.', + security: publicEndpoint ? [] : [{ bearerAuth: [] }], + ...(input + ? { requestBody: { required: true, content: json(ref(input)) } } + : {}), + responses: { + '200': { + description: 'Success', + content: json({ + type: 'object', + required: ['code', 'msg', 'data'], + properties: { + code: { const: 200 }, + msg: { type: 'string' }, + data: result ? ref(result) : { type: 'null' }, + }, + }), + }, + ...Object.fromEntries( + [400, 401, 403, 404, 409, 503].map((status) => [ + status, + { + description: 'See error.key for a stable machine-readable reason.', + content: json(ref('Error')), + }, + ]), + ), + }, + }) + const pathId = { + name: 'id', + in: 'path', + required: true, + schema: { type: 'string' }, + } + + return { + openapi: '3.1.0', + info: { + title: 'Ray Admin API', + version: '1.0.0', + description: + 'Mock and real backends share this contract. Route component values are identifiers from the frontend view catalog, never executable code.', + }, + servers: [ + { + url: '/ray-template/api', + description: + 'Default demo base. Replace with VITE_API_BASE_URL for your backend.', + }, + ], + components: { + schemas, + securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer' } }, + }, + paths: { + '/admin/demo/people': { + get: operation('getDemoPeople', 'DemoPeople', void 0, void 0, true), + }, + '/admin/demo/request': { + get: operation( + 'getRequestFixture', + 'DemoRequest', + void 0, + void 0, + true, + ), + }, + '/admin/demo/charts': { + get: operation('getDemoCharts', 'DemoCharts', void 0, void 0, true), + }, + '/admin/demo/orders/search': { + post: operation( + 'searchDemoOrders', + 'DemoOrders', + void 0, + 'DemoOrderQuery', + true, + ), + }, + '/admin/demo/owners/search': { + post: operation( + 'searchDemoOwners', + 'DemoOwners', + void 0, + 'DemoOwnerQuery', + true, + ), + }, + '/admin/auth/login': { + post: operation('login', 'LoginResult', void 0, 'LoginInput', true), + }, + '/admin/auth/session': { get: operation('getSession', 'Session') }, + '/admin/auth/logout': { post: operation('logout', null) }, + '/admin/route-config': { + get: operation('getRouteConfig', 'RouteConfig', void 0, void 0, true), + put: operation( + 'updateRouteConfig', + 'RouteConfig', + 'routes:write', + 'RouteConfig', + ), + }, + '/admin/users/options': { + get: operation('getUserOptions', 'UserOptions', 'users:read'), + }, + '/admin/users': { + get: { + ...operation('listUsers', 'UserList', 'users:read'), + parameters: [ + { + name: 'page', + in: 'query', + schema: { type: 'integer', minimum: 1, default: 1 }, + }, + { + name: 'pageSize', + in: 'query', + schema: { + type: 'integer', + minimum: 1, + maximum: 100, + default: 10, + }, + }, + ...['name', 'username', 'email', 'departmentId', 'role'].map( + (name) => ({ name, in: 'query', schema: { type: 'string' } }), + ), + { + name: 'status', + in: 'query', + schema: { type: 'string', enum: ['enabled', 'disabled'] }, + }, + ], + }, + post: operation('createUser', 'User', 'users:create', 'UserInput'), + }, + '/admin/users/{id}': { + parameters: [pathId], + get: operation('getUser', 'User', 'users:read'), + put: operation('updateUser', 'User', 'users:update', 'UserInput'), + }, + '/admin/users/batch-delete': { + post: operation('deleteUsers', 'Changed', 'users:delete', 'Ids'), + }, + '/admin/users/status': { + patch: operation( + 'updateUserStatus', + 'Changed', + 'users:status', + 'StatusInput', + ), + }, + '/admin/users/reset': { + post: operation('resetDemoUsers', 'Changed', 'users:reset'), + }, + }, + } +} diff --git a/apps/admin/src/api/demo/contracts.ts b/apps/admin/src/api/demo/contracts.ts new file mode 100644 index 00000000..43d0d18d --- /dev/null +++ b/apps/admin/src/api/demo/contracts.ts @@ -0,0 +1,60 @@ +import * as v from 'valibot' + +export const personSchema = v.object({ + id: v.string(), + name: v.string(), + age: v.number(), + address: v.string(), + createDate: v.string(), + email: v.string(), +}) +export const peopleResultSchema = v.object({ + items: v.array(personSchema), + total: v.number(), +}) +export const requestFixtureSchema = v.object({ + ticket: v.object({ id: v.string(), title: v.string(), status: v.string() }), + cities: v.record( + v.string(), + v.object({ temperature: v.number(), humidity: v.number() }), + ), +}) +export const orderSchema = v.object({ + id: v.number(), + orderNo: v.string(), + productIndex: v.number(), + productId: v.string(), + statusIndex: v.number(), + status: v.string(), + createdAt: v.string(), + orgId: v.string(), + ownerId: v.string(), + ownerIndex: v.number(), + warehouseIndex: v.number(), + warehouseId: v.string(), + amount: v.number(), + invoiced: v.boolean(), + delivery: v.string(), + deliveryAt: v.number(), + deliveryTime: v.string(), + product: v.string(), + statusLabel: v.string(), + organization: v.string(), + owner: v.string(), +}) +export type DemoOrder = v.InferOutput +export const ordersResultSchema = v.object({ + items: v.array(orderSchema), + total: v.number(), +}) +export const ownerOptionsSchema = v.array( + v.object({ value: v.string(), label: v.string() }), +) +export const chartsSchema = v.object({ + days: v.array(v.string()), + orders: v.array(v.number()), + visits: v.array(v.number()), + sources: v.array(v.object({ key: v.string(), value: v.number() })), + lines: v.array(v.object({ name: v.string(), values: v.array(v.number()) })), +}) +export type DemoCharts = v.InferOutput diff --git a/apps/admin/src/api/demo/data.ts b/apps/admin/src/api/demo/data.ts new file mode 100644 index 00000000..1378ba51 --- /dev/null +++ b/apps/admin/src/api/demo/data.ts @@ -0,0 +1,38 @@ +import { adminRequest } from '@/api/admin/client' +import { + chartsSchema, + ordersResultSchema, + ownerOptionsSchema, +} from './contracts' + +export * from './contracts' + +export const getSearchOrders = ( + query: Record, + locale: string, + signal?: AbortSignal, + fail = false, +) => + adminRequest('demo/orders/search', ordersResultSchema, { + method: 'post', + data: { query, locale, fail }, + signal, + }) +export const getSearchOwners = ( + orgId: string, + keyword: string, + locale: string, + signal: AbortSignal, + fail = false, +) => + adminRequest('demo/owners/search', ownerOptionsSchema, { + method: 'post', + data: { orgId, keyword, locale, fail }, + signal, + }) +export const getDemoCharts = (refresh = false, signal?: AbortSignal) => + adminRequest('demo/charts', chartsSchema, { + method: 'get', + params: { refresh }, + signal, + }) diff --git a/apps/admin/src/api/demo/mock/person.ts b/apps/admin/src/api/demo/mock/person.ts index e4d7ccbd..30b8ad54 100644 --- a/apps/admin/src/api/demo/mock/person.ts +++ b/apps/admin/src/api/demo/mock/person.ts @@ -1,4 +1,5 @@ -import { request } from '@/axios' +import { adminRequest } from '@/api/admin/client' +import { peopleResultSchema } from '@/api/demo/data' import type { Person, PersonListParams } from '@/demo-data/people' import type { PaginationResponse } from '@/types' @@ -8,17 +9,16 @@ export const getPersonList = async ( params: PersonListParams, signal?: AbortSignal, ) => { - if (import.meta.env.DEV) { - return request>({ - url: '/api/list', - method: 'get', - params, - signal, - cancelConfig: { cancel: !signal }, - }) - } + const result = await adminRequest('demo/people', peopleResultSchema, { + method: 'get', + params, + signal, + }) - const { listPeople } = await import('@/demo-data/people') - - return listPeople(params) + return { + code: 200, + msg: 'OK', + data: result.items, + total: result.total, + } satisfies PaginationResponse } diff --git a/apps/admin/src/api/demo/test.ts b/apps/admin/src/api/demo/test.ts index c839ab8a..9817afae 100644 --- a/apps/admin/src/api/demo/test.ts +++ b/apps/admin/src/api/demo/test.ts @@ -1,14 +1,15 @@ -import { request } from '@/axios' +import { adminRequest, apiUrl } from '@/api/admin/client' +import { requestFixtureSchema } from './data' interface RequestFixture { ticket: { id: string; title: string; status: string } cities: Record } -export const requestFixtureUrl = `${import.meta.env.BASE_URL}examples/request.json` +export const requestFixtureUrl = apiUrl('admin/demo/request') export const getRequestFixture = () => - request({ url: requestFixtureUrl, method: 'get' }) + adminRequest('demo/request', requestFixtureSchema, { method: 'get' }) export const getWeather = async (city: string) => { const { cities } = await getRequestFixture() diff --git a/apps/admin/src/axios/axios-interceptor/request/plugins/request-headers.ts b/apps/admin/src/axios/axios-interceptor/request/plugins/request-headers.ts index a114a483..ea1a8edc 100644 --- a/apps/admin/src/axios/axios-interceptor/request/plugins/request-headers.ts +++ b/apps/admin/src/axios/axios-interceptor/request/plugins/request-headers.ts @@ -1,40 +1,43 @@ import { APP_CATCH_KEY } from '@/app-config' -import type { - AxiosRequestInterceptor, - RequestInterceptorConfig, -} from '@/axios/types' +import type { AxiosRequestInterceptor } from '@/axios/types' import { appendRequestHeaders } from '@/axios/utils/append-request-headers' -import { getStorage } from '@/utils' +import { getStorage } from '@/utils/cache' -/** - * - * 这里只是示例如何获取到系统缓存的 token 并且返回请求头 token 的 key 和 value - * 尽可能的拆分每个拦截器的功能函数 - * 这是这个包存在的意义 - * - * 当然你也可以根据 request instance 来特殊处理, 这里暂时不做演示 - */ -const requestHeaderToken = (ins: RequestInterceptorConfig, mode: string) => { - const token = getStorage(APP_CATCH_KEY.token, 'localStorage') +const injectRequestHeaders: AxiosRequestInterceptor = (config) => { + const token = getStorage(APP_CATCH_KEY.token, 'localStorage') - if (ins.url) { - // TODO: 根据 url 不同是否设置 token - } + if ( + !token || + !config.url || + Object.keys(config.headers ?? {}).some( + (name) => name.toLowerCase() === 'authorization', + ) + ) + return - return { - key: 'X-TOKEN', - value: token, - } -} + const configured = + import.meta.env.VITE_API_BASE_URL?.trim() || + `${import.meta.env.BASE_URL}api/` + const base = new URL( + configured.endsWith('/') ? configured : `${configured}/`, + document.baseURI, + ) + const target = new URL( + config.url, + config.baseURL + ? new URL(config.baseURL, document.baseURI) + : document.baseURI, + ) -/** 注入请求头信息 */ -const injectRequestHeaders: AxiosRequestInterceptor = (ins, mode) => { - appendRequestHeaders(ins, [ - requestHeaderToken(ins, mode), - { - key: 'Demo-Header-Key', - value: 'Demo Header Value', - }, + // 只向接入方明确配置的 API 来源和路径发送会话,不污染第三方或静态资源请求。 + if ( + target.origin !== base.origin || + !target.pathname.startsWith(base.pathname) + ) + return + + appendRequestHeaders(config, [ + { key: 'Authorization', value: `Bearer ${token}` }, ]) } diff --git a/apps/admin/src/axios/instance.ts b/apps/admin/src/axios/instance.ts index ba666936..34027de3 100644 --- a/apps/admin/src/axios/instance.ts +++ b/apps/admin/src/axios/instance.ts @@ -13,4 +13,12 @@ const client = createHttpClient({ }) export const axiosCanceler = client.canceler +export const installMockRequestGuard = ( + guard: (url: string) => Promise, +) => + client.request.interceptors.request.use(async (config) => { + await guard(client.request.getUri(config)) + + return config + }) export default client.request diff --git a/apps/admin/src/documentation-example.tsx b/apps/admin/src/documentation-example.tsx index f892576c..862e29a5 100644 --- a/apps/admin/src/documentation-example.tsx +++ b/apps/admin/src/documentation-example.tsx @@ -1,4 +1,5 @@ import './styles/entry' +import { apiMockEnabled } from '@/api/admin/client' import AppNaiveGlobalProvider from '@/app-components/provider/AppNaiveGlobalProvider' import AppStyleProvider from '@/app-components/provider/AppStyleProvider' import AppWatermarkProvider from '@/app-components/provider/AppWatermarkProvider' @@ -116,6 +117,13 @@ const DocumentationExample = defineComponent({ async function mountExample() { useMemoryCache() + + if (apiMockEnabled) { + const { enableApiMock } = await import('./mocks/browser') + + await enableApiMock() + } + const app = createApp(DocumentationExample) app.use(createPinia()) diff --git a/apps/admin/src/hooks/template/index.ts b/apps/admin/src/hooks/template/index.ts index 61389735..25442c08 100644 --- a/apps/admin/src/hooks/template/index.ts +++ b/apps/admin/src/hooks/template/index.ts @@ -10,3 +10,4 @@ export * from './useSiderScroll' export * from './useContentScroll' export * from './useI18n' export * from './useVueRouter' +export * from './useAccess' diff --git a/apps/admin/src/hooks/template/useAccess.ts b/apps/admin/src/hooks/template/useAccess.ts new file mode 100644 index 00000000..b9197e1c --- /dev/null +++ b/apps/admin/src/hooks/template/useAccess.ts @@ -0,0 +1,17 @@ +import { useSigningGetters } from '@/store' + +export function useAccess() { + const { getPermissions } = useSigningGetters() + const hasPermission = ( + codes: string | readonly string[], + mode: 'all' | 'any' = 'all', + ) => { + const required = typeof codes === 'string' ? [codes] : codes + + return mode === 'all' + ? required.every((code) => getPermissions.value.includes(code)) + : required.some((code) => getPermissions.value.includes(code)) + } + + return { hasPermission, permissions: getPermissions } +} diff --git a/apps/admin/src/layout/components/Search/GlobalSearch/index.scss b/apps/admin/src/layout/components/Search/GlobalSearch/index.scss index 2e3e2090..12c9459e 100644 --- a/apps/admin/src/layout/components/Search/GlobalSearch/index.scss +++ b/apps/admin/src/layout/components/Search/GlobalSearch/index.scss @@ -1,84 +1,99 @@ -$globalSearchWidth: 650px; +.global-search.n-card { + width: min(650px, calc(100vw - 40px)); + margin: 60px auto auto; + border-radius: 12px; -.global-search { - position: fixed; - width: $globalSearchWidth; - left: 50%; - margin-left: calc(0px - $globalSearchWidth / 2); - top: 60px; - - & .global-search__wrapper { - box-sizing: border-box; - - & .global-search__card { - border-radius: 6px; - min-width: 560px; - - & .r-icon { - color: var(--r-theme-primary-color); - } - - & .n-card__action { - padding: 8px 12px; - } - - > .n-card-content, - & .n-spin-content { - min-height: 90px; - } - - & .content-item { - padding: 12px; - border-radius: 6px; - cursor: pointer; - transition: background-color 0.3s var(--r-bezier); - border: 1px solid var(--n-border-color); - - & .content-item-icon { - @include flexCenter; - } - } - - & .item-icon { - min-width: 24px; - border-radius: 4px; - border: 1px solid var(--n-border-color); - padding: 3px 6px; - background-color: var(--n-action-color); - } - - & .item-icon, - & .item-label { - transform: scale(0.75); - font-weight: bolder; - } - } + .n-card__action { + padding: 12px 20px; } } -.n-flex.global-search__card-content { - & .content-item.content-item--active, - & .content-item:hover { - background-color: var(--r-theme-primary-fade-color); - } +.global-search__header, +.global-search__group-heading, +.global-search__item, +.global-search__help { + display: flex; + align-items: center; +} - & .content-item { - position: relative; - transition: var(--r-bezier); +.global-search__header, +.global-search__group-heading { + justify-content: space-between; +} +.global-search__header { + gap: 16px; +} +.global-search__group { + margin-top: 20px; +} +.global-search__group-heading { + min-height: 28px; + margin-bottom: 8px; - & .content-item-icon__enter { - position: absolute; - width: 18px; - height: 18px; - right: 16px; - opacity: 0; - } - } - - & .content-item.content-item--active, - & .content-item:hover { - & .content-item-icon__enter { - opacity: 1; - } + h2 { + font-size: 13px; + font-weight: 500; + color: var(--r-text-secondary); + } +} +.global-search__item { + gap: 4px; + border: 1px solid var(--r-line); + border-radius: 8px; + margin-block: 6px; + padding-inline-end: 8px; + + &:hover, + &:focus-within { + background: var(--r-surface-hover); + } +} +.global-search__destination { + display: flex; + flex: 1; + align-items: center; + gap: 12px; + min-width: 0; + min-height: 46px; + padding: 10px 12px; + border: 0; + border-radius: 8px; + background: transparent; + color: var(--r-text); + text-align: start; + cursor: pointer; + line-height: 1.5; + + > span { + overflow-wrap: anywhere; + } + .r-icon { + flex-shrink: 0; + color: var(--r-theme-primary-color); + } +} +.global-search__favorite { + flex-shrink: 0; + font-size: 20px; +} +.global-search__empty { + padding: 36px 12px; + text-align: center; + color: var(--r-text-secondary); +} +.global-search__hint { + margin-top: 12px; + color: var(--r-text-secondary); +} +.global-search__help { + flex-wrap: wrap; + gap: 16px; + font-size: 12px; + color: var(--r-text-secondary); + + kbd { + padding: 2px 5px; + border: 1px solid var(--r-line); + border-radius: 4px; } } diff --git a/apps/admin/src/layout/components/Search/GlobalSearch/index.tsx b/apps/admin/src/layout/components/Search/GlobalSearch/index.tsx index 34994d59..0b654afd 100644 --- a/apps/admin/src/layout/components/Search/GlobalSearch/index.tsx +++ b/apps/admin/src/layout/components/Search/GlobalSearch/index.tsx @@ -1,46 +1,52 @@ -import { positionSelectedMenuItem } from '@/layout/utils/position-selected-menu-item' import './index.scss' import { RIcon } from '@/components' -import { useDevice } from '@/hooks' -import type { AppRouteMeta } from '@/router/types' -import { useMenuActions, useMenuGetters } from '@/store' +import { useDevice, useI18n } from '@/hooks' +import { positionSelectedMenuItem } from '@/layout/utils/position-selected-menu-item' +import { + useMenuActions, + useMenuGetters, + useNavigationHistoryActions, + useNavigationHistoryGetters, +} from '@/store' import type { AppMenuOption } from '@/types' import { useEventListener } from '@vueuse/core' -import { - NCard, - NFlex, - NInput, - NModal, - NResult, - NScrollbar, - NText, -} from 'naive-ui' +import { NButton, NCard, NInput, NModal, NScrollbar } from 'naive-ui' +import type { InputInst } from 'naive-ui' export default defineComponent({ name: 'GlobalSearch', - props: { - show: { - type: Boolean, - default: false, - }, - }, + props: { show: { type: Boolean, default: false } }, emits: ['update:show'], setup(props, { emit }) { + const { t } = useI18n('navigationSearch') const { changeMenuModelValue } = useMenuActions() const { getMenuOptions } = useMenuGetters() - + const { recentPaths, favoritePaths, storageUnavailable } = + useNavigationHistoryGetters() + const { recordVisit, toggleFavorite, clearRecent } = + useNavigationHistoryActions() + const input = shallowRef() + const inputId = useId() + const searchValue = ref('') + const activeIndex = ref(0) + const rowButtons = new Map() + const resetSearch = () => { + searchValue.value = '' + activeIndex.value = 0 + } const modelShow = computed({ get: () => props.show, - set: (val) => { - emit('update:show', val) + set: (value) => { + emit('update:show', value) - if (!val) { - resetSearchSomeValue() - } + if (!value) resetSearch() + }, + }) + const { isTabletOrSmaller } = useDevice({ + observer: (small) => { + if (small) modelShow.value = false }, }) - const searchValue = ref('') - const searchElementIndex = ref(0) const visibleLeaves = computed(() => { const leaves: AppMenuOption[] = [] const visit = (items: AppMenuOption[]) => { @@ -56,253 +62,270 @@ export default defineComponent({ return leaves }) - const searchOptions = computed(() => { + const menuByPath = computed( + () => new Map(visibleLeaves.value.map((item) => [item.fullPath, item])), + ) + const savedOptions = (paths: readonly string[]) => + paths.flatMap((path) => { + const option = menuByPath.value.get(path) + + return option ? [option] : [] + }) + const groups = computed(() => { const term = searchValue.value.trim().toLocaleLowerCase() - return term - ? visibleLeaves.value.filter(({ breadcrumbLabel }) => - breadcrumbLabel?.toLocaleLowerCase().includes(term), - ) - : [] - }) + if (term) + return [ + { + key: 'results', + options: visibleLeaves.value.filter((item) => + item.breadcrumbLabel?.toLocaleLowerCase().includes(term), + ), + }, + ] - watch(searchOptions, () => { - searchElementIndex.value = 0 + return [ + { key: 'favorites', options: savedOptions(favoritePaths.value) }, + { + key: 'recent', + options: savedOptions( + recentPaths.value.filter( + (path) => !favoritePaths.value.includes(path), + ), + ), + }, + ].filter(({ options }) => options.length) }) - const helperTipOptions = [ - { - icon: ['↑', '↓'], - label: '切换', - plain: true, + const options = computed(() => + groups.value.flatMap((group) => group.options), + ) + + watch(options, () => { + activeIndex.value = 0 + }) + watch( + () => props.show, + (show) => { + if (show) resetSearch() }, - { - icon: ['↵'], - label: '选择', - plain: true, - }, - { - icon: ['esc'], - label: '关闭', - plain: true, - }, - ] - const resetSearchSomeValue = () => { - searchValue.value = '' - searchElementIndex.value = 0 + ) + + const openPage = async (option: AppMenuOption) => { + // 从当前菜单重新解析,缓存里的旧路径不能绕过权限或路由来源变化。 + const current = menuByPath.value.get(option.fullPath) + + if (!current) return + + await changeMenuModelValue(current.fullPath, current) + + if (current.meta.windowOpen) recordVisit(current.fullPath) + else { + modelShow.value = false + positionSelectedMenuItem() + } } + const moveResult = (event: KeyboardEvent, fromInput = false) => { + if (event.isComposing || !options.value.length) return - // 断点 observer 会同步执行,先初始化其调用的重置函数。 - const { isTabletOrSmaller } = useDevice({ - observer: (val) => { - // 当处于小尺寸状态时,自动关闭搜索框 - if (val) { - modelShow.value = false - } - }, - }) + if (fromInput && event.key === 'Enter') { + event.preventDefault() + void openPage(options.value[activeIndex.value]!) - // 按下 ctrl + k 或者 command + k 激活搜索栏 - const registerArouseKeyboard = (e: KeyboardEvent) => { - if (modelShow.value) { return } - if ((e.ctrlKey || e.metaKey) && e.key === 'k') { - e.preventDefault() - e.stopPropagation() - resetSearchSomeValue() - - modelShow.value = true - } - } - - const searchItemClick = async (option: AppMenuOption) => { - if (!option.meta.windowOpen) modelShow.value = false - - await changeMenuModelValue(option.fullPath, option) - - if (!option.meta.windowOpen) positionSelectedMenuItem() - } - - // 渲染搜索菜单前缀图标,如果没有则用 icon table 代替 - const RenderPreIcon = (meta: AppRouteMeta) => { - const { icon } = meta - - if (typeof icon === 'string' && icon) { - return - } else if (typeof icon === 'function') { - return - } else { - return - } - } - - const registerChangeSearchElementIndex = (event: KeyboardEvent) => { - const { key } = event - - if (!['ArrowUp', 'ArrowDown', 'Enter'].includes(key)) return + if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return event.preventDefault() - event.stopPropagation() + const count = options.value.length - const options = searchOptions.value + activeIndex.value = fromInput + ? event.key === 'ArrowDown' + ? 0 + : count - 1 + : (activeIndex.value + (event.key === 'ArrowDown' ? 1 : -1) + count) % + count + const button = rowButtons.get(options.value[activeIndex.value]!.fullPath) - if (!options.length) return + button?.focus({ preventScroll: true }) + button?.scrollIntoView?.({ block: 'nearest' }) + } + const toggle = (path: string) => { + toggleFavorite(path) - if (key === 'Enter') { - const selected = options[searchElementIndex.value] - - if (selected) void searchItemClick(selected) + if (!searchValue.value.trim()) void nextTick(() => input.value?.focus()) + } + useEventListener(window, 'keydown', (event: KeyboardEvent) => { + if (event.isComposing || isTabletOrSmaller.value || modelShow.value) return + + if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') { + event.preventDefault() + resetSearch() + modelShow.value = true } + }) - const offset = key === 'ArrowUp' ? -1 : 1 - - searchElementIndex.value = - (searchElementIndex.value + offset + options.length) % options.length - } - - const SearchItem = ({ - menuOption, - active, - }: { - menuOption: AppMenuOption - active: boolean - }) => ( - searchItemClick(menuOption) }} - > -
{RenderPreIcon(menuOption.meta)}
-
{menuOption.breadcrumbLabel}
- -
- ) - - useEventListener(window, 'keydown', registerArouseKeyboard) - - return { - searchValue, - searchOptions, - searchElementIndex, - modelShow, - helperTipOptions, - isTabletOrSmaller, - SearchItem, - registerChangeSearchElementIndex, - } - }, - render() { - const { - isTabletOrSmaller, - searchOptions, - searchElementIndex, - SearchItem, - registerChangeSearchElementIndex, - } = this - - return isTabletOrSmaller ? ( -
- ) : ( - - - - ) + + ), + action: () => ( +
+ + ↑ ↓ {t('move')} + + + ↵ {t('open')} + + + Esc {t('close')} + + {recentPaths.value.length > 0 && ( + + {t('clearRecent')} + + )} +
+ ), + }} + + + ) }, }) diff --git a/apps/admin/src/locales/lang/en-US/demoDetails.json b/apps/admin/src/locales/lang/en-US/demoDetails.json index 852ffd72..9abbba4a 100644 --- a/apps/admin/src/locales/lang/en-US/demoDetails.json +++ b/apps/admin/src/locales/lang/en-US/demoDetails.json @@ -211,7 +211,8 @@ "hidePattern": "Hide decals", "series": "Data state", "revision": "Data revision {value}", - "unmounted": "Chart disposed" + "unmounted": "Chart disposed", + "loadFailed": "Could not load chart data. Please retry." }, "about": { "title": "About Ray Template", diff --git a/apps/admin/src/locales/lang/en-US/menu.json b/apps/admin/src/locales/lang/en-US/menu.json index dbf39725..abc265fd 100644 --- a/apps/admin/src/locales/lang/en-US/menu.json +++ b/apps/admin/src/locales/lang/en-US/menu.json @@ -57,5 +57,7 @@ "TableHooksOutput": "Export and print", "RouteManagement": "Route management", "RouteManagementVisual": "Visual editor", - "RouteManagementJson": "JSON configuration" + "RouteManagementJson": "JSON configuration", + "SystemManagement": "System management", + "UserManagement": "Users" } diff --git a/apps/admin/src/locales/lang/en-US/navigationSearch.json b/apps/admin/src/locales/lang/en-US/navigationSearch.json new file mode 100644 index 00000000..093c7d22 --- /dev/null +++ b/apps/admin/src/locales/lang/en-US/navigationSearch.json @@ -0,0 +1,16 @@ +{ + "title": "Search pages", + "placeholder": "Enter a page name", + "favorites": "Favorites", + "recent": "Recently visited", + "results": "Search results", + "clearRecent": "Clear history", + "addFavorite": "Favorite {title}", + "removeFavorite": "Unfavorite {title}", + "noResults": "No matching pages", + "empty": "Search for a page and use the star to save a favorite.", + "storageUnavailable": "Your browser cannot save history right now. It remains available for this visit.", + "move": "Move", + "open": "Open", + "close": "Close" +} diff --git a/apps/admin/src/locales/lang/en-US/routeManagement.json b/apps/admin/src/locales/lang/en-US/routeManagement.json index d33727cf..63107875 100644 --- a/apps/admin/src/locales/lang/en-US/routeManagement.json +++ b/apps/admin/src/locales/lang/en-US/routeManagement.json @@ -3,17 +3,17 @@ "title": "Route JSON configuration", "description": "Switch route sources, preview the menu and validate page configuration as JSON.", "active": "Active · {source}", - "fallback": "Load failed. Static routes are active.", + "fallback": "API loading failed; using initial routes", "source": "Route source", - "static": "Static", + "static": "Initial configuration", "local": "Local JSON", - "remote": "Backend", - "staticHint": "Use the TypeScript routes bundled with the app. Applying changes reloads the page.", + "remote": "Server API", + "staticHint": "Use initial JSON routes for offline recovery. Select the server API for the online experience.", "localHint": "Validate and save the JSON in this browser. Applying changes reloads the page.", - "remoteHint": "Fetch JSON from the deployed endpoint at startup. If loading or validation fails, use static routes.", - "apply": "Apply and reload", + "remoteHint": "Routes are fetched through the API at startup. Saving submits the current JSON and reloads. If loading fails, the initial configuration is used with an error notice.", + "apply": "Save and apply", "manifest": "Route configuration", - "loadStatic": "Load static routes", + "loadStatic": "Load initial configuration", "loadRemote": "Fetch backend routes", "import": "Import JSON", "export": "Export JSON", @@ -37,8 +37,8 @@ "addPage": "Add to configuration", "visualTitle": "Visual route editor", "visualDescription": "Select a menu item to edit its path, view and access rules.", - "visualDraft": "Local configuration draft", - "visualHint": "The draft starts with the active routes. Applying reloads the app and affects this browser only. Use JSON configuration for advanced fields such as aliases and view props.", + "visualDraft": "Route configuration draft", + "visualHint": "The draft starts from active routes. Saving submits it through the API and reloads the app. The online demo persists it in this browser’s Mock database.", "validateDraft": "Validate", "draftValid": "Configuration is valid", "resetDraft": "Reload active configuration", diff --git a/apps/admin/src/locales/lang/en-US/userManagement.json b/apps/admin/src/locales/lang/en-US/userManagement.json new file mode 100644 index 00000000..a6263420 --- /dev/null +++ b/apps/admin/src/locales/lang/en-US/userManagement.json @@ -0,0 +1,85 @@ +{ + "title": "User management", + "descriptionMock": "Manage members by organization. The online demo uses Mock APIs, with data saved in this browser.", + "descriptionServer": "Manage member profiles, roles and account status by organization.", + "organization": "Organization", + "createUser": "Add user", + "editUser": "Edit user", + "details": "User details", + "username": "Username", + "name": "Name", + "email": "Email", + "phone": "Phone", + "department": "Department", + "role": "Role", + "status": "Status", + "createdAt": "Created at", + "remark": "Notes", + "actions": "Actions", + "enabled": "Enabled", + "disabled": "Disabled", + "enable": "Enable", + "disable": "Disable", + "view": "Details", + "edit": "Edit", + "delete": "Delete", + "save": "Save user", + "cancel": "Cancel", + "optional": "Optional", + "required": "Complete this field", + "usernameHint": "2–32 characters, without spaces", + "nameHint": "Enter a name", + "emailInvalid": "Enter a valid email address", + "selected": "{count} selected", + "clearSelection": "Clear selection", + "batchEnable": "Enable selected", + "batchDisable": "Disable selected", + "batchDelete": "Delete selected", + "confirmDelete": "Delete users?", + "deleteOne": "Delete {name}? This removes the user record.", + "deleteMany": "Delete the {count} selected users? This removes their records.", + "confirmEnable": "Enable users?", + "confirmDisable": "Disable users?", + "changeMany": "This updates the {count} selected users.", + "updated": "Users updated", + "saved": "User saved", + "reset": "Restore demo data", + "resetConfirm": "Restore initial demo users? This replaces users added, edited or deleted in this browser.", + "unsaved": "You have unsaved changes. Discard them?", + "discard": "Discard changes", + "optionsFailed": "Could not load organizations and roles", + "retry": "Retry", + "viewNamed": "View details for {name}", + "editNamed": "Edit {name}", + "deleteNamed": "Delete {name}", + "enableNamed": "Enable {name}", + "disableNamed": "Disable {name}", + "departments": { + "company": "Ray Studio", + "product": "Product design", + "engineering": "Engineering", + "platform": "Platform", + "experience": "Experience", + "operations": "Customer operations" + }, + "roles": { + "admin": "Administrator", + "manager": "Manager", + "member": "Member" + }, + "errors": { + "invalid": "Check the input, department and role.", + "duplicateUsername": "This username is already in use.", + "duplicateEmail": "This email is already in use.", + "notFound": "This user no longer exists. Refresh the list.", + "storage": "The browser could not save demo data. Changes were not submitted. Keep the form open and retry.", + "selfProtected": "You cannot delete or disable your account, or change your own role.", + "unauthorized": "Your session has expired. Sign in again.", + "invalidCredentials": "Incorrect username or password.", + "forbidden": "Your account does not have permission for this action.", + "invalidRoutes": "The route configuration failed validation.", + "requestFailed": "The request failed. Please retry." + }, + "allUsers": "All users", + "apiContract": "API contract" +} diff --git a/apps/admin/src/locales/lang/en-US/views/login/index.json b/apps/admin/src/locales/lang/en-US/views/login/index.json index ed968060..1d082ee7 100644 --- a/apps/admin/src/locales/lang/en-US/views/login/index.json +++ b/apps/admin/src/locales/lang/en-US/views/login/index.json @@ -21,5 +21,7 @@ "RegisterHint": "This registration example is ready to connect to your account service.", "Provider": "Sign in with {provider}", "ProviderHint": "The {provider} sign-in option is a demo.", - "QRHint": "Scan to open the Ray Template source code." + "QRHint": "Scan to open the Ray Template source code.", + "UseManager": "Manager account", + "UseMember": "Read-only account" } diff --git a/apps/admin/src/locales/lang/zh-CN/demoDetails.json b/apps/admin/src/locales/lang/zh-CN/demoDetails.json index 68a0f64f..f8fa9475 100644 --- a/apps/admin/src/locales/lang/zh-CN/demoDetails.json +++ b/apps/admin/src/locales/lang/zh-CN/demoDetails.json @@ -211,7 +211,8 @@ "hidePattern": "隐藏贴花", "series": "数据状态", "revision": "数据版本 {value}", - "unmounted": "已卸载" + "unmounted": "已卸载", + "loadFailed": "图表数据加载失败,请重试。" }, "about": { "title": "关于 Ray Template", diff --git a/apps/admin/src/locales/lang/zh-CN/menu.json b/apps/admin/src/locales/lang/zh-CN/menu.json index ad8d2766..00870dcc 100644 --- a/apps/admin/src/locales/lang/zh-CN/menu.json +++ b/apps/admin/src/locales/lang/zh-CN/menu.json @@ -57,5 +57,7 @@ "TableHooksOutput": "导出与打印", "RouteManagement": "路由管理", "RouteManagementVisual": "可视化配置", - "RouteManagementJson": "JSON 配置" + "RouteManagementJson": "JSON 配置", + "SystemManagement": "系统管理", + "UserManagement": "用户管理" } diff --git a/apps/admin/src/locales/lang/zh-CN/navigationSearch.json b/apps/admin/src/locales/lang/zh-CN/navigationSearch.json new file mode 100644 index 00000000..30c3eccc --- /dev/null +++ b/apps/admin/src/locales/lang/zh-CN/navigationSearch.json @@ -0,0 +1,16 @@ +{ + "title": "搜索页面", + "placeholder": "输入页面名称", + "favorites": "收藏", + "recent": "最近访问", + "results": "搜索结果", + "clearRecent": "清空记录", + "addFavorite": "收藏 {title}", + "removeFavorite": "取消收藏 {title}", + "noResults": "没有找到匹配的页面", + "empty": "搜索页面,并点击星标收藏常用入口。", + "storageUnavailable": "浏览器暂时无法保存记录,本次访问中仍可使用。", + "move": "切换", + "open": "打开", + "close": "关闭" +} diff --git a/apps/admin/src/locales/lang/zh-CN/routeManagement.json b/apps/admin/src/locales/lang/zh-CN/routeManagement.json index 3f784eb8..a78335a2 100644 --- a/apps/admin/src/locales/lang/zh-CN/routeManagement.json +++ b/apps/admin/src/locales/lang/zh-CN/routeManagement.json @@ -3,17 +3,17 @@ "title": "路由 JSON 配置", "description": "切换路由来源,预览并校验菜单和页面的 JSON 配置。", "active": "当前生效 · {source}", - "fallback": "加载失败,已使用静态路由", + "fallback": "接口加载失败,已使用内置初始配置", "source": "路由来源", - "static": "静态路由", + "static": "内置初始配置", "local": "本机 JSON", - "remote": "后端接口", - "staticHint": "使用随应用发布的 TypeScript 路由。应用设置时会重新加载页面。", + "remote": "服务端接口", + "staticHint": "使用内置 JSON 初始配置,适合离线恢复。正常在线体验请选择服务端接口。", "localHint": "校验并保存编辑器中的 JSON,仅在此浏览器生效。应用设置时会重新加载页面。", - "remoteHint": "每次启动从部署指定的接口读取 JSON。请求或校验失败时自动恢复到静态路由。", - "apply": "应用并重新加载", + "remoteHint": "启动时通过接口读取路由;保存会提交当前 JSON 并重新加载。请求失败时使用内置初始配置并显示原因。", + "apply": "保存并应用", "manifest": "路由配置", - "loadStatic": "载入静态配置", + "loadStatic": "载入初始配置", "loadRemote": "读取后端配置", "import": "导入 JSON", "export": "导出 JSON", @@ -37,8 +37,8 @@ "addPage": "添加到配置", "visualTitle": "路由可视化配置", "visualDescription": "从菜单树选择一项,直接编辑它的路径、页面与访问规则。", - "visualDraft": "本机配置草稿", - "visualHint": "草稿从当前生效的路由开始。应用后会重新加载,仅在此浏览器生效;别名、组件参数等高级字段可在 JSON 配置中编辑。", + "visualDraft": "路由配置草稿", + "visualHint": "草稿从当前生效配置开始。保存时通过接口提交并重新加载;在线演示会持久化到当前浏览器的 Mock 数据库。", "validateDraft": "校验配置", "draftValid": "校验通过", "resetDraft": "重载生效配置", diff --git a/apps/admin/src/locales/lang/zh-CN/userManagement.json b/apps/admin/src/locales/lang/zh-CN/userManagement.json new file mode 100644 index 00000000..301f6516 --- /dev/null +++ b/apps/admin/src/locales/lang/zh-CN/userManagement.json @@ -0,0 +1,85 @@ +{ + "title": "用户管理", + "descriptionMock": "按组织管理成员资料与状态。在线演示通过 Mock 接口读写,数据保存在当前浏览器。", + "descriptionServer": "按组织管理成员资料、角色与账号状态。", + "organization": "组织架构", + "createUser": "新增用户", + "editUser": "编辑用户", + "details": "用户详情", + "username": "账号", + "name": "姓名", + "email": "邮箱", + "phone": "联系电话", + "department": "所属组织", + "role": "角色", + "status": "状态", + "createdAt": "创建时间", + "remark": "备注", + "actions": "操作", + "enabled": "已启用", + "disabled": "已停用", + "enable": "启用", + "disable": "停用", + "view": "详情", + "edit": "编辑", + "delete": "删除", + "save": "保存用户", + "cancel": "取消", + "optional": "选填", + "required": "请填写此项", + "usernameHint": "2–32 个字符,不含空格", + "nameHint": "输入姓名", + "emailInvalid": "请输入有效的邮箱地址", + "selected": "已选 {count} 项", + "clearSelection": "取消选择", + "batchEnable": "批量启用", + "batchDisable": "批量停用", + "batchDelete": "批量删除", + "confirmDelete": "确认删除用户", + "deleteOne": "删除用户「{name}」?该操作会移除这条用户记录。", + "deleteMany": "删除已选择的 {count} 位用户?该操作会移除这些用户记录。", + "confirmEnable": "确认启用用户", + "confirmDisable": "确认停用用户", + "changeMany": "将更新已选择的 {count} 位用户。", + "updated": "用户数据已更新", + "saved": "用户已保存", + "reset": "恢复演示数据", + "resetConfirm": "恢复初始演示用户?本浏览器中新增、编辑和删除的用户数据将被替换。", + "unsaved": "还有未保存的修改,确认放弃吗?", + "discard": "放弃修改", + "optionsFailed": "组织和角色加载失败", + "retry": "重试", + "viewNamed": "查看 {name} 的详情", + "editNamed": "编辑 {name}", + "deleteNamed": "删除 {name}", + "enableNamed": "启用 {name}", + "disableNamed": "停用 {name}", + "departments": { + "company": "Ray 工作室", + "product": "产品设计", + "engineering": "研发中心", + "platform": "平台开发", + "experience": "体验开发", + "operations": "客户运营" + }, + "roles": { + "admin": "管理员", + "manager": "管理者", + "member": "普通成员" + }, + "errors": { + "invalid": "请检查输入内容、组织和角色。", + "duplicateUsername": "该账号已存在,请使用其他账号。", + "duplicateEmail": "该邮箱已被使用,请检查后重试。", + "notFound": "用户已不存在,请刷新列表。", + "storage": "浏览器无法保存演示数据,本次修改未提交。请保留表单并重试。", + "selfProtected": "不能删除、停用当前账号或修改自己的角色。", + "unauthorized": "登录已失效,请重新登录。", + "invalidCredentials": "账号或密码错误。", + "forbidden": "当前账号没有执行此操作的权限。", + "invalidRoutes": "路由配置未通过校验。", + "requestFailed": "请求失败,请稍后重试。" + }, + "allUsers": "全部用户", + "apiContract": "API 接入契约" +} diff --git a/apps/admin/src/locales/lang/zh-CN/views/login/index.json b/apps/admin/src/locales/lang/zh-CN/views/login/index.json index 87f52969..675f13d3 100644 --- a/apps/admin/src/locales/lang/zh-CN/views/login/index.json +++ b/apps/admin/src/locales/lang/zh-CN/views/login/index.json @@ -21,5 +21,7 @@ "RegisterHint": "此页面是注册流程的接入示例,可连接项目的账号服务。", "Provider": "通过 {provider} 登录", "ProviderHint": "{provider} 登录是演示入口。", - "QRHint": "扫码访问 Ray Template 源码。" + "QRHint": "扫码访问 Ray Template 源码。", + "UseManager": "管理者账号", + "UseMember": "只读账号" } diff --git a/apps/admin/src/main.ts b/apps/admin/src/main.ts index e88b6b3a..45f03bcf 100644 --- a/apps/admin/src/main.ts +++ b/apps/admin/src/main.ts @@ -2,6 +2,7 @@ import App from './App' import './styles/entry' import type { App as AppType } from 'vue' import { setupRayTemplateCore } from './__ray-template' +import { apiMockEnabled } from './api/admin/client' import { installAutocompleteDefaults } from './app-components/provider/AppAutocompleteDefaults' import { GLOBAL_CLASS_NAMES } from './app-config' import { setupDayjs } from './dayjs' @@ -9,6 +10,7 @@ import { setupDirectives } from './directives' import { setupI18n } from './locales' import { setupRouter } from './router' import { setupStore } from './store' +import { piniaSigningStore } from './store/modules/signing' const bootSplash = () => document.getElementById(GLOBAL_CLASS_NAMES.preLoadingAnimation) @@ -28,8 +30,15 @@ const showBootError = (error: unknown) => { * 注册时应该注意每个插件的加载顺序。 */ const setupPlugins = async (inst: AppType) => { + if (apiMockEnabled) { + const { enableApiMock } = await import('./mocks/browser') + + await enableApiMock() + } + setupStore(inst) await setupI18n(inst) + await inst.runWithContext(() => piniaSigningStore().restoreSession()) await setupRouter(inst) setupDayjs() setupDirectives(inst) diff --git a/apps/admin/src/mocks/browser.ts b/apps/admin/src/mocks/browser.ts new file mode 100644 index 00000000..3323c1a5 --- /dev/null +++ b/apps/admin/src/mocks/browser.ts @@ -0,0 +1,61 @@ +import { apiMockEnabled, apiUrl } from '@/api/admin/client' +import { installMockRequestGuard } from '@/axios/instance' +import { getStorageInstance } from '@/utils/cache-backend' +import { setupWorker } from 'msw/browser' +import { createMockConnection } from './connection' +import { createAdminDatabase } from './database' +import { createAdminHandlers } from './handlers' + +let ready: Promise | undefined + +export function enableApiMock() { + if (!apiMockEnabled) return Promise.resolve() + + ready ??= (async () => { + const base = apiUrl('') + const handlers = createAdminHandlers( + createAdminDatabase(getStorageInstance('localStorage')), + base, + ) + let worker = setupWorker(...handlers) + const start = () => + worker.start({ + serviceWorker: { + url: `${import.meta.env.BASE_URL}mockServiceWorker.js`, + options: { scope: import.meta.env.BASE_URL }, + }, + quiet: true, + onUnhandledRequest: (request, print) => { + if (request.url.startsWith(base)) print.error() + }, + }) + + await start() + + const ensureReady = createMockConnection( + async () => { + const response = await fetch(apiUrl('admin/mock-health'), { + cache: 'no-store', + credentials: 'omit', + redirect: 'error', + signal: AbortSignal.timeout(5000), + }) + + return response.ok && response.headers.get('x-ray-mock') === 'active' + }, + async () => { + await worker.stop() + worker = setupWorker(...handlers) + await start() + }, + ) + + // Chromium 可能回收后台 worker;先探测并恢复,再发送业务请求,避免写请求意外穿透。 + installMockRequestGuard(async (url) => { + if (new URL(url, document.baseURI).href.startsWith(base)) + await ensureReady() + }) + })() + + return ready +} diff --git a/apps/admin/src/mocks/connection.ts b/apps/admin/src/mocks/connection.ts new file mode 100644 index 00000000..94928e1a --- /dev/null +++ b/apps/admin/src/mocks/connection.ts @@ -0,0 +1,21 @@ +export function createMockConnection( + probe: () => Promise, + restart: () => Promise, +) { + let checking: Promise | undefined + + return () => { + checking ??= (async () => { + if (await probe().catch(() => false)) return + + await restart() + + if (!(await probe().catch(() => false))) + throw new Error('Mock connection could not be restored.') + })().finally(() => { + checking = void 0 + }) + + return checking + } +} diff --git a/apps/admin/src/mocks/data/charts.json b/apps/admin/src/mocks/data/charts.json new file mode 100644 index 00000000..1fee5cf3 --- /dev/null +++ b/apps/admin/src/mocks/data/charts.json @@ -0,0 +1,45 @@ +{ + "days": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], + "orders": [120, 200, 150, 80, 70, 110, 130], + "visits": [12, 220, 250, 180, 20, 10, 190], + "sources": [ + { + "key": "search", + "value": 1048 + }, + { + "key": "direct", + "value": 735 + }, + { + "key": "email", + "value": 580 + }, + { + "key": "ads", + "value": 484 + } + ], + "lines": [ + { + "name": "Email", + "values": [120, 132, 101, 134, 90, 230, 210] + }, + { + "name": "Union Ads", + "values": [220, 182, 191, 234, 290, 330, 310] + }, + { + "name": "Video Ads", + "values": [150, 232, 201, 154, 190, 330, 410] + }, + { + "name": "Direct", + "values": [320, 332, 301, 334, 390, 330, 320] + }, + { + "name": "Search Engine", + "values": [820, 932, 901, 934, 1290, 1330, 1320] + } + ] +} diff --git a/apps/admin/src/mocks/data/orders.ts b/apps/admin/src/mocks/data/orders.ts new file mode 100644 index 00000000..8807610e --- /dev/null +++ b/apps/admin/src/mocks/data/orders.ts @@ -0,0 +1,104 @@ +import type { TableProParams } from '@ray-template/ui/table-pro' + +export const statuses = ['pending', 'paid', 'closed'] as const +export const organizations = ['north', 'south'] as const +export const products = ['notes', 'keyboard', 'notebook', 'monitor'] as const +export const warehouses = [ + 'north-main', + 'north-backup', + 'south-main', + 'south-backup', +] as const +export const owners = [ + { id: 'n1', orgId: 'north' }, + { id: 'n2', orgId: 'north' }, + { id: 's1', orgId: 'south' }, + { id: 's2', orgId: 'south' }, +] as const + +export const orders = Array.from({ length: 96 }, (_, index) => { + const ownerIndex = index % owners.length + const { orgId, id: ownerId } = owners[ownerIndex] + const productIndex = Math.floor(index / 3) % products.length + const statusIndex = index % statuses.length + const warehouseIndex = Math.floor(index / 8) % warehouses.length + const day = 1 + (index % 12) + const hour = index % 3 === 0 ? 9 : 14 + + return { + id: index + 1, + orderNo: `ORD-${String(index + 1).padStart(3, '0')}`, + productIndex, + productId: products[productIndex], + statusIndex, + status: statuses[statusIndex], + createdAt: `2026-11-${String(day).padStart(2, '0')}`, + orgId, + ownerId, + ownerIndex, + warehouseIndex, + warehouseId: warehouses[warehouseIndex], + amount: [0, 59, 129, 199, 349, 699, 1299, 2499][index % 8], + invoiced: Math.floor(index / 4) % 2 === 0, + delivery: index % 3 === 0 ? 'express' : 'standard', + deliveryAt: new Date(2026, 10, day + 1, hour).getTime(), + deliveryTime: hour === 9 ? '09:00:00' : '14:00:00', + } +}) + +export function orderMatchesQuery( + row: (typeof orders)[number] & { product: string }, + query: TableProParams, +) { + const { + keyword, + status, + createdFrom, + createdTo, + orgId, + ownerId, + productId, + warehouseId, + minAmount, + invoiced, + delivery, + deliveryFrom, + deliveryTo, + deliveryTime, + } = query + + return ( + `${row.orderNo} ${row.product}` + .toLowerCase() + .includes(String(keyword ?? '').toLowerCase()) && + (!Array.isArray(status) || status.includes(row.status)) && + (typeof createdFrom !== 'string' || row.createdAt >= createdFrom) && + (typeof createdTo !== 'string' || row.createdAt <= createdTo) && + (orgId == null || row.orgId === orgId) && + (ownerId == null || row.ownerId === ownerId) && + (productId == null || row.productId === productId) && + (warehouseId == null || row.warehouseId === warehouseId) && + (typeof minAmount !== 'number' || row.amount >= minAmount) && + (invoiced == null || row.invoiced === invoiced) && + (delivery == null || row.delivery === delivery) && + (typeof deliveryFrom !== 'number' || row.deliveryAt >= deliveryFrom) && + (typeof deliveryTo !== 'number' || row.deliveryAt <= deliveryTo) && + (deliveryTime == null || row.deliveryTime === deliveryTime) + ) +} + +export function waitForDemo(delay: number, signal: AbortSignal) { + return new Promise((resolve, reject) => { + signal.throwIfAborted() + const abort = () => { + clearTimeout(timer) + reject(signal.reason) + } + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort) + resolve() + }, delay) + + signal.addEventListener('abort', abort, { once: true }) + }) +} diff --git a/apps/admin/public/examples/request.json b/apps/admin/src/mocks/data/request.json similarity index 65% rename from apps/admin/public/examples/request.json rename to apps/admin/src/mocks/data/request.json index f8458dea..7ff10a34 100644 --- a/apps/admin/public/examples/request.json +++ b/apps/admin/src/mocks/data/request.json @@ -1,5 +1,9 @@ { - "ticket": { "id": "RAY-024", "title": "Review the workspace", "status": "ready" }, + "ticket": { + "id": "RAY-024", + "title": "Review the workspace", + "status": "ready" + }, "cities": { "Hangzhou": { "temperature": 19, "humidity": 66 }, "Shanghai": { "temperature": 17, "humidity": 73 }, diff --git a/apps/admin/src/mocks/data/routes.json b/apps/admin/src/mocks/data/routes.json new file mode 100644 index 00000000..c6ef0ff0 --- /dev/null +++ b/apps/admin/src/mocks/data/routes.json @@ -0,0 +1,488 @@ +{ + "version": 1, + "routes": [ + { + "path": "/dashboard", + "component": "dashboard", + "meta": { + "i18nKey": "menu.Dashboard", + "icon": "navigation/dashboard", + "order": 0 + } + }, + { + "path": "/system", + "meta": { + "i18nKey": "menu.SystemManagement", + "icon": "navigation/database", + "order": 10 + }, + "children": [ + { + "path": "users", + "name": "UserManagement", + "component": "system/users", + "meta": { + "i18nKey": "menu.UserManagement", + "icon": "navigation/table" + } + } + ] + }, + { + "path": "/tables", + "meta": { + "i18nKey": "menu.Table", + "icon": "navigation/table", + "order": 10, + "extra": { + "label": "TablePro" + } + }, + "children": [ + { + "path": "data", + "meta": { + "i18nKey": "menu.TableData" + }, + "children": [ + { + "path": "/tables/basic", + "name": "TableDemoBasic", + "component": "demo/tables/basic", + "meta": { + "i18nKey": "menu.TableBasic" + } + }, + { + "path": "/tables/remote", + "name": "TableDemoRemote", + "component": "demo/tables/remote", + "meta": { + "i18nKey": "menu.TableRemote" + } + }, + { + "path": "/tables/controlled", + "name": "TableDemoControlled", + "component": "demo/tables/controlled", + "meta": { + "i18nKey": "menu.TableControlled" + } + }, + { + "path": "/tables/search", + "name": "TableDemoSearch", + "component": "demo/tables/search", + "meta": { + "i18nKey": "menu.TableSearch" + } + } + ] + }, + { + "path": "tools", + "meta": { + "i18nKey": "menu.TableTools" + }, + "children": [ + { + "path": "/tables/auto-height", + "name": "TableDemoAutoHeight", + "component": "demo/tables/auto-height", + "meta": { + "i18nKey": "menu.TableAutoHeight" + } + }, + { + "path": "/tables/columns", + "name": "TableDemoColumns", + "component": "demo/tables/columns", + "meta": { + "i18nKey": "menu.TableColumns" + } + }, + { + "path": "/tables/custom", + "name": "TableDemoCustom", + "component": "demo/tables/custom", + "meta": { + "i18nKey": "menu.TableCustom" + } + }, + { + "path": "/tables/printing", + "name": "TableDemoPrinting", + "component": "demo/tables/printing", + "meta": { + "i18nKey": "menu.TablePrinting" + } + } + ] + }, + { + "path": "hooks", + "meta": { + "i18nKey": "menu.TableHooks" + }, + "children": [ + { + "path": "/tables/hooks-query", + "name": "TableDemoHooksQuery", + "component": "demo/tables/hooks-query", + "meta": { + "i18nKey": "menu.TableHooksQuery" + } + }, + { + "path": "/tables/hooks-selection", + "name": "TableDemoHooksSelection", + "component": "demo/tables/hooks-selection", + "meta": { + "i18nKey": "menu.TableHooksSelection" + } + }, + { + "path": "/tables/hooks-output", + "name": "TableDemoHooksOutput", + "component": "demo/tables/hooks-output", + "meta": { + "i18nKey": "menu.TableHooksOutput" + } + } + ] + } + ] + }, + { + "path": "/examples/components", + "meta": { + "i18nKey": "menu.DemoComponents", + "icon": "navigation/components", + "order": 20 + }, + "children": [ + { + "path": "/form", + "component": "demo/form", + "meta": { + "i18nKey": "menu.Form", + "icon": "navigation/form", + "extra": { + "label": "useForm" + } + } + }, + { + "path": "/modal-demo", + "component": "demo/modal-demo", + "meta": { + "i18nKey": "menu.Modal", + "icon": "navigation/window" + } + }, + { + "path": "/segment", + "component": "demo/segment", + "meta": { + "i18nKey": "menu.Segment", + "icon": "navigation/components", + "extra": { + "label": "segment" + } + } + }, + { + "path": "/draggable-card", + "component": "demo/draggable-card", + "meta": { + "i18nKey": "menu.DraggableCard", + "icon": "action/draggable", + "extra": { + "label": "drag" + } + } + }, + { + "path": "/echart", + "component": "demo/echart", + "meta": { + "i18nKey": "menu.Echart", + "icon": "navigation/echart", + "extra": { + "label": "useChart" + } + } + }, + { + "path": "/flow", + "component": "demo/flow-demo", + "meta": { + "i18nKey": "menu.Flow", + "icon": "navigation/flow" + } + }, + { + "path": "/iframe", + "component": "demo/iframe", + "meta": { + "noLocalTitle": "iframe", + "icon": "navigation/window" + } + } + ] + }, + { + "path": "/examples/assets", + "meta": { + "i18nKey": "menu.DemoAssets", + "icon": "navigation/icons", + "order": 30 + }, + "children": [ + { + "path": "/svg-icons", + "component": "demo/svg-icons", + "meta": { + "i18nKey": "menu.SvgIcon", + "icon": "navigation/icons" + } + }, + { + "path": "/qrcode", + "component": "demo/qrcode", + "meta": { + "i18nKey": "menu.QRCode", + "icon": "navigation/qr_code" + } + }, + { + "path": "/barcode", + "component": "demo/barcode-demo", + "meta": { + "i18nKey": "menu.Barcode", + "icon": "navigation/barcode", + "extra": { + "label": "new" + } + } + } + ] + }, + { + "path": "/examples/interaction", + "meta": { + "i18nKey": "menu.DemoInteraction", + "icon": "action/mouse", + "order": 40 + }, + "children": [ + { + "path": "/template-hooks", + "name": "TemplateHooks", + "component": "demo/template-hooks", + "meta": { + "i18nKey": "menu.TemplateHooks", + "icon": "navigation/components" + } + }, + { + "path": "/web-hooks", + "name": "WebHooks", + "component": "demo/hooks/web-hooks", + "meta": { + "i18nKey": "menu.WebHooks", + "icon": "action/mouse" + } + }, + { + "path": "/directive", + "component": "demo/directive", + "meta": { + "i18nKey": "menu.Directive", + "icon": "action/adjustment", + "extra": { + "label": "ellipsis" + } + } + }, + { + "path": "/context-menu", + "component": "demo/context-menu", + "meta": { + "i18nKey": "menu.ContextMenu", + "icon": "action/more" + } + }, + { + "path": "/scroll-reveal", + "component": "demo/scroll-reveal", + "meta": { + "i18nKey": "menu.scrollReveal", + "icon": "directional/expanded", + "hidden": true + } + } + ] + }, + { + "path": "/examples/navigation", + "meta": { + "i18nKey": "menu.DemoNavigation", + "icon": "navigation/layout", + "order": 50 + }, + "children": [ + { + "path": "/layout-demo", + "name": "LayoutDemo", + "component": "demo/layout-demo", + "meta": { + "i18nKey": "menu.LayoutDemo", + "icon": "navigation/layout" + } + }, + { + "path": "/router-demo", + "component": "layout", + "meta": { + "i18nKey": "menu.RouterDemo", + "icon": "navigation/routing" + }, + "children": [ + { + "path": "router-demo-home", + "component": "demo/router-demo/router-demo-home", + "meta": { + "noLocalTitle": "人员信息(平级模式)" + } + }, + { + "path": "router-demo-detail", + "component": "demo/router-demo/router-demo-detail", + "meta": { + "noLocalTitle": "信息详情", + "sameLevel": true + } + } + ] + }, + { + "path": "/multi", + "component": "layout", + "meta": { + "i18nKey": "menu.MultiMenu", + "icon": "navigation/menu", + "extra": { + "label": "cache" + } + }, + "children": [ + { + "path": "multi-menu-one", + "name": "MultiMenuOne", + "component": "demo/multi/views/multi-menu-one", + "meta": { + "noLocalTitle": "多级菜单-1", + "keepAlive": true + } + }, + { + "path": "multi-menu-two", + "name": "MultiMenuTwo", + "component": "layout", + "meta": { + "noLocalTitle": "多级菜单-2" + }, + "children": [ + { + "path": "sub-menu-other", + "name": "SubMenuOther", + "component": "demo/multi/views/multi-menu-two/views/sub-menu-other", + "meta": { + "noLocalTitle": "多级菜单-2-1", + "keepAlive": true + } + }, + { + "path": "sub-menu", + "name": "SubMenu", + "component": "layout", + "meta": { + "noLocalTitle": "多级菜单-2-2", + "keepAlive": true + }, + "children": [ + { + "path": "sub-menu-one", + "name": "MultiMenuTwoOne", + "component": "demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one", + "meta": { + "noLocalTitle": "多级菜单-2-2-1", + "keepAlive": true + } + } + ] + } + ] + } + ] + } + ] + }, + { + "path": "/examples/utilities", + "meta": { + "i18nKey": "menu.DemoUtilities", + "icon": "navigation/database", + "order": 60 + }, + "children": [ + { + "path": "/axios", + "name": "RAxios", + "component": "demo/axios", + "meta": { + "i18nKey": "menu.Axios", + "icon": "logo/axios", + "keepAlive": true + } + }, + { + "path": "/cache-demo", + "component": "demo/cache-demo", + "meta": { + "i18nKey": "menu.CacheDemo", + "icon": "navigation/database" + } + }, + { + "path": "/precision", + "component": "demo/precision", + "meta": { + "i18nKey": "menu.CalculatePrecision", + "icon": "navigation/other" + } + }, + { + "path": "/rely-about", + "component": "demo/rely/views/rely-about", + "meta": { + "i18nKey": "menu.RelyAbout", + "icon": "navigation/rely" + } + } + ] + }, + { + "path": "/doc/doc-inside", + "name": "RTemplateDoc", + "component": "demo/doc", + "meta": { + "i18nKey": "menu.DocLocalInside", + "icon": "navigation/document", + "order": 70 + } + } + ] +} diff --git a/apps/admin/src/mocks/data/users.ts b/apps/admin/src/mocks/data/users.ts new file mode 100644 index 00000000..600f4a2c --- /dev/null +++ b/apps/admin/src/mocks/data/users.ts @@ -0,0 +1,69 @@ +import type { AdminUser, UserOptions } from '@/api/admin/contracts' + +const departments = [ + { id: 'product', parentId: 'company' }, + { id: 'engineering', parentId: 'company' }, + { id: 'platform', parentId: 'engineering' }, + { id: 'experience', parentId: 'engineering' }, + { id: 'operations', parentId: 'company' }, +] + +export const initialUserOptions: UserOptions = { + departments: [ + { + id: 'company', + parentId: null, + name: 'Ray Studio', + labelKey: 'userManagement.departments.company', + }, + ...departments.map((item) => ({ + ...item, + name: item.id, + labelKey: `userManagement.departments.${item.id}`, + })), + ], + roles: ['admin', 'manager', 'member'].map((value) => ({ + value, + label: value, + labelKey: `userManagement.roles.${value}`, + })), +} + +export const createInitialUsers = (): AdminUser[] => + [ + 'Alex Chen', + 'Jordan Lee', + 'Casey Lin', + 'Morgan Wu', + 'Taylor Wang', + 'Avery Liu', + 'Riley Zhao', + 'Jamie Sun', + 'Robin Xu', + 'Sam Zhou', + 'Drew Huang', + 'Quinn Yang', + 'Skyler He', + 'Cameron Lu', + 'Reese Ma', + 'Parker Guo', + 'Charlie Yu', + 'Dakota Shen', + 'Emery Han', + 'Finley Luo', + 'Hayden Tang', + 'Jules Gao', + 'Kendall Song', + 'Logan Feng', + ].map((name, index) => ({ + id: `demo-user-${index + 1}`, + username: `user${String(index + 1).padStart(3, '0')}`, + name, + email: `user${index + 1}@example.com`, + phone: '', + departmentId: departments[index % departments.length]!.id, + role: index === 0 ? 'admin' : index % 5 === 0 ? 'manager' : 'member', + status: index % 6 === 5 ? 'disabled' : 'enabled', + remark: '', + createdAt: new Date(Date.UTC(2026, 0, index + 1, 9)).toISOString(), + })) diff --git a/apps/admin/src/mocks/database.ts b/apps/admin/src/mocks/database.ts new file mode 100644 index 00000000..bbbfa9fe --- /dev/null +++ b/apps/admin/src/mocks/database.ts @@ -0,0 +1,383 @@ +import { + idsSchema, + loginInputSchema, + loginResultSchema, + permissionCodes, + statusInputSchema, + userInputSchema, + userListQuerySchema, + userSchema, +} from '@/api/admin/contracts' +import type { + AdminUser, + SessionInfo, + UserInput, + UserListParams, +} from '@/api/admin/contracts' +import { parseRouteConfig } from '@/router/config/contract' +import type { RouteConfig } from '@/router/config/schema' +import * as v from 'valibot' +import initialRoutes from './data/routes.json' +import { createInitialUsers, initialUserOptions } from './data/users' + +export class MockApiError extends Error { + constructor( + public readonly status: number, + public readonly key: string, + ) { + super(key) + } +} + +const permissionsFor = (role: string): string[] => + role === 'admin' + ? [...permissionCodes] + : role === 'manager' + ? [ + 'users:read', + 'users:create', + 'users:update', + 'users:status', + 'routes:read', + ] + : ['users:read', 'routes:read'] +const snapshotSchema = v.object({ + version: v.literal(1), + users: v.array(userSchema), + routes: v.unknown(), + sessions: v.array(loginResultSchema), +}) + +export function createAdminDatabase(storage?: Storage) { + const key = 'rayMockAdmin.v1' + let users = createInitialUsers() + let routes = parseRouteConfig(JSON.stringify(initialRoutes)) + let sessions: v.InferOutput[] = [] + + try { + const raw = storage?.getItem(key) + + if (raw) { + const value = v.parse(snapshotSchema, JSON.parse(raw)) + const parsedRoutes = parseRouteConfig(JSON.stringify(value.routes)) + + if (new Set(value.users.map(({ id }) => id)).size !== value.users.length) + throw new Error('Duplicate user id') + + users = value.users + routes = parsedRoutes + sessions = value.sessions.filter( + (session) => Date.parse(session.expiresAt) > Date.now(), + ) + } + } catch { + // 损坏的演示数据库使用初始数据;不会把缓存内容当作可执行路由。 + } + + const commit = (next: { + users?: AdminUser[] + routes?: RouteConfig + sessions?: typeof sessions + }) => { + try { + storage?.setItem( + key, + JSON.stringify({ version: 1, users, routes, sessions, ...next }), + ) + } catch { + throw new MockApiError(503, 'storage') + } + + users = next.users ?? users + routes = next.routes ?? routes + sessions = next.sessions ?? sessions + } + const profile = (user: AdminUser): SessionInfo => ({ + user: { + id: user.id, + username: user.username, + name: user.name, + role: user.role, + }, + permissions: permissionsFor(user.role), + }) + const authorize = ( + token: string | null, + permission?: string, + ): SessionInfo => { + const session = sessions.find( + (item) => + item.accessToken === token && Date.parse(item.expiresAt) > Date.now(), + ) + const user = + session && + users.find( + (item) => item.id === session.user.id && item.status === 'enabled', + ) + + if (!user) throw new MockApiError(401, 'unauthorized') + + const result = profile(user) + + if (permission && !result.permissions.includes(permission)) + throw new MockApiError(403, 'forbidden') + + return result + } + const parseInput = ( + schema: S, + input: unknown, + ): v.InferOutput => { + const parsed = v.safeParse(schema, input) + + if (!parsed.success) throw new MockApiError(400, 'invalid') + + return parsed.output + } + const findUser = (id: string) => { + const user = users.find((item) => item.id === id) + + if (!user) throw new MockApiError(404, 'notFound') + + return user + } + const validateUser = (input: unknown, id?: string): UserInput => { + const value = parseInput(userInputSchema, input) + + if ( + !initialUserOptions.departments.some( + (item) => item.id === value.departmentId, + ) || + !initialUserOptions.roles.some((item) => item.value === value.role) + ) + throw new MockApiError(400, 'invalid') + + if ( + users.some( + (item) => + item.id !== id && + item.username.toLowerCase() === value.username.toLowerCase(), + ) + ) + throw new MockApiError(409, 'duplicateUsername') + + if ( + users.some( + (item) => + item.id !== id && + item.email.toLowerCase() === value.email.toLowerCase(), + ) + ) + throw new MockApiError(409, 'duplicateEmail') + + return value + } + const assertEditable = ( + session: SessionInfo, + user: Pick, + ) => { + if (session.user.role !== 'admin' && user.role === 'admin') + throw new MockApiError(403, 'forbidden') + } + const includesDepartment = (parent: string, id: string): boolean => { + if (parent === id) return true + + const department = initialUserOptions.departments.find( + (item) => item.id === id, + ) + + return department?.parentId + ? includesDepartment(parent, department.parentId) + : false + } + + return { + authorize, + login(input: unknown) { + const { username, password } = parseInput(loginInputSchema, input) + const aliases: Record = { + 'Ray Admin': 'user001', + admin: 'user001', + manager: 'user011', + member: 'user002', + } + const user = users.find( + (item) => + item.username === (aliases[username] ?? username) && + item.status === 'enabled', + ) + + if (!user || password !== '123456') + throw new MockApiError(401, 'invalidCredentials') + + const session = { + ...profile(user), + accessToken: `mock-${crypto.randomUUID()}`, + expiresAt: new Date(Date.now() + 24 * 3600 * 1000).toISOString(), + } + + commit({ + sessions: [ + ...sessions.filter((item) => Date.parse(item.expiresAt) > Date.now()), + session, + ], + }) + + return session + }, + logout(token: string | null) { + commit({ + sessions: sessions.filter((item) => item.accessToken !== token), + }) + + return null + }, + getRoutes() { + return structuredClone(routes) + }, + saveRoutes(input: unknown, token: string | null) { + authorize(token, 'routes:write') + let config: RouteConfig + + try { + config = parseRouteConfig(JSON.stringify(input)) + } catch { + throw new MockApiError(400, 'invalidRoutes') + } + + commit({ routes: config }) + + return structuredClone(config) + }, + getOptions(token: string | null) { + const session = authorize(token, 'users:read') + + return { + ...initialUserOptions, + roles: initialUserOptions.roles.map((role) => ({ + ...role, + disabled: session.user.role !== 'admin' && role.value === 'admin', + })), + } + }, + listUsers(params: UserListParams, token: string | null) { + authorize(token, 'users:read') + params = parseInput(userListQuerySchema, params) + const { page = 1, pageSize = 10 } = params + + if ( + !Number.isSafeInteger(page) || + page < 1 || + !Number.isSafeInteger(pageSize) || + pageSize < 1 || + pageSize > 100 + ) + throw new MockApiError(400, 'invalid') + + const matches = users.filter( + (user) => + (['name', 'username', 'email'] as const).every( + (key) => + !params[key] || + user[key] + .toLowerCase() + .includes(params[key]!.trim().toLowerCase()), + ) && + (!params.departmentId || + includesDepartment(params.departmentId, user.departmentId)) && + (!params.status || user.status === params.status) && + (!params.role || user.role === params.role), + ) + + return { + items: structuredClone( + matches.slice((page - 1) * pageSize, page * pageSize), + ), + total: matches.length, + } + }, + getUser(id: string, token: string | null) { + authorize(token, 'users:read') + + return structuredClone(findUser(id)) + }, + saveUser(input: unknown, token: string | null, id?: string) { + const session = authorize(token, id ? 'users:update' : 'users:create') + const existing = id ? findUser(id) : void 0 + + if (existing) assertEditable(session, existing) + + const value = validateUser(input, id) + + assertEditable(session, value) + + if ( + id === session.user.id && + (value.status !== 'enabled' || value.role !== session.user.role) + ) + throw new MockApiError(409, 'selfProtected') + + const user = { + ...value, + id: existing?.id ?? crypto.randomUUID(), + createdAt: existing?.createdAt ?? new Date().toISOString(), + } + + commit({ + users: existing + ? users.map((item) => (item.id === id ? user : item)) + : [user, ...users], + }) + + return structuredClone(user) + }, + deleteUsers(input: unknown, token: string | null) { + const session = authorize(token, 'users:delete') + const { ids } = parseInput(idsSchema, input) + + for (const id of ids) { + const user = findUser(id) + + assertEditable(session, user) + + if (id === session.user.id) throw new MockApiError(409, 'selfProtected') + } + + const remaining = users.filter((item) => !ids.includes(item.id)) + const affected = users.length - remaining.length + + commit({ users: remaining }) + + return { affected } + }, + changeStatus(input: unknown, token: string | null) { + const session = authorize(token, 'users:status') + const { ids, status } = parseInput(statusInputSchema, input) + + for (const id of ids) { + assertEditable(session, findUser(id)) + + if (id === session.user.id && status === 'disabled') + throw new MockApiError(409, 'selfProtected') + } + + commit({ + users: users.map((user) => + ids.includes(user.id) ? { ...user, status } : user, + ), + }) + + return { affected: new Set(ids).size } + }, + resetUsers(token: string | null) { + authorize(token, 'users:reset') + const next = createInitialUsers() + + commit({ users: next }) + + return { affected: next.length } + }, + } +} + +export type AdminDatabase = ReturnType diff --git a/apps/admin/src/mocks/handlers.ts b/apps/admin/src/mocks/handlers.ts new file mode 100644 index 00000000..a9f24dbe --- /dev/null +++ b/apps/admin/src/mocks/handlers.ts @@ -0,0 +1,213 @@ +import type { UserListParams } from '@/api/admin/contracts' +import { listPeople } from '@/demo-data/people' +import { searchCopy } from '@/views/demo/tables/search-copy' +import { delay, http, HttpResponse } from 'msw' +import * as v from 'valibot' +import charts from './data/charts.json' +import { orderMatchesQuery, orders, owners } from './data/orders' +import requestFixture from './data/request.json' +import { MockApiError } from './database' +import type { AdminDatabase } from './database' + +export function createAdminHandlers(database: AdminDatabase, apiBase: string) { + const url = (path: string) => `${apiBase}${path}` + const token = (request: Request) => + request.headers.get('Authorization')?.replace(/^Bearer /u, '') ?? null + const respond = async (action: () => unknown | Promise) => { + await delay(120) + + try { + return HttpResponse.json({ code: 200, msg: 'OK', data: await action() }) + } catch (error) { + const failure = + error instanceof MockApiError ? error : new MockApiError(400, 'invalid') + + return HttpResponse.json( + { + code: failure.status, + msg: failure.key, + data: null, + error: { key: failure.key }, + }, + { status: failure.status }, + ) + } + } + + return [ + http.get(url('admin/mock-health'), () => + HttpResponse.json( + { code: 200, msg: 'OK', data: { ready: true } }, + { headers: { 'x-ray-mock': 'active' } }, + ), + ), + http.get(url('admin/demo/request'), () => respond(() => requestFixture)), + http.get(url('admin/demo/charts'), ({ request }) => + respond(() => + new URL(request.url).searchParams.get('refresh') === 'true' + ? { + ...charts, + lines: charts.lines.map((line) => ({ + ...line, + values: line.values.map(() => + Math.floor((Math.random() + 1) * 100), + ), + })), + } + : charts, + ), + ), + http.post(url('admin/demo/owners/search'), ({ request }) => + respond(async () => { + const body = v.parse( + v.object({ + orgId: v.string(), + keyword: v.string(), + locale: v.string(), + fail: v.optional(v.boolean()), + }), + await request.json(), + ) + + await delay(body.orgId === 'north' ? 680 : 330) + + if (body.fail) throw new MockApiError(503, 'requestFailed') + + const copy = body.locale === 'zh-CN' ? searchCopy.zh : searchCopy.en + + return owners.flatMap(({ id, orgId }, index) => + orgId === body.orgId && + copy.people[index] + .toLowerCase() + .includes(body.keyword.trim().toLowerCase()) + ? [{ label: copy.people[index], value: id }] + : [], + ) + }), + ), + http.post(url('admin/demo/orders/search'), ({ request }) => + respond(async () => { + const body = v.parse( + v.object({ + query: v.record(v.string(), v.unknown()), + locale: v.string(), + fail: v.optional(v.boolean()), + }), + await request.json(), + ) + + if (body.fail) throw new MockApiError(503, 'requestFailed') + + const copy = body.locale === 'zh-CN' ? searchCopy.zh : searchCopy.en + const matches = orders + .map((row) => ({ + ...row, + product: copy.products[row.productIndex], + statusLabel: copy.statuses[row.statusIndex], + organization: copy.teams[row.orgId === 'north' ? 0 : 1], + owner: copy.people[row.ownerIndex], + })) + .filter((row) => orderMatchesQuery(row, body.query)) + const page = Number(body.query.page ?? 1) + const pageSize = Number(body.query.pageSize ?? 5) + + if ( + !Number.isSafeInteger(page) || + page < 1 || + !Number.isSafeInteger(pageSize) || + pageSize < 1 || + pageSize > 100 + ) + throw new MockApiError(400, 'invalid') + + return { + items: matches.slice((page - 1) * pageSize, page * pageSize), + total: matches.length, + } + }), + ), + http.post(url('admin/auth/login'), ({ request }) => + respond(async () => database.login(await request.json())), + ), + http.get(url('admin/auth/session'), ({ request }) => + respond(() => database.authorize(token(request))), + ), + http.post(url('admin/auth/logout'), ({ request }) => + respond(() => database.logout(token(request))), + ), + http.get(url('admin/route-config'), () => + respond(() => database.getRoutes()), + ), + http.put(url('admin/route-config'), ({ request }) => + respond(async () => + database.saveRoutes(await request.json(), token(request)), + ), + ), + http.get(url('admin/users/options'), ({ request }) => + respond(() => database.getOptions(token(request))), + ), + http.post(url('admin/users/batch-delete'), ({ request }) => + respond(async () => + database.deleteUsers(await request.json(), token(request)), + ), + ), + http.patch(url('admin/users/status'), ({ request }) => + respond(async () => + database.changeStatus(await request.json(), token(request)), + ), + ), + http.post(url('admin/users/reset'), ({ request }) => + respond(() => database.resetUsers(token(request))), + ), + http.get(url('admin/users'), ({ request }) => + respond(() => { + const search = new URL(request.url).searchParams + const params = Object.fromEntries(search) as UserListParams + + params.page = search.has('page') ? Number(search.get('page')) : 1 + params.pageSize = search.has('pageSize') + ? Number(search.get('pageSize')) + : 10 + + return database.listUsers(params, token(request)) + }), + ), + http.post(url('admin/users'), ({ request }) => + respond(async () => + database.saveUser(await request.json(), token(request)), + ), + ), + http.get(url('admin/users/:id'), ({ request, params }) => + respond(() => database.getUser(String(params.id), token(request))), + ), + http.put(url('admin/users/:id'), ({ request, params }) => + respond(async () => + database.saveUser( + await request.json(), + token(request), + String(params.id), + ), + ), + ), + http.get(url('admin/demo/people'), ({ request }) => + respond(() => { + const query = new URL(request.url).searchParams + + const result = listPeople({ + page: Number(query.get('page') ?? 1), + pageSize: Number(query.get('pageSize') ?? 10), + name: query.get('name') ?? void 0, + email: query.get('email') ?? void 0, + sortAge: + query.get('sortAge') === 'ascend' + ? 'ascend' + : query.get('sortAge') === 'descend' + ? 'descend' + : void 0, + }) + + return { items: result.data, total: result.total } + }), + ), + ] +} diff --git a/apps/admin/src/router/README.md b/apps/admin/src/router/README.md index e77ca3f6..ed7093ed 100644 --- a/apps/admin/src/router/README.md +++ b/apps/admin/src/router/README.md @@ -4,7 +4,7 @@ 登录后,打开 **路由管理**。两个子页面均由应用外壳注册,使用相同的 `admin` 角色守卫。 -- **可视化配置**(`/#/route-management/visual`):从当前生效的菜单树编辑页面、分组、重定向与外链,调整顺序、角色、显隐与缓存。可校验或导出草稿,也可应用并重新加载;应用仅在当前浏览器生效。已有别名、页面参数等高级字段会随草稿保留。 +- **可视化配置**(`/#/route-management/visual`):从当前生效的菜单树编辑页面、分组、重定向与外链,调整顺序、角色、显隐与缓存。可校验或导出草稿,也可应用并重新加载;通过标准接口保存并重新加载;Mock 数据库的修改仅在当前浏览器生效。已有别名、页面参数等高级字段会随草稿保留。 - **JSON 配置**(`/#/route-management/json`):管理静态、本机或后端来源,编辑或导入完整 JSON、校验和预览配置树,并导出 JSON、标准 JSON Schema 和可用页面清单。旧地址 `/#/route-management` 会跳转到这里。 | 来源 | 读取行为 | 应用方式 | @@ -17,7 +17,7 @@ ## 后端与 AI 契约 -部署时提供 `VITE_ROUTE_CONFIG_URL=/api/route-config`,或使用启用 CORS 的 HTTPS 地址。客户端请求 `GET`,接受 `application/json`,超时 5 秒。同源请求可用会话 Cookie。接口直接返回下方 JSON,导入、导出和接口响应使用同一结构。 +部署时提供 `VITE_ROUTE_CONFIG_URL=/api/route-config`,或使用启用 CORS 的 HTTPS 地址。客户端请求 `GET`,接受 `application/json`,超时 5 秒。同源请求可用会话 Cookie。标准接口把下方路由 JSON 放在 `{ code: 200, msg: "OK", data }` 的 `data` 中;导入和导出直接使用路由 JSON。旧的 `VITE_ROUTE_CONFIG_URL` 继续接受原始 JSON。完整读写接口见[服务端契约](../../../docs/guide/backend.md)。 ```json { @@ -64,6 +64,5 @@ node --input-type=module -e "import {getRouteJsonSchema} from './src/router/conf ## 扩展静态页面 -新增页面时先在 [页面注册表](config/views.ts) 注册稳定 ID 和组件名,再从 `src/router/modules` 的路由记录用 `routeView(id)` 引用。静态模块默认导出一条记录。分组可以使用 `LAYOUT` 和 `children`,叶子在同一个应用布局中渲染。简体中文和英文菜单文案分别写入两份 `menu.json`。 - +新增页面时先在 [页面注册表](config/views.ts) 注册稳定 ID 和组件名,再在 [Mock 初始 JSON](../mocks/data/routes.json) 或路由接口返回的数据里使用该 `component` ID。`name` 与缓存页面组件名保持一致。前端不再递归读取 TypeScript 菜单模块;初始 JSON 同时作为显式离线恢复来源。正常启动与编辑保存分别请求标准 GET/PUT 接口,简体中文和英文菜单文案仍放在两份 `menu.json`。 系统配置和白名单见 [router-config.ts](../app-config/router-config.ts)。在 Vue setup 之外读取路由器时使用 `useVueRouter()`。变更后运行 `pnpm harness verify routing`,并核对菜单跳转、直达、刷新、切换来源、角色和缓存。 diff --git a/apps/admin/src/router/app-route-modules.ts b/apps/admin/src/router/app-route-modules.ts index fcacdfed..73333cb6 100644 --- a/apps/admin/src/router/app-route-modules.ts +++ b/apps/admin/src/router/app-route-modules.ts @@ -1,6 +1,7 @@ +import initialRoutes from '@/mocks/data/routes.json' +import { parseRouteConfig, toRuntimeRoutes } from './config/contract' import { DEFAULT_HOME_PATH, ROUTE_MANAGEMENT_PATH } from './constant' import type { AppRouteRecordRaw } from './types' -import { combineRawRouteModules } from './utils/combine-raw-route-modules' import { expandRoutes } from './utils/expand-routes' import { orderRoutes } from './utils/order-routes' @@ -28,7 +29,8 @@ const managementRoute: AppRouteRecordRaw = { ], } -export const getStaticAppRoutes = () => orderRoutes(combineRawRouteModules()) +export const getStaticAppRoutes = () => + orderRoutes(toRuntimeRoutes(parseRouteConfig(JSON.stringify(initialRoutes)))) let activeRoutes: AppRouteRecordRaw[] | undefined diff --git a/apps/admin/src/router/config/source.ts b/apps/admin/src/router/config/source.ts index 7ec06639..38186d70 100644 --- a/apps/admin/src/router/config/source.ts +++ b/apps/admin/src/router/config/source.ts @@ -1,3 +1,5 @@ +import { getAdminRoutes, updateAdminRoutes } from '@/api/admin' +import { apiUrl } from '@/api/admin/client' import { APP_CATCH_KEY } from '@/app-config' import type { RouteConfig } from './schema' @@ -10,7 +12,8 @@ interface Preference { const storageKey = 'rayRouteConfig.v1' -export const remoteRouteUrl = import.meta.env.VITE_ROUTE_CONFIG_URL?.trim() +export const remoteRouteUrl = + import.meta.env.VITE_ROUTE_CONFIG_URL?.trim() || apiUrl('admin/route-config') function readPreference(): Preference { try { @@ -45,6 +48,12 @@ export const routeSourceStatus: { } = { requested: preference.source, active: 'static' } export async function fetchRemoteRouteConfig(): Promise { + if (!import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()) { + const { parseRouteConfig } = await import('./contract') + + return parseRouteConfig(JSON.stringify(await getAdminRoutes())) + } + if (!remoteRouteUrl) throw new Error('VITE_ROUTE_CONFIG_URL is missing.') const url = new URL(remoteRouteUrl, document.baseURI) @@ -68,6 +77,16 @@ export async function fetchRemoteRouteConfig(): Promise { return parseRouteConfig(await response.text()) } +export async function saveRemoteRouteConfig(config: RouteConfig) { + if (import.meta.env.VITE_ROUTE_CONFIG_URL?.trim()) + throw new Error( + 'VITE_ROUTE_CONFIG_URL is a read-only legacy endpoint. Configure VITE_API_BASE_URL for route writes.', + ) + + await updateAdminRoutes(config) + saveRouteSource('remote') +} + export async function loadRouteConfig(): Promise { if (preference.source === 'static') return diff --git a/apps/admin/src/router/config/views.ts b/apps/admin/src/router/config/views.ts index 09f6eee7..5504d0a9 100644 --- a/apps/admin/src/router/config/views.ts +++ b/apps/admin/src/router/config/views.ts @@ -1,5 +1,9 @@ const views = { dashboard: { load: () => import('@/views/dashboard'), name: 'RDashboard' }, + 'system/users': { + load: () => import('@/views/user-management'), + name: 'UserManagement', + }, 'demo/axios': { load: () => import('@/views/demo/axios/index'), name: 'RAxios', diff --git a/apps/admin/src/router/modules/dashboard.ts b/apps/admin/src/router/modules/dashboard.ts deleted file mode 100644 index 6f3a5654..00000000 --- a/apps/admin/src/router/modules/dashboard.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import { LAYOUT } from '@/router/constant' -import type { AppRouteRecordRaw } from '@/router/types' - -const dashboard: AppRouteRecordRaw = { - path: '/dashboard', - component: routeView('dashboard'), - meta: { - i18nKey: t('menu.Dashboard'), - icon: 'navigation/dashboard', - order: 0, - }, -} - -export default dashboard diff --git a/apps/admin/src/router/modules/demo/assets.ts b/apps/admin/src/router/modules/demo/assets.ts deleted file mode 100644 index abc1b42c..00000000 --- a/apps/admin/src/router/modules/demo/assets.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import type { AppRouteRecordRaw } from '@/router/types' - -export default { - path: '/examples/assets', - meta: { i18nKey: t('menu.DemoAssets'), icon: 'navigation/icons', order: 30 }, - children: [ - { - path: '/svg-icons', - component: routeView('demo/svg-icons'), - meta: { - i18nKey: t('menu.SvgIcon'), - icon: 'navigation/icons', - }, - }, - { - path: '/qrcode', - component: routeView('demo/qrcode'), - meta: { - i18nKey: t('menu.QRCode'), - icon: 'navigation/qr_code', - }, - }, - { - path: '/barcode', - component: routeView('demo/barcode-demo'), - meta: { - i18nKey: t('menu.Barcode'), - icon: 'navigation/barcode', - extra: { - label: 'new', - }, - }, - }, - ], -} satisfies AppRouteRecordRaw diff --git a/apps/admin/src/router/modules/demo/components.ts b/apps/admin/src/router/modules/demo/components.ts deleted file mode 100644 index fb74c056..00000000 --- a/apps/admin/src/router/modules/demo/components.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import type { AppRouteRecordRaw } from '@/router/types' - -export default { - path: '/examples/components', - meta: { - i18nKey: t('menu.DemoComponents'), - icon: 'navigation/components', - order: 20, - }, - children: [ - { - path: '/form', - component: routeView('demo/form'), - meta: { - i18nKey: t('menu.Form'), - icon: 'navigation/form', - extra: { - label: 'useForm', - }, - }, - }, - { - path: '/modal-demo', - component: routeView('demo/modal-demo'), - meta: { - i18nKey: t('menu.Modal'), - icon: 'navigation/window', - }, - }, - { - path: '/segment', - component: routeView('demo/segment'), - meta: { - i18nKey: t('menu.Segment'), - icon: 'navigation/components', - extra: { - label: 'segment', - }, - }, - }, - { - path: '/draggable-card', - component: routeView('demo/draggable-card'), - meta: { - i18nKey: t('menu.DraggableCard'), - icon: 'action/draggable', - extra: { - label: 'drag', - }, - }, - }, - { - path: '/echart', - component: routeView('demo/echart'), - meta: { - i18nKey: t('menu.Echart'), - icon: 'navigation/echart', - extra: { - label: 'useChart', - }, - }, - }, - { - path: '/flow', - component: routeView('demo/flow-demo'), - meta: { - i18nKey: t('menu.Flow'), - icon: 'navigation/flow', - }, - }, - { - path: '/iframe', - component: routeView('demo/iframe'), - meta: { - icon: 'navigation/window', - noLocalTitle: 'iframe', - }, - }, - ], -} satisfies AppRouteRecordRaw diff --git a/apps/admin/src/router/modules/demo/doc.ts b/apps/admin/src/router/modules/demo/doc.ts deleted file mode 100644 index 172b0bfe..00000000 --- a/apps/admin/src/router/modules/demo/doc.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import type { AppRouteRecordRaw } from '@/router/types' - -export default { - path: '/doc/doc-inside', - name: 'RTemplateDoc', - component: routeView('demo/doc'), - meta: { - i18nKey: t('menu.DocLocalInside'), - icon: 'navigation/document', - order: 70, - }, -} satisfies AppRouteRecordRaw diff --git a/apps/admin/src/router/modules/demo/interaction.ts b/apps/admin/src/router/modules/demo/interaction.ts deleted file mode 100644 index 019b0e52..00000000 --- a/apps/admin/src/router/modules/demo/interaction.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import type { AppRouteRecordRaw } from '@/router/types' - -export default { - path: '/examples/interaction', - meta: { i18nKey: t('menu.DemoInteraction'), icon: 'action/mouse', order: 40 }, - children: [ - { - path: '/template-hooks', - name: 'TemplateHooks', - component: routeView('demo/template-hooks'), - meta: { - i18nKey: t('menu.TemplateHooks'), - icon: 'navigation/components', - }, - }, - { - path: '/web-hooks', - name: 'WebHooks', - component: routeView('demo/hooks/web-hooks'), - meta: { i18nKey: t('menu.WebHooks'), icon: 'action/mouse' }, - }, - { - path: '/directive', - component: routeView('demo/directive'), - meta: { - i18nKey: t('menu.Directive'), - icon: 'action/adjustment', - extra: { - label: 'ellipsis', - }, - }, - }, - { - path: '/context-menu', - component: routeView('demo/context-menu'), - meta: { - i18nKey: t('menu.ContextMenu'), - icon: 'action/more', - }, - }, - { - path: '/scroll-reveal', - component: routeView('demo/scroll-reveal'), - meta: { - i18nKey: t('menu.scrollReveal'), - icon: 'directional/expanded', - hidden: true, - }, - }, - ], -} satisfies AppRouteRecordRaw diff --git a/apps/admin/src/router/modules/demo/navigation.ts b/apps/admin/src/router/modules/demo/navigation.ts deleted file mode 100644 index 16bc5773..00000000 --- a/apps/admin/src/router/modules/demo/navigation.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import { LAYOUT } from '@/router/constant' -import type { AppRouteRecordRaw } from '@/router/types' - -export default { - path: '/examples/navigation', - meta: { - i18nKey: t('menu.DemoNavigation'), - icon: 'navigation/layout', - order: 50, - }, - children: [ - { - path: '/layout-demo', - name: 'LayoutDemo', - component: routeView('demo/layout-demo'), - meta: { i18nKey: t('menu.LayoutDemo'), icon: 'navigation/layout' }, - }, - { - path: '/router-demo', - component: LAYOUT, - meta: { - i18nKey: t('menu.RouterDemo'), - icon: 'navigation/routing', - }, - children: [ - { - path: 'router-demo-home', - component: routeView('demo/router-demo/router-demo-home'), - meta: { - noLocalTitle: '人员信息(平级模式)', - }, - }, - { - path: 'router-demo-detail', - component: routeView('demo/router-demo/router-demo-detail'), - meta: { - noLocalTitle: '信息详情', - sameLevel: true, - }, - }, - ], - }, - { - path: '/multi', - component: LAYOUT, - meta: { - i18nKey: t('menu.MultiMenu'), - icon: 'navigation/menu', - extra: { - label: 'cache', - }, - }, - children: [ - { - path: 'multi-menu-one', - name: 'MultiMenuOne', - component: routeView('demo/multi/views/multi-menu-one'), - meta: { - noLocalTitle: '多级菜单-1', - keepAlive: true, - }, - }, - { - path: 'multi-menu-two', - name: 'MultiMenuTwo', - component: LAYOUT, - meta: { - noLocalTitle: '多级菜单-2', - }, - children: [ - { - path: 'sub-menu-other', - name: 'SubMenuOther', - component: routeView( - 'demo/multi/views/multi-menu-two/views/sub-menu-other', - ), - meta: { - noLocalTitle: '多级菜单-2-1', - keepAlive: true, - }, - }, - { - path: 'sub-menu', - name: 'SubMenu', - component: LAYOUT, - meta: { - noLocalTitle: '多级菜单-2-2', - keepAlive: true, - }, - children: [ - { - path: 'sub-menu-one', - name: 'MultiMenuTwoOne', - component: routeView( - 'demo/multi/views/multi-menu-two/views/sub-menu/views/multi-menu-two-one', - ), - meta: { - noLocalTitle: '多级菜单-2-2-1', - keepAlive: true, - }, - }, - ], - }, - ], - }, - ], - }, - ], -} satisfies AppRouteRecordRaw diff --git a/apps/admin/src/router/modules/demo/tables.ts b/apps/admin/src/router/modules/demo/tables.ts deleted file mode 100644 index 129c70d7..00000000 --- a/apps/admin/src/router/modules/demo/tables.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import type { AppRouteRecordRaw } from '@/router/types' - -const tables: AppRouteRecordRaw = { - path: '/tables', - meta: { - i18nKey: t('menu.Table'), - icon: 'navigation/table', - order: 10, - extra: { label: 'TablePro' }, - }, - children: [ - { - path: 'data', - meta: { i18nKey: t('menu.TableData') }, - children: [ - { - path: '/tables/basic', - name: 'TableDemoBasic', - component: routeView('demo/tables/basic'), - meta: { i18nKey: t('menu.TableBasic') }, - }, - { - path: '/tables/remote', - name: 'TableDemoRemote', - component: routeView('demo/tables/remote'), - meta: { i18nKey: t('menu.TableRemote') }, - }, - { - path: '/tables/controlled', - name: 'TableDemoControlled', - component: routeView('demo/tables/controlled'), - meta: { i18nKey: t('menu.TableControlled') }, - }, - { - path: '/tables/search', - name: 'TableDemoSearch', - component: routeView('demo/tables/search'), - meta: { i18nKey: t('menu.TableSearch') }, - }, - ], - }, - { - path: 'tools', - meta: { i18nKey: t('menu.TableTools') }, - children: [ - { - path: '/tables/auto-height', - name: 'TableDemoAutoHeight', - component: routeView('demo/tables/auto-height'), - meta: { i18nKey: t('menu.TableAutoHeight') }, - }, - { - path: '/tables/columns', - name: 'TableDemoColumns', - component: routeView('demo/tables/columns'), - meta: { i18nKey: t('menu.TableColumns') }, - }, - { - path: '/tables/custom', - name: 'TableDemoCustom', - component: routeView('demo/tables/custom'), - meta: { i18nKey: t('menu.TableCustom') }, - }, - { - path: '/tables/printing', - name: 'TableDemoPrinting', - component: routeView('demo/tables/printing'), - meta: { i18nKey: t('menu.TablePrinting') }, - }, - ], - }, - { - path: 'hooks', - meta: { i18nKey: t('menu.TableHooks') }, - children: [ - { - path: '/tables/hooks-query', - name: 'TableDemoHooksQuery', - component: routeView('demo/tables/hooks-query'), - meta: { i18nKey: t('menu.TableHooksQuery') }, - }, - { - path: '/tables/hooks-selection', - name: 'TableDemoHooksSelection', - component: routeView('demo/tables/hooks-selection'), - meta: { i18nKey: t('menu.TableHooksSelection') }, - }, - { - path: '/tables/hooks-output', - name: 'TableDemoHooksOutput', - component: routeView('demo/tables/hooks-output'), - meta: { i18nKey: t('menu.TableHooksOutput') }, - }, - ], - }, - ], -} - -export default tables diff --git a/apps/admin/src/router/modules/demo/utilities.ts b/apps/admin/src/router/modules/demo/utilities.ts deleted file mode 100644 index 8f04b040..00000000 --- a/apps/admin/src/router/modules/demo/utilities.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { t } from '@/hooks/web/useI18n' -import { routeView } from '@/router/config/views' -import type { AppRouteRecordRaw } from '@/router/types' - -export default { - path: '/examples/utilities', - meta: { - i18nKey: t('menu.DemoUtilities'), - icon: 'navigation/database', - order: 60, - }, - children: [ - { - path: '/axios', - name: 'RAxios', - component: routeView('demo/axios'), - meta: { - i18nKey: t('menu.Axios'), - icon: 'logo/axios', - keepAlive: true, - }, - }, - { - path: '/cache-demo', - component: routeView('demo/cache-demo'), - meta: { - i18nKey: t('menu.CacheDemo'), - icon: 'navigation/database', - }, - }, - { - path: '/precision', - component: routeView('demo/precision'), - meta: { - i18nKey: t('menu.CalculatePrecision'), - icon: 'navigation/other', - }, - }, - { - path: '/rely-about', - component: routeView('demo/rely/views/rely-about'), - meta: { - i18nKey: t('menu.RelyAbout'), - icon: 'navigation/rely', - }, - }, - ], -} satisfies AppRouteRecordRaw diff --git a/apps/admin/src/router/utils/combine-raw-route-modules.ts b/apps/admin/src/router/utils/combine-raw-route-modules.ts deleted file mode 100644 index fe2fc7c7..00000000 --- a/apps/admin/src/router/utils/combine-raw-route-modules.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { AppRouteRecordRaw, RouteModules } from '@/router/types' - -/** - * - * @returns 所有路由模块 - * - * @description - * 自动合并所有路由模块,每一个 ts 文件都视为一个 route module 与 views 一一对应。 - * 会将 modules 中每一个 ts 文件当作一个路由模块,即使你以分包的形式创建了路由模块。 - * - * 请注意,如果更改了 modules 的目录位置或者该方法的位置,需要同步更改 import.meta.glob 方法的路径。 - * 该方法会以本文件为起始位置去查找对应 URL 目录的资源。 - * - * 如果组件的 name 属性出现重复或者冲突,会导致一些意想不到的情况。 - */ -export const combineRawRouteModules = () => { - const modulesFiles: RouteModules = import.meta.glob( - '@/router/modules/**/*.ts', - { - eager: true, - }, - ) - - const modules = Object.keys(modulesFiles).reduce((pre, curr) => { - const module = modulesFiles[curr].default - - if (module) { - pre.push(module) - } else { - throw new Error( - `[combineRawRouteModules]: ${curr} module must export default.`, - ) - } - - return pre - }, [] as AppRouteRecordRaw[]) - - return modules -} diff --git a/apps/admin/src/router/utils/index.ts b/apps/admin/src/router/utils/index.ts index 25dcc80f..e3231eae 100644 --- a/apps/admin/src/router/utils/index.ts +++ b/apps/admin/src/router/utils/index.ts @@ -1,4 +1,3 @@ -export * from './combine-raw-route-modules' export * from './expand-routes' export * from './order-routes' export * from './permission' diff --git a/apps/admin/src/store/README.md b/apps/admin/src/store/README.md index 39906679..7f8f8d04 100644 --- a/apps/admin/src/store/README.md +++ b/apps/admin/src/store/README.md @@ -96,3 +96,7 @@ setRuntimeState('globalSpinning', false) - 菜单树和路径索引在角色变化或显式刷新时构建,不修改模块中的原始路由。路由完成后用 Vue Router 已匹配的记录同步标签页和面包屑。 - 保留原有缓存键和标签列表结构。恢复时按已注册路由和角色重建旧标签,忽略已经删除或不可访问的路由。只有标签列表变化时才写会话缓存。 - KeepAlive 按最近访问顺序更新,去重并按上限裁剪。主题合并仅由生效主题驱动,色弱模式和文档标题独立监听。 + +## 最近访问与收藏 + +`navigation-history` 经 `useNavigationHistoryGetters` / `useNavigationHistoryActions` 暴露。按会话用户 id 隔离 Local Storage,只保存最多 10 个去重的最近菜单路径与收藏路径,不保存搜索词、标题、URL 查询参数或页面数据。显示和导航时从当前可见菜单重新解析,已撤权、隐藏或删除的路径不显示。切换账号即时清空内存视图并读取对应缓存;清空历史不删除收藏。 diff --git a/apps/admin/src/store/hooks/useNavigationHistoryStore.ts b/apps/admin/src/store/hooks/useNavigationHistoryStore.ts new file mode 100644 index 00000000..50ae2090 --- /dev/null +++ b/apps/admin/src/store/hooks/useNavigationHistoryStore.ts @@ -0,0 +1,18 @@ +import { piniaNavigationHistoryStore } from '../modules/navigation-history' + +export const useNavigationHistoryGetters = () => { + const store = piniaNavigationHistoryStore() + + return { + recentPaths: computed(() => store.recentPaths), + favoritePaths: computed(() => store.favoritePaths), + storageUnavailable: computed(() => store.storageUnavailable), + } +} + +export const useNavigationHistoryActions = () => { + const { recordVisit, toggleFavorite, clearRecent } = + piniaNavigationHistoryStore() + + return { recordVisit, toggleFavorite, clearRecent } +} diff --git a/apps/admin/src/store/hooks/useSigningStore.ts b/apps/admin/src/store/hooks/useSigningStore.ts index aeaef32f..1635f1cc 100644 --- a/apps/admin/src/store/hooks/useSigningStore.ts +++ b/apps/admin/src/store/hooks/useSigningStore.ts @@ -9,18 +9,22 @@ export const useSigningGetters = () => { * 获取登陆返回信息。 */ const getSigningCallback = computed(() => variable.signingCallback) + const getPermissions = computed(() => variable.permissions) return { getSigningCallback, + getPermissions, } } export const useSigningActions = () => { - const { signing, logout, clearSigningCallback } = piniaSigningStore() + const { signing, logout, clearSigningCallback, restoreSession } = + piniaSigningStore() return { signing, logout, clearSigningCallback, + restoreSession, } } diff --git a/apps/admin/src/store/index.ts b/apps/admin/src/store/index.ts index 25bdd222..4add3769 100644 --- a/apps/admin/src/store/index.ts +++ b/apps/admin/src/store/index.ts @@ -16,6 +16,7 @@ export * from './hooks/useSigningStore' export * from './hooks/useKeepAliveStore' export * from './hooks/useRuntimeStore' export * from './hooks/useLockScreenStore' +export * from './hooks/useNavigationHistoryStore' // Store hooks 是业务访问入口;应用卸载时同时释放 Pinia 作用域及其订阅。 export const setupStore = (app: App) => { diff --git a/apps/admin/src/store/modules/menu/index.ts b/apps/admin/src/store/modules/menu/index.ts index 5b7d080e..3a029ed1 100644 --- a/apps/admin/src/store/modules/menu/index.ts +++ b/apps/admin/src/store/modules/menu/index.ts @@ -12,6 +12,7 @@ import { updateObjectValue } from '@/utils/update-object-value' import { pick } from 'lodash-es' import { NEllipsis } from 'naive-ui' import type { LocationQuery, RouteRecordNormalized } from 'vue-router' +import { piniaNavigationHistoryStore } from '../navigation-history' import { piniaSigningStore } from '../signing' import { pickRouteRecordNormalizedConstant } from './constant' import { @@ -60,6 +61,7 @@ export const piniaMenuStore = defineStore( currentMenuOption: null, // 当前激活菜单项 }) const signing = piniaSigningStore() + const navigationHistory = piniaNavigationHistoryStore() const menuIndex = new Map< string, { option: AppMenuOption; parentPath: string } @@ -217,6 +219,14 @@ export const piniaMenuStore = defineStore( menuState.currentMenuOption = option + if ( + option.show !== false && + !option.children?.length && + !option.fullPath.includes(':') + ) { + navigationHistory.recordVisit(option.fullPath) + } + if (menuState.menuKey !== option.key) { menuState.menuKey = option.key setStorage(APP_CATCH_KEY.appMenuKey, option.key) diff --git a/apps/admin/src/store/modules/navigation-history/index.ts b/apps/admin/src/store/modules/navigation-history/index.ts new file mode 100644 index 00000000..e949c699 --- /dev/null +++ b/apps/admin/src/store/modules/navigation-history/index.ts @@ -0,0 +1,117 @@ +import { APP_CATCH_KEY } from '@/app-config' +import { getStorageInstance } from '@/utils/cache-backend' +import { piniaSigningStore } from '../signing' + +const validPath = (value: unknown): value is string => + typeof value === 'string' && + value.startsWith('/') && + !value.startsWith('//') && + value.length <= 512 && + !/[?#:]/u.test(value) + +const readPaths = (value: unknown, limit: number): string[] => + Array.isArray(value) + ? [...new Set(value.filter(validPath))].slice(0, limit) + : [] + +export const piniaNavigationHistoryStore = defineStore( + 'navigation-history', + () => { + const signing = piniaSigningStore() + const recentPaths = ref([]) + const favoritePaths = ref([]) + const storageUnavailable = ref(false) + const account = computed( + () => signing.signingCallback.id || signing.signingCallback.name || '', + ) + const cacheKey = () => + `${APP_CATCH_KEY.appGlobalSearchOptions}:v1:${encodeURIComponent(account.value)}` + + watch( + account, + () => { + recentPaths.value = [] + favoritePaths.value = [] + storageUnavailable.value = false + + if (!account.value) return + + try { + const raw = getStorageInstance('localStorage').getItem(cacheKey()) + const value: unknown = raw === null ? null : JSON.parse(raw) + + if ( + value && + typeof value === 'object' && + 'version' in value && + value.version === 1 + ) { + recentPaths.value = readPaths( + 'recent' in value ? value.recent : null, + 10, + ) + favoritePaths.value = readPaths( + 'favorites' in value ? value.favorites : null, + 300, + ) + } + } catch { + storageUnavailable.value = true + } + }, + { immediate: true, flush: 'sync' }, + ) + + const persist = () => { + if (!account.value) return + + try { + getStorageInstance('localStorage').setItem( + cacheKey(), + JSON.stringify({ + version: 1, + recent: recentPaths.value, + favorites: favoritePaths.value, + }), + ) + storageUnavailable.value = false + } catch { + storageUnavailable.value = true + } + } + + const recordVisit = (path: string) => { + if (!account.value || !validPath(path) || recentPaths.value[0] === path) + return + + recentPaths.value = [ + path, + ...recentPaths.value.filter((item) => item !== path), + ].slice(0, 10) + persist() + } + + const toggleFavorite = (path: string) => { + if (!account.value || !validPath(path)) return + + favoritePaths.value = favoritePaths.value.includes(path) + ? favoritePaths.value.filter((item) => item !== path) + : [...favoritePaths.value, path].slice(0, 300) + persist() + } + + const clearRecent = () => { + recentPaths.value = [] + persist() + } + + return { + recentPaths, + favoritePaths, + storageUnavailable, + recordVisit, + toggleFavorite, + clearRecent, + } + }, +) diff --git a/apps/admin/src/store/modules/signing/index.ts b/apps/admin/src/store/modules/signing/index.ts index d3cb2d4a..ef679cce 100644 --- a/apps/admin/src/store/modules/signing/index.ts +++ b/apps/admin/src/store/modules/signing/index.ts @@ -1,24 +1,22 @@ +import { getAdminSession, loginAdmin, logoutAdmin } from '@/api/admin' +import { AdminApiError } from '@/api/admin/client' import { APP_CATCH_KEY } from '@/app-config' -import { useSiderBar } from '@/hooks' +import { useSiderBar, useVueRouter } from '@/hooks' import type { SigningCallback, SigningForm, SigningResponse, } from '@/store/modules/signing/types' -import { removeStorage } from '@/utils/cache' -import { isEmpty } from 'lodash-es' +import { getStorage, removeStorage, setStorage } from '@/utils/cache' /** 登录状态仓库,使用 localStorage 持久化 signingCallback。 */ export const piniaSigningStore = defineStore( 'signing', () => { - const { clearRoutes, replace } = useRouter() + const { router } = useVueRouter() + const permissions = ref([]) const state = reactive({ - /** - * - * 登陆返回信息(可以存放用户名、权限、头像等一些信息) - * 路由鉴权依赖该属性中的 role 属性, 如果需要更改请同步更改: router/basic.ts、router/permission.ts - */ + /** 用户资料由会话接口刷新;role 用于现有路由和菜单守卫。 */ signingCallback: {} as SigningCallback, }) @@ -27,32 +25,45 @@ export const piniaSigningStore = defineStore( * @param signingFormValue 用户登录信息 * * @description - * 0: 登陆成功, 1: 登陆失败 + * 请求标准登录接口,保存返回的会话 token、资料与权限码。 + * 保留组件侧 code=0 的成功约定;接口错误通过 Promise 拒绝。 */ - const signing = ( + const signing = async ( signingFormValue: SigningForm, ): Promise => { - return new Promise((resolve, reject) => { - if (!isEmpty(signingFormValue)) { - state.signingCallback = { - role: 'admin', - name: signingFormValue.name, - avatar: 'https://avatars.githubusercontent.com/u/51957438?v=4', - } + const session = await loginAdmin( + signingFormValue.name, + signingFormValue.pwd, + ) - resolve({ - code: 0, - message: '登陆成功', - data: state.signingCallback, - }) - } else { - reject({ - code: 1, - message: '登陆失败', - data: null, - }) - } - }) + setStorage(APP_CATCH_KEY.token, session.accessToken, 'localStorage') + state.signingCallback = session.user + permissions.value = session.permissions + + return { code: 0, message: 'OK', data: state.signingCallback } + } + + const restoreSession = async () => { + permissions.value = [] + + if (!getStorage(APP_CATCH_KEY.token, 'localStorage')) { + state.signingCallback = {} as SigningCallback + + return + } + + try { + const session = await getAdminSession() + + state.signingCallback = session.user + permissions.value = session.permissions + } catch (error) { + if (!(error instanceof AdminApiError) || error.code !== 401) throw error + + removeStorage(APP_CATCH_KEY.token, 'localStorage') + removeStorage(APP_CATCH_KEY.signing, 'localStorage') + state.signingCallback = {} as SigningCallback + } } /** @@ -75,6 +86,8 @@ export const piniaSigningStore = defineStore( // 提示信息 window.$message.info('账号退出中...') + state.signingCallback = {} as SigningCallback + permissions.value = [] // 移除所有 sessionStorage 缓存 removeStorage('__all_sessionStorage__', 'sessionStorage') // 移除指定 localStorage 缓存 @@ -88,8 +101,8 @@ export const piniaSigningStore = defineStore( closeAll() if (toSigning) { - clearRoutes() - replace('/') + router.clearRoutes() + void router.replace('/') setTimeout(() => { window.location.reload() @@ -102,12 +115,20 @@ export const piniaSigningStore = defineStore( * 退出登陆并且清空缓存数据 * 延迟 300ms 后强制刷新当前系统 */ - const logout = () => { - clearSigningCallback(true) + const logout = async () => { + try { + await logoutAdmin() + } catch { + // 服务端暂时不可达时,仍允许用户完成本地退出。 + } finally { + clearSigningCallback(true) + } } return { ...toRefs(state), + permissions, + restoreSession, signing, logout, clearSigningCallback, diff --git a/apps/admin/src/store/modules/signing/types.ts b/apps/admin/src/store/modules/signing/types.ts index ccb360c8..e910a2e9 100644 --- a/apps/admin/src/store/modules/signing/types.ts +++ b/apps/admin/src/store/modules/signing/types.ts @@ -6,6 +6,8 @@ export interface SigningForm extends GlobalRecordable { } export interface SigningCallback extends Recordable { + id?: string + username?: string role: string name: string avatar?: string diff --git a/apps/admin/src/views/demo/axios/index.tsx b/apps/admin/src/views/demo/axios/index.tsx index 4257d0d2..c959a0cc 100644 --- a/apps/admin/src/views/demo/axios/index.tsx +++ b/apps/admin/src/views/demo/axios/index.tsx @@ -1,3 +1,4 @@ +import type { ApiResponse } from '@/api/admin/contracts' import { getRequestFixture, getWeather, @@ -13,7 +14,9 @@ export default defineComponent({ name: 'RAxios', setup() { const { t } = useI18n('demoDetails') - const manual = useRequest>>( + const manual = useRequest< + ApiResponse>> + >( { url: requestFixtureUrl, method: 'get', cancelConfig: { cancel: true } }, { manual: true }, ) @@ -63,7 +66,9 @@ export default defineComponent({ ) : manual.error.value ? ( t('request.failed') ) : manual.data.value ? ( -
{JSON.stringify(manual.data.value.ticket, null, 2)}
+
+                    {JSON.stringify(manual.data.value.data.ticket, null, 2)}
+                  
) : ( t('request.waiting') )} diff --git a/apps/admin/src/views/demo/echart/index.tsx b/apps/admin/src/views/demo/echart/index.tsx index 9ce0e960..c96bb886 100644 --- a/apps/admin/src/views/demo/echart/index.tsx +++ b/apps/admin/src/views/demo/echart/index.tsx @@ -1,6 +1,8 @@ import DemoPage from '../components/DemoPage' import DemoResult from '../components/DemoResult' import './index.scss' +import { getDemoCharts } from '@/api/demo/data' +import type { DemoCharts } from '@/api/demo/data' import { RChart, useChart } from '@/components' import { useI18n } from '@/hooks' import { NButton, NCard, NFlex, NSwitch } from 'naive-ui' @@ -11,6 +13,10 @@ const Echart = defineComponent({ const [register, { dispose, render }] = useChart() const [register2, { dispose: dispose2, render: render2 }] = useChart() const { t } = useI18n('demoDetails.chart') + const chartData = shallowRef() + const requestController = new AbortController() + + onScopeDispose(() => requestController.abort()) const chartLoading = ref(false) const chartAria = ref(false) @@ -30,19 +36,19 @@ const Echart = defineComponent({ grid: { left: 44, right: 14, top: 42, bottom: 26 }, xAxis: { type: 'category', - data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + data: chartData.value?.days ?? [], }, yAxis: { type: 'value' }, series: [ { name: t('orders'), - data: [120, 200, 150, 80, 70, 110, 130], + data: chartData.value?.orders ?? [], type: 'bar', barMaxWidth: 24, }, { name: t('visits'), - data: [12, 220, 250, 180, 20, 10, 190], + data: chartData.value?.visits ?? [], type: 'bar', barMaxWidth: 24, }, @@ -57,97 +63,34 @@ const Echart = defineComponent({ radius: ['40%', '68%'], center: ['50%', '46%'], label: { show: false }, - data: [ - { value: 1048, name: t('search') }, - { value: 735, name: t('direct') }, - { value: 580, name: t('email') }, - { value: 484, name: t('ads') }, - ], + data: (chartData.value?.sources ?? []).map(({ key, value }) => ({ + value, + name: t(key), + })), }, ], })) - const baseLineOptions = ref({ - tooltip: { - trigger: 'axis', - axisPointer: { - type: 'cross', - }, - }, - legend: { - type: 'scroll', - bottom: 0, - }, - grid: { - left: 52, - right: 20, - top: 20, - bottom: 58, - }, + const baseLineOptions = computed(() => ({ + tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } }, + legend: { type: 'scroll', bottom: 0 }, + grid: { left: 52, right: 20, top: 20, bottom: 58 }, xAxis: [ { type: 'category', boundaryGap: false, - data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + data: chartData.value?.days ?? [], }, ], - yAxis: [ - { - type: 'value', - }, - ], - series: [ - { - name: 'Email', - type: 'line', - stack: 'Total', - areaStyle: {}, - emphasis: { - focus: 'series', - }, - data: [120, 132, 101, 134, 90, 230, 210], - }, - { - name: 'Union Ads', - type: 'line', - stack: 'Total', - areaStyle: {}, - emphasis: { - focus: 'series', - }, - data: [220, 182, 191, 234, 290, 330, 310], - }, - { - name: 'Video Ads', - type: 'line', - stack: 'Total', - areaStyle: {}, - emphasis: { - focus: 'series', - }, - data: [150, 232, 201, 154, 190, 330, 410], - }, - { - name: 'Direct', - type: 'line', - stack: 'Total', - areaStyle: {}, - emphasis: { - focus: 'series', - }, - data: [320, 332, 301, 334, 390, 330, 320], - }, - { - name: 'Search Engine', - type: 'line', - stack: 'Total', - areaStyle: {}, - emphasis: { - focus: 'series', - }, - data: [820, 932, 901, 934, 1290, 1330, 1320], - }, - ], - }) + yAxis: [{ type: 'value' }], + series: (chartData.value?.lines ?? []).map((line) => ({ + name: line.name, + type: 'line', + stack: 'Total', + areaStyle: {}, + emphasis: { focus: 'series' }, + data: line.values, + })), + })) const handleLoadingShow = (bool: boolean) => { state.loading = bool @@ -162,22 +105,24 @@ const Echart = defineComponent({ state.lineVisible = false } - const updateChartOptions = () => { + const loadCharts = async (refresh = false) => { state.loading1 = true - const createData = () => Math.floor((Math.random() + 1) * 100) - - setTimeout(() => { - baseLineOptions.value.series[0].data = new Array(7) - .fill(0) - .map(() => createData()) - baseLineOptions.value.series[1].data = new Array(7) - .fill(0) - .map(() => createData()) + try { + chartData.value = await getDemoCharts(refresh, requestController.signal) + if (refresh) state.revision += 1 + } catch { + if (!requestController.signal.aborted) + window.$message.error(t('loadFailed')) + } finally { state.loading1 = false - state.revision += 1 - }, 1000) + } + } + + void loadCharts() + const updateChartOptions = () => { + void loadCharts(true) } return { diff --git a/apps/admin/src/views/demo/tables/auto-height.tsx b/apps/admin/src/views/demo/tables/auto-height.tsx index d100cbc3..1db1afe2 100644 --- a/apps/admin/src/views/demo/tables/auto-height.tsx +++ b/apps/admin/src/views/demo/tables/auto-height.tsx @@ -1,27 +1,30 @@ import { RTablePro } from '@/components' -import { listPeople } from '@/demo-data/people' import { useI18n } from '@/hooks/template/useI18n' import { NCheckbox } from 'naive-ui' import { createPeopleColumns } from './people' +import { usePeopleData } from './usePeopleData' export default defineComponent({ name: 'TableDemoAutoHeight', setup() { const { t } = useI18n('table') - const { data } = listPeople() + const { data, loading } = usePeopleData() const virtual = ref(false) const footer = ref(false) const action = ref(false) const columns = computed(() => createPeopleColumns(t)) - const ages = [...new Set(data.slice(0, 10).map(({ age }) => age))].sort( - (a, b) => a - b, + const ages = computed(() => + [...new Set(data.value.slice(0, 10).map(({ age }) => age))].sort( + (a, b) => a - b, + ), ) return () => ( ({ value: age, label: String(age) })), + options: ages.value.map((age) => ({ + value: age, + label: String(age), + })), }, ]} > diff --git a/apps/admin/src/views/demo/tables/basic.tsx b/apps/admin/src/views/demo/tables/basic.tsx index dbb4869e..90bc01cc 100644 --- a/apps/admin/src/views/demo/tables/basic.tsx +++ b/apps/admin/src/views/demo/tables/basic.tsx @@ -1,20 +1,22 @@ import { RTablePro } from '@/components' -import { listPeople } from '@/demo-data/people' import { useI18n } from '@/hooks/template/useI18n' import { createPeopleColumns } from './people' +import { usePeopleData } from './usePeopleData' export default defineComponent({ name: 'TableDemoBasic', setup() { const { t } = useI18n('table') - const { data } = listPeople({ page: 1, pageSize: 10 }) + const { data, loading } = usePeopleData(() => ({ page: 1, pageSize: 10 })) const columns = computed(() => createPeopleColumns(t).map((column) => { if ('key' in column && column.key === 'age') return { ...column, - sorter: (a: (typeof data)[number], b: (typeof data)[number]) => - a.age - b.age, + sorter: ( + a: (typeof data.value)[number], + b: (typeof data.value)[number], + ) => a.age - b.age, } return column @@ -22,7 +24,13 @@ export default defineComponent({ ) return () => ( - + ) }, }) diff --git a/apps/admin/src/views/demo/tables/columns.tsx b/apps/admin/src/views/demo/tables/columns.tsx index ad593708..72bb4fa8 100644 --- a/apps/admin/src/views/demo/tables/columns.tsx +++ b/apps/admin/src/views/demo/tables/columns.tsx @@ -1,16 +1,16 @@ import { RTablePro } from '@/components' -import { listPeople } from '@/demo-data/people' import type { Person } from '@/demo-data/people' import { useI18n } from '@/hooks/template/useI18n' import { NCheckbox } from 'naive-ui' import type { DataTableColumns } from 'naive-ui' import { createPeopleColumns } from './people' +import { usePeopleData } from './usePeopleData' export default defineComponent({ name: 'TableDemoColumns', setup() { const { t } = useI18n('table') - const { data } = listPeople() + const { data, loading } = usePeopleData() const showId = ref(true) const columns = computed>(() => [ @@ -31,7 +31,8 @@ export default defineComponent({ return () => ( () - const result = computed(() => - listPeople({ - page: page.value, - pageSize: pageSize.value, - name: name.value, - }), - ) + const { data, total, loading } = usePeopleData(() => ({ + page: page.value, + pageSize: pageSize.value, + name: name.value, + })) const columns = computed(() => createPeopleColumns((key) => t(`table.${key}`)), ) @@ -25,13 +23,14 @@ export default defineComponent({ (page.value = value), diff --git a/apps/admin/src/views/demo/tables/custom.tsx b/apps/admin/src/views/demo/tables/custom.tsx index 322425d4..86ce3a3b 100644 --- a/apps/admin/src/views/demo/tables/custom.tsx +++ b/apps/admin/src/views/demo/tables/custom.tsx @@ -1,14 +1,14 @@ import { RTablePro, useTablePro } from '@/components' -import { listPeople } from '@/demo-data/people' import { useI18n } from '@/hooks/template/useI18n' import { NButton, NFlex, NInput } from 'naive-ui' import { createPeopleColumns } from './people' +import { usePeopleData } from './usePeopleData' export default defineComponent({ name: 'TableDemoCustom', setup() { const { t } = useI18n('table') - const { data } = listPeople() + const { data, loading } = usePeopleData() const [register, { setPage, setPageSize }] = useTablePro() const email = ref('') const selected = ref<(string | number)[]>([]) @@ -21,7 +21,8 @@ export default defineComponent({ () const columns = computed(() => @@ -77,7 +77,8 @@ export default defineComponent({ onRegister={register} title={t('table.directory')} columns={columns.value} - data={data} + data={data.value} + loading={loading.value} search={[ { key: 'name', diff --git a/apps/admin/src/views/demo/tables/hooks-selection.tsx b/apps/admin/src/views/demo/tables/hooks-selection.tsx index 66545a8e..081e338f 100644 --- a/apps/admin/src/views/demo/tables/hooks-selection.tsx +++ b/apps/admin/src/views/demo/tables/hooks-selection.tsx @@ -1,5 +1,4 @@ import { RTablePro, useTablePro } from '@/components' -import { listPeople } from '@/demo-data/people' import type { Person } from '@/demo-data/people' import { useI18n } from '@/hooks/template/useI18n' import { NButton, NFlex } from 'naive-ui' @@ -7,6 +6,7 @@ import type { DataTableColumns } from 'naive-ui' import DemoPage from '../components/DemoPage' import DemoResult from '../components/DemoResult' import { createPeopleColumns } from './people' +import { usePeopleData } from './usePeopleData' export default defineComponent({ name: 'TableDemoHooksSelection', @@ -14,7 +14,7 @@ export default defineComponent({ const { t } = useI18n() const [register, { isReady, getCurrentPageData, getTableInstance }] = useTablePro() - const { data } = listPeople() + const { data, loading } = usePeopleData() const checked = ref<(string | number)[]>([]) const marked = shallowRef(new Set()) const columns = computed>(() => [ @@ -103,7 +103,8 @@ export default defineComponent({ onRegister={register} title={t('table.directory')} columns={columns.value} - data={data} + data={data.value} + loading={loading.value} v-model:checkedRowKeys={checked.value} search={[ { diff --git a/apps/admin/src/views/demo/tables/printing.tsx b/apps/admin/src/views/demo/tables/printing.tsx index a1991895..08c6aac3 100644 --- a/apps/admin/src/views/demo/tables/printing.tsx +++ b/apps/admin/src/views/demo/tables/printing.tsx @@ -1,17 +1,17 @@ import './printing.scss' import { RTablePro } from '@/components' import type { TableProInst } from '@/components' -import { listPeople } from '@/demo-data/people' import { useI18n } from '@/hooks/template/useI18n' import { NButton } from 'naive-ui' import { useTemplateRef } from 'vue' import { createPeopleColumns } from './people' +import { usePeopleData } from './usePeopleData' export default defineComponent({ name: 'TableDemoPrinting', setup() { const { t } = useI18n('table') - const { data } = listPeople() + const { data, loading } = usePeopleData() const table = shallowRef() const summary = useTemplateRef('summary') @@ -20,7 +20,8 @@ export default defineComponent({ ref={table} title={t('printDemoTitle')} columns={createPeopleColumns(t)} - data={data} + data={data.value} + loading={loading.value} pageSize={20} scrollX={920} search={[{ key: 'name', label: t('name'), placeholder: t('nameHint') }]} diff --git a/apps/admin/src/views/demo/tables/remote.tsx b/apps/admin/src/views/demo/tables/remote.tsx index a3e47c7d..16f85dce 100644 --- a/apps/admin/src/views/demo/tables/remote.tsx +++ b/apps/admin/src/views/demo/tables/remote.tsx @@ -65,7 +65,7 @@ export default defineComponent({ toolbar: () => ( <> - {t(import.meta.env.DEV ? 'httpSource' : 'localSource')} + {t('httpSource')} {checked.value.length ? ( { - const ownerIndex = index % owners.length - const { orgId, id: ownerId } = owners[ownerIndex] - const productIndex = Math.floor(index / 3) % products.length - const statusIndex = index % statuses.length - const warehouseIndex = Math.floor(index / 8) % warehouses.length - const day = 1 + (index % 12) - const hour = index % 3 === 0 ? 9 : 14 - - return { - id: index + 1, - orderNo: `ORD-${String(index + 1).padStart(3, '0')}`, - productIndex, - productId: products[productIndex], - statusIndex, - status: statuses[statusIndex], - createdAt: `2026-11-${String(day).padStart(2, '0')}`, - orgId, - ownerId, - ownerIndex, - warehouseIndex, - warehouseId: warehouses[warehouseIndex], - amount: [0, 59, 129, 199, 349, 699, 1299, 2499][index % 8], - invoiced: Math.floor(index / 4) % 2 === 0, - delivery: index % 3 === 0 ? 'express' : 'standard', - deliveryAt: new Date(2026, 10, day + 1, hour).getTime(), - deliveryTime: hour === 9 ? '09:00:00' : '14:00:00', - } -}) - -export function orderMatchesQuery( - row: (typeof orders)[number] & { product: string }, - query: TableProParams, -) { - const { - keyword, - status, - createdFrom, - createdTo, - orgId, - ownerId, - productId, - warehouseId, - minAmount, - invoiced, - delivery, - deliveryFrom, - deliveryTo, - deliveryTime, - } = query - - return ( - `${row.orderNo} ${row.product}` - .toLowerCase() - .includes(String(keyword ?? '').toLowerCase()) && - (!Array.isArray(status) || status.includes(row.status)) && - (typeof createdFrom !== 'string' || row.createdAt >= createdFrom) && - (typeof createdTo !== 'string' || row.createdAt <= createdTo) && - (orgId == null || row.orgId === orgId) && - (ownerId == null || row.ownerId === ownerId) && - (productId == null || row.productId === productId) && - (warehouseId == null || row.warehouseId === warehouseId) && - (typeof minAmount !== 'number' || row.amount >= minAmount) && - (invoiced == null || row.invoiced === invoiced) && - (delivery == null || row.delivery === delivery) && - (typeof deliveryFrom !== 'number' || row.deliveryAt >= deliveryFrom) && - (typeof deliveryTo !== 'number' || row.deliveryAt <= deliveryTo) && - (deliveryTime == null || row.deliveryTime === deliveryTime) - ) -} - -export function waitForDemo(delay: number, signal: AbortSignal) { - return new Promise((resolve, reject) => { - signal.throwIfAborted() - const abort = () => { - clearTimeout(timer) - reject(signal.reason) - } - const timer = setTimeout(() => { - signal.removeEventListener('abort', abort) - resolve() - }, delay) - - signal.addEventListener('abort', abort, { once: true }) - }) -} +export { + statuses, + organizations, + products, + warehouses, +} from '@/mocks/data/orders' diff --git a/apps/admin/src/views/demo/tables/search.tsx b/apps/admin/src/views/demo/tables/search.tsx index abafa3c2..4a5a3eff 100644 --- a/apps/admin/src/views/demo/tables/search.tsx +++ b/apps/admin/src/views/demo/tables/search.tsx @@ -1,4 +1,6 @@ import './search.scss' +import { getSearchOrders, getSearchOwners } from '@/api/demo/data' +import type { DemoOrder } from '@/api/demo/data' import { useSettingGetters } from '@/store' import { RTablePro, useTablePro } from '@ray-template/ui/table-pro' import type { @@ -29,13 +31,9 @@ import { import DemoPage from '../components/DemoPage' import { searchCopy } from './search-copy' import { - orderMatchesQuery, - orders, organizations, - owners, products, statuses, - waitForDemo, warehouses, } from './search-fixtures' @@ -85,12 +83,13 @@ export default defineComponent({ name: 'TableDemoSearch', setup() { const { getLocaleLanguage } = useSettingGetters() + const queryParams = computed(() => ({ locale: getLocaleLanguage.value })) const copy = computed(() => getLocaleLanguage.value === 'zh-CN' ? searchCopy.zh : searchCopy.en, ) const id = useId() const [register, table] = useTablePro() - const source = ref<'local' | 'remote'>('local') + const source = ref<'local' | 'remote'>('remote') const submitMode = ref<'manual' | 'change'>('manual') const more = ref(false) const scenario = ref() @@ -106,7 +105,7 @@ export default defineComponent({ detail: Trace['detail'], delay: number, signal: AbortSignal, - result: () => T, + result: () => Promise, ) => { const id = ++requestId const entry: Trace = { id, kind, detail, phase: 'pending' } @@ -119,8 +118,10 @@ export default defineComponent({ } try { - await waitForDemo(delay, signal) - const value = result() + signal.throwIfAborted() + const value = await result() + + signal.throwIfAborted() finish('success') @@ -131,14 +132,39 @@ export default defineComponent({ } } - const rows = computed(() => - orders.map((row) => ({ - ...row, - product: copy.value.products[row.productIndex], - statusLabel: copy.value.statuses[row.statusIndex], - organization: copy.value.teams[row.orgId === 'north' ? 0 : 1], - owner: copy.value.people[row.ownerIndex], - })), + const rows = shallowRef([]) + const rowsLoading = ref(false) + + watch( + [source, getLocaleLanguage], + async ([mode, locale], _, cleanup) => { + if (mode !== 'local') return + + const controller = new AbortController() + + cleanup(() => controller.abort()) + rowsLoading.value = true + + try { + rows.value = ( + await getSearchOrders( + { page: 1, pageSize: 100 }, + locale, + controller.signal, + ) + ).items + } catch { + if (!controller.signal.aborted) + window.$message.error( + locale === 'zh-CN' + ? '查询失败,请重试。' + : 'Query failed. Please retry.', + ) + } finally { + if (!controller.signal.aborted) rowsLoading.value = false + } + }, + { immediate: true }, ) const money = computed( () => @@ -157,7 +183,7 @@ export default defineComponent({ ) const deliveryDetails: TableProColumn = { type: 'expand', - renderExpand: (row: (typeof orders)[number]) => { + renderExpand: (row: DemoOrder) => { const labels = copy.value const details = [ [labels.warehouse, labels.warehouseLabels[row.warehouseIndex]], @@ -231,18 +257,9 @@ export default defineComponent({ failOwnerOnce = false - return track('owner', org, org === 'north' ? 800 : 450, signal, () => { - if (fail) throw new Error('Simulated assignee request failure') - - return owners.flatMap(({ id, orgId }, index) => { - const label = copy.value.people[index] - - return orgId === org && - label.toLowerCase().includes(keyword.trim().toLowerCase()) - ? [{ label, value: id }] - : [] - }) - }) + return track('owner', org, org === 'north' ? 800 : 450, signal, () => + getSearchOwners(org, keyword, getLocaleLanguage.value, signal, fail), + ) } const search = computed(() => { @@ -424,18 +441,15 @@ export default defineComponent({ listPayload.value = query failListOnce = false - return track('list', page, 400, signal, () => { - if (fail) throw new Error('Simulated list request failure') - - const matched = rows.value.filter((row) => - orderMatchesQuery(row, query), + return track('list', page, 400, signal, async () => { + const result = await getSearchOrders( + query, + getLocaleLanguage.value, + signal, + fail, ) - const start = (page - 1) * pageSize - return { - data: matched.slice(start, start + pageSize), - total: matched.length, - } + return { data: result.items, total: result.total } }) } @@ -582,6 +596,8 @@ export default defineComponent({ search={search.value} data={source.value === 'local' ? rows.value : void 0} request={source.value === 'remote' ? request : void 0} + params={queryParams.value} + loading={source.value === 'local' && rowsLoading.value} pageSize={5} pagination={pagination} scrollX={more.value ? 700 : 645} diff --git a/apps/admin/src/views/demo/tables/usePeopleData.ts b/apps/admin/src/views/demo/tables/usePeopleData.ts new file mode 100644 index 00000000..477523f1 --- /dev/null +++ b/apps/admin/src/views/demo/tables/usePeopleData.ts @@ -0,0 +1,40 @@ +import { getPersonList } from '@/api/demo/mock/person' +import type { Person, PersonListParams } from '@/api/demo/mock/person' +import { useI18n } from '@/hooks' + +export function usePeopleData( + query: () => PersonListParams = () => ({ page: 1, pageSize: 100 }), +) { + const data = shallowRef([]) + const total = ref(0) + const loading = ref(false) + const { t } = useI18n('tableHooks.queryPhase') + let controller: AbortController | undefined + const load = async () => { + controller?.abort() + const active = new AbortController() + + controller = active + data.value = [] + total.value = 0 + loading.value = true + + try { + const result = await getPersonList(query(), active.signal) + + if (!active.signal.aborted) { + data.value = result.data + total.value = result.total + } + } catch { + if (!active.signal.aborted) window.$message?.error(t('failed')) + } finally { + if (!active.signal.aborted) loading.value = false + } + } + + watch(query, load, { immediate: true, deep: true }) + onScopeDispose(() => controller?.abort()) + + return { data, total, loading, reload: load } +} diff --git a/apps/admin/src/views/login/components/Signing/index.tsx b/apps/admin/src/views/login/components/Signing/index.tsx index 48e6d505..7dca89c0 100644 --- a/apps/admin/src/views/login/components/Signing/index.tsx +++ b/apps/admin/src/views/login/components/Signing/index.tsx @@ -50,7 +50,6 @@ export default defineComponent({ if (res.code !== 0) throw new Error(res.message) - setStorage(APP_CATCH_KEY.token, 'tokenValue', 'localStorage') setStorage(APP_CATCH_KEY.signing, res.data, 'localStorage') await router.push(resolveLandingPath(router, getRootPath.value)) } catch { @@ -119,6 +118,21 @@ export default defineComponent({ > {t('UseDemo')} + + {(['manager', 'member'] as const).map((role) => ( + { + signingForm.name = role + signingForm.pwd = '123456' + void handleLogin() + }} + > + {t(role === 'manager' ? 'UseManager' : 'UseMember')} + + ))} + ) diff --git a/apps/admin/src/views/route-management/index.tsx b/apps/admin/src/views/route-management/index.tsx index df17366d..536c36c4 100644 --- a/apps/admin/src/views/route-management/index.tsx +++ b/apps/admin/src/views/route-management/index.tsx @@ -8,6 +8,7 @@ import { fetchRemoteRouteConfig, remoteRouteUrl, routeSourceStatus, + saveRemoteRouteConfig, saveRouteSource, } from '@/router/config/source' import type { RouteSource } from '@/router/config/source' @@ -100,7 +101,8 @@ export default defineComponent({ ) newPage.path = '' newPage.title = '' - source.value = 'local' + + if (source.value === 'static') source.value = 'remote' } catch (reason) { report(reason) } @@ -116,7 +118,9 @@ export default defineComponent({ if (selected.size > 256 * 1024) throw new Error(t('fileLimit')) draft.value = await selected.text() - source.value = 'local' + + if (source.value === 'static') source.value = 'remote' + validate() } catch (reason) { report(reason) @@ -135,15 +139,23 @@ export default defineComponent({ busy.value = false } } - const apply = () => { - const config = source.value === 'local' ? validate() : void 0 + const apply = async () => { + if (busy.value) return - if (source.value === 'local' && !config) return + const config = source.value !== 'static' ? validate() : void 0 + + if (source.value !== 'static' && !config) return try { - saveRouteSource(source.value, config) + busy.value = true + + if (source.value === 'remote' && config) + await saveRemoteRouteConfig(config) + else saveRouteSource(source.value, config) } catch (reason) { report(reason) + } finally { + busy.value = false } } diff --git a/apps/admin/src/views/route-management/visual.tsx b/apps/admin/src/views/route-management/visual.tsx index 0636f5bd..2d40d076 100644 --- a/apps/admin/src/views/route-management/visual.tsx +++ b/apps/admin/src/views/route-management/visual.tsx @@ -1,10 +1,14 @@ import './index.scss' import AppPageHeader from '@/app-components/app/AppPageHeader' -import { useI18n } from '@/hooks' +import { useAccess, useI18n } from '@/hooks' import { getStaticAppRoutes } from '@/router/app-route-modules' import { exportRouteConfig, parseRouteConfig } from '@/router/config/contract' import type { RouteConfigRecord } from '@/router/config/schema' -import { routeSourceStatus, saveRouteSource } from '@/router/config/source' +import { + fetchRemoteRouteConfig, + routeSourceStatus, + saveRemoteRouteConfig, +} from '@/router/config/source' import { findRouteView, routeViewCatalog } from '@/router/config/views' import { joinRoutePath } from '@/router/utils/join-route-path' import { orderRoutes } from '@/router/utils/order-routes' @@ -42,6 +46,8 @@ export default defineComponent({ name: 'RouteManagementVisual', setup() { const { t } = useI18n('routeManagement') + const { hasPermission } = useAccess() + const saving = ref(false) const text = (key: string) => t(key) const { t: translate } = useI18n() const records = ref([]) @@ -97,10 +103,13 @@ export default defineComponent({ error.value = reason instanceof Error ? reason.message : String(reason) valid.value = false } - const load = () => { + const load = async () => { try { const config = - routeSourceStatus.config ?? exportRouteConfig(getStaticAppRoutes()) + routeSourceStatus.active === 'remote' + ? await fetchRemoteRouteConfig() + : (routeSourceStatus.config ?? + exportRouteConfig(getStaticAppRoutes())) records.value = orderRoutes(structuredClone(config.routes)) selected.value = tree.value.options[0]?.key as number | undefined @@ -112,7 +121,7 @@ export default defineComponent({ } watch(records, clearResult, { deep: true }) - load() + void load() const validate = () => { try { @@ -128,15 +137,20 @@ export default defineComponent({ report(reason) } } - const apply = () => { + const apply = async () => { + if (saving.value || !hasPermission('routes:write')) return + const config = validate() if (!config) return try { - saveRouteSource('local', config) + saving.value = true + await saveRemoteRouteConfig(config) } catch (reason) { report(reason) + } finally { + saving.value = false } } const add = (kind: Kind, parent?: RouteConfigRecord) => { @@ -334,7 +348,12 @@ export default defineComponent({

{text('visualHint')}

- + {text('apply')} diff --git a/apps/admin/src/views/user-management/UserEditor.tsx b/apps/admin/src/views/user-management/UserEditor.tsx new file mode 100644 index 00000000..9ed1bc8b --- /dev/null +++ b/apps/admin/src/views/user-management/UserEditor.tsx @@ -0,0 +1,337 @@ +import { createUser, updateUser } from '@/api/admin' +import { AdminApiError } from '@/api/admin/client' +import type { AdminUser, UserInput, UserOptions } from '@/api/admin/contracts' +import { RForm, useForm } from '@/components' +import { useI18n } from '@/hooks' +import { + NAlert, + NButton, + NFlex, + NFormItem, + NInput, + NModal, + NRadio, + NRadioGroup, + NSelect, +} from 'naive-ui' +import type { FormRules, InputInst } from 'naive-ui' +import type { PropType } from 'vue' + +export default defineComponent({ + name: 'UserEditor', + props: { + user: { type: Object as PropType, default: void 0 }, + options: { type: Object as PropType, required: true }, + departmentId: { type: String, default: void 0 }, + currentUserId: { type: String, default: void 0 }, + }, + emits: { close: () => true, saved: (_user: AdminUser) => true }, + setup(props, { emit }) { + const { t } = useI18n('userManagement') + const { t: translate } = useI18n() + const initial: UserInput = { + username: props.user?.username ?? '', + name: props.user?.name ?? '', + email: props.user?.email ?? '', + phone: props.user?.phone ?? '', + departmentId: + props.user?.departmentId ?? + props.departmentId ?? + props.options.departments.find((item) => item.parentId)?.id ?? + props.options.departments[0]?.id ?? + '', + role: + props.user?.role ?? + props.options.roles.find( + (item) => item.value === 'member' && !item.disabled, + )?.value ?? + props.options.roles.find((item) => !item.disabled)?.value ?? + '', + status: props.user?.status ?? 'enabled', + remark: props.user?.remark ?? '', + } + const [register, { validate, formConditionRef: model }] = + useForm(initial) + const saving = ref(false) + const error = ref('') + const discardRequested = ref(false) + const firstInput = shallowRef() + const formElement = shallowRef() + const id = useId() + const self = props.user?.id === props.currentUserId + const rules = computed(() => ({ + username: [ + { required: true, message: t('required'), trigger: 'blur' }, + { + validator: (_, value: string) => + value.trim().length >= 2 && + value.trim().length <= 32 && + /^\S+$/u.test(value.trim()), + message: t('usernameHint'), + trigger: 'blur', + }, + ], + name: { + required: true, + whitespace: true, + message: t('required'), + trigger: 'blur', + }, + email: [ + { required: true, message: t('required'), trigger: 'blur' }, + { type: 'email', message: t('emailInvalid'), trigger: 'blur' }, + ], + departmentId: { + required: true, + message: t('required'), + trigger: 'change', + }, + role: { required: true, message: t('required'), trigger: 'change' }, + })) + const close = () => { + if (saving.value) return + + if (JSON.stringify(model.value) !== JSON.stringify(initial)) + discardRequested.value = true + else emit('close') + } + const submit = async (event: Event) => { + event.preventDefault() + + if (saving.value) return + + saving.value = true + error.value = '' + + try { + try { + await validate() + } catch (reason) { + await nextTick() + const field = Array.isArray(reason) + ? reason + .flat() + .find((item) => item && typeof item.field === 'string')?.field + : '' + const control = ['username', 'name', 'email'].includes(field) + ? formElement.value?.querySelector( + `input[name="${field}"]`, + ) + : formElement.value?.querySelector( + '.n-base-selection [tabindex="0"], .n-base-selection input', + ) + + if (control) control.focus() + else firstInput.value?.focus() + + return + } + + const user = props.user + ? await updateUser(props.user.id, model.value) + : await createUser(model.value) + + emit('saved', user) + } catch (reason) { + error.value = t( + `errors.${reason instanceof AdminApiError ? reason.key : 'requestFailed'}`, + ) + } finally { + saving.value = false + } + } + + return () => ( + { + if (!show) close() + }} + onAfterEnter={() => firstInput.value?.focus()} + > +
+ { + if (event.isComposing && event.key === 'Enter') + event.preventDefault() + }, + }} + > +
+ + + + + + + + + + + + + + ({ + value: item.id, + label: item.labelKey ? translate(item.labelKey) : item.name, + }))} + filterable + /> + + + ({ + ...item, + label: item.labelKey + ? translate(item.labelKey) + : item.label, + }))} + /> + + + + + {t('enabled')} + {t('disabled')} + + + + + + +
+ {error.value && ( + + )} +
+ {t('unsaved')} + emit('close')} + > + {t('discard')} + +
+ + + {t('cancel')} + + + {t('save')} + + +
+
+
+ ) + }, +}) diff --git a/apps/admin/src/views/user-management/index.scss b/apps/admin/src/views/user-management/index.scss new file mode 100644 index 00000000..9a1155f9 --- /dev/null +++ b/apps/admin/src/views/user-management/index.scss @@ -0,0 +1,134 @@ +.user-management { + display: flex; + flex-direction: column; + gap: 24px; + container-type: inline-size; + block-size: calc( + var(--layout-content-height, 100dvh) - 2 * + var(--layout-content-gutter, 16px) + ); + min-block-size: 0; + + > .r-page-header { + flex: none; + } + + > .n-spin-container { + flex: 1; + min-block-size: 0; + } + > .n-spin-container > .n-spin-content { + block-size: 100%; + } + &__layout { + display: grid; + grid-template-columns: 220px minmax(0, 1fr); + grid-template-rows: minmax(0, 1fr); + block-size: 100%; + min-block-size: 0; + gap: 20px; + } + &__organization, + &__list-viewport { + min-inline-size: 0; + min-block-size: 0; + } + &__organization .n-card__content-scrollbar { + overscroll-behavior: contain; + } + &__list-viewport { + block-size: 100%; + } + &__list { + min-inline-size: 0; + block-size: 100%; + display: flex; + flex-direction: column; + gap: 12px; + + > .r-table { + --r-table-height: auto; + flex: 1 0 20rem; + min-block-size: 20rem; + } + } + &__selection { + flex: none; + } + &__organization .n-scrollbar-container, + &__list-viewport > .n-scrollbar-container, + .n-data-table-base-body { + overscroll-behavior: contain; + } + &--stacked &__list { + block-size: auto; + min-block-size: 100%; + } + &--stacked &__list > .r-table { + flex: none; + min-block-size: auto; + } + &__identity { + display: grid; + gap: 4px; + line-height: 1.5; + padding-block: 4px; + } + &__identity strong { + font-weight: 500; + } + &__identity span { + font-size: 12px; + color: var(--r-text-secondary); + } + &__selection { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px; + padding: 12px 16px; + background: var(--r-surface); + border: 1px solid var(--r-line); + border-radius: 8px; + } +} +.user-management__modal.n-card { + width: min(700px, calc(100vw - 32px)); + max-height: calc(100dvh - 40px); + overflow: auto; +} +.user-management__modal--details.n-card { + width: min(560px, calc(100vw - 32px)); + overflow-wrap: anywhere; +} +.user-management__form-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0 20px; +} +.user-management__form-wide { + grid-column: 1 / -1; +} +.user-management__feedback { + margin-bottom: 12px; +} +.user-management__discard { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 44px; + margin-bottom: 12px; + color: var(--r-text-secondary); +} +@container (max-width: 850px) { + .user-management__layout { + grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(100px, 1fr) minmax(0, 3fr); + } +} +@media (max-width: 600px) { + .user-management__form-grid { + grid-template-columns: minmax(0, 1fr); + } +} diff --git a/apps/admin/src/views/user-management/index.tsx b/apps/admin/src/views/user-management/index.tsx new file mode 100644 index 00000000..07eded43 --- /dev/null +++ b/apps/admin/src/views/user-management/index.tsx @@ -0,0 +1,576 @@ +import './index.scss' +import { + deleteUsers, + getUser, + getUserOptions, + getUsers, + resetDemoUsers, + updateUserStatus, +} from '@/api/admin' +import { AdminApiError, apiMockEnabled } from '@/api/admin/client' +import type { AdminUser, UserOptions, UserStatus } from '@/api/admin/contracts' +import AppPageHeader from '@/app-components/app/AppPageHeader' +import { RIcon, RTablePro } from '@/components' +import type { TableProInst } from '@/components' +import { useAccess, useI18n } from '@/hooks' +import { + useSettingGetters, + useSigningActions, + useSigningGetters, +} from '@/store' +import type { TableProSearchFieldConfig } from '@ray-template/ui/table-pro' +import { useElementSize } from '@vueuse/core' +import { + NAlert, + NButton, + NCard, + NDescriptions, + NDescriptionsItem, + NFlex, + NModal, + NResult, + NScrollbar, + NSpin, + NTag, + NTree, +} from 'naive-ui' +import type { DataTableColumns, TreeOption } from 'naive-ui' +import UserEditor from './UserEditor' + +export default defineComponent({ + name: 'UserManagement', + setup() { + const { t } = useI18n('userManagement') + const { t: translate } = useI18n() + const { hasPermission } = useAccess() + const { getSigningCallback } = useSigningGetters() + const { restoreSession } = useSigningActions() + const { getLocaleLanguage } = useSettingGetters() + const table = shallowRef() + const pageElement = shallowRef() + const { width } = useElementSize(pageElement) + const stacked = computed(() => width.value > 0 && width.value <= 850) + const options = shallowRef() + const optionError = ref(false) + const optionLoading = ref(false) + const departmentId = ref('') + const queryParams = computed(() => ({ departmentId: departmentId.value })) + const pagination = { pageSizes: [10, 20, 50] } + const searchFields = computed(() => [ + { key: 'name', label: t('name'), placeholder: t('nameHint') }, + { key: 'username', label: t('username') }, + { + type: 'select', + key: 'status', + label: t('status'), + options: [ + { value: 'enabled', label: t('enabled') }, + { value: 'disabled', label: t('disabled') }, + ], + }, + ]) + const checked = ref<(string | number)[]>([]) + const editorOpen = ref(false) + const editing = shallowRef() + const details = shallowRef() + const loadingUser = ref('') + const busy = ref(false) + const abort = new AbortController() + + onScopeDispose(() => abort.abort()) + const errorText = (error: unknown) => + t( + `errors.${error instanceof AdminApiError ? error.key : 'requestFailed'}`, + ) + const loadOptions = async () => { + optionLoading.value = true + optionError.value = false + + try { + options.value = await getUserOptions(abort.signal) + } catch { + if (!abort.signal.aborted) optionError.value = true + } finally { + optionLoading.value = false + } + } + + void loadOptions() + + const departmentLabel = (id: string) => { + const department = options.value?.departments.find( + (item) => item.id === id, + ) + + return department?.labelKey + ? translate(department.labelKey) + : (department?.name ?? (id || t('allUsers'))) + } + const roleLabel = (value: string) => { + const role = options.value?.roles.find((item) => item.value === value) + + return role?.labelKey ? translate(role.labelKey) : (role?.label ?? value) + } + const tree = computed(() => { + const visit = (parentId: string | null): TreeOption[] => + (options.value?.departments ?? []) + .filter((item) => item.parentId === parentId) + .map((item) => ({ + key: item.id, + label: departmentLabel(item.id), + children: visit(item.id), + })) + + return [{ key: '', label: t('allUsers'), children: visit(null) }] + }) + const roleEditable = (user: AdminUser) => + !options.value?.roles.find((role) => role.value === user.role)?.disabled + const editable = (user: AdminUser) => + hasPermission('users:update') && roleEditable(user) + const removable = (user: AdminUser) => + hasPermission('users:delete') && + roleEditable(user) && + user.id !== getSigningCallback.value.id + const reload = async () => { + checked.value = [] + await table.value?.reload(true) + } + const mutate = async (action: () => Promise) => { + if (busy.value) return false + + busy.value = true + + try { + await action() + await reload() + window.$message.success(t('updated')) + + return true + } catch (error) { + window.$message.error(errorText(error)) + + return false + } finally { + busy.value = false + } + } + const confirmDelete = (ids: string[], name?: string) => + window.$dialog.warning({ + title: t('confirmDelete'), + content: name + ? t('deleteOne', { name }) + : t('deleteMany', { count: ids.length }), + positiveText: t('delete'), + negativeText: t('cancel'), + onPositiveClick: () => mutate(() => deleteUsers(ids)), + }) + const changeStatus = (ids: string[], status: UserStatus) => + window.$dialog.warning({ + title: t(status === 'enabled' ? 'confirmEnable' : 'confirmDisable'), + content: t('changeMany', { count: ids.length }), + positiveText: t(status === 'enabled' ? 'enable' : 'disable'), + negativeText: t('cancel'), + onPositiveClick: () => mutate(() => updateUserStatus(ids, status)), + }) + const openUser = async (id: string, edit = false) => { + if (loadingUser.value) return + + loadingUser.value = id + + try { + const user = await getUser(id, abort.signal) + + if (abort.signal.aborted) return + + if (edit) { + editing.value = user + editorOpen.value = true + } else details.value = user + } catch (error) { + window.$message.error(errorText(error)) + } finally { + loadingUser.value = '' + } + } + const columns = computed>(() => { + const result: DataTableColumns = [ + { + type: 'selection', + width: 44, + disabled: (row) => + row.id === getSigningCallback.value.id || !roleEditable(row), + }, + { + title: t('name'), + key: 'name', + minWidth: 155, + render: (row) => ( +
+ {row.name} + {row.username} +
+ ), + }, + { + title: t('email'), + key: 'email', + minWidth: 210, + ellipsis: { tooltip: true }, + }, + { + title: t('department'), + key: 'departmentId', + width: 130, + render: (row) => departmentLabel(row.departmentId), + }, + { + title: t('role'), + key: 'role', + width: 110, + render: (row) => roleLabel(row.role), + }, + { + title: t('status'), + key: 'status', + width: 90, + render: (row) => ( + + {t(row.status)} + + ), + }, + { + title: t('actions'), + key: 'actions', + fixed: stacked.value ? void 0 : 'right', + width: 240, + allowExport: false, + render: (row) => ( + + void openUser(row.id)} + > + {t('view')} + + {editable(row) && ( + void openUser(row.id, true)} + > + {t('edit')} + + )} + {hasPermission('users:status') && + row.id !== getSigningCallback.value.id && + roleEditable(row) && ( + + changeStatus( + [row.id], + row.status === 'enabled' ? 'disabled' : 'enabled', + ) + } + > + {t(row.status === 'enabled' ? 'disable' : 'enable')} + + )} + {removable(row) && ( + confirmDelete([row.id], row.name)} + > + {t('delete')} + + )} + + ), + }, + ] + + return hasPermission(['users:delete', 'users:status'], 'any') + ? result + : result.filter((column) => column.type !== 'selection') + }) + const closeEditor = () => { + editorOpen.value = false + editing.value = void 0 + } + const saved = async (user: AdminUser) => { + closeEditor() + window.$message.success(t('saved')) + + if (user.id === getSigningCallback.value.id) await restoreSession() + + await reload() + } + const reset = () => + window.$dialog.warning({ + title: t('reset'), + content: t('resetConfirm'), + positiveText: t('reset'), + negativeText: t('cancel'), + onPositiveClick: () => + mutate(async () => { + await resetDemoUsers() + departmentId.value = '' + await table.value?.resetSearch() + }), + }) + + return () => ( +
+ + {hasPermission('users:create') && ( + { + editing.value = void 0 + editorOpen.value = true + }} + > + {t('createUser')} + + )} + {apiMockEnabled && hasPermission('users:reset') && ( + + {t('reset')} + + )} + + {t('apiContract')} + + + + {optionError.value ? ( + + void loadOptions()}>{t('retry')} + + ) : ( + options.value && ( +
+ + + options.value!.departments.some( + (child) => child.parentId === item.id, + ), + ) + .map((item) => item.id), + ]} + selectedKeys={[departmentId.value]} + onUpdateSelectedKeys={(keys) => { + departmentId.value = String(keys[0] ?? '') + checked.value = [] + }} + /> + + + {checked.value.length > 0 && ( +
+ + {t('selected', { count: checked.value.length })} + + { + checked.value = [] + }} + > + {t('clearSelection')} + + {hasPermission('users:status') && ( + <> + + changeStatus(checked.value.map(String), 'enabled') + } + > + {t('batchEnable')} + + + changeStatus( + checked.value.map(String), + 'disabled', + ) + } + > + {t('batchDisable')} + + + )} + {hasPermission('users:delete') && ( + + confirmDelete(checked.value.map(String)) + } + > + {t('batchDelete')} + + )} +
+ )} + { + checked.value = [] + }} + onUpdatePage={() => { + checked.value = [] + }} + onUpdatePageSize={() => { + checked.value = [] + }} + downloadCsvTableOptions={{ fileName: 'users' }} + getCsvCell={(value, _row, column) => + column.key === 'departmentId' + ? departmentLabel(String(value)) + : column.key === 'role' + ? roleLabel(String(value)) + : column.key === 'status' + ? t(String(value)) + : String(value ?? '') + } + /> +
+
+ ) + )} +
+ {editorOpen.value && options.value && ( + void saved(user)} + /> + )} + { + if (!show) details.value = void 0 + }} + preset="card" + class="user-management__modal user-management__modal--details" + title={t('details')} + aria-label={t('details')} + > + {details.value && ( + + {( + [ + 'username', + 'name', + 'email', + 'phone', + 'departmentId', + 'role', + 'status', + 'createdAt', + 'remark', + ] as const + ).map((key) => ( + + {key === 'departmentId' + ? departmentLabel(details.value!.departmentId) + : key === 'role' + ? roleLabel(details.value!.role) + : key === 'status' + ? t(details.value!.status) + : key === 'createdAt' + ? new Intl.DateTimeFormat(getLocaleLanguage.value, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(details.value!.createdAt)) + : details.value![key] || '—'} + + ))} + + )} + +
+ ) + }, +}) diff --git a/apps/docs/.vitepress/sidebar.mts b/apps/docs/.vitepress/sidebar.mts index a4ba0e0c..ad4b389b 100644 --- a/apps/docs/.vitepress/sidebar.mts +++ b/apps/docs/.vitepress/sidebar.mts @@ -21,6 +21,7 @@ const guide = [ entry('路由、菜单与权限', '/guide/routing'), entry('应用布局与状态', '/guide/layout'), entry('接口、取消与 Mock', '/guide/requests'), + entry('服务端接入与标准契约', '/guide/backend'), entry('主题与国际化', '/guide/appearance'), entry('工程检查与部署', '/guide/tooling'), ], diff --git a/apps/docs/guide/backend.md b/apps/docs/guide/backend.md new file mode 100644 index 00000000..5bd7ca3c --- /dev/null +++ b/apps/docs/guide/backend.md @@ -0,0 +1,130 @@ +# 服务端接入与标准契约 + +登录、会话、用户管理与路由管理使用同一套 HTTP API。开发环境与静态在线演示都由 MSW 在网络层模拟响应;页面和 Store 不直接读取 Mock 数据库。接入自有服务端时,保留页面与调用方法,替换接口地址和实现即可。 + + + +下载 OpenAPI 3.1 契约 + +契约从 `apps/admin/src/api/admin/contracts.ts` 和路由 Schema 生成,含请求体、响应、查询参数、Bearer 认证与权限码。修改后运行 `pnpm api:generate`;全量验证中的 `pnpm api:check` 检查文件与运行时 Schema 一致。 + +## 接入步骤 + +在 `apps/admin/.env.local` 配置并重新启动或构建: + +```dotenv +VITE_API_MOCK=false +VITE_API_BASE_URL=https://your-api.example.com/api/ +``` + +也可以使用同源 `/api/`,由部署代理转发。设置 `VITE_API_BASE_URL` 后默认关闭 Mock,显式 `VITE_API_MOCK=true` 才重新启用。接口基址可以包含版本前缀;页面只通过 `api/admin` 的方法调用,不拼接固定域名。`VITE_*` 会进入浏览器产物,仅用于公开配置。 + +Mock 在应用启动前完成 Service Worker 注册。每次 API 请求前检查内部健康标记;浏览器回收 worker 后,使用公开 API 恢复,失败则阻止业务请求继续发送,表单和演示数据保持原样。内部 `GET /admin/mock-health` 仅由 Mock 使用,关闭 Mock 后不请求这个接口。默认脚本路径为 `/ray-template/mockServiceWorker.js`,作用域为应用 base;静态服务器必须按原路径提供该文件。浏览器需要 HTTPS 或 localhost。真实后端模式不启动 Mock,也不会在请求失败时返回伪造业务数据。当前锁定 MSW 2.11.6,安装不自动执行其 worker 复制脚本;升级时显式运行 `pnpm exec msw init apps/admin/public --save`,再做契约和浏览器验证。 + +## 统一响应 + +成功使用 HTTP 200 和以下包络: + +```json +{ + "code": 200, + "msg": "OK", + "data": { "items": [], "total": 0 } +} +``` + +分页请求使用 `page`(从 1 开始)、`pageSize`(1–100);响应 `data.items` 是当前页,`data.total` 是所有条件生效后的总数。筛选在分页前执行。详情和写入直接把单个对象放入 `data`;批量变更返回 `{ "affected": 2 }`。 + +失败同时使用对应的 HTTP 状态和 `code`,`data` 为 `null`: + +```json +{ + "code": 409, + "msg": "duplicateUsername", + "data": null, + "error": { "key": "duplicateUsername" } +} +``` + +400 表示输入不合法,401 表示会话失效,403 表示权限不足,404 表示对象不存在,409 表示账号/邮箱冲突或当前账号保护,503 表示演示数据库写入失败。`error.key` 是稳定的业务错误标识;可选的 `error.fields` 为字段到错误键的映射。API 层把错误转换为 `AdminApiError`,用户页将已约定的错误键翻译为中英文提示。读取响应也会经过 Schema 校验。 + +## 登录、会话与权限 + +| 方法和路径 | 输入 | 成功的 data | +| ------------------------- | ------------------------ | ----------------------------------------------- | +| `POST /admin/auth/login` | `{ username, password }` | `{ accessToken, expiresAt, user, permissions }` | +| `GET /admin/auth/session` | Bearer token | `{ user, permissions }` | +| `POST /admin/auth/logout` | Bearer token | `null` | + +```json +{ + "user": { "id": "u-1", "username": "admin", "name": "Alex", "role": "admin" }, + "permissions": [ + "users:read", + "users:create", + "users:update", + "routes:read", + "routes:write" + ] +} +``` + +应用使用 `Authorization: Bearer `。每次启动重新请求会话资料与权限,401 清除失效会话;其他启动请求失败保留错误,避免用旧权限继续工作。当前模板的路由角色契约是单个 `user.role`,路由 `meta.role` 为允许访问的角色数组。权限码独立于角色名称,可由自有服务端自由组织。 + +```tsx +import { useAccess } from '@/hooks' + +const { hasPermission } = useAccess() + +// 多个权限默认全部满足;第二个参数传 'any' 时任意一个满足即可。 +hasPermission('users:create') +hasPermission(['users:update', 'users:delete'], 'any') +``` + +前端权限用于菜单、导航和操作入口;服务端须独立校验每次业务请求。Mock 也会验证权限,直接发送请求无法绕过只读账号、管理员操作或当前账号保护。演示账号 `admin`(也兼容 `Ray Admin`)、`manager`、`member` 的密码均为 `123456`,分别对应全部权限、用户维护权限、只读权限。Mock token 与演示密码只用于在线体验,不是生产认证实现。 + +## 用户管理 + +| 方法和路径 | 输入 | 需要的权限 | +| -------------------------------- | ----------------------------------------------------- | -------------- | +| `GET /admin/users/options` | 无 | `users:read` | +| `GET /admin/users` | 分页及 `name/username/email/departmentId/role/status` | `users:read` | +| `GET /admin/users/{id}` | 路径 id | `users:read` | +| `POST /admin/users` | `UserInput` | `users:create` | +| `PUT /admin/users/{id}` | 完整 `UserInput` | `users:update` | +| `POST /admin/users/batch-delete` | `{ ids: string[] }` | `users:delete` | +| `PATCH /admin/users/status` | `{ ids: string[], status: "enabled" 或 "disabled" }` | `users:status` | +| `POST /admin/users/reset` | 无,仅演示恢复入口 | `users:reset` | + +```json +{ + "username": "alex", + "name": "Alex", + "email": "alex@example.com", + "phone": "", + "departmentId": "engineering", + "role": "member", + "status": "enabled", + "remark": "" +} +``` + +响应用户增加稳定的 `id` 与 ISO 8601 `createdAt`。账号与邮箱不区分大小写检查唯一性,更新时保留 id 与创建时间。组织选项由接口返回 `{ departments: [{ id, parentId, name, labelKey? }], roles: [{ value, label, labelKey?, disabled? }] }`,部门过滤包含子组织。`labelKey` 可选,用于演示中的中英文翻译;自有后端直接提供名称即可。 + +批量操作在接口层整体校验后提交,避免一部分成功一部分失败;当前账号不可被删除、停用或通过编辑更换角色。Mock 数据库将用户、路由与会话持久化在当前浏览器;写入失败时保留原数据并返回错误,编辑表单可重试。用户页的恢复按钮只在 Mock 模式显示。 + +## 路由管理 + +`GET /admin/route-config` 是公开的前端启动配置接口,返回 `data: { version: 1, routes: [...] }`;路由元数据不包含业务秘密。`PUT /admin/route-config` 以同一结构提交,需要 `routes:write`。若自有系统需要受保护的菜单读取,可在 API 适配层把读取移到登录后,并保留登录与错误页的启动路由。 + +现有菜单表已迁到 `apps/admin/src/mocks/data/routes.json`,作为 Mock 初始数据库和显式离线恢复来源。正常在线启动走 GET,路由可视化与 JSON 的接口模式保存走 PUT,成功后重新加载并从接口读回。导入、导出与接口中的路由内容使用同一结构,详情见[路由契约](./routing)。 + +前端 `router/config/views.ts` 保留组件 ID 白名单,接口只返回 ID;后端或 AI 不需要传递组件代码。登录、404 和受保护的路由管理入口由外壳保留。原 `VITE_ROUTE_CONFIG_URL` 仍兼容旧的原始 JSON 读取接口;完整读写接入使用上面的标准 API 基址。 + +## 在线验证 + +打开浏览器 Network,依次登录、进入用户管理、查询、新增编辑、打开详情与保存路由,能够看到对应的 HTTP 请求。在线演示响应标记为来自 Service Worker;它模拟服务端协议,静态站点无需另外部署服务进程。接入真实后端后,同样的页面请求直接发往配置的基址。 + +用户页复用 `RTablePro`、`RForm/useForm` 和 Naive UI。桌面下两个区域填满内容区:组织卡片使用 `contentScrollable`,表格使用 `autoHeight`;窄屏上下排布时分别由现有滚动组件承载,避免页面越长越高。 diff --git a/apps/docs/guide/first-page.md b/apps/docs/guide/first-page.md index 9d081237..05b6f4d7 100644 --- a/apps/docs/guide/first-page.md +++ b/apps/docs/guide/first-page.md @@ -34,26 +34,26 @@ export default defineComponent({ ## 接入菜单 -在 `apps/admin/src/router/modules/orders.ts` 添加: +先在 `apps/admin/src/router/config/views.ts` 的 `views` 中登记组件白名单: ```ts -import type { AppRouteRecordRaw } from '@/router/types' - -const orders: AppRouteRecordRaw = { - path: '/orders', - name: 'Orders', - component: () => import('@/views/orders'), - meta: { - i18nKey: 'menu.Orders', - icon: 'navigation/table', - order: 20, - }, -} - -export default orders +orders: { load: () => import('@/views/orders'), name: 'Orders' }, ``` -在 `apps/admin/src/locales/lang/zh-CN/menu.json` 和 `apps/admin/src/locales/lang/en-US/menu.json` 分别加入 `Orders` 的翻译。重新加载工作台,从菜单打开订单页,再刷新一次,确认路由可恢复。 +在 Mock 初始路由 JSON `apps/admin/src/mocks/data/routes.json` 中加入以下记录,或由自己的路由接口返回: + +```json +{ + "path": "/orders", + "name": "Orders", + "component": "orders", + "meta": { "i18nKey": "menu.Orders", "icon": "navigation/table", "order": 20 } +} +``` + +在中英文 `menu.json` 中加入 `Orders` 翻译。已有浏览器修改过路由时,进入路由管理载入初始配置并保存到接口,或直接在管理页添加该记录;重新加载后,从菜单、直接地址和刷新三条路径检查页面。 + +现成的「系统管理 → 用户管理」已演示组织筛选、远端查询、新增编辑、详情、批量操作和接口权限。可先对照这条完整流程,再接入自己的业务。其 API 与数据结构见[标准契约](./backend)。 ## 接入 API diff --git a/apps/docs/guide/layout.md b/apps/docs/guide/layout.md index 6cd15ca3..2cb61ce8 100644 --- a/apps/docs/guide/layout.md +++ b/apps/docs/guide/layout.md @@ -54,3 +54,9 @@ updateSettingState('layoutConfig', { [布局说明与插槽](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/layout/README.md) · [状态实现与持久化](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/README.md) 更细的状态字段与更新动作见 [Setting Store](../reference/store/setting)、[Runtime Store](../reference/store/runtime) 和 [布局 Hooks](../reference/hooks/layout)。 + +## 最近访问和收藏 + +桌面搜索支持 Ctrl/Command + K。输入页面名称查找,点击星标收藏;空关键词时显示收藏与最近访问,方向键、回车和 Tab 可操作。记录按会话用户 id 隔离,刷新后恢复;清空记录保留收藏。缓存只存菜单路径,展示时重新依据当前菜单和权限筛选,语言切换沿用当前翻译。窄屏继续使用导航抽屉。 + +内容页需要撑满工作区时,先复用布局的 `--layout-content-height`、`RTablePro autoHeight` 和 `--r-table-height`,以及 Naive UI 的 `NCard contentScrollable` / `NScrollbar`。父容器提供确定高度,Flex/Grid 子项设置 `min-block-size: 0` 后再承载内部滚动;单纯填充与滚动无需新增通用组件。用户管理页展示了左右独立滚动与窄屏上下排布。 diff --git a/apps/docs/guide/requests.md b/apps/docs/guide/requests.md index d6d0b046..e73023af 100644 --- a/apps/docs/guide/requests.md +++ b/apps/docs/guide/requests.md @@ -48,13 +48,11 @@ export function loadOrders( ## 从演示切到真实服务 -开发时人员列表请求 `GET /api/list`,由 Vite Mock 中间件处理。GitHub Pages 只能提供静态文件;插件 `build: true` 生成的 [独立 Mock 服务](https://vite-plugin-mock-dev-server.netlify.app/guide/mock-service) 需要 Node.js 进程。Pages 打包会跳过 `mockServer/`。 +开发、生产预览和 GitHub Pages 共用 MSW HTTP Mock。登录、用户、路由、人员表格、图表与请求示例都通过 API 层发送请求,在线演示由应用 base 下的 Service Worker 响应;不再在生产环境直接调用本地数据函数。选择本地筛选的表格示例,也先通过接口取得数据,再由组件完成本地排序、分页与筛选。 -Pages 上「远端分页」与「查询与分页」直接按需加载 `apps/admin/src/demo-data/people.ts`,与开发接口复用筛选、排序和分页实现,访问不依赖 `/api/list`。用 `pnpm pages:build` 构建后,将 `dist/pages` 挂载在静态站点的 `/ray-template/` 路径,打开 `/ray-template/#/tables/remote` 验证。不要用 Vite 的接口响应判断 Pages 是否具备 API 能力。 +设置 `VITE_API_MOCK=false` 和 `VITE_API_BASE_URL` 后,请求直达自己的服务端。完整请求/响应结构、错误码、会话、权限码及可下载 OpenAPI 见[服务端接入指南](./backend)。Mock 持久化仅属于当前浏览器,多用户共享数据和正式会话由真实后端负责。 -若后续有多个示例必须连同 Axios 拦截器一起演练,可以在演示构建显式启用 [MSW 浏览器拦截](https://mswjs.io/guides/integrations/browser),将 worker 放在 `/ray-template/` 下并等待注册后再启动应用。需要真实认证、共享写入或 HTTP 服务端行为时,另部署 API。业务项目应换成自己的 API 和会话;浏览器端 `VITE_*` 变量不能放密钥。 - -[请求实例](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/instance.ts) · [演示接口](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/api/demo/mock/person.ts) +[请求实例](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/instance.ts) · [业务 API](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/api/admin/index.ts) ## useRequest 与手动执行 @@ -73,6 +71,6 @@ export function useOrderSummary() { 调用 `run()` 触发手动加载。这个包装的请求函数从 `fetchOptions` 读取配置,不会把 `run(...)` 参数自动映射成请求体或 query;需要动态 service 时用同入口导出的 `useHookPlusRequest(service, options?)`,在 service 中调用 `request`。错误提示由业务配置或响应拦截器负责,当前默认拦截器不消费 `responseSuccessMessage` / `responseErrorMessage` 两个类型字段。 -默认头注入包含演示 `X-TOKEN` 与示例头。对接真实接口时在请求插件中校验目标来源,并按后端约定设置认证头。模板 Axios 实例用来请求自己的业务接口;第三方地址使用明确配置的独立客户端。 +默认仅向已配置的 API 基址注入 `Authorization: Bearer `,不覆盖调用方提供的认证头。模板 Axios 实例用来请求自己的业务接口;第三方地址使用明确配置的独立客户端。 [请求 Hook](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/index.ts) · [请求配置类型](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/http/src/types.ts) · [头注入实现](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/axios-interceptor/request/plugins/request-headers.ts) diff --git a/apps/docs/guide/routing.md b/apps/docs/guide/routing.md index caa74d44..2e816033 100644 --- a/apps/docs/guide/routing.md +++ b/apps/docs/guide/routing.md @@ -4,7 +4,7 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue' -在 `apps/admin/src/router/modules` 写默认导出的路由模块。模板递归收集文件,按 `meta.order` 排序;路由树用于菜单与面包屑,页面记录展开后注册到 Vue Router。默认使用 hash 路由,例如 `/ray-template/#/orders`。 +正常启动从 `GET /admin/route-config` 读取版本化路由 JSON,按 `meta.order` 排序;路由树用于菜单与面包屑,页面记录展开后注册到 Vue Router。Mock 的初始路由表位于 `apps/admin/src/mocks/data/routes.json`,前端只保留组件 ID 注册表和外壳必需路由。默认使用 hash 路由,例如 `/ray-template/#/orders`。 ## 路由配置交互校验 @@ -16,6 +16,12 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue' <<< @/examples/RouteConfigDemo.vue ::: +## 在线编辑与接口接入 + +路由管理的可视化和 JSON 页面从当前生效配置创建草稿。可视化保存及 JSON 的服务端模式通过 `PUT /admin/route-config` 提交,成功后重新加载并从接口读回;Mock 写入会在当前浏览器刷新后保留。JSON 页面仍可显式切换为本机配置或内置初始配置,用于离线恢复。 + +接口请求体为 `{ version: 1, routes: [...] }`,读取和写入响应都放在统一 `{ code, msg, data }` 包络的 `data` 中。`component` 必须是 `router/config/views.ts` 的注册 ID;新增前端页面先注册 ID,再由接口返回其路由记录。详见[服务端标准契约](./backend)。 + ## 常用元数据 | 字段 | 作用 | @@ -30,7 +36,7 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue' | `ignoreAutoResetScroll` | 允许页面保留内容区滚动位置,详见滚动工具实现。 | | `extra` | 菜单标记的文本、图标、类型和显隐,见 [useBadge](../reference/hooks/navigation#usebadge)。 | -嵌套子路由使用相对路径时会继承父路径。内置示例按用途分组,并以绝对路径保留原有页面地址。查看 [布局与路由示例](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/router/modules/demo/navigation.ts) 里的分组及多级菜单。 +嵌套子路由使用相对路径时会继承父路径。内置示例按用途分组,并以绝对路径保留原有页面地址。查看 [布局与路由示例](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/mocks/data/routes.json) 里的分组及多级菜单。 ## 登录和角色 diff --git a/apps/docs/public/contracts/admin-api.json b/apps/docs/public/contracts/admin-api.json new file mode 100644 index 00000000..27789158 --- /dev/null +++ b/apps/docs/public/contracts/admin-api.json @@ -0,0 +1,3247 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Ray Admin API", + "version": "1.0.0", + "description": "Mock and real backends share this contract. Route component values are identifiers from the frontend view catalog, never executable code." + }, + "servers": [ + { + "url": "/ray-template/api", + "description": "Default demo base. Replace with VITE_API_BASE_URL for your backend." + } + ], + "components": { + "schemas": { + "UserInput": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 32, + "minLength": 2, + "pattern": "^\\S+$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "email": { + "type": "string", + "maxLength": 120, + "format": "email" + }, + "phone": { + "type": "string", + "maxLength": 24, + "pattern": "^[+\\d ()-]*$" + }, + "departmentId": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "role": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + }, + "remark": { + "type": "string", + "maxLength": 300 + } + }, + "required": [ + "username", + "name", + "email", + "phone", + "departmentId", + "role", + "status", + "remark" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "User": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 32, + "minLength": 2, + "pattern": "^\\S+$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "email": { + "type": "string", + "maxLength": 120, + "format": "email" + }, + "phone": { + "type": "string", + "maxLength": 24, + "pattern": "^[+\\d ()-]*$" + }, + "departmentId": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "role": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + }, + "remark": { + "type": "string", + "maxLength": 300 + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "username", + "name", + "email", + "phone", + "departmentId", + "role", + "status", + "remark", + "id", + "createdAt" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "UserList": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 32, + "minLength": 2, + "pattern": "^\\S+$" + }, + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "email": { + "type": "string", + "maxLength": 120, + "format": "email" + }, + "phone": { + "type": "string", + "maxLength": 24, + "pattern": "^[+\\d ()-]*$" + }, + "departmentId": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "role": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + }, + "remark": { + "type": "string", + "maxLength": 300 + }, + "id": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "username", + "name", + "email", + "phone", + "departmentId", + "role", + "status", + "remark", + "id", + "createdAt" + ] + } + }, + "total": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "items", + "total" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "UserOptions": { + "type": "object", + "properties": { + "departments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "parentId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "name": { + "type": "string" + }, + "labelKey": { + "type": "string" + } + }, + "required": [ + "id", + "parentId", + "name" + ] + } + }, + "roles": { + "type": "array", + "items": { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "label": { + "type": "string" + }, + "labelKey": { + "type": "string" + }, + "disabled": { + "type": "boolean" + } + }, + "required": [ + "value", + "label" + ] + } + } + }, + "required": [ + "departments", + "roles" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "LoginInput": { + "type": "object", + "properties": { + "username": { + "type": "string", + "maxLength": 80, + "minLength": 1 + }, + "password": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "required": [ + "username", + "password" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "LoginResult": { + "type": "object", + "properties": { + "user": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "username": { + "type": "string" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "avatar": { + "type": "string" + } + }, + "required": [ + "id", + "username", + "name", + "role" + ] + }, + "permissions": { + "type": "array", + "items": { + "type": "string" + } + }, + "accessToken": { + "type": "string", + "minLength": 1 + }, + "expiresAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "user", + "permissions", + "accessToken", + "expiresAt" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Session": { + "type": "object", + "properties": { + "user": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "username": { + "type": "string" + }, + "name": { + "type": "string" + }, + "role": { + "type": "string" + }, + "avatar": { + "type": "string" + } + }, + "required": [ + "id", + "username", + "name", + "role" + ] + }, + "permissions": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "user", + "permissions" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Ids": { + "type": "object", + "properties": { + "ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "maxItems": 500 + } + }, + "required": [ + "ids" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "StatusInput": { + "type": "object", + "properties": { + "ids": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1, + "maxItems": 500 + }, + "status": { + "enum": [ + "enabled", + "disabled" + ], + "type": "string" + } + }, + "required": [ + "ids", + "status" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Changed": { + "type": "object", + "properties": { + "affected": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "affected" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "RouteConfig": { + "type": "object", + "properties": { + "version": { + "const": 1 + }, + "routes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/?(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute or relative child path. Supports named and optional parameters." + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[A-Za-z_][\\w.-]*$", + "description": "Unique Vue Router name. Required for keepAlive." + }, + "component": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered view ID. Use layout for a menu group." + }, + "alias": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + "minItems": 1, + "maxItems": 16 + } + ], + "description": "Absolute alternative path(s) for a leaf." + }, + "redirect": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute path of another configured page." + }, + "props": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "object", + "propertyNames": { + "not": { + "pattern": "^(?:[oO][nN]|innerHTML$|outerHTML$|srcdoc$|__proto__$|constructor$|prototype$)" + } + }, + "additionalProperties": {} + } + ], + "description": "Pass route params (true) or a JSON object to the view." + }, + "meta": { + "type": "object", + "properties": { + "i18nKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Translation key for the menu title." + }, + "noLocalTitle": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ], + "description": "Literal title if i18nKey is absent." + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$", + "description": "IconName from src/icons/manifest.ts." + }, + "role": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "maxItems": 32, + "description": "Allowed roles. Omitted or empty means any authenticated role." + }, + "hidden": { + "type": "boolean", + "description": "Hide from the menu. Direct navigation still uses the role guard." + }, + "sameLevel": { + "type": "boolean", + "description": "Append a breadcrumb without replacing the current tab." + }, + "order": { + "type": "number", + "description": "Menu sort order at the top level." + }, + "env": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "maxItems": 16 + } + ], + "description": "Vite mode(s) in which the menu item is visible." + }, + "windowOpen": { + "type": "string", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?:\\/\\/", + "description": "Open this HTTP(S) URL in a new tab." + }, + "ignoreAutoResetScroll": { + "type": "boolean", + "description": "Keep the content scroll position on navigation." + }, + "keepAlive": { + "type": "boolean", + "description": "Keep the view mounted. name must match the registered view name." + }, + "extra": { + "type": "object", + "properties": { + "label": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "i18nLabel": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$" + }, + "show": { + "type": "boolean" + }, + "type": { + "enum": [ + "default", + "primary", + "info", + "success", + "warning", + "error" + ], + "type": "string" + } + }, + "required": [], + "additionalProperties": false, + "description": "Optional menu badge." + } + }, + "required": [], + "additionalProperties": false + }, + "children": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RouteConfig/$defs/0" + }, + "minItems": 1, + "maxItems": 300 + } + }, + "required": [ + "path", + "meta" + ], + "additionalProperties": false + }, + "maxItems": 300 + } + }, + "required": [ + "version", + "routes" + ], + "additionalProperties": false, + "title": "Ray Template route configuration", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "0": { + "type": "object", + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/?(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute or relative child path. Supports named and optional parameters." + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[A-Za-z_][\\w.-]*$", + "description": "Unique Vue Router name. Required for keepAlive." + }, + "component": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Registered view ID. Use layout for a menu group." + }, + "alias": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$" + }, + "minItems": 1, + "maxItems": 16 + } + ], + "description": "Absolute alternative path(s) for a leaf." + }, + "redirect": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??)(?:\\/(?:[\\w~.-]+|:[A-Za-z_]\\w*\\??))*$", + "description": "Absolute path of another configured page." + }, + "props": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "object", + "propertyNames": { + "not": { + "pattern": "^(?:[oO][nN]|innerHTML$|outerHTML$|srcdoc$|__proto__$|constructor$|prototype$)" + } + }, + "additionalProperties": {} + } + ], + "description": "Pass route params (true) or a JSON object to the view." + }, + "meta": { + "type": "object", + "properties": { + "i18nKey": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Translation key for the menu title." + }, + "noLocalTitle": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ], + "description": "Literal title if i18nKey is absent." + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$", + "description": "IconName from src/icons/manifest.ts." + }, + "role": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "maxItems": 32, + "description": "Allowed roles. Omitted or empty means any authenticated role." + }, + "hidden": { + "type": "boolean", + "description": "Hide from the menu. Direct navigation still uses the role guard." + }, + "sameLevel": { + "type": "boolean", + "description": "Append a breadcrumb without replacing the current tab." + }, + "order": { + "type": "number", + "description": "Menu sort order at the top level." + }, + "env": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "maxItems": 16 + } + ], + "description": "Vite mode(s) in which the menu item is visible." + }, + "windowOpen": { + "type": "string", + "maxLength": 2048, + "pattern": "^[Hh][Tt][Tt][Pp][Ss]?:\\/\\/", + "description": "Open this HTTP(S) URL in a new tab." + }, + "ignoreAutoResetScroll": { + "type": "boolean", + "description": "Keep the content scroll position on navigation." + }, + "keepAlive": { + "type": "boolean", + "description": "Keep the view mounted. name must match the registered view name." + }, + "extra": { + "type": "object", + "properties": { + "label": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + { + "type": "number" + } + ] + }, + "i18nLabel": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "icon": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "pattern": "^[\\w-]+\\/[\\w-]+$" + }, + "show": { + "type": "boolean" + }, + "type": { + "enum": [ + "default", + "primary", + "info", + "success", + "warning", + "error" + ], + "type": "string" + } + }, + "required": [], + "additionalProperties": false, + "description": "Optional menu badge." + } + }, + "required": [], + "additionalProperties": false + }, + "children": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RouteConfig/$defs/0" + }, + "minItems": 1, + "maxItems": 300 + } + }, + "required": [ + "path", + "meta" + ], + "additionalProperties": false + } + } + }, + "DemoCharts": { + "type": "object", + "properties": { + "days": { + "type": "array", + "items": { + "type": "string" + } + }, + "orders": { + "type": "array", + "items": { + "type": "number" + } + }, + "visits": { + "type": "array", + "items": { + "type": "number" + } + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "number" + } + }, + "required": [ + "key", + "value" + ] + } + }, + "lines": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "values": { + "type": "array", + "items": { + "type": "number" + } + } + }, + "required": [ + "name", + "values" + ] + } + } + }, + "required": [ + "days", + "orders", + "visits", + "sources", + "lines" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoPeople": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "age": { + "type": "number" + }, + "address": { + "type": "string" + }, + "createDate": { + "type": "string" + }, + "email": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "age", + "address", + "createDate", + "email" + ] + } + }, + "total": { + "type": "number" + } + }, + "required": [ + "items", + "total" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoRequest": { + "type": "object", + "properties": { + "ticket": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "status": { + "type": "string" + } + }, + "required": [ + "id", + "title", + "status" + ] + }, + "cities": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "temperature": { + "type": "number" + }, + "humidity": { + "type": "number" + } + }, + "required": [ + "temperature", + "humidity" + ] + } + } + }, + "required": [ + "ticket", + "cities" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOrders": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "number" + }, + "orderNo": { + "type": "string" + }, + "productIndex": { + "type": "number" + }, + "productId": { + "type": "string" + }, + "statusIndex": { + "type": "number" + }, + "status": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "orgId": { + "type": "string" + }, + "ownerId": { + "type": "string" + }, + "ownerIndex": { + "type": "number" + }, + "warehouseIndex": { + "type": "number" + }, + "warehouseId": { + "type": "string" + }, + "amount": { + "type": "number" + }, + "invoiced": { + "type": "boolean" + }, + "delivery": { + "type": "string" + }, + "deliveryAt": { + "type": "number" + }, + "deliveryTime": { + "type": "string" + }, + "product": { + "type": "string" + }, + "statusLabel": { + "type": "string" + }, + "organization": { + "type": "string" + }, + "owner": { + "type": "string" + } + }, + "required": [ + "id", + "orderNo", + "productIndex", + "productId", + "statusIndex", + "status", + "createdAt", + "orgId", + "ownerId", + "ownerIndex", + "warehouseIndex", + "warehouseId", + "amount", + "invoiced", + "delivery", + "deliveryAt", + "deliveryTime", + "product", + "statusLabel", + "organization", + "owner" + ] + } + }, + "total": { + "type": "number" + } + }, + "required": [ + "items", + "total" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOwners": { + "type": "array", + "items": { + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "value", + "label" + ] + }, + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOrderQuery": { + "type": "object", + "properties": { + "query": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + "locale": { + "type": "string" + }, + "fail": { + "type": "boolean" + } + }, + "required": [ + "query", + "locale" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "DemoOwnerQuery": { + "type": "object", + "properties": { + "orgId": { + "type": "string" + }, + "keyword": { + "type": "string" + }, + "locale": { + "type": "string" + }, + "fail": { + "type": "boolean" + } + }, + "required": [ + "orgId", + "keyword", + "locale" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + }, + "Error": { + "type": "object", + "properties": { + "code": { + "type": "number" + }, + "msg": { + "type": "string" + }, + "data": { + "type": "null" + }, + "error": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "fields": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string" + } + } + }, + "required": [ + "key" + ] + } + }, + "required": [ + "code", + "msg", + "data" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema" + } + }, + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer" + } + } + }, + "paths": { + "/admin/demo/people": { + "get": { + "operationId": "getDemoPeople", + "summary": "getDemoPeople", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoPeople" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/request": { + "get": { + "operationId": "getRequestFixture", + "summary": "getRequestFixture", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoRequest" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/charts": { + "get": { + "operationId": "getDemoCharts", + "summary": "getDemoCharts", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoCharts" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/orders/search": { + "post": { + "operationId": "searchDemoOrders", + "summary": "searchDemoOrders", + "description": "Session or public bootstrap endpoint.", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DemoOrderQuery" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoOrders" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/demo/owners/search": { + "post": { + "operationId": "searchDemoOwners", + "summary": "searchDemoOwners", + "description": "Session or public bootstrap endpoint.", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DemoOwnerQuery" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/DemoOwners" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/auth/login": { + "post": { + "operationId": "login", + "summary": "login", + "description": "Session or public bootstrap endpoint.", + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/LoginResult" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/auth/session": { + "get": { + "operationId": "getSession", + "summary": "getSession", + "description": "Session or public bootstrap endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Session" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/auth/logout": { + "post": { + "operationId": "logout", + "summary": "logout", + "description": "Session or public bootstrap endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "type": "null" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/route-config": { + "get": { + "operationId": "getRouteConfig", + "summary": "getRouteConfig", + "description": "Session or public bootstrap endpoint.", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/RouteConfig" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateRouteConfig", + "summary": "updateRouteConfig", + "description": "Required permission: routes:write.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RouteConfig" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/RouteConfig" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/options": { + "get": { + "operationId": "getUserOptions", + "summary": "getUserOptions", + "description": "Required permission: users:read.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/UserOptions" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users": { + "get": { + "operationId": "listUsers", + "summary": "listUsers", + "description": "Required permission: users:read.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/UserList" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "page", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "default": 1 + } + }, + { + "name": "pageSize", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 10 + } + }, + { + "name": "name", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "username", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "email", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "departmentId", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "role", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "status", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "enabled", + "disabled" + ] + } + } + ] + }, + "post": { + "operationId": "createUser", + "summary": "createUser", + "description": "Required permission: users:create.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/User" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/{id}": { + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "get": { + "operationId": "getUser", + "summary": "getUser", + "description": "Required permission: users:read.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/User" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "put": { + "operationId": "updateUser", + "summary": "updateUser", + "description": "Required permission: users:update.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/User" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/batch-delete": { + "post": { + "operationId": "deleteUsers", + "summary": "deleteUsers", + "description": "Required permission: users:delete.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ids" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Changed" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/status": { + "patch": { + "operationId": "updateUserStatus", + "summary": "updateUserStatus", + "description": "Required permission: users:status.", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StatusInput" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Changed" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/admin/users/reset": { + "post": { + "operationId": "resetDemoUsers", + "summary": "resetDemoUsers", + "description": "Required permission: users:reset.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "code", + "msg", + "data" + ], + "properties": { + "code": { + "const": 200 + }, + "msg": { + "type": "string" + }, + "data": { + "$ref": "#/components/schemas/Changed" + } + } + } + } + } + }, + "400": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "See error.key for a stable machine-readable reason.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + } + } +} diff --git a/apps/docs/reference/store/signing.md b/apps/docs/reference/store/signing.md index b6907578..dd661aa9 100644 --- a/apps/docs/reference/store/signing.md +++ b/apps/docs/reference/store/signing.md @@ -1,14 +1,15 @@ # Signing Store -`useSigningGetters().getSigningCallback` 返回账号信息引用。登录前可能为空对象,成功后主要字段为 `name`、`role`、`avatar?`。角色用于客户端路由判断,后端仍需对每次请求校验会话和权限。 +`useSigningGetters().getSigningCallback` 返回会话用户资料,主要字段为 `id`、`username`、`name`、`role`、`avatar?`。`getPermissions` 返回当前会话的权限码;前端菜单与操作分别消费角色和权限,后端独立检查业务请求。 -| 方法 | 行为 | -| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `signing(form)` | 接收 `{ name, pwd }`。模板演示对非空表单返回固定的 `admin` 角色,不校验密码。成功解析为 `{ code: 0, data, message }`;空表单拒绝,包含 `code: 1` 和 `data: null`。 | -| `clearSigningCallback(toSigning)` | 清理当前应用登录和菜单缓存、Session Storage,并尝试关闭标签。`true` 时还会清路由、回到登录页并安排刷新。 | -| `logout()` | 调用 `clearSigningCallback(true)`。 | +| 方法 | 行为 | +| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `signing({ name, pwd })` | 调用标准登录接口,保存返回的 token、资料与权限。为兼容组件调用,动作成功仍返回 `{ code: 0, data, message }`;错误拒绝。HTTP 接口本身使用标准 `{ code: 200, msg, data }` 包络。 | +| `restoreSession()` | 启动时重新读取用户资料与权限,401 清除失效会话;网络或协议错误拒绝,不沿用旧权限。 | +| `clearSigningCallback(toSigning)` | 清理当前应用登录、菜单与 Session Storage,关闭标签;`true` 时回登录页并刷新。 | +| `logout()` | 先请求服务端注销,再清理本地会话。 | -登录演示页面在 `signing` 成功后写入演示 token 和签入信息;Store 的 `signing` 动作自身不签发 token。请求插件从 Local Storage 读取 token,Pinia 另外持久化 `signingCallback`。对接实际身份系统时,把 token 写入、角色刷新与退出清理视为同一条流程。 +Pinia 仅持久化用户资料;权限由会话接口刷新。搜索收藏和最近访问按稳定用户 id 隔离,旧的演示资料没有 id 时才使用名称。接口输入、输出和真实后端接入见[服务端契约](../../guide/backend)。 ```ts import { useSigningActions, useSigningGetters } from '@/store' diff --git a/docs/architecture.md b/docs/architecture.md index 648911dc..48891ac0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -28,13 +28,13 @@ Ray Template 是一个 pnpm workspace:后台负责宿主集成,文档站解 ## 关键运行链路 -| 链路 | 调用顺序与边界 | 继续阅读 | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -| 后台启动 | [index.html](../apps/admin/index.html) → [main.ts](../apps/admin/src/main.ts) → Pinia → 国际化 → Router → Day.js → 指令与自动补全设置 → 挂载 [App.tsx](../apps/admin/src/App.tsx)。普通和无界模式共用插件注册顺序。 | [布局与启动](../harness/context/layout.md) | -| 导航与缓存 | [路由初始化](../apps/admin/src/router/index.ts)加载来源 → [应用模块](../apps/admin/src/router/app-route-modules.ts)展开配置 → 注册守卫和页面 → 应用菜单 Store 与布局消费路由。应用维护缓存名单,共享壳渲染过渡与 KeepAlive。 | [路由](../harness/context/routing.md)、[布局](../harness/context/layout.md) | -| 请求与演示数据 | [API](../apps/admin/src/api) → [应用 Axios 实例](../apps/admin/src/axios/instance.ts) → [共享客户端](../packages/http/src/client.ts)。开发 Mock 走 HTTP;静态人员演示可用本地数据。生产会话和资源授权由接入方后端负责。 | [API](../harness/context/api.md) | -| 文档示例 | 文档可直接消费共享包;需要后台上下文时由 [AdminExample.vue](../apps/docs/examples/AdminExample.vue) 嵌入 [example.html](../apps/admin/example.html),使用独立启动、限定路由和内存缓存。 | [文档与示例](../harness/context/docs.md) | -| 应用配置 | [Vite](../vite.config.ts) 注入 `__APP_CFG__` 和 `__DEV__`;[应用配置](../apps/admin/src/app-config)按设计、请求、路由和缓存分组。 | [构建与工具链](../harness/context/toolchain.md) | +| 链路 | 调用顺序与边界 | 继续阅读 | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| 后台启动 | [index.html](../apps/admin/index.html) → [main.ts](../apps/admin/src/main.ts) → Pinia → 国际化 → Router → Day.js → 指令与自动补全设置 → 挂载 [App.tsx](../apps/admin/src/App.tsx)。普通和无界模式共用插件注册顺序。 | [布局与启动](../harness/context/layout.md) | +| 导航与缓存 | [路由初始化](../apps/admin/src/router/index.ts)加载来源 → [应用模块](../apps/admin/src/router/app-route-modules.ts)展开配置 → 注册守卫和页面 → 应用菜单 Store 与布局消费路由。应用维护缓存名单,共享壳渲染过渡与 KeepAlive。 | [路由](../harness/context/routing.md)、[布局](../harness/context/layout.md) | +| 请求与演示数据 | [API](../apps/admin/src/api) → [应用 Axios 实例](../apps/admin/src/axios/instance.ts) → [共享客户端](../packages/http/src/client.ts)。开发与静态在线演示共用 HTTP Mock,用户、会话与路由由接口读写;真实会话和资源授权由接入方后端负责。 | [API](../harness/context/api.md) | +| 文档示例 | 文档可直接消费共享包;需要后台上下文时由 [AdminExample.vue](../apps/docs/examples/AdminExample.vue) 嵌入 [example.html](../apps/admin/example.html),使用独立启动、限定路由和内存缓存。 | [文档与示例](../harness/context/docs.md) | +| 应用配置 | [Vite](../vite.config.ts) 注入 `__APP_CFG__` 和 `__DEV__`;[应用配置](../apps/admin/src/app-config)按设计、请求、路由和缓存分组。 | [构建与工具链](../harness/context/toolchain.md) | 公开行为变更按[应用与文档联动](docs-handoff.md)维护指南和可运行示例。页面排版见[视觉与排版](ui-design.md);代码注释见[注释规范](comment-style.md)。 @@ -45,7 +45,7 @@ Ray Template 是一个 pnpm workspace:后台负责宿主集成,文档站解 | 配置 | 检查范围 | | ------------------------------------ | ----------------------------------------------------------------------------------------- | | [应用](../tsconfig.app.json) | 后台 `apps/admin/src`、Vue JSX 和生成声明。 | -| [Node](../tsconfig.node.json) | 根构建与测试配置、`vite-helper`、后台 Mock。 | +| [Node](../tsconfig.node.json) | 根构建与测试配置、`vite-helper`、构建辅助。 | | [测试](../tsconfig.test.json) | `__test__` 与引用源码,加载 Vitest 和 Node 类型。运行时环境由 Vitest 配置及测试文件决定。 | | [共享包](../tsconfig.packages.json) | `packages/*/src`,不继承应用别名或自动导入声明。 | | [文档站](../apps/docs/tsconfig.json) | 独立检查文档示例,由 `pnpm docs:check` 执行。 | diff --git a/docs/docs-handoff.md b/docs/docs-handoff.md index 73fc9efd..c54b7d9c 100644 --- a/docs/docs-handoff.md +++ b/docs/docs-handoff.md @@ -9,7 +9,7 @@ | 组件入口与 TablePro | [公开导出](../apps/admin/src/components/index.ts)、[TablePro 契约](../packages/ui/src/RTablePro/README.md)、[表格示例](../apps/admin/src/views/demo/tables) | `base/`、`pro/` 深层路径失效;`RTable`、`useTable` 已移除。`useTablePro` 保留注册写法,提供 `isReady` 和当前页取数。远端 `total` 是筛选后的总数;取消依赖请求函数传递 signal;导出和打印默认仅当前页可见数据列。 | | 路由与权限 | [路由说明](../apps/admin/src/router/README.md)、[路由类型](../apps/admin/src/router/types.ts)、[权限守卫](../apps/admin/src/router/utils/permission.ts) | 菜单显隐不等于访问授权;会话和接口权限由后端校验。缓存需要路由 name 对应组件 name,验证菜单进入、直达和刷新。 | | 布局与 Pinia | [布局插槽和偏好](../apps/admin/src/layout/README.md)、[Store 约定](../apps/admin/src/store/README.md) | 全局 UI 单例已迁入 `runtime`,不持久化。保留历史设置和锁屏格式;自定义内容插槽时,由接入方负责保留请求取消及路由缓存。 | -| 请求与 Mock | [Axios 实现](../apps/admin/src/axios/instance.ts)、[取消器](../packages/http/src/RequestCanceler.ts)、[人员查询](../apps/admin/src/api/demo/mock/person.ts) | 实例成功返回 body,失败拒绝;调用方传 signal 时关闭模板的默认 signal 注入。Mock HTTP 仅用于开发,静态演示有独立本地数据分支。 | +| 请求与 Mock | [Axios 实现](../apps/admin/src/axios/instance.ts)、[取消器](../packages/http/src/RequestCanceler.ts)、[标准业务 API](../apps/admin/src/api/admin/index.ts) | 实例成功返回 body,失败拒绝;调用方传 signal 时关闭模板的默认 signal 注入。开发与静态在线演示共用 MSW HTTP Mock;关闭 Mock 后直接连接标准服务端接口。 | | Hooks、工具与图标 | [Hooks 行为](../apps/admin/src/hooks/README.md)、[工具兼容入口](../apps/admin/src/utils/README.md)、[图标生成](../packages/icons/src/A_README.md) | `@/hooks` 与 `@/utils` 公共入口保留;旧裸图标仅在缓存读取边界按唯一名称迁移。截图和打印测试不代表原生浏览器能力验收。 | | 工具链与部署 | [工具链记录](toolchain-upgrade.md)、[架构地图](architecture.md)、[Vite 配置](../vite.custom.config.ts) | Node/pnpm 以清单为准。应用 base 为 `/ray-template/`,内置文档为 `/ray-template/docs/`。已发布旧站仍使用 `/ray-template-doc/`。 | diff --git a/docs/toolchain-upgrade.md b/docs/toolchain-upgrade.md index 321b84ab..8b25d526 100644 --- a/docs/toolchain-upgrade.md +++ b/docs/toolchain-upgrade.md @@ -190,9 +190,17 @@ Ray Admin 的应用入口迁到 `apps/admin`,文档和应用经公开入口使 `pnpm harness verify` 通过 69 个测试文件的 294 个用例。合并产物核对了 22 个文档页中的 26 处内嵌入口和源码。Chrome 生产预览验证了 TablePro 样式、明暗主题、中文分页及失败重试,抽测了组件、指令、Hooks、工具交互和正常后台登录入口。桌面和 390px 预览中的边框内边距均为 12px。 -## GitHub Pages 静态 Mock +## 2026-11-05 HTTP Mock 与服务端契约 -人员数据函数由开发接口与生产浏览器演示共用。`pnpm pages:build` 继续组装应用和文档,并从 Pages 产物排除需要 Node.js 运行的 `mockServer/`。本地独立服务构建和开发中间件保持原入口。部署子路径与静态验收方法见[请求指南](../apps/docs/guide/requests.md#从演示切到真实服务)。 +演示已统一为 MSW 2.11.6:启动时等待 Service Worker 就绪,开发、生产预览与 GitHub Pages 复用同一套处理器。移除了仅开发可用的旧 Vite Mock 插件和生产直接调用本地人员数据的分支。初始路由迁入 Mock JSON,在线读写使用标准 GET/PUT 接口;组件白名单和外壳路由仍由前端持有。 + +浏览器验收复现了 MSW 3.x 约五分钟后失去拦截的[已知问题](https://github.com/mswjs/msw/issues/2801),因此固定使用 2.11.6。业务请求前探测 Mock 标记,丢失时通过公开 stop/start API 恢复;恢复失败时阻止业务请求穿透。上游修复并通过长时运行与后台恢复验收后再评估升级。官方 worker 保持原样,不手工修改库的消息协议。 + +`pnpm api:generate` 从运行时 Schema 生成可下载的 OpenAPI 3.1;`pnpm api:check` 校验契约和 MSW 官方 worker 同步,并纳入全量检查。递归路由 Schema 的引用定位到所属 OpenAPI 组件,回归测试检查全部引用可解析。Node/pnpm 版本保持清单要求。接入与部署边界见[服务端指南](../apps/docs/guide/backend.md)。 + +- Node.js 26.13.0、pnpm 12.16.1 下,`pnpm harness verify` 通过类型、Lint、格式、包边界、79 个测试文件的 357 个用例,以及后台和文档生产构建。报告:`.harness-local/runs/all-z0kewW/report.json`。 +- 浏览器完成用户增删改查、重复输入与取消、批量操作、只读账号、收藏与历史隔离、键盘搜索、接口路由保存和刷新读回。1280px 桌面与 390px 窄屏验证两个区域独立滚动、中英文及明暗主题;文档契约入口返回最终 JSON。证据:`.harness-local/browser/admin-2026-11-05/report.json`。 +- Chrome 自动化连接中断后,完整生产验收使用独立的内置 Chromium 预览。长时间操作后 Mock 请求仍由 Service Worker 返回;当前浏览器工具不支持强制终止 worker,恢复并发与失败阻断由回归测试覆盖。未连接真实后端,未部署或运行远端 CI。 ## 参考资料 diff --git a/harness/README.md b/harness/README.md index 6f9dcbbd..aeec0dce 100644 --- a/harness/README.md +++ b/harness/README.md @@ -23,6 +23,7 @@ pnpm harness verify ## 工程约定 +- 新增能力或组件前,先检索并查看项目现有组件、Hooks 与已安装组件库的 API 和调用示例,确认是否能通过既有 Props、插槽或布局 CSS 组合实现。已有能力足够时直接复用;只有确认存在能力缺口时才新增组件,并在现有任务记录或交付说明中交代缺口与选择。不要仅因需要撑满高度、滚动容器或一层样式包装就创建新组件。 - UI 沿用 Vue 3 Composition API、`defineComponent` + TSX 与现有 SFC 的 `