11 Commits
Author SHA1 Message Date
wangdefa efcb84eaa8 发布 v0.8.0
CI / test (push) Successful in 42s
Release / release (push) Successful in 43s
2026-07-21 19:40:45 +08:00
wangdefa 6129173fe6 三页面重设计与移动端适配;接入 PWA 与构建分包
CI / test (push) Successful in 47s
2026-07-21 19:26:22 +08:00
wangdefa ac457282ce 新增对象存储/账单/保留IP页面,成本今天视图与样式收敛
CI / test (push) Successful in 42s
2026-07-21 12:11:22 +08:00
wangdefa d813225ac4 发布 v0.7.3
CI / test (push) Successful in 26s
Release / release (push) Successful in 27s
2026-07-17 16:58:12 +08:00
wangdefa 3475ce7ce6 回传日志去高度限制与文案同步,错误 toast 可展开详情
CI / test (push) Successful in 27s
2026-07-17 16:53:03 +08:00
wangdefa c0229b60c1 实例表单:默认 2C12G、去免费文案、配额按 AD 联动 2026-07-17 16:53:03 +08:00
wangdefa fbed8d1ea4 删除未引用的 PageHeader 死组件
CI / test (push) Successful in 26s
2026-07-17 12:19:28 +08:00
wangdefa 1fc5d74d8a 发布 v0.7.2
CI / test (push) Successful in 26s
Release / release (push) Successful in 26s
2026-07-16 21:25:40 +08:00
wangdefa 4606fbfd4f 设置页上游预算项、代理状态列、调用日志 Tokens 列宽
CI / test (push) Successful in 26s
2026-07-16 21:20:14 +08:00
wangdefa 0ff0e22e56 发布 v0.7.1
CI / test (push) Successful in 25s
Release / release (push) Successful in 26s
2026-07-16 16:41:03 +08:00
wangdefa 6ea222e5ab 审计日志搜索框:防抖检索、回溯进度与补批封顶
CI / test (push) Successful in 27s
2026-07-16 16:36:42 +08:00
119 changed files with 13121 additions and 1130 deletions
+6
View File
@@ -1,5 +1,11 @@
# API 层与状态管理规范
- 所有请求经统一 request 封装(`src/api/request`):注入 JWT、401 统一跳登录、错误统一提示;组件内不直接 `fetch`/裸 axios。
- `request``body` 传**对象**,封装内部统一 `JSON.stringify`;调用方自己 stringify 会双重编码,后端报 `cannot unmarshal string into …`(2026-07-14 ai-settings 开关踩坑)。
- 跨页面共享状态才进 Pinia;页面内状态用 `ref`/`computed` 就地管理,不把一切塞 store。
- 请求函数返回类型化数据(`Promise<Instance[]>`),错误向上抛由封装层兜底,不在每个调用点重复 try/catch。
- 消息提示统一走 `useToast`(`src/composables/useToast`),禁止组件直接 `useMessage`:超长错误(如 OCI 透传)自动折叠成「标题 + 展开详情」,显式传 detail 可自定义折叠内容。
- 账单域(round14 起):发票/付款方式 DTO 在 `types/api.ts`,请求走 `api/billing.ts`;发票 PDF 接口带 JWT 不能裸 `<a href>`,统一经 `downloadInvoicePdf`(rawFetch→blob→触发保存)。发票 tab 的 403 不当普通错误弹 toast,转受限卡提示 osp-gateway policy;「未付余额」口径只计 OPEN/PAST_DUE,PAYMENT_SUBMITTED 已提交扣款不计入。
- 发票列表按年懒加载(round15 起):`listInvoices(id, year)` 初始拉当年、空则自动往前探,手动逐年加载,连空 2 年停;明细/PDF 预览/付款方式一律弹窗(NModal),不用 NDrawer。对象存储 Archive 层:查看器「下载」在非 Restored 时禁用、「分享」一律禁用(PAR 对 Archive 无效);列表有 Restoring 对象时 30s 静默轮询自动停;公共读桶(visibility=ObjectRead)「复制 URI」变「复制 URL」(对象名整体 encodeURIComponent 拼公网直链)。
- Usage API 的成本时序对无出账记录的时段**不返回行**:图表轴不能用返回数据的 key 排序生成,须前端按范围生成完整标签再补零(CostTab `fullLabels()`),否则断轴缺刻度。
- 大列表禁止全量拉取(2026-07-21 PAR 复盘):几千行进 `ref` + NDataTable 会全量响应式代理化 + 建树,主线程打满数秒——服务端有游标就走 remote 分页,交互复用 ObjectBrowser 的「游标栈 + 上一页/下一页」模式(游标分页拿不到总数,头部计数用「本页 N(+)」表述);`listPars` 返回 `{items, nextPage}`,每页 100。OCI 写后读有秒级最终一致性(换 IP 后 GetVnic 仍回旧值):变更成功不能只重查一次,要带预期值开限时轮询窗口(VnicPanel `ipExpect` 90s,收敛后再 emit changed 联动父级刷新)。
@@ -1,59 +0,0 @@
# Component Guidelines
> How components are built in this project.
---
## Overview
<!--
Document your project's component conventions here.
Questions to answer:
- What component patterns do you use?
- How are props defined?
- How do you handle composition?
- What accessibility standards apply?
-->
(To be filled by the team)
---
## Component Structure
<!-- Standard structure of a component file -->
(To be filled by the team)
---
## Props Conventions
<!-- How props should be defined and typed -->
(To be filled by the team)
---
## Styling Patterns
<!-- How styles are applied (CSS modules, styled-components, Tailwind, etc.) -->
(To be filled by the team)
---
## Accessibility
<!-- A11y requirements and patterns -->
(To be filled by the team)
---
## Common Mistakes
<!-- Component-related mistakes your team has made -->
(To be filled by the team)
@@ -1,6 +1,6 @@
# 前端目录结构
> Vue 3 前端工程的目录职责与命名约定。
> Vue 3 前端工程(`oci-portal-dash/`)的目录职责与命名约定。
## 目录职责
-51
View File
@@ -1,51 +0,0 @@
# Hook Guidelines
> How hooks are used in this project.
---
## Overview
<!--
Document your project's hook conventions here.
Questions to answer:
- What custom hooks do you have?
- How do you handle data fetching?
- What are the naming conventions?
- How do you share stateful logic?
-->
(To be filled by the team)
---
## Custom Hook Patterns
<!-- How to create and structure custom hooks -->
(To be filled by the team)
---
## Data Fetching
<!-- How data fetching is handled (React Query, SWR, etc.) -->
(To be filled by the team)
---
## Naming Conventions
<!-- Hook naming rules (use*, etc.) -->
(To be filled by the team)
---
## Common Mistakes
<!-- Hook-related mistakes your team has made -->
(To be filled by the team)
@@ -1,51 +0,0 @@
# Quality Guidelines
> Code quality standards for frontend development.
---
## Overview
<!--
Document your project's quality standards here.
Questions to answer:
- What patterns are forbidden?
- What linting rules do you enforce?
- What are your testing requirements?
- What code review standards apply?
-->
(To be filled by the team)
---
## Forbidden Patterns
<!-- Patterns that should never be used and why -->
(To be filled by the team)
---
## Required Patterns
<!-- Patterns that must always be used -->
(To be filled by the team)
---
## Testing Requirements
<!-- What level of testing is expected -->
(To be filled by the team)
---
## Code Review Checklist
<!-- What reviewers should check -->
(To be filled by the team)
@@ -1,51 +0,0 @@
# State Management
> How state is managed in this project.
---
## Overview
<!--
Document your project's state management conventions here.
Questions to answer:
- What state management solution do you use?
- How is local vs global state decided?
- How do you handle server state?
- What are the patterns for derived state?
-->
(To be filled by the team)
---
## State Categories
<!-- Local state, global state, server state, URL state -->
(To be filled by the team)
---
## When to Use Global State
<!-- Criteria for promoting state to global -->
(To be filled by the team)
---
## Server State
<!-- How server data is cached and synchronized -->
(To be filled by the team)
---
## Common Mistakes
<!-- State management mistakes your team has made -->
(To be filled by the team)
@@ -1,6 +1,6 @@
# 样式与设计 Token 规范
> Anthropic 风(warm editorial)设计体系:色板、字体、圆角与反模式清单。代码事实源:`src/theme/tokens.ts`(JS 侧唯一来源)与 `src/assets/main.css`(Tailwind `@theme`)。
> Anthropic 风(warm editorial)设计体系:色板、字体、圆角与反模式清单。代码事实源:`oci-portal-dash/src/theme/tokens.ts`(JS 侧唯一来源)与 `oci-portal-dash/src/assets/main.css`(Tailwind `@theme`)。
## 基本规则
@@ -64,6 +64,13 @@
大圆角(>8px 的按钮/卡片)、任何渐变(含品牌色渐变文字)、玻璃拟态/毛玻璃、霓虹光晕、彩色大投影、emoji 当图标、深紫深蓝"AI 感"配色、满屏色块卡片、弹跳动效。
## 结构复用约定(2026-07-21 样式一致性收敛后固化)
- **面板头**:一律用 `PanelHeader`(title + desc + 默认插槽放右侧动作 + `#title-extra` 放徽标/计数),不再手写 `border-b … px-4.5 py-3.5` 头部;结构确实特殊的(带面包屑/筛选工具条)保持自定义但 padding 必须 `px-4.5 py-3.5`。面板一级标题 `text-sm font-semibold`,`text-[13px] font-semibold` 只允许出现在面板内的二级小节/行内标题。
- **空态/错误态**:整卡(panel 级)一律 `EmptyCard`(错误态 `title="…加载失败" :note="错误信息"`);表格内空态交给 NDataTable 自带 empty;手写灰字仅限行内小空位(如 IPv6「无」)。
- **浮层投影**:下拉/确认弹层/整页提示卡统一 `shadow-overlay`(@theme `--shadow-overlay`),圆角不超过 `rounded-lg`;禁止再写 `shadow-[0_18px…]` 一类逐处任意值。
- **恒暗页面**(网页 VNC 等):色值从 `@/theme/tokens``darkTokens` 取,不硬编码 hex;需要给组件 prop 传具体色时同样从 tokens/darkTokens 引。
## Common Mistake: NModal 宽度不能用 Tailwind class
**Symptom**:`<NModal preset="card" class="w-[480px]">` 弹窗实际渲染为全宽。
@@ -106,6 +113,14 @@
验证方法:build 后 `grep -o 'html\.dark[^}]*}' dist/assets/<view>-*.css` 核对编译产物选择器,或线上 DevTools 看 computed style 是否命中。
## Common Mistake:AppInputNumber 全局样式假定 suffix 只有步进两键
**Symptom**:`AppInputNumber``clearable` 后步进箭头挤出输入框右缘(2026-07 抢机表单「引导卷」实例)。
**Cause**:`main.css``.app-input-number``.n-input__suffix` 设为 26px 宽 2 行网格,并用 `:last-child` / `:nth-last-child(2)` 定位 add / minus;naive-ui 在 `clearable` 时于 suffix 首位额外渲染 `.n-base-clear`(无值时也存在),网格自动放置把它排进隐式第 2 列,竖栏被撑爆。
**Fix / Prevention**:已在 `main.css` 全局处理——`.n-base-clear` 绝对定位脱离网格流悬浮竖栏左侧,`.n-input:has(.n-base-clear)` 的 wrapper `padding-right` 加宽避让。今后给 `AppInputNumber` 追加会向 suffix 注入元素的 prop(loading / 自定义 suffix 插槽等)时,须同步检查该网格假设。
## 组件速查:NQrCode 去白底
NQrCode 自带 inline `background-color:#FFF; padding:12px`(props 可控)。两主题都不垫任何色块的方案:`:padding="0" background-color="transparent"` + `:color="app.dark ? '#f5f4ed' : '#141413'"`——暗色下反色渲染(浅模块透明底),主流扫码器(iOS 相机 / Google Lens / 新版 ML Kit)可识别,扫不动时弹窗内的手动密钥是兜底。color 是响应式 prop,切主题自动重绘。(历史方案「html.dark 下垫 #f5f4ed 浅底」因用户不接受色块框已废弃。)
-51
View File
@@ -1,51 +0,0 @@
# Type Safety
> Type safety patterns in this project.
---
## Overview
<!--
Document your project's type safety conventions here.
Questions to answer:
- What type system do you use?
- How are types organized?
- What validation library do you use?
- How do you handle type inference?
-->
(To be filled by the team)
---
## Type Organization
<!-- Where types are defined, shared types vs local types -->
(To be filled by the team)
---
## Validation
<!-- Runtime validation patterns (Zod, Yup, io-ts, etc.) -->
(To be filled by the team)
---
## Common Patterns
<!-- Type utilities, generics, type guards -->
(To be filled by the team)
---
## Forbidden Patterns
<!-- any, type assertions, etc. -->
(To be filled by the team)
+5
View File
@@ -14,3 +14,8 @@
- `v-for` 必须带 `key`,且不与 `v-if` 写在同一元素上。
- 组件内样式一律 `scoped`;跨组件复用样式上提到全局 token 或工具类。
- 复用逻辑抽 composable(`useXxx` 命名,放 `composables/`);单文件组件函数遵循 ≤30 行的项目约定。
- 二次确认一律用 `components/ConfirmPop.vue`(批次8 起替代裸 NPopconfirm):kind 分 danger/warn/plain 三态,`onConfirm` 返回 Promise 时确认按钮自动 loading 且弹层锁定;双按钮抉择场景(如终止实例选是否保留引导卷)仍用 `dialog.warning`
- 文件类型图标用 `components/objectstorage/FileIcon.vue`(Catppuccin Icons):图标数据由 `node scripts/gen-file-icons.mjs` 从 devDependency `@iconify-json/catppuccin` 提取到 `fileIcons.ts`(生成文件勿手改);新增类型改脚本 PICK 列表后再生成,禁止整包 import iconify JSON 进 bundle。
- highlight.js 高亮输出的配色是全局 `.code-hl` 类(`assets/main.css`,引用设计 token 明暗自适应),给容器加该类即可,勿在组件 scoped 里重复定义;markdown 渲染必须 marked + DOMPurify 消毒后再 v-html,两库一律动态 import 保持独立 chunk。
- 对象内容数据面分两路(round11 起):预览/编辑走面板中转 `getObjectContent`/`putObjectContent`(GET ≤20MB / PUT ≤5MB,保存以 If-Match 防并发,412 走覆盖确认),**不签发 PAR**;分享/下载/上传仍走 PAR 直连,勿把大流量改经面板。对象查看统一入口是 `ObjectViewerModal`(预览编辑合一,左内容右信息),office/pdf 用 `@vue-office/*` 且必须 `defineAsyncComponent` 动态加载保持独立 chunk。
- 在线编辑器是 CodeMirror 6(`viewer/TextEditPane.vue`,round13 起):核心/语言包/legacy-modes 全部动态 import;自定义 HighlightStyle **不带 fallback**(否则被 basicSetup 内置 defaultHighlightStyle 压过),配色引用设计 token 与 `.code-hl` 语义一致;hljs 只服务只读渲染(预览/md),不再用于编辑。格式化走 `objectstorage/format.ts`(json 原生,其余 prettier standalone 插件按需动态 import)。
+1 -1
View File
@@ -24,4 +24,4 @@
- **并发安全**:用户可能同时在编辑器里改文件,所有写入必须带上次读到的 etag,冲突时以用户改动为基准重新套用变更,绝不无条件覆盖。
- **链接纪律**:交付给人的永远是 claude.ai/design 链接;`serve_url`(claudeusercontent.com)是带项目令牌的短时链接,仅供自动化浏览器验证,不得外发。
- **平台边界**:Claude Design 没有本地 skill/plugin 市场与内部生成 agent,设计由当前会话直接产出;风格底座与评审职责由 token 清单(含反模式)与渲染验证循环承接。
- **导出衔接**:定稿 .dc.html 即结构化 HTML/CSS,实现阶段按 `.trellis/frontend/` 前端规范翻译成 Vue SFC + Naive UI themeOverrides,token 一一对应。
- **导出衔接**:定稿 .dc.html 即结构化 HTML/CSS,实现阶段按 `.trellis/spec/frontend/` 前端规范翻译成 Vue SFC + Naive UI themeOverrides,token 一一对应。
+1
View File
@@ -23,6 +23,7 @@ These guides help you **ask the right questions before coding**.
|-------|---------|-------------|
| [Code Reuse Thinking Guide](./code-reuse-thinking-guide.md) | Identify patterns and reduce duplication | When you notice repeated patterns |
| [Cross-Layer Thinking Guide](./cross-layer-thinking-guide.md) | Think through data flow across layers | Features spanning multiple layers |
| [Design Workflow](./design-workflow.md) | Claude Design 设计稿产出与评审流程 | 出 UI 设计稿 / 评审视觉方案时 |
---
+75
View File
@@ -2,6 +2,81 @@
格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)(版本段不记日期),版本号遵循语义化版本。
## [0.8.0]
### Added
- 新增对象存储管理:按租户 / 区域 / 区间创建存储桶(可选可见性、存储层和版本控制),后续可更新可见性 / 版本控制,并支持非空桶后台清空删除与存储用量展示;对象浏览支持虚拟目录、本层搜索、游标分页、批量操作、Archive 恢复及上传 / 下载任务队列
- 新增对象内容预览与在线编辑:支持图片、文本 / 代码、Markdown、SVG、DOCX、XLSX、PDF 及实验性 PPTX 预览;CodeMirror 提供语法高亮与搜索,支持格式美化、`If-Match` 冲突保护、重命名、分享和下载
- 新增对象存储 PAR 分享管理:支持对象级只读 / 读写链接和桶级读写(`AnyObjectReadWrite`)链接、自定义 1–720 小时有效期、游标分页、单条 / 全部删除
- 租户详情新增「发票」页:汇总未付与年度金额,按年加载发票,查看费用明细、PDF 预览 / 下载、默认付款方式并在线付款;对无权限、非 PAYG 与账单平台不适用账号提供专门说明
- 网络页新增保留公网 IP 管理;创建实例和附加 VNIC 支持临时 / 保留 / 不分配三种公网 IPv4 方式,主 / 次网卡可改用临时或保留 IP
- VCN 详情新增便捷操作与安全列表规则编辑,可一键启用 IPv6 / 放行默认规则,并行内新增、修改、删除入站与出站规则
- 成本分析新增「今天」小时视图,以及按服务展开产品(SKU)明细;实例列表新增终止操作
- 新增 PWA:HTTPS 下可添加到主屏幕并以独立窗口运行,Service Worker 自动更新且不缓存 `/api/*``/ai/*` 实时请求
### Changed
- 全面适配 ≤767px 移动端:侧栏改为「总览 / 租户 / 实例 / 日志 / 更多」底栏,租户与实例列表卡片化,详情信息可折叠,详情 Tab 与配额筛选器可横向滚动,表单弹窗全屏并适配安全区
- AI 网关重构为「密钥与渠道 / 接入与模型」双 Tab;渠道名称可悬停查看关联租户并跳转租户详情
- 区间选择器改为树形层级展示并统一用于实例、网络、存储;多处确认操作改为带语义提示和防重复提交状态的确认气泡
- 设置页通知开关、安全数值项与抢机熔断阈值改为失焦 / 切换即时保存
- Office 预览、CodeMirror、Prettier、Markdown / 高亮等大型依赖按用途分包并按需加载;Office 大块不进入 PWA 首次预缓存
### Fixed
- 修复成本分析「近 14 天 / 近 30 天」切换未把所选时间范围传给接口,结果不随选择变化
- 修复多 VNIC 实例流量曲线只读取首块网卡、时间轴被新网卡短序列截断;现按日期聚合全部 VNIC
- 修复主 / 次网卡更换公网 IP 后详情仍显示旧地址;在 90 秒窗口内轮询至新地址收敛,并联动刷新实例顶部信息
- 修复多处异步确认操作弹层挂起且可重复提交;确认按钮现展示进行态并锁定重复操作
- 修复区间选择器丢失父子层级、长名称溢出,以及回传日志租户选择器被外部宽度样式压窄 / 越界
- 补齐 VNIC、卷挂载、IPv6 等既有写操作的系统日志中文动作说明,上述路由不再显示「-」
- 修复面板内表格圆角 / 阴影叠加造成的四角露缝,并补齐窄屏表格的横向滚动提示
## [0.7.3]
### Added
- 实例规格表单配额判定改为数据驱动(shape `quotaNames` × compute limits,按行 scope 区分 AD / 区域限额),删除硬编码映射,覆盖全部带配额名的 shape;选定可用域后 Shape 选项按该 AD 配额禁用并标注「该 AD 无配额」,选定 Shape 后可用域选项禁用 / 标注无配额 AD
- 创建实例可用域留空且默认 AD-1 对所选 shape 无配额时,自动落位首个有配额的可用域(字段可见可改;抢机表单保持留空 = 轮询语义)
### Changed
- 创建实例默认规格 4 OCPU / 24 GB → 2 OCPU / 12 GB(创建与抢机共用表单)
- 实例表单(创建 / 调整规格 / 抢机)去除「免费额度」「永久免费」标注与「容量不足可改用抢机任务」「A1 免费额度上限」等提示;免费 shape 仍置顶排序
- 回传日志表格移除最大高度限制,行为与系统日志 / AI 调用一致;页脚与通知设置说明同步「创建不回传,避免抢机噪声」
- 创建实例失败 / 部分成功提示改为「短标题 + 展开详情」形态,逐台错误进详情块、可复制
### Fixed
- 修复批量接口全部失败(HTTP 500 + `errors` 数组)时提示只显示「请求失败(500)」:统一请求层现解析 `errors` 数组,展示具体失败原因
## [0.7.2]
### Added
- 设置页 AI Tab「Responses 直通」面板新增「上游无响应预算」输入(30..900 秒,失焦 / 回车提交,即时生效),与流式保险丝同面板并网格对齐
- 代理列表新增「状态」列(检测中 / 正常 / 异常):与地区同源于经代理链路的出口探测,探测失败即视为异常,「重测」联动刷新;页脚说明同步
### Changed
- AI 调用日志 Tokens(入/出)列加宽并禁止换行,大用量流式行不再折行;原「流式保险丝」独立面板并入「Responses 直通」
## [0.7.1]
### Added
- 租户详情 · 审计日志新增搜索框(标签式查询框,样式对齐配额页):500ms 防抖,回车 / 清空即时生效且关键字未变不发起重复请求;匹配事件 / 资源 / 操作者等可见字段,不区分大小写、支持 `*` 通配
- 审计分页状态行新增「已回溯至 …」进度提示;搜索命中稀疏时自动补批封顶(2 次)后停驻,由「加载更早」按钮显式继续,不再无人值守回溯整个保留期
### Changed
- 审计页脚说明同步数据源变更:每批约 200 条、搜索匹配可见字段;详情弹窗原始 JSON 来源标注改为「来自 OCI 审计日志」
### Fixed
- 修复审计列表加载中刷新 / 更换关键字时,在途旧响应混入新信息流的竞态(代次校验丢弃过期响应)
## [0.7.0]
### Added
+4
View File
@@ -28,6 +28,10 @@ npm run build # 类型检查 + 产物构建到 dist/
1. **静态直出**`dist/` 交给 Caddy/nginx 伺服,`/api/*``/ai/*` 反代到后端
2. **单文件嵌入**:产物经后端 `go:embed` 打进单个二进制。本仓库 Release 流程(tag `v*`)自动构建并发布 `dist.zip`,后端 Release 流程从这里下载嵌入;本地则 `npm run build` 后把 `dist/` 内容拷入后端 `internal/webui/dist/`
### PWA
构建产物自带 PWAvite-plugin-pwa`manifest.webmanifest` + Service Worker),HTTPS 部署下手机浏览器可「添加到主屏幕」以独立窗口运行;前端发版后用户刷新即自动更新(`registerType: autoUpdate`)。Service Worker 只预缓存应用壳(约 4.6MB,office 预览大块按需缓存),`/api/*``/ai/*` 一律直连不缓存。图标源自 `public/favicon.svg`,改版时需同步重生成 `public/pwa-*.png``apple-touch-icon.png`
## 规范
编码规范与项目约定见 [AGENTS.md](AGENTS.md) 与 [.trellis/spec/](.trellis/spec/)。
+2
View File
@@ -4,6 +4,8 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="theme-color" content="#F5F4ED" />
<title>OCI Portal</title>
</head>
<body>
+5185 -7
View File
File diff suppressed because it is too large Load Diff
+25 -2
View File
@@ -1,7 +1,7 @@
{
"name": "oci-portal-dash",
"private": true,
"version": "0.2.0",
"version": "0.8.0",
"type": "module",
"scripts": {
"dev": "vite",
@@ -12,10 +12,31 @@
"format": "prettier --write src/"
},
"dependencies": {
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-go": "^6.0.1",
"@codemirror/lang-html": "^6.4.11",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.1",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/lang-sql": "^6.10.0",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/legacy-modes": "^6.5.3",
"@novnc/novnc": "^1.7.0",
"@prettier/plugin-xml": "^3.4.2",
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^2.0.10",
"@vue-office/pptx": "^1.0.1",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"codemirror": "^6.0.2",
"dompurify": "^3.4.12",
"echarts": "^6.1.0",
"highlight.js": "^11.11.1",
"marked": "^18.0.6",
"marked-highlight": "^2.2.4",
"naive-ui": "^2.41.0",
"pinia": "^2.3.0",
"vue": "^3.5.13",
@@ -23,6 +44,7 @@
"vue-router": "^4.5.0"
},
"devDependencies": {
"@iconify-json/catppuccin": "^1.2.17",
"@tailwindcss/vite": "^4.0.0",
"@tsconfig/node22": "^22.0.0",
"@types/node": "^22.10.7",
@@ -32,10 +54,11 @@
"@vue/tsconfig": "^0.7.0",
"eslint": "^9.18.0",
"eslint-plugin-vue": "^9.32.0",
"prettier": "^3.4.2",
"prettier": "^3.9.5",
"tailwindcss": "^4.0.0",
"typescript": "~5.7.3",
"vite": "^6.0.7",
"vite-plugin-pwa": "^1.3.0",
"vue-tsc": "^2.2.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
%PDF-1.4
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj
4 0 obj << /Length 90 >> stream
BT /F1 24 Tf 72 760 Td (OCI Portal PDF sample) Tj ET
BT /F1 12 Tf 72 730 Td (rendered via vue-office/pdf) Tj ET
endstream endobj
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj
trailer << /Root 1 0 R /Size 6 >>
%%EOF
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+55
View File
@@ -0,0 +1,55 @@
// 从 @iconify-json/catppuccin(Catppuccin VSCode Icons)提取对象存储用到的文件类型图标,
// 生成 src/components/objectstorage/fileIcons.ts 静态模块,避免把 659 个图标全量打进 bundle。
// 再生成:node scripts/gen-file-icons.mjs
import { createRequire } from 'node:module'
import { writeFileSync } from 'node:fs'
const require = createRequire(import.meta.url)
const { icons } = require('@iconify-json/catppuccin/icons.json')
// 图标名 → 该集合内的 icon key(catppuccin 集为 16x16)
const PICK = [
'folder',
'file',
'image',
'json',
'yaml',
'toml',
'properties',
'python',
'javascript',
'typescript',
'markdown',
'database',
'bash',
'go',
'zip',
'pdf',
'video',
'audio',
'html',
'css',
'text',
'log',
'csv',
'xml',
'binary',
'ms-word',
'ms-excel',
'ms-powerpoint'
]
const entries = PICK.map((name) => {
const icon = icons[name]
if (!icon) throw new Error(`icon not found: ${name}`)
return ` ${JSON.stringify(name)}:\n '${icon.body.replaceAll("'", "\\'")}',`
}).join('\n')
const out = `// 由 scripts/gen-file-icons.mjs 从 @iconify-json/catppuccin 提取,勿手改;
// 来源:Catppuccin VSCode Icons(MIT),16x16 viewBox。
export const FILE_ICON_BODIES: Record<string, string> = {
${entries}
}
`
writeFileSync(new URL('../src/components/objectstorage/fileIcons.ts', import.meta.url), out)
console.log(`written ${PICK.length} icons`)
+3 -1
View File
@@ -1,4 +1,4 @@
import { request } from './request'
import { mockOn, mocked, request } from './request'
import type {
AiCallLog,
AiCatalogModel,
@@ -49,6 +49,8 @@ export function updateAiKeyContentLog(id: number, hours: number): Promise<AiKey>
// ---- 渠道(号池)----
export function listAiChannels(): Promise<AiChannel[]> {
// mock 缺此分支时请求会打到真后端,mock token 401 导致演示模式被登出
if (mockOn) return mocked([])
return request<{ items: AiChannel[] }>('/ai-channels').then((r) => r.items)
}
+2 -2
View File
@@ -17,9 +17,9 @@ export function getInstanceTraffic(
export interface CostQuery {
startTime?: string
endTime?: string
granularity?: 'DAILY' | 'MONTHLY'
granularity?: 'HOURLY' | 'DAILY' | 'MONTHLY'
queryType?: 'COST' | 'USAGE'
groupBy?: 'service' | 'skuName' | 'region' | 'compartmentName'
groupBy?: 'service' | 'skuName' | 'region' | 'compartmentName' | 'service,skuName'
}
export function getCosts(cfgId: number, query: CostQuery = {}): Promise<CostItem[]> {
+51
View File
@@ -0,0 +1,51 @@
import { mockInvoiceLines, mockInvoices, mockPaymentMethods } from './mock'
import { mockOn, mocked, rawFetch, request } from './request'
import type { Invoice, InvoiceLine, PaymentMethod } from '@/types/api'
// 账单(OSP Gateway):发票数据挂租户主区域,面板后端代理转发。
/** 列出发票;year 传自然年按开票时间过滤(前端按年懒加载),缺省全量 */
export function listInvoices(id: number, year?: number): Promise<Invoice[]> {
if (mockOn)
return mocked(
year ? mockInvoices.filter((i) => (i.timeInvoice ?? '').startsWith(String(year))) : mockInvoices,
)
return request(`/oci-configs/${id}/invoices`, { query: { year } })
}
export function listInvoiceLines(id: number, internalId: string): Promise<InvoiceLine[]> {
if (mockOn) return mocked(mockInvoiceLines)
return request(`/oci-configs/${id}/invoices/${encodeURIComponent(internalId)}/lines`)
}
/** 按订阅默认付款方式支付发票;email 接收 OSP 付款回执 */
export function payInvoice(id: number, internalId: string, email: string): Promise<{ status: string }> {
if (mockOn) return mocked({ status: 'submitted' })
return request(`/oci-configs/${id}/invoices/${encodeURIComponent(internalId)}/pay`, {
method: 'POST',
body: { email },
})
}
export function listPaymentMethods(id: number): Promise<PaymentMethod[]> {
if (mockOn) return mocked(mockPaymentMethods)
return request(`/oci-configs/${id}/payment-methods`)
}
/** 拉取发票 PDF 原文(接口带 JWT 不能裸链接);预览与下载共用 */
export function fetchInvoicePdf(id: number, internalId: string): Promise<Blob> {
if (mockOn) return fetch('/mock-samples/sample.pdf').then((r) => r.blob())
return rawFetch(`/oci-configs/${id}/invoices/${encodeURIComponent(internalId)}/pdf`).then((r) =>
r.blob(),
)
}
/** 触发浏览器保存(blob 已在手时用,如预览框内下载) */
export function saveInvoicePdf(blob: Blob, name: string) {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${name}.pdf`
a.click()
URL.revokeObjectURL(url)
}
+42 -1
View File
@@ -187,7 +187,35 @@ export function removeIpv6(
// ---- VNIC 管理 ----
export function listVnics(cfgId: number, instanceId: string, region?: string): Promise<Vnic[]> {
if (mockOn) return mocked([])
if (mockOn)
return mocked([
{
attachmentId: 'ocid1.vnicattachment..a1',
vnicId: 'ocid1.vnic..v1',
displayName: instanceId.slice(-12),
isPrimary: true,
privateIp: '10.0.0.11',
publicIp: '141.147.60.10',
ipv6Addresses: ['2603:c020:400d:aa01::1'],
subnetId: 'ocid1.subnet..pub',
subnetName: 'public-subnet',
lifecycleState: 'ATTACHED',
timeCreated: '2026-05-20T14:32:00Z',
},
{
attachmentId: 'ocid1.vnicattachment..a2',
vnicId: 'ocid1.vnic..v2',
displayName: 'vnic-secondary',
isPrimary: false,
privateIp: '10.0.0.12',
publicIp: '',
ipv6Addresses: [],
subnetId: 'ocid1.subnet..pub',
subnetName: 'public-subnet',
lifecycleState: 'ATTACHED',
timeCreated: '2026-07-20T08:00:00Z',
},
])
return request(`/oci-configs/${cfgId}/instances/${encodeURIComponent(instanceId)}/vnics`, {
query: { region },
})
@@ -213,6 +241,19 @@ export function detachVnic(cfgId: number, attachmentId: string, region?: string)
})
}
/** 更换指定 VNIC 的临时公网 IP,返回新地址;绑定保留 IP 的网卡会被拒绝 */
export function changeVnicPublicIp(
cfgId: number,
vnicId: string,
region?: string,
): Promise<{ publicIp: string }> {
if (mockOn) return mocked({ publicIp: '130.61.99.7' }, 800)
return request(`/oci-configs/${cfgId}/vnics/${encodeURIComponent(vnicId)}/change-public-ip`, {
method: 'POST',
body: { region: region ?? '' },
})
}
/** 为指定 VNIC 添加 IPv6address 留空自动分配。删除复用实例级 removeIpv6(按地址遍历全部网卡) */
export function addVnicIpv6(
cfgId: number,
+245
View File
@@ -1,4 +1,8 @@
import type {
Bucket,
ObjectSummary,
Par,
ReservedIp,
SecuritySetting,
AuditEvent,
BootVolume,
@@ -14,6 +18,8 @@ import type {
ImageInfo,
Instance,
InstanceTraffic,
Invoice,
InvoiceLine,
Ipv6Report,
LimitItem,
LogEvent,
@@ -23,6 +29,7 @@ import type {
OciConfig,
Overview,
PasswordPolicy,
PaymentMethod,
RegionInfo,
RegionSubscription,
SecurityList,
@@ -509,6 +516,7 @@ export const mockRegionSubs: RegionSubscription[] = [
]
export const mockLimits: LimitItem[] = [
// A1:三个 AD 均有配额 + 区域总额(镜像真实免费租户形态)
{
name: 'standard-a1-core-count',
scopeType: 'AD',
@@ -517,6 +525,19 @@ export const mockLimits: LimitItem[] = [
used: 4,
available: 0,
},
{
name: 'standard-a1-core-count',
scopeType: 'AD',
availabilityDomain: 'RssO:EU-FRANKFURT-1-AD-2',
value: 4,
},
{
name: 'standard-a1-core-count',
scopeType: 'AD',
availabilityDomain: 'RssO:EU-FRANKFURT-1-AD-3',
value: 4,
},
{ name: 'standard-a1-core-regional-count', scopeType: 'REGION', value: 4 },
{
name: 'standard-a1-memory-count',
scopeType: 'AD',
@@ -525,14 +546,27 @@ export const mockLimits: LimitItem[] = [
used: 24,
available: 0,
},
// Micro:仅 AD-2 有配额(AD 受限 shape,驱动创建表单自动落位)
{
name: 'standard-e2-micro-core-count',
scopeType: 'AD',
availabilityDomain: 'RssO:EU-FRANKFURT-1-AD-1',
value: 0,
},
{
name: 'standard-e2-micro-core-count',
scopeType: 'AD',
availabilityDomain: 'RssO:EU-FRANKFURT-1-AD-2',
value: 2,
used: 1,
available: 1,
},
{
name: 'standard-e2-micro-core-count',
scopeType: 'AD',
availabilityDomain: 'RssO:EU-FRANKFURT-1-AD-3',
value: 0,
},
{
name: 'standard-e4-core-count',
scopeType: 'AD',
@@ -542,6 +576,15 @@ export const mockLimits: LimitItem[] = [
available: 4,
},
{ name: 'vcn-count', scopeType: 'REGION', value: 50, used: 2, available: 48 },
// 对象存储:额度条数据源(免费号 20GB 上限)
{
name: 'storage-bytes',
scopeType: 'REGION',
value: 21474836480,
used: 2003218,
available: 21472833262,
},
{ name: 'bucket-count', scopeType: 'REGION', value: 10000, used: 5, available: 9995 },
{ name: 'volume-backup-count', scopeType: 'REGION', value: 100, used: 6, available: 94 },
]
@@ -995,6 +1038,128 @@ export const mockTraffic: InstanceTraffic = {
],
}
export const mockBuckets: Bucket[] = [
{
name: 'backups',
namespace: 'mocknamespace',
visibility: 'NoPublicAccess',
storageTier: 'Standard',
versioningOn: true,
approximateCount: 128,
approximateSize: 4.2 * 1024 ** 3,
timeCreated: '2025-11-03T14:20:00Z',
},
{
name: 'static-assets',
namespace: 'mocknamespace',
visibility: 'ObjectRead',
storageTier: 'Standard',
versioningOn: false,
approximateCount: 56,
approximateSize: 820 * 1024 ** 2,
timeCreated: '2025-12-18T09:41:00Z',
},
// 超长桶名样本:走查删除确认标题 / 桶设置弹窗的截断表现
{
name: 'oci-logs._flowlogs.ocid1.tenancy.oc1..aaaaaaaa57ydufmess6ni2vsjjkfmvbi',
namespace: 'mocknamespace',
visibility: 'NoPublicAccess',
storageTier: 'Standard',
versioningOn: false,
approximateCount: 3021,
approximateSize: 1.1 * 1024 ** 3,
timeCreated: '2026-03-22T06:10:00Z',
},
]
export const mockObjects: ObjectSummary[] = [
{ name: 'db/daily/app-0718.sql.gz', size: 3.2 * 1024 ** 3, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-18T03:30:00Z' },
{ name: 'db/app.sql.gz', size: 3.4 * 1024 ** 3, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-19T03:30:00Z' },
{ name: 'db/wal-0007.tar', size: 1.7 * 1024 ** 3, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-18T03:30:00Z' },
{ name: 'db/2025-snapshot.tar', size: 890 * 1024 ** 2, storageTier: 'Archive', archivalState: 'Archived', timeModified: '2026-01-02T22:05:00Z' },
{ name: 'config.yaml', size: 2100, storageTier: 'Standard', archivalState: '', timeModified: '2026-06-30T11:02:00Z' },
{ name: 'README.md', size: 1800, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-15T08:20:00Z' },
{ name: 'logo.svg', size: 2400, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-10T15:44:00Z' },
{ name: '季度报告.docx', size: 384 * 1024, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-08T09:12:00Z' },
{ name: '预算表.xlsx', size: 92 * 1024, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-12T14:03:00Z' },
{ name: '发布计划.pptx', size: 1.6 * 1024 ** 2, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-17T10:30:00Z' },
{ name: '架构说明.pdf', size: 512, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-19T16:40:00Z' },
{ name: 'gateway.json', size: 84, storageTier: 'Standard', archivalState: '', timeModified: '2026-07-20T09:10:00Z' },
]
/** mock 对象文本内容(面板中转预览/编辑用);office/pdf 经 /mock-samples/ 静态样例提供 */
export const mockObjectContents: Record<string, string> = {
'gateway.json': `{"name":"gw","port":8080,"tls":true,"upstreams":["10.0.0.2","10.0.0.3"],"limits":{"burst":64}}`,
'config.yaml': `server:
port: 8080
host: 0.0.0.0
database:
driver: sqlite
path: /data/app.db
log:
level: info
format: json
`,
'README.md': `# 对象存储示例
这是一段 **markdown** 预览示例,支持围栏代码块高亮:
\`\`\`python
def hello(name: str) -> str:
return f"hello {name}"
\`\`\`
\`\`\`bash
pip install -r requirements.txt
python main.py --port 8080
\`\`\`
- 列表项一
- 列表项二
> 引用块:预览与编辑经面板中转,不再签发 PAR。
`,
'logo.svg': `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120">
<circle cx="60" cy="60" r="50" fill="#C96442" />
<text x="60" y="68" text-anchor="middle" font-size="28" fill="#fff">OCI</text>
</svg>
`,
}
export const mockPars: Par[] = [
{
id: 'par-mock-1',
name: 'par-db-app.sql.gz',
objectName: 'db/app.sql.gz',
accessType: 'ObjectRead',
timeExpires: '2026-07-21T03:30:00Z',
timeCreated: '2026-07-20T03:30:00Z',
},
]
export const mockReservedIps: ReservedIp[] = [
{
id: 'ocid1.publicip.oc1..r1',
displayName: 'tokyo-keep-1',
ipAddress: '155.248.200.10',
lifecycleState: 'ASSIGNED',
assignedInstanceId: 'ocid1.instance.oc1..inst1',
assignedInstanceName: 'tokyo-web-1',
timeCreated: '2026-05-12T08:00:00Z',
},
{
id: 'ocid1.publicip.oc1..r2',
displayName: 'spare-ip',
ipAddress: '152.69.198.88',
lifecycleState: 'AVAILABLE',
assignedInstanceId: '',
assignedInstanceName: '',
timeCreated: '2026-07-01T02:00:00Z',
},
]
export const mockVcns: Record<number, Vcn[]> = {
1: [
{
@@ -1269,6 +1434,14 @@ export const mockCompartments: Record<number, Compartment[]> = {
lifecycleState: 'ACTIVE',
timeCreated: '2026-06-01T00:00:00Z',
},
{
id: 'ocid1.compartment.oc1..devsandbox',
name: 'dev-sandbox',
description: 'dev 下的嵌套子区间',
parentId: 'ocid1.compartment.oc1..dev',
lifecycleState: 'ACTIVE',
timeCreated: '2026-06-10T00:00:00Z',
},
],
}
@@ -1374,6 +1547,12 @@ export const mockShapes: ComputeShape[] = [
memoryMinGBs: 1,
memoryMaxGBs: 512,
processorDescription: '3.0 GHz Ampere® Altra™',
quotaNames: [
'standard-a1-memory-count',
'standard-a1-memory-regional-count',
'standard-a1-core-count',
'standard-a1-core-regional-count',
],
},
{
name: 'VM.Standard.E2.1.Micro',
@@ -1382,6 +1561,7 @@ export const mockShapes: ComputeShape[] = [
ocpus: 1,
memoryInGBs: 1,
processorDescription: '2.0 GHz AMD EPYC™ 7551',
quotaNames: ['standard-e2-micro-core-count'],
},
{
name: 'VM.Standard.E4.Flex',
@@ -1392,6 +1572,7 @@ export const mockShapes: ComputeShape[] = [
memoryMinGBs: 1,
memoryMaxGBs: 1024,
processorDescription: '2.55 GHz AMD EPYC™ 7J13',
quotaNames: ['standard-e4-core-count', 'standard-e4-memory-count'],
},
{
name: 'VM.Standard.E5.Flex',
@@ -1715,3 +1896,67 @@ export const mockLogWebhooks = new Map<number, LogWebhookInfo>()
// OCI 侧回传链路:mock 态记录「已一键创建」的租户
export const mockLogRelays = new Map<number, boolean>()
// ---- 账单:发票 / 明细 / 付款方式 ----
export const mockInvoices: Invoice[] = [
{
id: 'inv-202607', internalId: '61001', number: '100482756', type: 'USAGE', status: 'OPEN',
isPaid: false, isPayable: true, isPaymentFailed: false, amount: 603.53, amountDue: 603.53,
currency: 'USD', timeInvoice: '2026-07-01T00:00:00Z', timeDue: '2026-07-31T00:00:00Z',
},
{
id: 'inv-202606', internalId: '61002', number: '100471203', type: 'USAGE', status: 'PAST_DUE',
isPaid: false, isPayable: true, isPaymentFailed: true, amount: 538.17, amountDue: 538.17,
currency: 'USD', timeInvoice: '2026-06-01T00:00:00Z', timeDue: '2026-06-30T00:00:00Z',
},
{
id: 'inv-202605', internalId: '61003', number: '100458820', type: 'USAGE', status: 'PAYMENT_SUBMITTED',
isPaid: false, isPayable: false, isPaymentFailed: false, amount: 512.4, amountDue: 512.4,
currency: 'USD', timeInvoice: '2026-05-01T00:00:00Z', timeDue: '2026-05-31T00:00:00Z',
},
{
id: 'inv-202604', internalId: '61004', number: '100446351', type: 'USAGE', status: 'CLOSED',
isPaid: true, isPayable: false, isPaymentFailed: false, amount: 529.02, amountDue: 0,
currency: 'USD', timeInvoice: '2026-04-01T00:00:00Z', timeDue: '2026-04-30T00:00:00Z',
},
{
id: 'inv-202603', internalId: '61005', number: '100433978', type: 'USAGE', status: 'CLOSED',
isPaid: true, isPayable: false, isPaymentFailed: false, amount: 498.75, amountDue: 0,
currency: 'USD', timeInvoice: '2026-03-01T00:00:00Z', timeDue: '2026-03-31T00:00:00Z',
},
{
id: 'inv-202602', internalId: '61006', number: '100421510', type: 'USAGE', status: 'CLOSED',
isPaid: true, isPayable: false, isPaymentFailed: false, amount: 533.19, amountDue: 0,
currency: 'USD', timeInvoice: '2026-02-01T00:00:00Z', timeDue: '2026-02-28T00:00:00Z',
},
{
id: 'inv-202512', internalId: '61007', number: '100409112', type: 'USAGE', status: 'CLOSED',
isPaid: true, isPayable: false, isPaymentFailed: false, amount: 476.4, amountDue: 0,
currency: 'USD', timeInvoice: '2025-12-01T00:00:00Z', timeDue: '2025-12-31T00:00:00Z',
},
{
id: 'inv-202511', internalId: '61008', number: '100396805', type: 'USAGE', status: 'CLOSED',
isPaid: true, isPayable: false, isPaymentFailed: false, amount: 441.87, amountDue: 0,
currency: 'USD', timeInvoice: '2025-11-01T00:00:00Z', timeDue: '2025-11-30T00:00:00Z',
},
]
export const mockInvoiceLines: InvoiceLine[] = [
{ product: 'Compute - Standard.E4.Flex - OCPU', orderNo: '89S1024', quantity: 744, unitPrice: 0.025, total: 18.6, currency: 'USD', timeStart: '2026-07-01T00:00:00Z', timeEnd: '2026-07-31T00:00:00Z' },
{ product: 'Compute - Standard.E4.Flex - Memory', orderNo: '89S1024', quantity: 11904, unitPrice: 0.0015, total: 17.86, currency: 'USD', timeStart: '2026-07-01T00:00:00Z', timeEnd: '2026-07-31T00:00:00Z' },
{ product: 'Block Volume - Performance Units', orderNo: '89S1024', quantity: 1488, unitPrice: 0.0017, total: 2.53, currency: 'USD', timeStart: '2026-07-01T00:00:00Z', timeEnd: '2026-07-31T00:00:00Z' },
{ product: 'Object Storage - Standard', orderNo: '89S1024', quantity: 512, unitPrice: 0.0255, total: 13.06, currency: 'USD', timeStart: '2026-07-01T00:00:00Z', timeEnd: '2026-07-31T00:00:00Z' },
{ product: 'Outbound Data Transfer', orderNo: '89S1024', quantity: 2048, unitPrice: 0.0085, total: 17.41, currency: 'USD', timeStart: '2026-07-01T00:00:00Z', timeEnd: '2026-07-31T00:00:00Z' },
{ product: 'Generative AI - Large Chat Tokens', orderNo: '89S1024', quantity: 3560.4, unitPrice: 0.15, total: 534.07, currency: 'USD', timeStart: '2026-07-01T00:00:00Z', timeEnd: '2026-07-31T00:00:00Z' },
]
export const mockPaymentMethods: PaymentMethod[] = [
{
method: 'CREDIT_CARD', cardType: 'VISA', lastDigits: '4242',
nameOnCard: 'LI MING', timeExpiration: '2028-08-01T00:00:00Z',
},
{
method: 'PAYPAL', email: 'billing@example.com', payerName: 'Li Ming',
billingAgreement: 'B-7KX3H2M9L4T9F2',
},
]
+20 -1
View File
@@ -1,6 +1,6 @@
import { mockIpv6Report, mockSecurityLists, mockSubnets, mockVcns } from './mock'
import { mockOn, mocked, request } from './request'
import type { CreateVcnRequest, Ipv6Report, SecurityList, Subnet, Vcn } from '@/types/api'
import type { CreateVcnRequest, Ipv6Report, SecurityList, SecurityRule, Subnet, Vcn } from '@/types/api'
export function listVcns(cfgId: number, region?: string, compartmentId?: string): Promise<Vcn[]> {
if (mockOn) return mocked(compartmentId ? [] : (mockVcns[cfgId] ?? []))
@@ -64,3 +64,22 @@ export function listSecurityLists(
if (mockOn) return mocked(mockSecurityLists.filter((s) => s.vcnId === vcnId || vcnId === ''))
return request(`/oci-configs/${cfgId}/security-lists`, { query: { vcnId, region } })
}
/** 更新安全列表;规则字段一经提供即整体替换,region 随请求体传递 */
export function updateSecurityList(
cfgId: number,
securityListId: string,
body: { region?: string; displayName?: string; ingressRules?: SecurityRule[]; egressRules?: SecurityRule[] },
): Promise<SecurityList> {
if (mockOn) {
const found = mockSecurityLists.find((s) => s.id === securityListId)
if (!found) return Promise.reject(new Error('安全列表不存在'))
if (body.ingressRules) found.ingressRules = body.ingressRules
if (body.egressRules) found.egressRules = body.egressRules
return mocked({ ...found }, 500)
}
return request(`/oci-configs/${cfgId}/security-lists/${encodeURIComponent(securityListId)}`, {
method: 'PUT',
body,
})
}
+361
View File
@@ -0,0 +1,361 @@
import { mockBuckets, mockObjectContents, mockObjects, mockPars } from './mock'
import { mockOn, mocked, rawFetch, request } from './request'
import type { Bucket, ListObjectsResult, ObjectDetail, Par, ParPage } from '@/types/api'
export function listBuckets(
cfgId: number,
region?: string,
compartmentId?: string,
): Promise<Bucket[]> {
if (mockOn) return mocked([...mockBuckets])
return request(`/oci-configs/${cfgId}/buckets`, { query: { region, compartmentId } })
}
export function createBucket(
cfgId: number,
body: {
region?: string
compartmentId?: string
name: string
publicRead?: boolean
storageTier?: string
versioningOn?: boolean
},
): Promise<Bucket> {
if (mockOn) {
const b: Bucket = {
name: body.name,
namespace: 'mocknamespace',
visibility: body.publicRead ? 'ObjectRead' : 'NoPublicAccess',
storageTier: body.storageTier || 'Standard',
versioningOn: !!body.versioningOn,
approximateCount: 0,
approximateSize: 0,
timeCreated: new Date().toISOString(),
}
mockBuckets.push(b)
return mocked(b, 600)
}
return request(`/oci-configs/${cfgId}/buckets`, { method: 'POST', body })
}
export function updateBucket(
cfgId: number,
bucket: string,
body: { region?: string; publicRead?: boolean; versioningOn?: boolean },
): Promise<Bucket> {
if (mockOn) {
const found = mockBuckets.find((b) => b.name === bucket)
if (!found) return Promise.reject(new Error('桶不存在'))
if (body.publicRead !== undefined)
found.visibility = body.publicRead ? 'ObjectRead' : 'NoPublicAccess'
if (body.versioningOn !== undefined) found.versioningOn = body.versioningOn
return mocked({ ...found }, 400)
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}`, {
method: 'PUT',
body,
})
}
/** queued=true 表示非空桶已转后台清空(对象全部版本+PAR)后删除 */
export function deleteBucket(
cfgId: number,
bucket: string,
region?: string,
): Promise<{ queued: boolean }> {
if (mockOn) {
const idx = mockBuckets.findIndex((b) => b.name === bucket)
if (idx >= 0) mockBuckets.splice(idx, 1)
return mocked({ queued: false })
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}`, {
method: 'DELETE',
query: { region },
})
}
export function listObjects(
cfgId: number,
bucket: string,
opts: { region?: string; prefix?: string; startWith?: string; limit?: number } = {},
): Promise<ListObjectsResult> {
if (mockOn) {
const prefix = opts.prefix ?? ''
const inScope = mockObjects.filter((o) => o.name.startsWith(prefix))
const prefixes = new Set<string>()
const objects = inScope.filter((o) => {
const rest = o.name.slice(prefix.length)
const slash = rest.indexOf('/')
if (slash < 0) return true
prefixes.add(prefix + rest.slice(0, slash + 1))
return false
})
return mocked({ objects, prefixes: [...prefixes], nextStartWith: '' })
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects`, {
query: {
region: opts.region,
prefix: opts.prefix || undefined,
startWith: opts.startWith || undefined,
limit: opts.limit,
},
})
}
export function deleteObject(
cfgId: number,
bucket: string,
object: string,
region?: string,
): Promise<void> {
if (mockOn) {
const idx = mockObjects.findIndex((o) => o.name === object)
if (idx >= 0) mockObjects.splice(idx, 1)
return mocked(undefined)
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects`, {
method: 'DELETE',
query: { region, object },
})
}
export function renameObject(
cfgId: number,
bucket: string,
source: string,
newName: string,
region?: string,
): Promise<void> {
if (mockOn) {
const found = mockObjects.find((o) => o.name === source)
if (found) found.name = newName
return mocked(undefined, 400)
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects/rename`, {
method: 'POST',
body: { region: region ?? '', source, newName },
})
}
export function restoreObject(
cfgId: number,
bucket: string,
object: string,
region?: string,
hours?: number,
): Promise<void> {
if (mockOn) {
// mock 态模拟取回中,便于走查「取回中」标签与后台轮询
const o = mockObjects.find((x) => x.name === object)
if (o) o.archivalState = 'Restoring'
return mocked(undefined, 500)
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects/restore`, {
method: 'POST',
body: { region: region ?? '', object, hours },
})
}
export function getObjectDetail(
cfgId: number,
bucket: string,
object: string,
region?: string,
): Promise<ObjectDetail> {
if (mockOn) {
const found = mockObjects.find((o) => o.name === object)
if (!found) return Promise.reject(new Error('对象不存在'))
return mocked({
name: found.name,
size: found.size,
contentType: 'application/octet-stream',
etag: 'a1b2c3d4-mock',
contentMd5: 'tYx0mockkQ==',
storageTier: found.storageTier,
archivalState: found.archivalState,
timeModified: found.timeModified,
metadata: null,
})
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects/detail`, {
query: { region, object },
})
}
export interface ObjectContent {
blob: Blob
contentType: string
etag: string
}
/** 读取对象内容(面板中转,不签发 PAR);超过 20MB 后端返回 413 */
export async function getObjectContent(
cfgId: number,
bucket: string,
object: string,
region?: string,
): Promise<ObjectContent> {
if (mockOn) return mockGetContent(object)
const resp = await rawFetch(
`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects/content`,
{ query: { region, object } },
)
return {
blob: await resp.blob(),
contentType: resp.headers.get('Content-Type') ?? '',
etag: resp.headers.get('ETag') ?? '',
}
}
const MOCK_CT: Record<string, string> = { md: 'text/markdown', svg: 'image/svg+xml' }
/** mock:文本走内容表,office/pdf 走 /mock-samples/ 静态样例 */
async function mockGetContent(object: string): Promise<ObjectContent> {
const ext = object.split('.').pop()?.toLowerCase() ?? ''
const text = mockObjectContents[object]
if (text !== undefined) {
await mocked(undefined, 300)
const ct = MOCK_CT[ext] ?? 'text/plain'
return { blob: new Blob([text], { type: ct }), contentType: ct, etag: 'mock-etag-1' }
}
// dev server 对不存在路径回退 index.html(200),按 Content-Type 识别缺样例
const resp = await fetch(`/mock-samples/sample.${ext}`)
if (!resp.ok || (resp.headers.get('Content-Type') ?? '').includes('text/html'))
throw new Error('mock 环境无该对象的样例内容')
return {
blob: await resp.blob(),
contentType: resp.headers.get('Content-Type') ?? '',
etag: 'mock-etag-1',
}
}
/** 保存对象内容(面板中转);ifMatch 冲突时抛 ApiError(status=412) */
export async function putObjectContent(
cfgId: number,
bucket: string,
object: string,
data: Blob | string,
contentType?: string,
ifMatch?: string,
region?: string,
): Promise<{ etag: string }> {
if (mockOn) return mockPutContent(object, data)
const headers: Record<string, string> = {}
if (contentType) headers['Content-Type'] = contentType
if (ifMatch) headers['If-Match'] = ifMatch
const resp = await rawFetch(
`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/objects/content`,
{ method: 'PUT', query: { region, object }, headers, body: data },
)
return (await resp.json()) as { etag: string }
}
async function mockPutContent(object: string, data: Blob | string): Promise<{ etag: string }> {
const text = typeof data === 'string' ? data : ''
mockObjectContents[object] = text
const found = mockObjects.find((o) => o.name === object)
if (found) {
found.size = typeof data === 'string' ? new Blob([data]).size : data.size
found.timeModified = new Date().toISOString()
}
return mocked({ etag: `mock-etag-${Date.now()}` }, 400)
}
export function createPar(
cfgId: number,
bucket: string,
body: {
region?: string
name?: string
objectName?: string
accessType: string
expiresHours?: number
},
): Promise<Par> {
if (mockOn) {
const par: Par = {
id: `par-${Date.now()}`,
name: body.name || `par-${body.objectName ?? bucket}`,
objectName: body.objectName ?? '',
accessType: body.accessType,
fullUrl: `https://objectstorage.mock.oraclecloud.com/p/tOkEn/n/mocknamespace/b/${bucket}/o/${encodeURIComponent(body.objectName ?? '')}`,
timeExpires: new Date(Date.now() + (body.expiresHours ?? 24) * 3600e3).toISOString(),
timeCreated: new Date().toISOString(),
}
mockPars.push({ ...par, fullUrl: undefined })
return mocked(par, 500)
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/pars`, {
method: 'POST',
body,
})
}
export function listPars(
cfgId: number,
bucket: string,
opts: { region?: string; page?: string; limit?: number } = {},
): Promise<ParPage> {
if (mockOn) return mocked({ items: [...mockPars], nextPage: '' })
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/pars`, {
query: { region: opts.region, page: opts.page, limit: opts.limit },
})
}
export function deletePar(
cfgId: number,
bucket: string,
parId: string,
region?: string,
): Promise<void> {
if (mockOn) {
const idx = mockPars.findIndex((p) => p.id === parId)
if (idx >= 0) mockPars.splice(idx, 1)
return mocked(undefined)
}
// parId 含 "/" 等字符,路径参数无法匹配路由,经 query 传递
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/pars`, {
method: 'DELETE',
query: { region, parId },
})
}
export function deleteAllPars(
cfgId: number,
bucket: string,
region?: string,
): Promise<{ deleted: number }> {
if (mockOn) {
const n = mockPars.length
mockPars.splice(0)
return mocked({ deleted: n }, 400)
}
return request(`/oci-configs/${cfgId}/buckets/${encodeURIComponent(bucket)}/pars`, {
method: 'DELETE',
query: { region, all: '1' },
})
}
/** 经预签名 PAR 直传对象到 OCI(不经面板中转),onProgress 回调 0-100 */
export function uploadViaPar(
parUrl: string,
file: File,
onProgress: (percent: number) => void,
): { promise: Promise<void>; abort: () => void } {
const xhr = new XMLHttpRequest()
const promise = new Promise<void>((resolve, reject) => {
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100))
}
xhr.onload = () =>
xhr.status >= 200 && xhr.status < 300
? resolve()
: reject(new Error(`上传失败(HTTP ${xhr.status})`))
xhr.onerror = () => reject(new Error('上传失败(网络错误)'))
xhr.onabort = () => reject(new Error('已取消上传'))
xhr.open('PUT', parUrl)
xhr.send(file)
})
return { promise, abort: () => xhr.abort() }
}
+46 -6
View File
@@ -4,10 +4,13 @@ const BASE = '/api/v1'
export class ApiError extends Error {
status: number
/** 后端透传的 OCI 错误码(如 OrganizationExclusionError),供调用方做能力适配 */
ociCode?: string
constructor(status: number, message: string) {
constructor(status: number, message: string, ociCode?: string) {
super(message)
this.status = status
this.ociCode = ociCode
}
}
@@ -31,9 +34,23 @@ function buildUrl(path: string, query?: RequestOptions['query']): string {
async function parseError(resp: Response): Promise<never> {
let message = `请求失败(${resp.status}`
let ociCode: string | undefined
try {
const body = (await resp.json()) as { error?: string; hint?: string }
if (body.error) message = body.hint ? `${body.hint}${body.error}` : body.error
const body = (await resp.json()) as {
error?: string
hint?: string
errors?: unknown[]
ociCode?: string
}
ociCode = body.ociCode
if (body.error) {
message = body.hint ? `${body.hint}${body.error}` : body.error
} else {
// 批量接口(如创建实例)全部失败时返回 errors 数组,逐行合并;
// 调用方以「短标题 + detail」经 useToast 展示,多行在详情块中逐行可读
const list = (body.errors ?? []).filter((e): e is string => typeof e === 'string')
if (list.length) message = list.join('\n')
}
} catch {
/* 非 JSON 响应体,保留默认消息 */
}
@@ -42,7 +59,7 @@ async function parseError(resp: Response): Promise<never> {
if (resp.status === 429 && !resp.url.includes('/auth/login') && location.pathname !== '/blocked') {
location.assign('/blocked')
}
throw new ApiError(resp.status, message)
throw new ApiError(resp.status, message, ociCode)
}
/** 统一请求封装:注入 JWT、401 登出、错误转 ApiError */
@@ -56,8 +73,31 @@ export async function request<T>(path: string, opts: RequestOptions = {}): Promi
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
})
if (!resp.ok) await parseError(resp)
if (resp.status === 204) return undefined as T
return (await resp.json()) as T
// 202/204 等成功响应可能无 body,直接 resp.json() 会抛 Unexpected end of JSON input
const text = await resp.text()
return (text ? JSON.parse(text) : undefined) as T
}
/** 原始请求:注入 JWT、错误同 request 转 ApiError,返回原始 Response(二进制内容读写用) */
export async function rawFetch(
path: string,
opts: {
method?: string
query?: RequestOptions['query']
headers?: Record<string, string>
body?: BodyInit
} = {},
): Promise<Response> {
const auth = useAuthStore()
const headers: Record<string, string> = { ...opts.headers }
if (auth.token) headers.Authorization = `Bearer ${auth.token}`
const resp = await fetch(buildUrl(path, opts.query), {
method: opts.method ?? 'GET',
headers,
body: opts.body,
})
if (!resp.ok) await parseError(resp)
return resp
}
export const mockOn = import.meta.env.VITE_MOCK === '1'
+75
View File
@@ -0,0 +1,75 @@
import { mockReservedIps } from './mock'
import { mockOn, mocked, request } from './request'
import type { ReservedIp } from '@/types/api'
export function listReservedIps(
cfgId: number,
region?: string,
compartmentId?: string,
): Promise<ReservedIp[]> {
if (mockOn) return mocked([...mockReservedIps])
return request(`/oci-configs/${cfgId}/reserved-ips`, { query: { region, compartmentId } })
}
export function createReservedIp(
cfgId: number,
region?: string,
displayName?: string,
compartmentId?: string,
): Promise<ReservedIp> {
if (mockOn) {
const ip: ReservedIp = {
id: `ocid1.publicip..${Date.now()}`,
displayName: displayName || 'reserved-ip',
ipAddress: '155.248.201.77',
lifecycleState: 'AVAILABLE',
assignedInstanceId: '',
assignedInstanceName: '',
timeCreated: new Date().toISOString(),
}
mockReservedIps.push(ip)
return mocked(ip, 600)
}
return request(`/oci-configs/${cfgId}/reserved-ips`, {
method: 'POST',
body: { region: region ?? '', compartmentId: compartmentId ?? '', displayName },
})
}
/** vnicId 非空绑到该网卡,否则绑 instanceId 主网卡;两者都空表示解绑 */
export function assignReservedIp(
cfgId: number,
publicIpId: string,
instanceId: string,
region?: string,
vnicId?: string,
): Promise<void> {
if (mockOn) {
const found = mockReservedIps.find((r) => r.id === publicIpId)
if (found) {
found.assignedInstanceId = instanceId || (vnicId ? 'ocid1.instance.oc1..byvnic' : '')
found.assignedInstanceName = instanceId || vnicId ? 'mock-instance' : ''
}
return mocked(undefined, 500)
}
return request(`/oci-configs/${cfgId}/reserved-ips/${encodeURIComponent(publicIpId)}`, {
method: 'PUT',
body: { region: region ?? '', instanceId, vnicId: vnicId ?? '' },
})
}
export function deleteReservedIp(
cfgId: number,
publicIpId: string,
region?: string,
): Promise<void> {
if (mockOn) {
const idx = mockReservedIps.findIndex((r) => r.id === publicIpId)
if (idx >= 0) mockReservedIps.splice(idx, 1)
return mocked(undefined)
}
return request(`/oci-configs/${cfgId}/reserved-ips/${encodeURIComponent(publicIpId)}`, {
method: 'DELETE',
query: { region },
})
}
+15 -8
View File
@@ -182,17 +182,24 @@ export function deleteUserApiKeys(
// ---- 审计日志 ----
/** 批式懒加载查询审计事件:cursor 空自当前时刻首查,
* 非空从上次响应游标向更早续取一批(~100 条,服务端分窗回溯) */
* 非空从上次响应游标向更早续取一批(~200 条,服务端分窗回溯);
* q 为服务端全文检索关键字,仅首查生效(续查沿用游标内嵌关键字) */
export function listAuditEvents(
id: number,
opts: { region?: string; cursor?: string; limit?: number } = {},
opts: { region?: string; cursor?: string; limit?: number; q?: string } = {},
): Promise<AuditEventsResult> {
// mock:首批带游标,续查一批后到尽头,演示懒加载链路
if (mockOn)
return mocked(
{ items: mockAuditEvents, cursor: opts.cursor ? undefined : 'mock-cursor', exhausted: !!opts.cursor },
300,
)
// mock:首批带游标,续查一批后到尽头,演示懒加载链路;q 演示不区分大小写的包含匹配
if (mockOn) {
const kw = (opts.q ?? '').replace(/\*/g, '').toLowerCase()
const items = kw
? mockAuditEvents.filter((e) =>
[e.eventName, e.resourceName, e.principalName, e.ipAddress, e.source].some((v) =>
(v ?? '').toLowerCase().includes(kw),
),
)
: mockAuditEvents
return mocked({ items, cursor: opts.cursor ? undefined : 'mock-cursor', exhausted: !!opts.cursor }, 300)
}
return request(`/oci-configs/${id}/audit-events`, { query: { ...opts } })
}
+128
View File
@@ -25,6 +25,9 @@
-apple-system, 'SF Pro Text', 'Helvetica Neue', 'PingFang SC', 'Noto Sans SC', sans-serif;
--font-serif: Georgia, 'Times New Roman', 'Songti SC', serif;
--font-mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
/* 浮层(下拉/整页提示卡)统一投影:比卡片的 1px 分层重一档,仍保持克制 */
--shadow-overlay: 0 8px 24px rgba(20, 20, 19, 0.1);
}
/* 暗色主题:html.dark 由 stores/app.ts 挂载,色值与 tokens.ts 的 darkTokens 同步 */
@@ -81,6 +84,42 @@ body {
background: color-mix(in srgb, var(--color-ink) 38%, transparent);
}
/* 表格滚动条常显:Naive 隐藏原生条(scrollbar-width:none)后全靠自绘 thumb,
而自绘条仅悬停时短暂出现且渲染链路脆弱,窄容器下用户无从得知表格可横滚。
现代 Chromium(121+)只认标准属性——computed 为 none 时 ::-webkit-* 规则
整体失效,故必须以更高特异性覆盖 scrollbar-width 本身(样式随全局瘦滚动条);
webkit 伪元素规则兜底老内核(Naive 把 scrollbar/thumb 清零,须逐项放开) */
.n-data-table .n-scrollbar > .n-scrollbar-container {
scrollbar-width: thin;
}
.n-data-table .n-scrollbar > .n-scrollbar-container::-webkit-scrollbar:horizontal {
display: block;
height: 7px;
background: transparent;
}
.n-data-table .n-scrollbar > .n-scrollbar-container::-webkit-scrollbar-thumb:horizontal {
display: block;
height: 7px;
border-radius: 4px;
background: color-mix(in srgb, var(--color-ink) 22%, transparent);
}
/* 租户选择器面板(移动端):popover follower 只会翻转不会平移,窄屏下
bottom-start / bottom-end 两个方向都放不下整块面板,必然被视口裁切;
改为覆盖 follower 定位,固定顶部整宽展示(follower 挂 body 下,无
transform 祖先,fixed 相对视口生效) */
@media (max-width: 767px) {
.v-binder-follower-content:has(.tenant-picker-panel) {
position: fixed !important;
inset: 60px 12px auto 12px !important;
transform: none !important;
}
.v-binder-follower-content:has(.tenant-picker-panel) .n-popover,
.tenant-picker-panel {
width: 100% !important;
}
}
/* 页面标题统一 serif */
.page-title {
font-family: var(--font-serif);
@@ -296,3 +335,92 @@ html.theme-switching *::before,
html.theme-switching *::after {
transition: none !important;
}
/* 区间树形选择器菜单(teleport 至 body,scoped 样式不可达):
容器留白,展开箭头与文本节奏对齐 Select 下拉 */
.n-tree-select-menu .n-tree {
padding: 5px 6px;
}
/* 代码高亮配色(highlight.js 输出):贴设计 token 的低饱和土色系,
预览弹窗与编辑器 overlay 共用;明暗两态随 token 自动切换 */
.code-hl .hljs-comment,
.code-hl .hljs-quote {
color: var(--color-ink-3);
font-style: italic;
}
.code-hl .hljs-keyword,
.code-hl .hljs-selector-tag,
.code-hl .hljs-meta {
color: var(--color-warn);
}
.code-hl .hljs-string,
.code-hl .hljs-regexp {
color: var(--color-ok);
}
.code-hl .hljs-number,
.code-hl .hljs-literal,
.code-hl .hljs-symbol {
color: var(--color-accent);
}
.code-hl .hljs-attr,
.code-hl .hljs-attribute,
.code-hl .hljs-property,
.code-hl .hljs-section,
.code-hl .hljs-selector-class,
.code-hl .hljs-selector-id {
color: var(--color-info);
}
.code-hl .hljs-title,
.code-hl .hljs-name,
.code-hl .hljs-built_in {
color: var(--color-ink);
font-weight: 600;
}
/* 移动端:Tab 条横向滑动;右缘渐隐暗示还有更多 Tab(Naive 无内建暗示),
滚动内容补尾部内边距,滚到底时末个 Tab 不被渐隐吃掉 */
@media (max-width: 767px) {
.n-tabs .n-tabs-nav-scroll-wrapper {
overflow-x: auto;
scrollbar-width: none;
-webkit-mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 28px), transparent);
mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 28px), transparent);
}
.n-tabs .n-tabs-nav-scroll-wrapper::-webkit-scrollbar {
display: none;
}
.n-tabs .n-tabs-nav-scroll-content {
padding-right: 28px;
}
}
/* 弹窗移动端全屏形态,FormModal 与各详情/表单弹窗共用(配 useMobileModal):
NModal teleport 到 body,组件 scoped 样式够不到,且按路由分包后单组件的
非 scoped 样式不保证已加载,故规则放全局。内容区吃满剩余高度限内滚动,
页脚实底常驻含手势区安全距。内容区类名此版本为 .n-card-content(footer
却是 .n-card__footer),两种拼写都盖住防升级回切 */
.form-modal-mobile {
display: flex;
flex-direction: column;
overflow: hidden;
}
.form-modal-mobile .form-modal-body {
max-height: none;
flex: 1;
min-height: 0;
}
.form-modal-mobile .n-card-content,
.form-modal-mobile .n-card__content {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
/* 无内层滚动容器的弹窗(详情类)内容直接在此滚;FormModal 内层
.form-modal-body 自会收缩到容器内,不触发此层滚动 */
overflow-y: auto;
}
.form-modal-mobile .n-card__footer {
padding-bottom: calc(16px + env(safe-area-inset-bottom));
background: var(--color-card);
}
+83
View File
@@ -0,0 +1,83 @@
<script setup lang="ts">
import { NTreeSelect, type TreeSelectOption } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import type { Compartment } from '@/types/api'
/** 区间选择器:按 parentId 组树,与官方控制台一致分层展示;
* 父级不在列表中的节点视为根 compartment 的直接子级,根以 value='' 表示。 */
const props = withDefaults(
defineProps<{
value: string
compartments: Compartment[]
rootLabel: string
loading?: boolean
disabled?: boolean
size?: 'small' | 'medium'
}>(),
{ size: 'small' },
)
const emit = defineEmits<{ 'update:value': [string] }>()
function groupByParent(list: Compartment[]): Map<string, Compartment[]> {
const ids = new Set(list.map((c) => c.id))
const map = new Map<string, Compartment[]>()
for (const c of list) {
const parent = ids.has(c.parentId) ? c.parentId : ''
map.set(parent, [...(map.get(parent) ?? []), c])
}
for (const arr of map.values()) arr.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
return map
}
function toNodes(map: Map<string, Compartment[]>, parent: string): TreeSelectOption[] | undefined {
const list = map.get(parent)
if (!list) return undefined
return list.map((c) => ({ label: c.name, key: c.id, children: toNodes(map, c.id) }))
}
const tree = computed<TreeSelectOption[]>(() => {
const map = groupByParent(props.compartments)
return [{ label: props.rootLabel, key: '', children: toNodes(map, '') }]
})
/** 选项异步加载,default-expand-all 不可靠,改为受控展开全部父节点 */
const expandedKeys = ref<Array<string | number>>([])
watch(
tree,
(nodes) => {
const keys: string[] = []
const walk = (list: TreeSelectOption[]) => {
for (const n of list) {
if (!n.children?.length) continue
keys.push(String(n.key))
walk(n.children)
}
}
walk(nodes)
expandedKeys.value = keys
},
{ immediate: true },
)
function onUpdate(v: string | number | Array<string | number> | null) {
emit('update:value', typeof v === 'string' ? v : '')
}
</script>
<template>
<NTreeSelect
class="min-w-0"
:value="value"
:options="tree"
:expanded-keys="expandedKeys"
:loading="loading"
:disabled="disabled"
:size="size"
:indent="18"
:consistent-menu-width="false"
filterable
@update:value="onUpdate"
@update:expanded-keys="(keys: Array<string | number>) => (expandedKeys = keys)"
/>
</template>
+144
View File
@@ -0,0 +1,144 @@
<script setup lang="ts">
import { NButton, NPopover, type PopoverPlacement } from 'naive-ui'
import { ref } from 'vue'
export type ConfirmKind = 'danger' | 'warn' | 'plain'
/**
* 统一确认气泡:替代 NPopconfirm 默认样式(批次8 设计稿)。
* onConfirm 返回 Promise 时确认按钮进入 loading,期间弹层不可关闭、不可重复提交。
*/
const props = withDefaults(
defineProps<{
title: string
content?: string
note?: string
kind?: ConfirmKind
confirmText?: string
cancelText?: string
placement?: PopoverPlacement
onConfirm?: () => unknown
}>(),
{
kind: 'danger',
confirmText: '确认',
cancelText: '取消',
placement: 'top',
content: undefined,
note: undefined,
onConfirm: undefined,
},
)
const show = ref(false)
const loading = ref(false)
function onUpdateShow(v: boolean) {
if (loading.value) return
show.value = v
}
async function confirm() {
if (loading.value) return
const r = props.onConfirm?.()
if (r instanceof Promise) {
loading.value = true
try {
await r
} finally {
loading.value = false
}
}
show.value = false
}
</script>
<template>
<NPopover
:show="show"
trigger="click"
:placement="placement"
raw
:show-arrow="false"
@update:show="onUpdateShow"
>
<template #trigger><slot name="trigger" /></template>
<div
class="w-[268px] rounded-lg border border-line bg-white p-4 pb-3.5 shadow-overlay"
>
<div class="flex items-center gap-2.5">
<span
class="flex h-[26px] w-[26px] flex-none items-center justify-center rounded-[7px]"
:class="
kind === 'danger'
? 'bg-err/12 text-err'
: kind === 'warn'
? 'bg-warn/14 text-warn'
: 'bg-wash text-ink-2'
"
>
<svg
v-if="kind === 'danger'"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
<svg
v-else-if="kind === 'warn'"
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
</svg>
<svg
v-else
width="14"
height="14"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="16" x2="12" y2="12" />
<line x1="12" y1="8" x2="12.01" y2="8" />
</svg>
</span>
<!-- 超长资源名(如桶名)单行截断,悬停 tooltip 看全文 -->
<span class="min-w-0 truncate text-[13.5px] font-semibold" :title="title">{{ title }}</span>
</div>
<div v-if="content" class="mt-2 pl-9 text-[12.5px] leading-relaxed text-ink-2">
{{ content }}
</div>
<div v-if="note" class="mt-1 pl-9 text-xs leading-normal text-ink-3">{{ note }}</div>
<div class="mt-3 flex justify-end gap-2">
<NButton size="small" :disabled="loading" @click="show = false">{{ cancelText }}</NButton>
<NButton
size="small"
:type="kind === 'danger' ? 'error' : 'primary'"
:loading="loading"
@click="confirm"
>
{{ confirmText }}
</NButton>
</div>
</div>
</NPopover>
</template>
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
import { useIsMobile } from '@/composables/useIsMobile'
/** 筛选器统一布局:桌面 flex-wrap 换行,移动端横滚一行 + 右缘渐隐暗示,
* 条目不换行不压缩(替代 max-md:!w-full 逐行堆叠吃满竖向空间的旧模式) */
const isMobile = useIsMobile()
</script>
<template>
<div :class="isMobile ? 'filter-scroll' : 'flex flex-wrap items-center gap-x-3 gap-y-2'">
<slot />
</div>
</template>
<style scoped>
.filter-scroll {
display: flex;
align-items: center;
gap: 8px;
overflow-x: auto;
scrollbar-width: none;
-webkit-mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 24px), transparent);
mask-image: linear-gradient(90deg, #000 0, #000 calc(100% - 24px), transparent);
padding-right: 24px;
}
.filter-scroll::-webkit-scrollbar {
display: none;
}
.filter-scroll > :deep(*) {
flex: none;
white-space: nowrap;
}
</style>
+34 -5
View File
@@ -1,7 +1,10 @@
<script setup lang="ts">
import { NButton, NModal } from 'naive-ui'
import { computed } from 'vue'
defineProps<{
import { useIsMobile } from '@/composables/useIsMobile'
const props = defineProps<{
show: boolean
title: string
submitting?: boolean
@@ -12,6 +15,15 @@ defineProps<{
}>()
const emit = defineEmits<{ 'update:show': [boolean]; submit: [] }>()
const isMobile = useIsMobile()
/** 移动端全屏(100dvh 覆盖底栏与手势区),桌面维持定宽居中 */
const modalStyle = computed(() =>
isMobile.value
? { width: '100vw', height: '100dvh', maxWidth: '100vw', margin: '0', borderRadius: '0' }
: { width: `${props.width ?? 480}px`, maxWidth: 'calc(100vw - 24px)' },
)
</script>
<template>
@@ -19,7 +31,8 @@ const emit = defineEmits<{ 'update:show': [boolean]; submit: [] }>()
:show="show"
preset="card"
:title="title"
:style="{ width: `${width ?? 480}px`, maxWidth: 'calc(100vw - 24px)' }"
:style="modalStyle"
:class="isMobile ? 'form-modal-mobile' : ''"
:mask-closable="!submitting"
:close-on-esc="!submitting"
@update:show="emit('update:show', $event)"
@@ -33,11 +46,17 @@ const emit = defineEmits<{ 'update:show': [boolean]; submit: [] }>()
</div>
<template #footer>
<div class="flex justify-end gap-2.5">
<NButton size="small" :disabled="submitting" @click="emit('update:show', false)">
<NButton
:size="isMobile ? 'medium' : 'small'"
:class="isMobile ? 'flex-1' : ''"
:disabled="submitting"
@click="emit('update:show', false)"
>
取消
</NButton>
<NButton
size="small"
:size="isMobile ? 'medium' : 'small'"
:class="isMobile ? 'flex-1' : ''"
:type="danger ? 'error' : 'primary'"
:loading="submitting"
:disabled="submitDisabled"
@@ -54,9 +73,19 @@ const emit = defineEmits<{ 'update:show': [boolean]; submit: [] }>()
/* 长表单不撑破视口:内容区限高滚动,页脚按钮常驻;
负 margin + 等量 padding 让滚动条贴弹窗边缘(变量继承自 .n-card) */
.form-modal-body {
max-height: min(62vh, calc(100vh - 220px));
overflow-y: auto;
margin-inline: calc(-1 * var(--n-padding-left, 24px));
padding-inline: var(--n-padding-left, 24px);
}
/* 限高只在桌面定宽形态生效:移动全屏由全局 .form-modal-mobile 的 flex:1
接管高度。不能靠全局规则 max-height:none 覆盖——main.css 先于组件
scoped 样式加载,同特异性下这里会反超,故直接用断点隔离 */
@media (min-width: 768px) {
.form-modal-body {
max-height: min(62vh, calc(100vh - 220px));
}
}
</style>
<!-- 移动端全屏形态 .form-modal-mobile 的规则在 main.css(全局):
NModal teleport body,scoped 够不到;且该类被各弹窗跨 chunk 复用 -->
+28
View File
@@ -0,0 +1,28 @@
<script setup lang="ts" generic="T">
import { NSpin } from 'naive-ui'
/** 移动端列表卡片化容器:接管加载 / 空态,卡片体由默认插槽渲染 */
const props = defineProps<{
items: T[]
loading?: boolean
itemKey: (item: T) => string | number
emptyText?: string
}>()
</script>
<template>
<div class="flex flex-col gap-2.5">
<div
v-if="props.loading && !props.items.length"
class="panel flex items-center justify-center py-10"
>
<NSpin size="small" />
</div>
<div v-else-if="!props.items.length" class="panel py-10 text-center text-[13px] text-ink-3">
{{ props.emptyText ?? '暂无数据' }}
</div>
<div v-for="it in props.items" v-else :key="props.itemKey(it)" class="panel px-4 py-3">
<slot :item="it"></slot>
</div>
</div>
</template>
-16
View File
@@ -1,16 +0,0 @@
<script setup lang="ts">
defineProps<{ title: string; sub?: string }>()
</script>
<template>
<div class="flex flex-wrap items-baseline justify-between gap-2">
<div class="flex items-baseline gap-3">
<h1 class="page-title">{{ title }}</h1>
<slot name="title-extra" />
</div>
<div class="flex items-center gap-2">
<span v-if="sub" class="text-[13px] text-ink-3">{{ sub }}</span>
<slot name="actions" />
</div>
</div>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
/** 面板标准头:统一 px-4.5 py-3.5 内距、text-sm 标题、text-xs 弱化描述。
* 右侧动作放默认插槽——固定在标题行右端,desc 独立成行,窄屏下按钮
* 不随描述折行漂移(移动端按钮位置统一);标题行内的徽标/计数放
* #title-extra;富文本描述放 #desc。 */
defineProps<{ title: string; desc?: string }>()
</script>
<template>
<div class="border-b border-line-soft px-4.5 py-3.5">
<div class="flex min-w-0 items-center justify-between gap-3">
<div class="flex min-w-0 items-center gap-2 text-sm font-semibold">
<span class="truncate">{{ title }}</span>
<slot name="title-extra" />
</div>
<div v-if="$slots.default" class="flex flex-none items-center gap-2">
<slot />
</div>
</div>
<div v-if="desc || $slots.desc" class="mt-0.5 text-xs text-ink-3">
<template v-if="desc">{{ desc }}</template>
<slot name="desc" />
</div>
</div>
</template>
+57
View File
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { NPopover } from 'naive-ui'
import { useRouter } from 'vue-router'
import { useRegionAlias } from '@/composables/useRegionAlias'
/** 租户悬停卡(AI 网关渠道 / 回传日志共用):别名、租户名称、主区域三行
* 加「前往租户」入口;触发文本本身不承载跳转,避免误触。 */
const props = defineProps<{
cfgId: number
/** 触发文本(渠道名 / 租户别名) */
label: string
alias?: string
tenancyName?: string
region?: string
/** 触发文本附加类(截断约束等) */
labelClass?: string
}>()
const router = useRouter()
const { alias: regionAlias } = useRegionAlias()
function go(e: MouseEvent) {
// 表格行自身可能有点击行为(如回传日志展开详情),跳转不冒泡
e.stopPropagation()
void router.push({ name: 'tenant-detail', params: { id: props.cfgId } })
}
</script>
<template>
<NPopover trigger="hover" placement="top-start" :style="{ maxWidth: '320px' }">
<template #trigger>
<span
class="cursor-help border-b border-dashed border-ink-3/50 text-[13px]"
:class="labelClass"
>
{{ label }}
</span>
</template>
<div class="flex min-w-40 flex-col text-xs">
<div class="pb-1.5 text-[13px] font-semibold break-all">{{ alias ?? label }}</div>
<div v-if="tenancyName" class="mono border-t border-line-soft py-1.5 break-all text-ink-2">
{{ tenancyName }}
</div>
<div v-if="region" class="border-t border-line-soft py-1.5 text-ink-2">
{{ regionAlias(region) }}
</div>
<button
type="button"
class="cursor-pointer border-t border-line-soft pt-1.5 text-left font-medium text-accent"
@click="go"
>
前往租户
</button>
</div>
</NPopover>
</template>
+7 -2
View File
@@ -1,12 +1,13 @@
<script setup lang="ts">
import { NInput, NPopover, NSpin } from 'naive-ui'
import { computed, nextTick, ref, watch } from 'vue'
import { computed, nextTick, ref, useAttrs, watch } from 'vue'
import type { OciConfigSummary } from '@/types/api'
/** 租户选择器:Popover 面板(搜索 + 左分组导航 + 右租户列表),替代平铺下拉。
* 单选(v-model:value)点行即选即关;多选(multiple + v-model:values)点行切换勾选。
* 搜索命中时忽略左侧分组限定。 */
defineOptions({ inheritAttrs: false })
const props = withDefaults(
defineProps<{
configs: OciConfigSummary[]
@@ -23,6 +24,9 @@ const props = withDefaults(
)
const emit = defineEmits<{ 'update:value': [number | null]; 'update:values': [number[]] }>()
/** 根组件是 NPopover,class 透传会落到弹出面板上把宽度压扁;改为只作用于默认触发按钮 */
const attrs = useAttrs()
/** 「未分组」导航项哨兵(空串已被「全部租户」占用) */
const UNGROUPED = '__ungrouped__'
@@ -107,6 +111,7 @@ const showClear = computed(
type="button"
class="group flex w-full cursor-pointer items-center gap-2 rounded-lg border bg-white px-3 text-left transition-colors"
:class="[
attrs.class as string,
size === 'small' ? 'h-7' : 'h-[34px]',
show ? 'border-accent ring-2 ring-accent/15' : 'border-line hover:border-accent/60',
]"
@@ -138,7 +143,7 @@ const showClear = computed(
</slot>
</template>
<div class="w-[min(560px,92vw)] overflow-hidden rounded-xl border border-line bg-card shadow-[0_18px_44px_rgba(20,20,19,0.16)]">
<div class="tenant-picker-panel w-[min(560px,92vw)] overflow-hidden rounded-lg border border-line bg-card shadow-overlay">
<div class="px-3.5 pt-3 pb-2.5">
<NInput ref="searchInput" v-model:value="query" size="small" placeholder="搜索租户别名 / 租户名称…" clearable>
<template #prefix>
+4 -1
View File
@@ -8,6 +8,7 @@ import {
syncAiChannelModels,
testAiChannelModel,
} from '@/api/aigateway'
import { useMobileModal } from '@/composables/useMobileModal'
import { useToast } from '@/composables/useToast'
import type { AiChannel, AiModelCacheItem } from '@/types/api'
@@ -16,6 +17,7 @@ const emit = defineEmits<{ 'update:show': [boolean]; changed: [] }>()
const toast = useToast()
const dialog = useDialog()
const { modalStyle, modalClass } = useMobileModal(640)
const rows = ref<AiModelCacheItem[]>([])
const loading = ref(false)
@@ -121,7 +123,8 @@ function confirmBlacklist(name: string) {
<NModal
:show="show"
preset="card"
:style="{ width: '640px', maxWidth: 'calc(100vw - 24px)' }"
:style="modalStyle"
:class="modalClass"
@update:show="emit('update:show', $event)"
>
<template #header>
+24 -12
View File
@@ -6,10 +6,12 @@ import { createAiChannel, deleteAiChannel, probeAiChannel, updateAiChannel } fro
import { listCachedRegions } from '@/api/configs'
import AiChannelModelsModal from '@/components/ai/AiChannelModelsModal.vue'
import GroupChips from '@/components/ai/GroupChips.vue'
import PanelHeader from '@/components/PanelHeader.vue'
import AppInputNumber from '@/components/AppInputNumber.vue'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import TenantHoverCard from '@/components/TenantHoverCard.vue'
import TenantPicker from '@/components/TenantPicker.vue'
import { useAsync } from '@/composables/useAsync'
import { fmtRelative } from '@/composables/useFormat'
@@ -25,6 +27,20 @@ const groupHints = computed(() => [...new Set(props.channels.map((c) => c.group)
const toast = useToast()
const dialog = useDialog()
const scope = useScopeStore()
/** 名称列:渠道名关联租户,悬停出统一租户卡(别名/名称/主区域/前往租户);
* 名称本身不承载跳转,单元格内截断 */
function nameCell(r: AiChannel) {
// scope 经 Pinia reactive 包装,useAsync 的 data ref 已深层解包,不能再 .value
const cfg = (scope.configs.data ?? []).find((c) => c.id === r.ociConfigId)
return h(TenantHoverCard, {
cfgId: r.ociConfigId,
label: r.name,
alias: cfg?.alias,
tenancyName: cfg?.tenancyName,
region: cfg?.region,
labelClass: 'inline-block max-w-full truncate align-bottom font-medium',
})
}
const PROBE_META: Record<Exclude<AiProbeStatus, ''>, { kind: 'run' | 'warn' | 'term' | 'stop'; label: string }> = {
ok: { kind: 'run', label: '可用' },
@@ -168,7 +184,7 @@ function probeBadge(r: AiChannel) {
}
const columns = computed<DataTableColumns<AiChannel>>(() => [
{ title: '名称', key: 'name', minWidth: 200, ellipsis: { tooltip: true }, render: (r) => h('span', { class: 'text-[13px] font-medium' }, r.name) },
{ title: '名称', key: 'name', minWidth: 200, render: nameCell },
{ title: '区域', key: 'region', width: 150, ellipsis: { tooltip: true }, render: (r) => h('span', { class: 'mono text-xs text-ink-2' }, r.region) },
{
title: '分组', key: 'group', width: 100,
@@ -198,19 +214,15 @@ const columns = computed<DataTableColumns<AiChannel>>(() => [
<template>
<div class="panel">
<div class="flex items-center justify-between gap-3 border-b border-line-soft px-4.5 py-3">
<div>
<div class="text-sm font-semibold">渠道(号池)</div>
<div class="mt-0.5 text-xs text-ink-3">
渠道 = 租户 × 区域;请求按优先级分组组内权重随机,429/超时自动换渠道重试,连续失败指数退避熔断
</div>
</div>
<PanelHeader
title="渠道(号池)"
desc="渠道 = 租户 × 区域;按优先级与权重分流,失败自动重试并熔断"
>
<NButton size="small" type="primary" @click="openCreate">添加渠道</NButton>
</div>
<NDataTable :columns="columns" :data="channels" :loading="loading" :bordered="false" size="small" />
</PanelHeader>
<NDataTable :columns="columns" :data="channels" :loading="loading" :bordered="false" size="small" :scroll-x="960" />
<div class="border-t border-line-soft bg-wash px-4.5 py-2.5 text-xs leading-relaxed text-ink-3">
探测三步:列模型(服务可见性) 同步模型缓存 max_tokens=16 试调(配额)· 探测成功自动复位熔断 ·
有渠道时系统自动维护AI渠道探测后台任务(每天 00:00 逐渠道探测,渠道清空自动暂停)
探测 = 列模型 同步缓存 试调验证配额;成功自动复位熔断 · 后台任务每日 00:00 自动逐渠道探测
</div>
<AiChannelModelsModal
+7 -9
View File
@@ -7,6 +7,7 @@ import GroupChips from '@/components/ai/GroupChips.vue'
import AppInputNumber from '@/components/AppInputNumber.vue'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import PanelHeader from '@/components/PanelHeader.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { fmtTime } from '@/composables/useFormat'
import type { AiKey, AiModel } from '@/types/api'
@@ -169,16 +170,13 @@ const columns = computed<DataTableColumns<AiKey>>(() => [
<template>
<div class="panel">
<div class="flex items-center justify-between gap-3 border-b border-line-soft px-4.5 py-3">
<div>
<div class="text-sm font-semibold">网关密钥</div>
<div class="mt-0.5 text-xs text-ink-3">
对外发放的访问凭证;明文仅创建时展示一次,库内只存哈希与尾 4 ;选了分组的密钥只在该分组渠道内负载均衡
</div>
</div>
<PanelHeader
title="网关密钥"
desc="对外发放的访问凭证;明文仅创建时展示一次;分组密钥只走该分组渠道"
>
<NButton size="small" type="primary" @click="openCreate">新建密钥</NButton>
</div>
<NDataTable :columns="columns" :data="keys" :loading="loading" :bordered="false" size="small" />
</PanelHeader>
<NDataTable :columns="columns" :data="keys" :loading="loading" :bordered="false" size="small" :scroll-x="1110" />
<FormModal
v-model:show="showForm"
+44 -2
View File
@@ -4,8 +4,13 @@ import { computed, ref, watch } from 'vue'
import { attachVnic } from '@/api/instances'
import { listSubnets } from '@/api/networks'
import { listReservedIps } from '@/api/reservedips'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import {
freeReservedIpOptions,
renderReservedIpLabel,
} from '@/components/network/reservedIpSelect'
import ToggleCard from '@/components/ToggleCard.vue'
import { useAsync } from '@/composables/useAsync'
import { shortAd } from '@/composables/useFormat'
@@ -29,10 +34,21 @@ const displayName = ref('')
const privateIp = ref('')
const assignPublicIp = ref(false)
const assignIpv6 = ref(false)
/** null = 临时公网 IP;选中保留 IP 时网卡就绪后由后台绑定 */
const reservedIpId = ref<string | null>(null)
/** vcnId 传空列全部子网:次要网卡允许跨 VCN */
const subnets = useAsync(() => listSubnets(props.cfgId, '', props.region), false)
const reservedIps = useAsync(async () => {
try {
return await listReservedIps(props.cfgId, props.region)
} catch {
return []
}
}, false)
const reservedOptions = computed(() => freeReservedIpOptions(reservedIps.data.value ?? []))
watch(
() => props.show,
(v) => {
@@ -42,11 +58,17 @@ watch(
privateIp.value = ''
assignPublicIp.value = false
assignIpv6.value = false
reservedIpId.value = null
void subnets.run()
void reservedIps.run()
}
},
)
watch(assignPublicIp, (on) => {
if (!on) reservedIpId.value = null
})
const options = computed<SelectOption[]>(() =>
(subnets.data.value ?? [])
.filter((s) => s.lifecycleState === 'AVAILABLE')
@@ -75,10 +97,15 @@ async function submit() {
subnetId: subnetId.value,
displayName: displayName.value.trim(),
privateIp: privateIp.value.trim(),
assignPublicIp: assignPublicIp.value,
assignPublicIp: assignPublicIp.value && !reservedIpId.value,
assignIpv6: assignIpv6.value,
reservedPublicIpId: reservedIpId.value ?? undefined,
})
message.success('附加请求已提交,OS 内需自行配置新网卡 IP')
message.success(
reservedIpId.value
? '附加请求已提交,网卡就绪后自动绑定保留 IP;OS 内需自行配置新网卡 IP'
: '附加请求已提交,OS 内需自行配置新网卡 IP',
)
emit('update:show', false)
emit('attached')
} catch (e) {
@@ -128,6 +155,21 @@ async function submit() {
:desc="publicIpBlocked ? '所选子网为私有子网,不可分配公网 IP' : '仅公有子网可用;临时地址,分离即释放'"
:disabled="publicIpBlocked"
/>
<FormField
v-if="assignPublicIp && !publicIpBlocked"
label="公网 IP 类型"
hint="选保留 IP 时网卡就绪后自动绑定,期间短暂无公网地址"
>
<NSelect
v-model:value="reservedIpId"
:options="reservedOptions"
:loading="reservedIps.loading.value"
:render-label="renderReservedIpLabel"
:consistent-menu-width="false"
clearable
placeholder="临时 IP(默认);可选保留 IP"
/>
</FormField>
<ToggleCard
v-model="assignIpv6"
title="自动分配 IPv6"
+116
View File
@@ -0,0 +1,116 @@
<script setup lang="ts">
import { NRadio, NRadioGroup, NSelect } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { changeVnicPublicIp } from '@/api/instances'
import { assignReservedIp, listReservedIps } from '@/api/reservedips'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import { freeReservedIpOptions, renderReservedIpLabel } from '@/components/network/reservedIpSelect'
import { useAsync } from '@/composables/useAsync'
import { useToast } from '@/composables/useToast'
/** 换公网 IP 弹窗(主卡/次卡通用):临时 IP 删旧分新,保留 IP 绑定固定地址;
* 两种路径旧公网 IP 都由后端自动释放(临时删除、保留解绑)。 */
const props = defineProps<{
show: boolean
cfgId: number
region?: string
vnicId: string
/** 网卡当前公网 IP,仅展示 */
currentIp?: string
}>()
const emit = defineEmits<{
'update:show': [boolean]
/** 换 IP 成功;newIp 为预期新地址,供父级做收敛轮询(拿不到时 undefined) */
changed: [payload: { vnicId: string; newIp?: string }]
}>()
const message = useToast()
const ipType = ref<'ephemeral' | 'reserved'>('ephemeral')
const reservedId = ref<string | null>(null)
const busy = ref(false)
const reservedIps = useAsync(async () => {
try {
return await listReservedIps(props.cfgId, props.region)
} catch {
return []
}
}, false)
const options = computed(() => freeReservedIpOptions(reservedIps.data.value ?? []))
watch(
() => props.show,
(show) => {
if (!show) return
ipType.value = 'ephemeral'
reservedId.value = null
void reservedIps.run()
},
)
async function submit() {
if (busy.value) return
busy.value = true
try {
const newIp = await applyChange()
emit('update:show', false)
emit('changed', { vnicId: props.vnicId, newIp })
} catch (e) {
message.error(e instanceof Error ? e.message : '操作失败')
} finally {
busy.value = false
}
}
/** 执行换 IP 并返回预期新地址;保留 IP 取所选项地址,拿不到时 undefined(轮询退化为比对旧值) */
async function applyChange(): Promise<string | undefined> {
if (ipType.value === 'reserved') {
await assignReservedIp(props.cfgId, reservedId.value!, '', props.region, props.vnicId)
message.success('保留 IP 已绑定,原公网 IP 已释放')
return (reservedIps.data.value ?? []).find((r) => r.id === reservedId.value)?.ipAddress || undefined
}
const { publicIp } = await changeVnicPublicIp(props.cfgId, props.vnicId, props.region)
message.success(`公网 IP 已更换为 ${publicIp}`)
return publicIp
}
</script>
<template>
<FormModal
:show="show"
title="更换公网 IP"
:width="440"
:submitting="busy"
:submit-disabled="ipType === 'reserved' && !reservedId"
submit-text="更换"
@update:show="emit('update:show', $event)"
@submit="submit"
>
<FormField v-if="currentIp" label="当前地址">
<span class="mono text-[12.5px]">{{ currentIp }}</span>
</FormField>
<FormField label="新地址类型" hint="临时 IP 删除;保留 IP 解绑回到未分配">
<NRadioGroup v-model:value="ipType">
<NRadio value="ephemeral">临时 IP</NRadio>
<NRadio value="reserved">保留 IP</NRadio>
</NRadioGroup>
</FormField>
<FormField v-if="ipType === 'reserved'" label="选择保留 IP">
<NSelect
v-model:value="reservedId"
:options="options"
:loading="reservedIps.loading.value"
:render-label="renderReservedIpLabel"
:consistent-menu-width="false"
placeholder="选择未绑定的保留 IP"
clearable
/>
<div v-if="!reservedIps.loading.value && !options.length" class="mt-1 text-xs text-ink-3">
无可用保留 IP,可在网络 保留 IP面板创建
</div>
</FormField>
</FormModal>
</template>
@@ -44,6 +44,11 @@ const canSubmit = computed(
async function submit() {
if (props.cfgId === null || !specForm.value) return
const spec = specForm.value.buildSpec()
if (spec.reservedPublicIpId && form.count > 1) {
message.warning('保留 IP 仅支持单台创建,请把数量改为 1')
return
}
submitting.value = true
try {
const result = await createInstances(props.cfgId, {
@@ -51,17 +56,18 @@ async function submit() {
compartmentId: props.compartmentId || undefined,
displayName: form.displayName.trim(),
count: form.count,
...specForm.value.buildSpec(),
...spec,
})
// 后端 errors / instances 为空时序列化为 null,判空防炸
const ok = result.instances?.length ?? 0
const failed = result.errors?.length ?? 0
if (failed) message.warning(`${ok} 台创建成功,${failed} 台失败${result.errors![0]}`)
if (failed) message.warning(`${ok} 台创建成功,${failed} 台失败`, result.errors!.join('\n'))
else message.success(`已创建 ${ok} 台实例`)
emit('update:show', false)
emit('created')
} catch (e) {
message.error(e instanceof Error ? e.message : '创建失败')
// 逐台错误(可能多行)收进「展开详情」,标题保持简短
message.error('创建实例失败', e instanceof Error && e.message ? e.message : undefined)
} finally {
submitting.value = false
}
@@ -90,17 +96,18 @@ async function submit() {
<InstanceSpecForm
ref="specForm"
sectioned
auto-pick-ad
:cfg-id="cfgId"
:region="region"
:compartment-id="compartmentId"
/>
<div
class="mt-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-line-soft bg-wash px-3 py-2 text-xs leading-relaxed text-ink-3"
v-if="specForm?.summary"
class="mt-3 rounded-lg border border-line-soft bg-wash px-3 py-2 text-xs leading-relaxed"
>
<span v-if="specForm?.summary" class="font-medium text-ink-2">
<span class="font-medium text-ink-2">
预估规格:{{ form.count }} · {{ specForm.summary }}
</span>
<span>容量不足Out of host capacity时可改用抢机任务反复尝试</span>
</div>
</FormModal>
</template>
+139 -36
View File
@@ -4,12 +4,15 @@ import { computed, onMounted, reactive, ref, watch } from 'vue'
import { listAvailabilityDomains, listImages, listShapes } from '@/api/instances'
import { listSubnets, listVcns } from '@/api/networks'
import { listReservedIps } from '@/api/reservedips'
import { freeReservedIpOptions, renderReservedIpLabel } from '@/components/network/reservedIpSelect'
import { listLimits } from '@/api/tenant'
import AppInputNumber from '@/components/AppInputNumber.vue'
import FormField from '@/components/FormField.vue'
import FormSection from '@/components/FormSection.vue'
import { shortAd } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import type { ComputeShape, LimitItem } from '@/types/api'
/** 实例规格表单(创建实例弹窗与抢机任务共用):
* Shape / 可用域 / 规格 / 镜像 / VCN 子网 / 引导卷 / 登录方式 / IP 分配。
@@ -22,6 +25,9 @@ const props = defineProps<{
sectioned?: boolean
/** 可用域字段说明;抢机任务留空为轮询语义,与手动创建(固定 AD-1)不同 */
adHint?: string
/** 创建场景:AD 留空(默认 AD-1)而所选 shape 在 AD-1 无配额时,自动落位首个有配额 AD;
* 抢机表单留空 = 轮询语义,勿开 */
autoPickAd?: boolean
}>()
/** VCN 选择的「自动创建」哨兵:提交时不传 subnetId,由后端建 VCN 与子网 */
@@ -30,14 +36,16 @@ const AUTO_VCN = '__auto__'
const blank = {
availabilityDomain: null as string | null,
shape: 'VM.Standard.A1.Flex',
ocpus: 4,
memoryInGBs: 24,
ocpus: 2,
memoryInGBs: 12,
imageId: null as string | null,
vcnId: AUTO_VCN,
subnetId: null as string | null,
bootVolumeSizeGBs: null as number | null,
bootVolumeVpusPerGB: 10,
assignPublicIp: true,
publicIpMode: 'ephemeral' as 'ephemeral' | 'reserved' | 'none',
reservedPublicIpId: null as string | null,
assignIpv6: true,
authMode: 'password' as 'password' | 'ssh',
randomPassword: true,
@@ -169,6 +177,12 @@ function applySpec(spec: Record<string, unknown>) {
if (typeof s.bootVolumeSizeGBs === 'number') form.bootVolumeSizeGBs = s.bootVolumeSizeGBs
if (typeof s.bootVolumeVpusPerGB === 'number') form.bootVolumeVpusPerGB = s.bootVolumeVpusPerGB
form.assignPublicIp = s.assignPublicIp !== false
if (typeof s.reservedPublicIpId === 'string' && s.reservedPublicIpId) {
form.publicIpMode = 'reserved'
form.reservedPublicIpId = s.reservedPublicIpId
} else {
form.publicIpMode = s.assignPublicIp !== false ? 'ephemeral' : 'none'
}
form.assignIpv6 = s.assignIpv6 !== false
form.authMode = typeof s.sshPublicKey === 'string' && s.sshPublicKey ? 'ssh' : 'password'
form.sshPublicKey = typeof s.sshPublicKey === 'string' ? s.sshPublicKey : ''
@@ -194,51 +208,82 @@ watch(
},
)
/** shape → OCI compute 配额名(官方 Limits by Service 命名);已知映射用于配额标注,
* 清单外的 shape 不判定配额。AD 维度多行求和 > 0 才认为有配额。 */
const SHAPE_QUOTAS: Record<string, string> = {
'VM.Standard.A1.Flex': 'standard-a1-core-count',
'VM.Standard.A2.Flex': 'standard-a2-core-count',
'VM.Standard.A4.Flex': 'standard-a4-core-count',
'VM.Standard.E2.1.Micro': 'standard-e2-micro-core-count',
'VM.Standard.E3.Flex': 'standard-e3-core-ad-count',
'VM.Standard.E4.Flex': 'standard-e4-core-count',
'VM.Standard.E5.Flex': 'standard-e5-core-count',
'VM.Standard.E6.Flex': 'standard-e6-core-count',
'VM.Standard3.Flex': 'standard3-core-count',
/** 免费类计费类型:仅用于排序置顶,不在选项文案中标注 */
const FREE_BILLING = new Set(['ALWAYS_FREE', 'LIMITED_FREE'])
/** shape 的核数配额名:quotaNames 排除 memory / reserved / reservable 变体,
* 剩余为核数(或实例数)限额名,与 compute limits 的 name 同名 */
function coreQuotaNames(s: ComputeShape): string[] {
return (s.quotaNames ?? []).filter(
(n) => !n.includes('memory') && !n.includes('reserved') && !n.includes('reservable'),
)
}
const BILLING_LABEL: Record<string, string> = {
ALWAYS_FREE: '永久免费',
LIMITED_FREE: '免费额度',
/** 单个 shape 的配额汇总:AD 行按 AD 求和,REGION 行累计为区域总额;无匹配行返回 null */
function shapeQuotaEntry(names: Set<string>, rows: LimitItem[]): ShapeQuota | null {
const byAd = new Map<string, number>()
let regional: number | null = null
let matched = false
for (const r of rows) {
if (!names.has(r.name)) continue
matched = true
if (r.scopeType === 'AD' && r.availabilityDomain) {
byAd.set(r.availabilityDomain, (byAd.get(r.availabilityDomain) ?? 0) + Math.max(r.value, 0))
} else if (r.scopeType === 'REGION') {
regional = (regional ?? 0) + Math.max(r.value, 0)
}
}
return matched ? { byAd, regional } : null
}
/** 已知映射 shape 的核数配额合计;未知映射或配额未加载返回 null(不判定) */
function quotaOf(shape: string): number | null {
const quota = SHAPE_QUOTAS[shape]
const items = limits.data.value ?? []
if (!quota || !items.length) return null
return items.filter((l) => l.name === quota).reduce((sum, l) => sum + (l.value > 0 ? l.value : 0), 0)
interface ShapeQuota {
byAd: Map<string, number> // AD 全名 → 核数配额
regional: number | null // 区域级总额,null = 无区域行
}
/** 全部 shape 的配额汇总;quotaNames 缺失或 limits 无匹配行的 shape 无条目(不判定) */
const quotaByShape = computed(() => {
const rows = limits.data.value ?? []
const out = new Map<string, ShapeQuota>()
if (!rows.length) return out
for (const s of shapes.data.value ?? []) {
const names = new Set(coreQuotaNames(s))
if (!names.size) continue
const entry = shapeQuotaEntry(names, rows)
if (entry) out.set(s.name, entry)
}
return out
})
/** shape 在指定 AD(null = 任一 AD)是否有配额;null = 数据不足不判定 */
function quotaInAd(name: string, ad: string | null): boolean | null {
const q = quotaByShape.value.get(name)
if (!q) return null
if (q.regional !== null && q.regional <= 0) return false
if (!q.byAd.size) return true // 仅区域级限额且 > 0
if (ad === null) return [...q.byAd.values()].some((v) => v > 0)
return (q.byAd.get(ad) ?? 0) > 0
}
/** 排序:免费 shape 优先 → VM.Standard 系列 → 其他 VM → 裸金属等 */
function shapeRank(s: { billingType: string; name: string }): number {
if (BILLING_LABEL[s.billingType]) return 0
if (FREE_BILLING.has(s.billingType)) return 0
if (s.name.startsWith('VM.Standard')) return 1
if (s.name.startsWith('VM.')) return 2
return 3
}
const shapeOptions = computed(() => {
// 清单全部来自 shapes 接口,不做本地预设;接口不可用时仍可手输(tag 模式)
// 清单全部来自 shapes 接口,不做本地预设;接口不可用时仍可手输(tag 模式);
// 选定 AD 时按该 AD 判定配额,未选时看任一 AD
const list = shapes.data.value ?? []
const ad = form.availabilityDomain
return [...list]
.sort((a, b) => shapeRank(a) - shapeRank(b) || a.name.localeCompare(b.name))
.map((s) => {
const free = BILLING_LABEL[s.billingType]
const quota = quotaOf(s.name)
const suffix = (free ? `${free}` : '') + (quota === 0 ? ' · 无配额' : '')
return { label: s.name + suffix, value: s.name, disabled: quota === 0 }
const ok = quotaInAd(s.name, ad)
const suffix = ok === false ? (ad ? ' · 该 AD 无配额' : ' · 无配额') : ''
return { label: s.name + suffix, value: s.name, disabled: ok === false }
})
})
@@ -288,10 +333,29 @@ const imageOptions = computed(() => {
.map((i) => ({ label: i.displayName, value: i.id }))
})
/** AD 选项按当前 shape 的配额标注并禁用无配额项;数据不足时不标注 */
const adOptions = computed(
() => ads.data.value?.map((ad) => ({ label: shortAd(ad), value: ad })) ?? [],
() =>
ads.data.value?.map((ad) => {
const ok = quotaInAd(form.shape, ad)
return {
label: shortAd(ad) + (ok === false ? '(无配额)' : ''),
value: ad,
disabled: ok === false,
}
}) ?? [],
)
// 创建场景(autoPickAd):AD 留空将由后端取 AD-1;所选 shape 在 AD-1 无配额
// 而其他 AD 有配额时,自动落位首个有配额 AD(字段可见,用户可改)
watch([() => form.shape, quotaByShape, () => ads.data.value], () => {
if (!props.autoPickAd || form.availabilityDomain !== null) return
const list = ads.data.value ?? []
if (!list.length || quotaInAd(form.shape, list[0]) !== false) return
const target = list.find((ad) => quotaInAd(form.shape, ad) === true)
if (target) form.availabilityDomain = target
})
const vcnOptions = computed(() => [
{ label: '自动创建(oci-portal-auto-vcn', value: AUTO_VCN },
...(vcns.data.value ?? []).map((v) => ({ label: v.displayName, value: v.id })),
@@ -322,15 +386,37 @@ watch(ipv6Supported, (v) => {
const valid = computed(() => {
if (!form.imageId) return false
if (form.vcnId !== AUTO_VCN && !form.subnetId) return false
if (form.publicIpMode === 'reserved' && !form.reservedPublicIpId) return false
return !isFlex.value || form.ocpus > 0
})
/** 规格摘要(父表单底部预估条用):shape 短名 + 弹性核内存 + 免费标注 */
// ---- 公网 IPv4 分配方式:临时 / 保留 / 不分配 ----
const publicIpModes = [
{ label: '临时 IP', value: 'ephemeral' },
{ label: '保留 IP', value: 'reserved' },
{ label: '不分配', value: 'none' },
]
const reservedIps = useAsync(async () => {
if (props.cfgId === null) return []
try {
return await listReservedIps(props.cfgId, props.region || undefined, props.compartmentId || undefined)
} catch {
return []
}
}, false)
const freeReservedOptions = computed(() => freeReservedIpOptions(reservedIps.data.value ?? []))
watch(
() => form.publicIpMode,
(mode) => {
if (mode === 'reserved') void reservedIps.run()
else form.reservedPublicIpId = null
},
)
/** 规格摘要(父表单底部预估条用):shape 短名 + 弹性核内存 */
const summary = computed(() => {
const parts = [form.shape.replace(/^VM\.Standard\.?/, '') || form.shape]
if (isFlex.value) parts.push(`${form.ocpus} OCPU · ${form.memoryInGBs} GB`)
const free = selectedShape.value && BILLING_LABEL[selectedShape.value.billingType]
if (free) parts.push(free)
return parts.join(' · ')
})
@@ -347,7 +433,9 @@ function buildSpec(): Record<string, unknown> {
bootVolumeSizeGBs: form.bootVolumeSizeGBs ?? undefined,
// 性能独立于大小:留空按镜像默认大小时同样生效(后端仅镜像启动源使用)
bootVolumeVpusPerGB: form.bootVolumeVpusPerGB || undefined,
assignPublicIp: form.assignPublicIp,
assignPublicIp: form.publicIpMode === 'ephemeral',
reservedPublicIpId:
form.publicIpMode === 'reserved' ? (form.reservedPublicIpId ?? undefined) : undefined,
assignIpv6: form.assignIpv6,
generateRootPassword: usePwd && form.randomPassword ? true : undefined,
rootPassword:
@@ -366,7 +454,7 @@ defineExpose({ valid, buildSpec, reset, applySpec, summary })
<FormField
label="Shape"
required
hint="清单来自租户当前区域实际提供的 shape(免费与无配额已标注),可手输其他"
hint="清单来自租户当前区域实际提供的 shape(无配额已标注),可手输其他"
>
<NSelect
v-model:value="form.shape"
@@ -526,8 +614,23 @@ defineExpose({ valid, buildSpec, reset, applySpec, summary })
placeholder="ssh-ed25519 AAAA…"
/>
</FormField>
<div class="grid grid-cols-2 gap-3 max-md:grid-cols-1">
<FormField label="公网 IPv4" hint="保留 IP:实例就绪后自动绑定,期间短暂无公网地址;仅单台创建可用">
<NSelect v-model:value="form.publicIpMode" :options="publicIpModes" />
</FormField>
<FormField v-if="form.publicIpMode === 'reserved'" label="保留 IP" required>
<NSelect
v-model:value="form.reservedPublicIpId"
:options="freeReservedOptions"
:loading="reservedIps.loading.value"
:render-label="renderReservedIpLabel"
:consistent-menu-width="false"
placeholder="选择未绑定的保留 IP"
filterable
/>
</FormField>
</div>
<div class="flex flex-wrap gap-5">
<NCheckbox v-model:checked="form.assignPublicIp">分配公网 IPv4</NCheckbox>
<NCheckbox v-model:checked="form.assignIpv6" :disabled="!ipv6Supported">
分配 IPv6{{ ipv6Supported ? '' : '(所选子网未启用)' }}
</NCheckbox>
@@ -37,13 +37,25 @@ const daysOptions = [
]
const series = computed(() => {
const vnic = traffic.data.value?.vnics[0]
if (!vnic) return null
const labels = vnic.outbound.map((p) => p.timestamp.slice(5, 10))
const vnics = traffic.data.value?.vnics ?? []
if (!vnics.length) return null
// 各 VNIC 时间序列长短不一(新挂网卡只有近几天),按日取并集逐日求和
const byDay = new Map<string, { inbound: number; outbound: number }>()
const bucket = (ts: string) => {
const key = ts.slice(0, 10)
let b = byDay.get(key)
if (!b) byDay.set(key, (b = { inbound: 0, outbound: 0 }))
return b
}
for (const v of vnics) {
for (const p of v.inbound) bucket(p.timestamp).inbound += p.bytes
for (const p of v.outbound) bucket(p.timestamp).outbound += p.bytes
}
const days = [...byDay.keys()].sort()
return {
labels,
outbound: vnic.outbound.map((p) => +(p.bytes / 1024 ** 3).toFixed(2)),
inbound: vnic.inbound.map((p) => +(p.bytes / 1024 ** 3).toFixed(2)),
labels: days.map((d) => d.slice(5)),
outbound: days.map((d) => +(byDay.get(d)!.outbound / 1024 ** 3).toFixed(2)),
inbound: days.map((d) => +(byDay.get(d)!.inbound / 1024 ** 3).toFixed(2)),
}
})
+2 -10
View File
@@ -37,18 +37,10 @@ watch(
},
)
const BILLING_LABEL: Record<string, string> = {
ALWAYS_FREE: '永久免费',
LIMITED_FREE: '免费额度',
}
const shapeOptions = computed(() => {
const list = shapes.data.value ?? []
if (!list.length) return [{ label: form.shape, value: form.shape }]
return list.map((s) => {
const free = BILLING_LABEL[s.billingType]
return { label: s.name + (free ? `${free}` : ''), value: s.name }
})
return list.map((s) => ({ label: s.name, value: s.name }))
})
const selectedShape = computed(
@@ -141,7 +133,7 @@ async function submit() {
</div>
<div class="text-xs leading-relaxed text-ink-3">
运行中实例 OCI 会自动重启完成变更更换 shape 要求镜像与目标 shape 架构兼容 aarch64
镜像不能换到 x86 shapeA1 免费额度上限 4 OCPU / 24 GB
镜像不能换到 x86 shape
</div>
</FormModal>
</template>
+82 -12
View File
@@ -1,16 +1,19 @@
<script setup lang="ts">
import { NButton, NPopconfirm, NSpin } from 'naive-ui'
import { NButton, NSpin } from 'naive-ui'
import { computed, ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { addVnicIpv6, detachVnic, listVnics, removeIpv6 } from '@/api/instances'
import ConfirmPop from '@/components/ConfirmPop.vue'
import FootNote from '@/components/FootNote.vue'
import AttachVnicModal from '@/components/instance/AttachVnicModal.vue'
import ChangeIpModal from '@/components/instance/ChangeIpModal.vue'
import LifecycleBadge from '@/components/LifecycleBadge.vue'
import OcidText from '@/components/OcidText.vue'
import { useAsync } from '@/composables/useAsync'
import { ATTACHMENT_TRANSIENT_STATES, useTransientPoll } from '@/composables/useTransientPoll'
import { useToast } from '@/composables/useToast'
import type { Vnic } from '@/types/api'
/** 网卡(VNIC)区块:每卡一主行 + IPv6 副行;IPv6 增删按卡操作。
* 删除复用实例级接口(后端按地址遍历全部网卡),添加走 per-VNIC 接口。 */
@@ -35,10 +38,46 @@ useTransientPoll(
() => vnics.data.value,
(list) =>
!!list?.some((v) => ATTACHMENT_TRANSIENT_STATES.includes(v.lifecycleState)) ||
((list?.length ?? 0) < expectAtLeast.value && Date.now() < expectUntil),
((list?.length ?? 0) < expectAtLeast.value && Date.now() < expectUntil) ||
// 已 ATTACHED 但公网 IP 尚未回填(临时分配 / 保留 IP 后台绑定滞后),窗口期内继续轮询
(Date.now() < expectUntil &&
!!list?.some((v) => v.lifecycleState === 'ATTACHED' && !v.publicIp)) ||
ipStale(list),
() => void vnics.run({ silent: true }),
)
// ---- 换 IP 收敛:OCI GetVnic 公网 IP 有秒级回填延迟,立即重查拿到的仍是旧值;
// 换 IP 成功后开 90s 窗口轮询,直到目标网卡 IP 更新,再通知父级刷实例详情顶卡 ----
const ipExpect = ref<{ vnicId: string; newIp?: string; oldIp?: string; until: number } | null>(null)
/** 目标网卡公网 IP 尚未刷新到预期值:窗口内视为过渡态继续轮询 */
function ipStale(list: Vnic[] | null | undefined): boolean {
const e = ipExpect.value
if (!e || Date.now() > e.until) return false
const v = (list ?? []).find((x) => x.vnicId === e.vnicId)
if (!v) return false
return e.newIp ? v.publicIp !== e.newIp : v.publicIp === e.oldIp
}
function onIpChanged(p: { vnicId: string; newIp?: string }) {
ipExpect.value = { ...p, oldIp: changeIpTarget.value.publicIp, until: Date.now() + 90_000 }
refresh()
}
// 收敛(或窗口过期)后清理并再通知父级:此刻数据源已是新 IP,顶卡才能刷到新值
watch(
() => vnics.data.value,
(list) => {
const e = ipExpect.value
if (!e) return
const expired = Date.now() > e.until
if (expired || !ipStale(list)) {
ipExpect.value = null
if (!expired) emit('changed')
}
},
)
const showAttach = ref(false)
const detaching = ref('')
const addingIpv6 = ref('')
@@ -56,6 +95,15 @@ function onAttached() {
refresh()
}
// ---- 换公网 IP:主卡/次卡统一走弹窗(可选临时或保留 IP) ----
const showChangeIp = ref(false)
const changeIpTarget = ref<{ vnicId: string; publicIp?: string }>({ vnicId: '' })
function openChangeIp(vnicId: string, publicIp?: string) {
changeIpTarget.value = { vnicId, publicIp }
showChangeIp.value = true
}
async function doDetach(attachmentId: string) {
detaching.value = attachmentId
try {
@@ -104,7 +152,7 @@ defineExpose({ refresh: () => vnics.run() })
<div class="min-w-0">
<div class="text-sm font-semibold">网卡VNIC</div>
<div class="mt-0.5 text-xs text-ink-3">
实例的全部虚拟网卡每张网卡可各自附加多个 IPv6
实例的全部虚拟网卡
</div>
</div>
<NButton size="small" type="primary" :disabled="disabled" @click="showAttach = true">
@@ -127,7 +175,7 @@ defineExpose({ refresh: () => vnics.run() })
<th class="border-b border-line-soft px-3 py-2 font-medium">公网 IP</th>
<th class="border-b border-line-soft px-3 py-2 font-medium">子网</th>
<th class="w-28 border-b border-line-soft px-3 py-2 font-medium">状态</th>
<th class="w-18 border-b border-line-soft py-2 pr-4.5 pl-3 font-medium">操作</th>
<th class="w-30 border-b border-line-soft py-2 pr-4.5 pl-3 font-medium">操作</th>
</tr>
</thead>
<tbody>
@@ -156,30 +204,44 @@ defineExpose({ refresh: () => vnics.run() })
<span v-else></span>
</td>
<td class="px-3 py-2.5 pb-1.5"><LifecycleBadge :state="v.lifecycleState" /></td>
<td class="py-2.5 pr-4.5 pb-1.5 pl-3">
<td class="py-2.5 pr-4.5 pb-1.5 pl-3 whitespace-nowrap">
<NButton
size="tiny"
quaternary
:disabled="disabled || v.lifecycleState !== 'ATTACHED' || !v.vnicId || busy"
@click="openChangeIp(v.vnicId, v.publicIp)"
>
IP
</NButton>
<NButton
v-if="v.isPrimary"
size="tiny"
quaternary
disabled
title="主网卡不可分离"
class="ml-1"
>
分离
</NButton>
<NPopconfirm v-else @positive-click="doDetach(v.attachmentId)">
<ConfirmPop
v-else
title="分离该网卡?"
content="其上全部 IP(含 IPv6)将一并释放。"
confirm-text="分离"
:on-confirm="() => doDetach(v.attachmentId)"
>
<template #trigger>
<NButton
size="tiny"
quaternary
type="error"
:loading="detaching === v.attachmentId"
class="ml-1"
:disabled="disabled || v.lifecycleState !== 'ATTACHED' || busy"
>
分离
</NButton>
</template>
分离该网卡其上全部 IP IPv6将一并释放
</NPopconfirm>
</ConfirmPop>
</td>
</tr>
<tr class="border-b border-line-soft last:border-b-0">
@@ -234,8 +296,7 @@ defineExpose({ refresh: () => vnics.run() })
</div>
<FootNote>
附加须实例运行中且 shape 有空余 VNIC 配额 · 主网卡不可分离 · 每卡 IPv6
可多个要求所在子网已启用 IPv6
附加须实例运行中且 shape 有空余 VNIC 配额
</FootNote>
<AttachVnicModal
@@ -246,5 +307,14 @@ defineExpose({ refresh: () => vnics.run() })
:attached-count="(vnics.data.value ?? []).length"
@attached="onAttached"
/>
<ChangeIpModal
v-model:show="showChangeIp"
:cfg-id="cfgId"
:region="region"
:vnic-id="changeIpTarget.vnicId"
:current-ip="changeIpTarget.publicIp"
@changed="onIpChanged"
/>
</div>
</template>
+17 -7
View File
@@ -5,13 +5,18 @@ import { computed, h, onMounted, reactive, ref } from 'vue'
import { listAiCallLogs, listAiContentLogs } from '@/api/aigateway'
import DetailFieldList, { type DetailRow } from '@/components/DetailFieldList.vue'
import DetailHero, { type HeroChip } from '@/components/DetailHero.vue'
import PanelHeader from '@/components/PanelHeader.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { useAutoRefresh } from '@/composables/useAutoRefresh'
import { fmtTime } from '@/composables/useFormat'
import { useIsMobile } from '@/composables/useIsMobile'
import { useMobileModal } from '@/composables/useMobileModal'
import type { AiCallLog, AiContentLog } from '@/types/api'
import { useToast } from '@/composables/useToast'
const message = useToast()
const isMobile = useIsMobile()
const { modalStyle, modalClass } = useMobileModal(600)
const rows = ref<AiCallLog[]>([])
const loading = ref(false)
@@ -21,6 +26,10 @@ const pagination = reactive({
itemCount: 0,
showSizePicker: true,
pageSizes: [20, 50, 100],
// 移动端页码槽位放不下会被裁切,切 simple 形态(‹ n/总页 )
get simple() {
return isMobile.value
},
onUpdatePage: (p: number) => {
pagination.page = p
void load()
@@ -69,7 +78,7 @@ function statusCell(row: AiCallLog) {
function tokensCell(row: AiCallLog) {
if (row.errMsg && !row.totalTokens) return h('span', { class: 'text-[13px] text-ink-3' }, '—')
const flow = row.stream ? ' · 流' : ''
return h('span', { class: 'mono text-[13px]' }, `${row.promptTokens} / ${row.completionTokens}${flow}`)
return h('span', { class: 'mono text-[13px] whitespace-nowrap' }, `${row.promptTokens} / ${row.completionTokens}${flow}`)
}
const columns: DataTableColumns<AiCallLog> = [
@@ -79,7 +88,7 @@ const columns: DataTableColumns<AiCallLog> = [
{ title: '模型', key: 'model', minWidth: 220, ellipsis: { tooltip: true }, render: (r) => h('span', { class: 'mono text-xs' }, r.model) },
{ title: '渠道', key: 'channelName', minWidth: 180, ellipsis: { tooltip: true }, render: (r) => h('span', { class: 'text-[13px]' }, r.channelName || '—') },
{ title: '状态', key: 'status', width: 80, render: statusCell },
{ title: 'Tokens(入/出)', key: 'tokens', width: 150, render: tokensCell },
{ title: 'Tokens(入/出)', key: 'tokens', width: 190, render: tokensCell },
{ title: '耗时', key: 'latencyMs', width: 80, render: (r) => h('span', { class: 'mono text-[13px]' }, fmtLatency(r.latencyMs)) },
{ title: '重试', key: 'retries', width: 60, render: (r) => h('span', { class: 'mono text-[13px]' }, String(r.retries)) },
]
@@ -194,10 +203,10 @@ const footerText = computed(() => {
<template>
<div class="panel">
<div class="border-b border-line-soft px-4.5 py-3">
<div class="text-sm font-semibold">AI 调用日志</div>
<div class="mt-0.5 text-xs text-ink-3">仅元数据与 token 用量,不记录对话内容;保留 90 / 5 万行 · 5 秒自动刷新</div>
</div>
<PanelHeader
title="AI 调用日志"
desc="仅元数据与 token 用量;保留 90 天 / 5 万行"
/>
<NDataTable
remote
:columns="columns"
@@ -206,10 +215,11 @@ const footerText = computed(() => {
:pagination="pagination"
:bordered="false"
:row-props="rowProps"
:scroll-x="1230"
size="small"
/>
<NModal v-model:show="showDetail" preset="card" closable :style="{ width: '600px', maxWidth: 'calc(100vw - 24px)' }">
<NModal v-model:show="showDetail" preset="card" closable :style="modalStyle" :class="modalClass">
<template #header>
<DetailHero
v-if="detail"
+49 -63
View File
@@ -1,29 +1,30 @@
<script setup lang="ts">
import { NDataTable, NModal, NPopover, type DataTableColumns } from 'naive-ui'
import { NDataTable, NModal, type DataTableColumns } from 'naive-ui'
import { computed, h, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { listConfigs } from '@/api/configs'
import { listLogEvents } from '@/api/logevents'
import DetailFieldList, { type DetailRow } from '@/components/DetailFieldList.vue'
import DetailHero, { type HeroChip } from '@/components/DetailHero.vue'
import FootNote from '@/components/FootNote.vue'
import JsonBlock from '@/components/JsonBlock.vue'
import PanelHeader from '@/components/PanelHeader.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import TenantHoverCard from '@/components/TenantHoverCard.vue'
import TenantPicker from '@/components/TenantPicker.vue'
import { eventLabel, eventTail } from '@/composables/useEventLabel'
import { useAutoRefresh } from '@/composables/useAutoRefresh'
import { fmtTime } from '@/composables/useFormat'
import { useIsMobile } from '@/composables/useIsMobile'
import { useMobileModal } from '@/composables/useMobileModal'
import { useAsync } from '@/composables/useAsync'
import { useRegionAlias } from '@/composables/useRegionAlias'
import { useScopeStore } from '@/stores/scope'
import type { LogEvent, OciConfigSummary } from '@/types/api'
import { useToast } from '@/composables/useToast'
const isMobile = useIsMobile()
const { modalStyle, modalClass } = useMobileModal(720)
const message = useToast()
const router = useRouter()
const scope = useScopeStore()
const { alias: regionAlias } = useRegionAlias()
const rows = ref<LogEvent[]>([])
const loading = ref(false)
@@ -48,6 +49,10 @@ const pagination = reactive({
itemCount: 0,
showSizePicker: true,
pageSizes: [20, 50, 100],
// 移动端页码槽位放不下会被裁切,切 simple 形态(‹ n/总页 )
get simple() {
return isMobile.value
},
onUpdatePage: (p: number) => {
pagination.page = p
void load()
@@ -87,35 +92,17 @@ const aliasById = computed(() => {
return map
})
/** 租户单元格:点击跳租户详情(阻止冒泡到行详情);hover 只展示值不加标签 */
/** 租户单元格:悬停出统一租户卡(别名/名称/主区域/前往租户),名称本身不跳转 */
function renderTenant(row: LogEvent) {
const label = aliasById.value.get(row.ociConfigId) ?? `#${row.ociConfigId}`
const cfg = cfgById.value.get(row.ociConfigId)
const link = h(
'span',
{
class: 'cursor-pointer border-b border-dashed border-ink-3/50 text-[13px] hover:text-accent',
onClick: (e: MouseEvent) => {
e.stopPropagation()
void router.push({ name: 'tenant-detail', params: { id: row.ociConfigId } })
},
},
return h(TenantHoverCard, {
cfgId: row.ociConfigId,
label,
)
if (!cfg) return link
return h(
NPopover,
{ trigger: 'hover', placement: 'right' },
{
trigger: () => link,
default: () =>
h('div', { class: 'flex flex-col gap-1 text-xs' }, [
h('div', { class: 'font-medium text-[13px]' }, cfg.alias),
h('div', { class: 'mono text-ink-2' }, cfg.tenancyName),
h('div', { class: 'text-ink-2' }, regionAlias(cfg.region)),
]),
},
)
alias: cfg?.alias,
tenancyName: cfg?.tenancyName,
region: cfg?.region,
})
}
/** 摘要头标题:事件中文名 → 类型尾段 → 解析状态兜底 */
@@ -167,9 +154,10 @@ const columns: DataTableColumns<LogEvent> = [
render: renderTenant,
},
{
// 固定宽:常见事件类型约 45 字符,弹性空间让给来源列
title: '事件类型',
key: 'eventType',
minWidth: 280,
width: 400,
ellipsis: { tooltip: true },
render: (row) =>
row.eventType
@@ -186,9 +174,10 @@ const columns: DataTableColumns<LogEvent> = [
: h('span', { class: 'text-[13px] text-ink-3' }, '—'),
},
{
// 弹性列:实例名可较长,宽屏下尽量完整展示
title: '来源',
key: 'source',
width: 160,
minWidth: 160,
ellipsis: { tooltip: true },
render: (row) => h('span', { class: 'text-[13px] text-ink-2' }, row.source || '—'),
},
@@ -211,27 +200,32 @@ useAutoRefresh(() => load(true))
<template>
<div class="panel">
<div
class="flex flex-wrap items-center justify-between gap-3 border-b border-line-soft px-4.5 py-3.5"
>
<div class="min-w-0">
<div class="text-sm font-semibold">回传日志</div>
<div class="mt-0.5 text-xs text-ink-3">
OCI 侧推送的关键审计事件(Connector Hub Notifications 面板 webhook)
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<TenantPicker
v-model:value="cfgFilter"
size="small"
clearable
placeholder="全部租户"
class="w-52"
:configs="scope.configs.data ?? []"
:loading="scope.configs.loading"
@update:value="onFilter"
/>
</div>
<PanelHeader title="回传日志" desc="OCI 侧推送的关键审计事件">
<TenantPicker
v-if="!isMobile"
v-model:value="cfgFilter"
size="small"
clearable
placeholder="全部租户"
class="w-52"
placement="bottom-end"
:configs="scope.configs.data ?? []"
:loading="scope.configs.loading"
@update:value="onFilter"
/>
</PanelHeader>
<!-- 移动端筛选独立成行全宽,不与标题挤同一行 -->
<div v-if="isMobile" class="border-b border-line-soft px-4.5 py-2.5">
<TenantPicker
v-model:value="cfgFilter"
size="small"
clearable
placeholder="全部租户"
class="w-full"
:configs="scope.configs.data ?? []"
:loading="scope.configs.loading"
@update:value="onFilter"
/>
</div>
<NDataTable
remote
@@ -240,18 +234,10 @@ useAutoRefresh(() => load(true))
:loading="loading"
:pagination="pagination"
:scroll-x="880"
:max-height="480"
:row-key="(r: LogEvent) => r.id"
:row-props="rowProps"
/>
<FootNote>
在租户详情「其他」tab 一键创建链路后,实例生命周期(Launch/Terminate/InstanceAction)、
用户与凭据(Create/Delete/UpdateUser、Create/DeleteApiKey、UpdateUserCapabilities)、
区域订阅与策略变更等关键审计事件将自动回传;消息按 MessageId 幂等去重,保留 90
天、总量超 2 万条时删除最旧,关键事件另经「通知管理 → 云端事件」推送告警
</FootNote>
<NModal v-model:show="showDetail" preset="card" closable :style="{ width: '720px', maxWidth: 'calc(100vw - 24px)' }">
<NModal v-model:show="showDetail" preset="card" closable :style="modalStyle" :class="modalClass">
<template #header>
<DetailHero
v-if="detail"
+25 -17
View File
@@ -5,15 +5,19 @@ import { computed, h, reactive, ref } from 'vue'
import { listSystemLogs } from '@/api/settings'
import DetailFieldList, { type DetailRow } from '@/components/DetailFieldList.vue'
import DetailHero, { type HeroChip } from '@/components/DetailHero.vue'
import FootNote from '@/components/FootNote.vue'
import JsonBlock from '@/components/JsonBlock.vue'
import PanelHeader from '@/components/PanelHeader.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { actionLabel } from '@/composables/useActionLabel'
import { useAutoRefresh } from '@/composables/useAutoRefresh'
import { fmtTime } from '@/composables/useFormat'
import { useIsMobile } from '@/composables/useIsMobile'
import { useMobileModal } from '@/composables/useMobileModal'
import type { SystemLog } from '@/types/api'
import { useToast } from '@/composables/useToast'
const isMobile = useIsMobile()
const { modalStyle, modalClass } = useMobileModal(640)
const message = useToast()
const rows = ref<SystemLog[]>([])
@@ -29,6 +33,10 @@ const pagination = reactive({
itemCount: 0,
showSizePicker: true,
pageSizes: [20, 50, 100],
// 移动端页码槽位放不下会被裁切,切 simple 形态(‹ n/总页 )
get simple() {
return isMobile.value
},
onUpdatePage: (p: number) => {
pagination.page = p
void load()
@@ -161,19 +169,25 @@ useAutoRefresh(() => load(true))
<template>
<div class="panel">
<div
class="flex flex-wrap items-center justify-between gap-3 border-b border-line-soft px-4.5 py-3.5"
>
<div class="min-w-0">
<div class="text-sm font-semibold">系统日志</div>
<div class="mt-0.5 text-xs text-ink-3">面板写操作与登录成败留痕用于审计与排障</div>
</div>
<PanelHeader title="系统日志" desc="面板写操作与登录成败留痕,用于审计与排障">
<NInput
v-if="!isMobile"
v-model:value="keyword"
size="small"
clearable
placeholder="搜索路径 / 用户名"
class="!w-64"
@keyup.enter="search"
@clear="onClear"
/>
</PanelHeader>
<!-- 移动端筛选独立成行全宽,不与标题挤同一行 -->
<div v-if="isMobile" class="border-b border-line-soft px-4.5 py-2.5">
<NInput
v-model:value="keyword"
size="small"
clearable
placeholder="搜索路径 / 用户名,回车确认"
class="max-w-60"
placeholder="搜索路径 / 用户名"
@keyup.enter="search"
@clear="onClear"
/>
@@ -188,13 +202,7 @@ useAutoRefresh(() => load(true))
:row-key="(r: SystemLog) => r.id"
:row-props="rowProps"
/>
<FootNote>
自动记录 secured 接口的全部写请求(POST / PUT /
DELETE)与登录成败,只存方法与路径等元数据、绝不记录请求体;失败请求另存响应错误文案与
User-Agent;日志保留 90 天,总量超 5 万条时自动删除最旧记录 · 点击行查看详情
</FootNote>
<NModal v-model:show="showDetail" preset="card" closable :style="{ width: '640px', maxWidth: 'calc(100vw - 24px)' }">
<NModal v-model:show="showDetail" preset="card" closable :style="modalStyle" :class="modalClass">
<template #header>
<DetailHero
v-if="detail"
+250
View File
@@ -0,0 +1,250 @@
<script setup lang="ts">
import { NButton, NDataTable, NModal, NSelect, type DataTableColumns } from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import { listInstances } from '@/api/instances'
import { assignReservedIp, createReservedIp, deleteReservedIp, listReservedIps } from '@/api/reservedips'
import ConfirmPop from '@/components/ConfirmPop.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { fmtTime } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import { useMobileModal } from '@/composables/useMobileModal'
import type { ReservedIp } from '@/types/api'
import { useToast } from '@/composables/useToast'
const props = defineProps<{ cfgId: number | null; region?: string; compartmentId?: string }>()
const message = useToast()
const { modalStyle, modalClass } = useMobileModal(420)
const ips = useAsync<ReservedIp[]>(async () => {
if (!props.cfgId) return []
try {
return await listReservedIps(props.cfgId, props.region, props.compartmentId)
} catch {
return []
}
}, false)
watch([() => props.cfgId, () => props.region, () => props.compartmentId], () => void ips.run(), {
immediate: true,
})
const creating = ref(false)
async function create() {
if (!props.cfgId) return
creating.value = true
try {
await createReservedIp(props.cfgId, props.region, undefined, props.compartmentId)
message.success('保留 IP 已创建')
void ips.run()
} catch (e) {
message.error(e instanceof Error ? e.message : '创建失败')
} finally {
creating.value = false
}
}
// ---- 绑定实例弹窗 ----
const showBind = ref(false)
const bindTarget = ref<ReservedIp | null>(null)
const bindInstanceId = ref<string | null>(null)
const binding = ref(false)
const instances = useAsync(async () => {
if (!props.cfgId) return []
try {
return await listInstances(props.cfgId, props.region, props.compartmentId)
} catch {
return []
}
}, false)
const instanceOptions = computed(() =>
(instances.data.value ?? [])
.filter((i) => !['TERMINATED', 'TERMINATING'].includes(i.lifecycleState))
.map((i) => ({ label: `${i.displayName}(${i.publicIp || '无公网 IP'})`, value: i.id })),
)
function openBind(row: ReservedIp) {
bindTarget.value = row
bindInstanceId.value = null
showBind.value = true
void instances.run()
}
async function doBind() {
if (!props.cfgId || !bindTarget.value || !bindInstanceId.value) return
binding.value = true
try {
await assignReservedIp(props.cfgId, bindTarget.value.id, bindInstanceId.value, props.region)
message.success('已绑定;实例原临时公网 IP 已释放')
showBind.value = false
void ips.run()
} catch (e) {
message.error(e instanceof Error ? e.message : '绑定失败')
} finally {
binding.value = false
}
}
async function unbind(row: ReservedIp) {
if (!props.cfgId) return
try {
await assignReservedIp(props.cfgId, row.id, '', props.region)
message.success('已解绑,实例暂无公网 IP')
void ips.run()
} catch (e) {
message.error(e instanceof Error ? e.message : '解绑失败')
}
}
async function remove(row: ReservedIp) {
if (!props.cfgId) return
try {
await deleteReservedIp(props.cfgId, row.id, props.region)
message.success('保留 IP 已删除')
void ips.run()
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败')
}
}
const columns = computed<DataTableColumns<ReservedIp>>(() => [
{
title: 'IP 地址',
key: 'ipAddress',
minWidth: 140,
render: (r) => h('span', { class: 'mono' }, r.ipAddress || '分配中…'),
},
{
title: '名称',
key: 'displayName',
minWidth: 130,
render: (r) => h('span', { class: 'text-[13px]' }, r.displayName),
},
{
title: '状态',
key: 'assigned',
minWidth: 110,
render: (r) =>
r.assignedInstanceId
? h(StatusBadge, { kind: 'run', label: '已绑定', dot: false })
: h(StatusBadge, { kind: 'check', label: '未绑定', dot: false }),
},
{
title: '绑定实例',
key: 'assignedInstanceName',
minWidth: 150,
render: (r) =>
h(
'span',
{ class: 'text-[13px] text-ink-2' },
r.assignedInstanceName || (r.assignedInstanceId ? r.assignedInstanceId.slice(-8) : '—'),
),
},
{
title: '创建时间',
key: 'timeCreated',
width: 150,
render: (r) => h('span', { class: 'text-[13px] text-ink-2' }, fmtTime(r.timeCreated)),
},
{
title: '操作',
key: 'actions',
width: 150,
render: (r) =>
h('div', { class: 'flex items-center gap-1' }, [
r.assignedInstanceId
? h(
ConfirmPop,
{
title: '解绑该保留 IP',
content: '解绑后实例将暂无公网 IP,直到重新绑定或分配临时 IP。',
kind: 'plain',
confirmText: '解绑',
onConfirm: () => unbind(r),
},
{ trigger: () => h(NButton, { size: 'tiny', quaternary: true }, { default: () => '解绑' }) },
)
: h(
NButton,
{ size: 'tiny', quaternary: true, onClick: () => openBind(r) },
{ default: () => '绑定实例' },
),
h(
ConfirmPop,
{
title: '删除该保留 IP',
content: '地址将归还 Oracle,无法找回。',
confirmText: '删除',
onConfirm: () => remove(r),
},
{
trigger: () =>
h(
NButton,
{ size: 'tiny', quaternary: true, type: 'error', disabled: !!r.assignedInstanceId },
{ default: () => '删除' },
),
},
),
]),
},
])
</script>
<template>
<div class="panel">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div>
<div class="text-sm font-semibold">保留 IP</div>
<div class="mt-0.5 text-xs text-ink-3">
区域级固定公网 IP,可换绑实例或创建实例时选用
</div>
</div>
<NButton size="small" type="primary" :loading="creating" @click="create">创建保留 IP</NButton>
</div>
<NDataTable
:columns="columns"
:data="ips.data.value ?? []"
:loading="ips.loading.value"
:scroll-x="820"
:row-key="(r: ReservedIp) => r.id"
/>
<NModal
v-model:show="showBind"
preset="card"
title="绑定保留 IP 到实例"
:style="modalStyle"
:class="modalClass"
>
<div class="flex flex-col gap-3">
<div class="text-[13px] text-ink-2">
将 <span class="mono">{{ bindTarget?.ipAddress }}</span> 绑定到实例主网卡;
实例现有临时公网 IP 会被释放,公网地址变更为该保留 IP。
</div>
<NSelect
v-model:value="bindInstanceId"
:options="instanceOptions"
:loading="instances.loading.value"
placeholder="选择实例"
filterable
/>
<div class="flex justify-end gap-2">
<NButton size="small" @click="showBind = false">取消</NButton>
<NButton
size="small"
type="primary"
:disabled="!bindInstanceId"
:loading="binding"
@click="doBind"
>
绑定
</NButton>
</div>
</div>
</NModal>
</div>
</template>
@@ -0,0 +1,295 @@
<script setup lang="ts">
import { NButton, NInput, NInputNumber, NSelect } from 'naive-ui'
import { reactive, ref } from 'vue'
import { updateSecurityList } from '@/api/networks'
import ConfirmPop from '@/components/ConfirmPop.vue'
import type { SecurityList, SecurityRule } from '@/types/api'
import { useToast } from '@/composables/useToast'
const props = defineProps<{
cfgId: number
list: SecurityList
region?: string
}>()
const emit = defineEmits<{ updated: [] }>()
const message = useToast()
type Dir = 'ingress' | 'egress'
const PROTOCOLS = [
{ label: '全部', value: 'all' },
{ label: 'TCP', value: '6' },
{ label: 'UDP', value: '17' },
{ label: 'ICMP', value: '1' },
{ label: 'ICMPv6', value: '58' },
]
function protoLabel(p: string): string {
return PROTOCOLS.find((o) => o.value === p)?.label ?? p
}
function portText(r: SecurityRule): string {
if (r.protocol !== '6' && r.protocol !== '17') return '—'
if (!r.portMin) return '全部'
return r.portMax && r.portMax !== r.portMin ? `${r.portMin}-${r.portMax}` : String(r.portMin)
}
/** 编辑缓冲;idx 为 -1 表示新增行 */
const editing = ref<{ dir: Dir; idx: number } | null>(null)
const draft = reactive<SecurityRule>({ protocol: '6', isStateless: false })
const saving = ref(false)
function rulesOf(dir: Dir): SecurityRule[] {
return dir === 'ingress' ? (props.list.ingressRules ?? []) : (props.list.egressRules ?? [])
}
function startEdit(dir: Dir, idx: number) {
const src = idx >= 0 ? rulesOf(dir)[idx] : undefined
Object.assign(draft, {
protocol: src?.protocol ?? '6',
source: src?.source,
destination: src?.destination,
isStateless: src?.isStateless ?? false,
portMin: src?.portMin,
portMax: src?.portMax,
description: src?.description,
})
if (!src) {
if (dir === 'ingress') draft.source = '0.0.0.0/0'
else draft.destination = '0.0.0.0/0'
}
editing.value = { dir, idx }
}
function buildDraft(dir: Dir): SecurityRule {
const r: SecurityRule = { protocol: draft.protocol, isStateless: false }
if (dir === 'ingress') r.source = draft.source?.trim()
else r.destination = draft.destination?.trim()
if (draft.protocol === '6' || draft.protocol === '17') {
if (draft.portMin) {
r.portMin = draft.portMin
r.portMax = draft.portMax || draft.portMin
}
}
if (draft.description?.trim()) r.description = draft.description.trim()
return r
}
/** 整表替换提交:规则字段一经提供即全量覆盖,两方向都要带上 */
async function submit(ingress: SecurityRule[], egress: SecurityRule[]) {
saving.value = true
try {
await updateSecurityList(props.cfgId, props.list.id, {
region: props.region,
ingressRules: ingress,
egressRules: egress,
})
message.success('规则已保存')
editing.value = null
emit('updated')
} catch (e) {
message.error(e instanceof Error ? e.message : '保存失败')
} finally {
saving.value = false
}
}
function saveEditing() {
const ed = editing.value
if (!ed) return
const cidr = ed.dir === 'ingress' ? draft.source : draft.destination
if (!cidr?.trim()) {
message.warning('CIDR 不能为空')
return
}
const next = rulesOf(ed.dir).slice()
const rule = buildDraft(ed.dir)
if (ed.idx >= 0) next[ed.idx] = rule
else next.push(rule)
const ing = ed.dir === 'ingress' ? next : (props.list.ingressRules ?? [])
const eg = ed.dir === 'egress' ? next : (props.list.egressRules ?? [])
void submit(ing, eg)
}
function removeRule(dir: Dir, idx: number): Promise<void> {
const next = rulesOf(dir).filter((_, i) => i !== idx)
const ing = dir === 'ingress' ? next : (props.list.ingressRules ?? [])
const eg = dir === 'egress' ? next : (props.list.egressRules ?? [])
return submit(ing, eg)
}
function isEditing(dir: Dir, idx: number): boolean {
return editing.value?.dir === dir && editing.value.idx === idx
}
</script>
<template>
<div class="flex flex-col gap-3 py-1">
<div v-for="dir in ['ingress', 'egress'] as const" :key="dir">
<div class="mb-1.5 text-[11.5px] font-semibold tracking-wide text-ink-3 uppercase">
{{ dir === 'ingress' ? '入站规则' : '出站规则' }}
</div>
<div class="overflow-hidden rounded-lg border border-line-soft bg-white">
<table class="w-full border-collapse text-[12.5px]">
<thead>
<tr class="text-left text-xs text-ink-3">
<th class="border-b border-line-soft px-3.5 py-1.5 font-semibold w-28">协议</th>
<th class="border-b border-line-soft px-3.5 py-1.5 font-semibold w-44">
{{ dir === 'ingress' ? '源' : '目标' }}
</th>
<th class="border-b border-line-soft px-3.5 py-1.5 font-semibold w-36">端口</th>
<th class="border-b border-line-soft px-3.5 py-1.5 font-semibold">描述</th>
<th class="border-b border-line-soft px-3.5 py-1.5 text-right font-semibold w-24">操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(r, idx) in rulesOf(dir)" :key="idx" :class="isEditing(dir, idx) ? 'bg-wash/60' : ''">
<template v-if="isEditing(dir, idx)">
<td class="border-b border-line-soft px-3.5 py-1.5">
<NSelect
v-model:value="draft.protocol"
size="tiny"
:options="PROTOCOLS"
class="!w-24"
:consistent-menu-width="false"
/>
</td>
<td class="border-b border-line-soft px-3.5 py-1.5">
<NInput
v-if="dir === 'ingress'"
v-model:value="draft.source"
size="tiny"
placeholder="0.0.0.0/0"
/>
<NInput v-else v-model:value="draft.destination" size="tiny" placeholder="0.0.0.0/0" />
</td>
<td class="border-b border-line-soft px-3.5 py-1.5">
<div
v-if="draft.protocol === '6' || draft.protocol === '17'"
class="flex items-center gap-1"
>
<NInputNumber
v-model:value="draft.portMin"
size="tiny"
:show-button="false"
placeholder="起"
class="!w-16"
/>
<span class="text-ink-3">-</span>
<NInputNumber
v-model:value="draft.portMax"
size="tiny"
:show-button="false"
placeholder="止"
class="!w-16"
/>
</div>
<span v-else class="text-ink-3"></span>
</td>
<td class="border-b border-line-soft px-3.5 py-1.5">
<NInput v-model:value="draft.description" size="tiny" placeholder="描述(可选)" />
</td>
<td class="border-b border-line-soft px-3.5 py-1.5 text-right whitespace-nowrap">
<NButton size="tiny" type="primary" :loading="saving" @click="saveEditing">保存</NButton>
<NButton size="tiny" quaternary class="ml-1" :disabled="saving" @click="editing = null">
取消
</NButton>
</td>
</template>
<template v-else>
<td class="border-b border-line-soft px-3.5 py-1.5">{{ protoLabel(r.protocol) }}</td>
<td class="mono border-b border-line-soft px-3.5 py-1.5">
{{ dir === 'ingress' ? r.source : r.destination }}
</td>
<td class="mono border-b border-line-soft px-3.5 py-1.5">{{ portText(r) }}</td>
<td class="border-b border-line-soft px-3.5 py-1.5 text-ink-2">{{ r.description || '—' }}</td>
<td class="border-b border-line-soft px-3.5 py-1.5 text-right whitespace-nowrap">
<NButton size="tiny" quaternary :disabled="!!editing" @click="startEdit(dir, idx)">
编辑
</NButton>
<ConfirmPop
title="删除该条规则?"
:content="`${protoLabel(r.protocol)} ${dir === 'ingress' ? r.source : r.destination} ${portText(r)}`"
:on-confirm="() => removeRule(dir, idx)"
>
<template #trigger>
<NButton size="tiny" quaternary type="error" class="ml-1" :disabled="!!editing">
删除
</NButton>
</template>
</ConfirmPop>
</td>
</template>
</tr>
<tr v-if="editing && editing.dir === dir && editing.idx === -1" class="bg-wash/60">
<td class="border-b border-line-soft px-3.5 py-1.5">
<NSelect
v-model:value="draft.protocol"
size="tiny"
:options="PROTOCOLS"
class="!w-24"
:consistent-menu-width="false"
/>
</td>
<td class="border-b border-line-soft px-3.5 py-1.5">
<NInput
v-if="dir === 'ingress'"
v-model:value="draft.source"
size="tiny"
placeholder="0.0.0.0/0"
/>
<NInput v-else v-model:value="draft.destination" size="tiny" placeholder="0.0.0.0/0" />
</td>
<td class="border-b border-line-soft px-3.5 py-1.5">
<div
v-if="draft.protocol === '6' || draft.protocol === '17'"
class="flex items-center gap-1"
>
<NInputNumber
v-model:value="draft.portMin"
size="tiny"
:show-button="false"
placeholder=""
class="!w-16"
/>
<span class="text-ink-3">-</span>
<NInputNumber
v-model:value="draft.portMax"
size="tiny"
:show-button="false"
placeholder=""
class="!w-16"
/>
</div>
<span v-else class="text-ink-3">—</span>
</td>
<td class="border-b border-line-soft px-3.5 py-1.5">
<NInput v-model:value="draft.description" size="tiny" placeholder="描述(可选)" />
</td>
<td class="border-b border-line-soft px-3.5 py-1.5 text-right whitespace-nowrap">
<NButton size="tiny" type="primary" :loading="saving" @click="saveEditing">保存</NButton>
<NButton size="tiny" quaternary class="ml-1" :disabled="saving" @click="editing = null">
取消
</NButton>
</td>
</tr>
<tr>
<td colspan="5" class="px-3.5 py-1.5">
<NButton
size="tiny"
dashed
:disabled="!!editing"
@click="startEdit(dir, -1)"
>
+ 添加{{ dir === 'ingress' ? '入站' : '出站' }}规则
</NButton>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
@@ -0,0 +1,26 @@
import type { SelectOption } from 'naive-ui'
import { h, type VNodeChild } from 'vue'
import type { ReservedIp } from '@/types/api'
export interface ReservedIpOption extends SelectOption {
label: string
value: string
name: string
}
/** 未绑定保留 IP → 下拉选项:label 仅 IP(回显紧凑不截断),名称在选项行内弱化展示 */
export function freeReservedIpOptions(ips: ReservedIp[]): ReservedIpOption[] {
return ips
.filter((r) => !r.assignedInstanceId)
.map((r) => ({ label: r.ipAddress || r.id.slice(-12), value: r.id, name: r.displayName }))
}
/** NSelect renderLabel:IP 等宽字体 + 名称灰字截断;配合 consistent-menu-width=false 使用 */
export function renderReservedIpLabel(option: SelectOption): VNodeChild {
const o = option as ReservedIpOption
return h('div', { class: 'flex min-w-0 items-baseline gap-2' }, [
h('span', { class: 'mono text-[13px]' }, o.label),
o.name ? h('span', { class: 'max-w-44 truncate text-xs text-ink-3' }, o.name) : null,
])
}
+58
View File
@@ -0,0 +1,58 @@
<script setup lang="ts">
import { computed } from 'vue'
import { extOf } from '@/components/objectstorage/codeHighlight'
import { FILE_ICON_BODIES } from '@/components/objectstorage/fileIcons'
const props = defineProps<{ name?: string; folder?: boolean; size?: number }>()
/** 扩展名 → Catppuccin 图标名;不在表内用通用 file */
const EXT_ICON: Record<string, string> = {
png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', webp: 'image',
svg: 'image', bmp: 'image', ico: 'image', avif: 'image',
json: 'json',
yaml: 'yaml', yml: 'yaml',
toml: 'toml',
ini: 'properties', conf: 'properties', cfg: 'properties', env: 'properties', properties: 'properties',
py: 'python',
js: 'javascript', mjs: 'javascript', cjs: 'javascript',
ts: 'typescript',
md: 'markdown',
sql: 'database', db: 'database', sqlite: 'database',
sh: 'bash', bash: 'bash', zsh: 'bash',
go: 'go',
zip: 'zip', tar: 'zip', gz: 'zip', tgz: 'zip', '7z': 'zip', rar: 'zip', bz2: 'zip', xz: 'zip',
pdf: 'pdf',
mp4: 'video', mov: 'video', mkv: 'video', avi: 'video', webm: 'video',
mp3: 'audio', wav: 'audio', flac: 'audio', ogg: 'audio', m4a: 'audio',
html: 'html', htm: 'html',
css: 'css', scss: 'css', less: 'css',
txt: 'text',
log: 'log',
csv: 'csv', tsv: 'csv',
xml: 'xml',
bin: 'binary', exe: 'binary', dmg: 'binary', iso: 'binary', img: 'binary', qcow2: 'binary',
doc: 'ms-word', docx: 'ms-word',
xls: 'ms-excel', xlsx: 'ms-excel',
ppt: 'ms-powerpoint', pptx: 'ms-powerpoint',
}
const body = computed(() => {
if (props.folder) return FILE_ICON_BODIES.folder
const key = EXT_ICON[extOf(props.name ?? '')] ?? 'file'
return FILE_ICON_BODIES[key] ?? FILE_ICON_BODIES.file
})
</script>
<template>
<!-- eslint-disable vue/no-v-html -- 图标 body 为构建期静态常量(Catppuccin Icons),非用户输入 -->
<svg
:width="size ?? 16"
:height="size ?? 16"
viewBox="0 0 16 16"
class="inline-block flex-none align-[-3px]"
aria-hidden="true"
v-html="body"
></svg>
<!-- eslint-enable vue/no-v-html -->
</template>
@@ -0,0 +1,900 @@
<script setup lang="ts">
import {
NButton,
NDataTable,
NDropdown,
NInput,
NRadio,
NRadioGroup,
NTabPane,
NTabs,
type DataTableColumns,
} from 'naive-ui'
import { computed, h, onBeforeUnmount, reactive, ref, watch } from 'vue'
import {
createPar,
deleteObject,
deletePar,
listObjects,
restoreObject,
uploadViaPar,
} from '@/api/objectstorage'
import AppInputNumber from '@/components/AppInputNumber.vue'
import ConfirmPop from '@/components/ConfirmPop.vue'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import FileIcon from '@/components/objectstorage/FileIcon.vue'
import ObjectViewerModal from '@/components/objectstorage/ObjectViewerModal.vue'
import ParPanel from '@/components/objectstorage/ParPanel.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { fmtBytes, fmtTime } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import { useIsMobile } from '@/composables/useIsMobile'
import type { Bucket, ObjectSummary } from '@/types/api'
import { useToast } from '@/composables/useToast'
const props = defineProps<{
cfgId: number | null
region?: string
bucket: string
/** 桶列表信息:hero 徽标与统计、查看器公网 URL 等;直达链接列表未回时为空 */
info?: Bucket
}>()
const emit = defineEmits<{ back: []; settings: [] }>()
const message = useToast()
/** hero 与 Tab:对象浏览 / 分享链接(PAR) */
const tab = ref<'objects' | 'par'>('objects')
/** 移动端 hero meta 默认收起,与租户/实例/VCN 详情一致 */
const isMobile = useIsMobile()
const heroExpanded = ref(false)
const PAGE_SIZE = 100
const prefix = ref('')
/** 本层搜索词:对当前已加载的行做客户端子串匹配,不发起服务端查询 */
const filterInput = ref('')
/** 上页游标栈:OCI 只回传 next 游标,上一页靠历史栈回放 */
const cursorStack = ref<string[]>([])
const cursor = ref('')
const result = useAsync(async () => {
if (!props.cfgId) return { objects: [], prefixes: [], nextStartWith: '' }
return listObjects(props.cfgId, props.bucket, {
region: props.region,
prefix: prefix.value,
startWith: cursor.value || undefined,
limit: PAGE_SIZE,
})
}, false)
watch([() => props.cfgId, () => props.bucket, prefix, cursor], () => void result.run(), {
immediate: true,
})
/** 有对象取回中(Restoring)时后台静默轮询,状态落定自动停 */
const POLL_MS = 30_000
let pollTimer = 0
watch(
() => (result.data.value?.objects ?? []).some((o) => o.archivalState === 'Restoring'),
(has) => {
window.clearInterval(pollTimer)
if (has) pollTimer = window.setInterval(() => void result.run({ silent: true }), POLL_MS)
},
)
onBeforeUnmount(() => window.clearInterval(pollTimer))
function enterFolder(p: string) {
cursorStack.value = []
cursor.value = ''
prefix.value = p
filterInput.value = ''
}
/** 面包屑段:桶根 + prefix 逐级 */
const crumbs = computed(() => {
const parts = prefix.value.split('/').filter(Boolean)
return parts.map((seg, i) => ({ label: `${seg}/`, prefix: parts.slice(0, i + 1).join('/') + '/' }))
})
/** 层级过深时仅展示末 2 段,其余收进「…」下拉,避免面包屑占满整行 */
const visibleCrumbs = computed(() =>
crumbs.value.length > 3 ? crumbs.value.slice(-2) : crumbs.value,
)
const foldedOptions = computed(() =>
crumbs.value.length > 3
? crumbs.value.slice(0, -2).map((c) => ({ label: c.prefix, key: c.prefix }))
: [],
)
function nextPage() {
const next = result.data.value?.nextStartWith
if (!next) return
cursorStack.value.push(cursor.value)
cursor.value = next
}
function prevPage() {
cursor.value = cursorStack.value.pop() ?? ''
}
// ---- : / , ----
interface TransferTask {
id: number
kind: 'up' | 'down'
name: string
percent: number
status: 'active' | 'done' | 'error'
/** 附注:如「已交由浏览器下载」(无进度) */
note?: string
error?: string
abort: () => void
retry: () => void
}
const transfers = ref<TransferTask[]>([])
const transfersCollapsed = ref(false)
let taskSeq = 0
const activeCount = computed(() => transfers.value.filter((t) => t.status === 'active').length)
const doneCount = computed(() => transfers.value.filter((t) => t.status === 'done').length)
function newTask(kind: 'up' | 'down', name: string, retry: () => void): TransferTask {
const task = reactive<TransferTask>({
id: ++taskSeq, kind, name, percent: 0, status: 'active', abort: () => {}, retry,
})
transfers.value.push(task)
transfersCollapsed.value = false
return task
}
function removeTask(task: TransferTask) {
task.abort()
transfers.value = transfers.value.filter((t) => t !== task)
}
function retryTask(task: TransferTask) {
transfers.value = transfers.value.filter((t) => t !== task)
task.retry()
}
function clearDone() {
transfers.value = transfers.value.filter((t) => t.status !== 'done')
}
// ---- :PAR , ----
const fileInput = ref<HTMLInputElement | null>(null)
function pickFiles() {
fileInput.value?.click()
}
async function onFilesPicked(e: Event) {
const files = [...((e.target as HTMLInputElement).files ?? [])]
;(e.target as HTMLInputElement).value = ''
await Promise.all(files.map((f) => uploadOne(f)))
void result.run({ silent: true })
}
/** objectName 进闭包:重试时不受当前浏览层级变化影响 */
function uploadOne(file: File, objectName = prefix.value + file.name) {
const task = newTask('up', file.name, () => uploadOne(file, objectName))
return doUpload(task, objectName, file)
}
async function doUpload(task: TransferTask, objectName: string, file: File) {
if (!props.cfgId) return
let parId = ''
try {
const par = await createPar(props.cfgId, props.bucket, {
region: props.region,
objectName,
accessType: 'ObjectWrite',
expiresHours: 1,
})
parId = par.id
const { promise, abort } = uploadViaPar(par.fullUrl!, file, (p) => (task.percent = p))
task.abort = abort
await promise
task.status = 'done'
task.percent = 100
} catch (err) {
task.status = 'error'
task.error = err instanceof Error ? err.message : '上传失败'
} finally {
if (parId) void cleanupPar(parId)
}
}
/** 上传用的一次性写链接用后即删,不留在分享链接列表;删除失败静默(1 小时自然过期) */
async function cleanupPar(parId: string) {
try {
await deletePar(props.cfgId!, props.bucket, parId, props.region)
} catch {
/* 忽略 */
} finally {
parPanel.value?.refresh()
}
}
// ---- : fetch , / ----
const DOWN_STREAM_LIMIT = 256 * 1024 * 1024
function download(name: string, size?: number) {
const known = size ?? result.data.value?.objects.find((o) => o.name === name)?.size ?? 0
const task = newTask('down', name.split('/').pop() || name, () => download(name, known))
return doDownload(task, name, known)
}
async function doDownload(task: TransferTask, name: string, size: number) {
if (!props.cfgId) return
try {
const par = await createPar(props.cfgId, props.bucket, {
region: props.region,
objectName: name,
accessType: 'ObjectRead',
expiresHours: 1,
})
const cleanable = await transferDown(task, par.fullUrl!, size)
task.status = 'done'
task.percent = 100
// (1 ),
if (cleanable) void cleanupPar(par.id)
else parPanel.value?.refresh()
} catch (err) {
if ((err as DOMException)?.name === 'AbortError') return
task.status = 'error'
task.error = err instanceof Error ? err.message : '下载失败'
}
}
/** 返回 true 表示内容已就地保存、PAR 可即刻清理;取消(AbortError)原样上抛 */
async function transferDown(task: TransferTask, url: string, size: number): Promise<boolean> {
if (!size || size > DOWN_STREAM_LIMIT) return browserOpen(task, url)
try {
const blob = await fetchWithProgress(task, url, size)
saveBlob(blob, task.name)
return true
} catch (err) {
if ((err as DOMException)?.name === 'AbortError') throw err
return browserOpen(task, url)
}
}
function browserOpen(task: TransferTask, url: string): boolean {
window.open(url, '_blank')
task.note = '已交由浏览器下载'
return false
}
async function fetchWithProgress(task: TransferTask, url: string, size: number): Promise<Blob> {
const ctrl = new AbortController()
task.abort = () => ctrl.abort()
const resp = await fetch(url, { signal: ctrl.signal })
if (!resp.ok || !resp.body) throw new Error(`下载失败(HTTP ${resp.status})`)
const total = Number(resp.headers.get('Content-Length')) || size
const reader = resp.body.getReader()
const chunks: BlobPart[] = []
let loaded = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
loaded += value.byteLength
task.percent = Math.min(99, Math.round((loaded / total) * 100))
}
return new Blob(chunks)
}
function saveBlob(blob: Blob, filename: string) {
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = filename
a.click()
window.setTimeout(() => URL.revokeObjectURL(a.href), 10_000)
}
// ---- : 0 name/ ----
const showNewFolder = ref(false)
const folderName = ref('')
const creatingFolder = ref(false)
async function doCreateFolder() {
if (!props.cfgId || !folderName.value.trim()) return
creatingFolder.value = true
let parId = ''
try {
const name = prefix.value + folderName.value.trim().replace(/\/+$/, '') + '/'
const par = await createPar(props.cfgId, props.bucket, {
region: props.region,
objectName: name,
accessType: 'ObjectWrite',
expiresHours: 1,
})
parId = par.id
await uploadViaPar(par.fullUrl!, new File([], name), () => {}).promise
message.success('文件夹已创建')
showNewFolder.value = false
folderName.value = ''
void result.run()
} catch (e) {
message.error(e instanceof Error ? e.message : '创建失败')
} finally {
if (parId) void cleanupPar(parId)
creatingFolder.value = false
}
}
// ---- ----
async function removeObject(name: string) {
if (!props.cfgId) return
try {
await deleteObject(props.cfgId, props.bucket, name, props.region)
message.success('对象已删除')
checkedKeys.value = checkedKeys.value.filter((k) => k !== name)
void result.run()
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败')
}
}
async function restore(name: string) {
if (!props.cfgId) return
try {
await restoreObject(props.cfgId, props.bucket, name, props.region)
message.success('取回已提交,约 1 小时后可下载 (24 小时有效)')
// Restoring ,
void result.run({ silent: true })
} catch (e) {
message.error(e instanceof Error ? e.message : '取回失败')
}
}
// ---- : ObjectRead*, AnyObjectRead*(objectName ) ----
const showPar = ref(false)
const parBusy = ref(false)
const parForm = reactive<{ objectName: string; accessType: string; expiresHours: number | null }>({
objectName: '',
accessType: 'ObjectRead',
expiresHours: 24,
})
const parUrl = ref('')
const parIsBucket = computed(() => !parForm.objectName)
/** 有效期快捷项;也可直接输入 1-720 任意小时数 */
const QUICK_HOURS = [
{ label: '1 小时', value: 1 },
{ label: '1 天', value: 24 },
{ label: '7 天', value: 168 },
{ label: '30 天', value: 720 },
]
const parPanel = ref<InstanceType<typeof ParPanel> | null>(null)
function openParModal(objectName: string) {
Object.assign(parForm, {
objectName,
accessType: objectName ? 'ObjectRead' : 'AnyObjectRead',
expiresHours: 24,
})
parUrl.value = ''
showPar.value = true
}
async function doCreatePar() {
if (!props.cfgId || !parForm.expiresHours) return
parBusy.value = true
try {
const par = await createPar(props.cfgId, props.bucket, {
region: props.region,
objectName: parForm.objectName,
accessType: parForm.accessType,
expiresHours: parForm.expiresHours,
})
parUrl.value = par.fullUrl ?? ''
parPanel.value?.refresh()
} catch (e) {
message.error(e instanceof Error ? e.message : '签发失败')
} finally {
parBusy.value = false
}
}
async function copyParUrl() {
await navigator.clipboard.writeText(parUrl.value)
message.success('链接已复制')
}
// ---- ----
const checkedKeys = ref<string[]>([])
async function batchDelete() {
for (const name of [...checkedKeys.value]) await removeObject(name)
}
async function batchDownload() {
for (const name of [...checkedKeys.value]) {
await download(name)
await new Promise((r) => setTimeout(r, 300))
}
}
// ---- :,/ ----
const viewerObject = ref('')
const showViewer = ref(false)
function openViewer(name: string) {
viewerObject.value = name
showViewer.value = true
}
interface Row {
key: string
isFolder: boolean
obj?: ObjectSummary
}
const rows = computed<Row[]>(() => {
const data = result.data.value
if (!data) return []
const folders = (data.prefixes ?? []).map((p) => ({ key: p, isFolder: true }))
// ()
const files = (data.objects ?? [])
.filter((o) => o.name !== prefix.value)
.map((o) => ({ key: o.name, isFolder: false, obj: o }))
const all = [...folders, ...files]
const q = filterInput.value.trim().toLowerCase()
if (!q) return all
return all.filter((r) => r.key.slice(prefix.value.length).toLowerCase().includes(q))
})
const columns = computed<DataTableColumns<Row>>(() => [
{ type: 'selection', disabled: (row) => row.isFolder },
{
title: '名称',
key: 'name',
minWidth: 260,
// , tooltip
ellipsis: { tooltip: true },
render: (row) =>
row.isFolder
? h(
'span',
{
class: 'mono inline-flex cursor-pointer items-center gap-1.5 text-[13px] font-medium hover:text-accent',
onClick: () => enterFolder(row.key),
},
[h(FileIcon, { folder: true }), row.key.slice(prefix.value.length)],
)
: h(
'span',
{
class: 'mono inline-flex cursor-pointer items-center gap-1.5 text-[13px] hover:text-accent',
onClick: () => openViewer(row.key),
},
[h(FileIcon, { name: row.key }), row.key.slice(prefix.value.length)],
),
},
{
title: '大小',
key: 'size',
width: 110,
render: (row) => h('span', { class: 'mono text-[12.5px]' }, row.isFolder ? '—' : fmtBytes(row.obj!.size)),
},
{
title: '存储层',
key: 'tier',
width: 110,
render: (row) => {
if (row.isFolder) return h('span', { class: 'text-ink-3' }, '—')
const o = row.obj!
if (o.storageTier === 'Archive')
return h(
'span',
{ class: 'rounded-full bg-warn/14 px-2 py-0.5 text-[11.5px] font-medium text-warn' },
o.archivalState === 'Restored'
? '已取回'
: o.archivalState === 'Restoring'
? '取回中'
: 'Archive',
)
return h('span', { class: 'text-[13px]' }, o.storageTier || 'Standard')
},
},
{
title: '修改时间',
key: 'time',
width: 150,
render: (row) =>
h(
'span',
{ class: 'text-[13px] text-ink-2' },
row.isFolder ? '—' : fmtTime(row.obj!.timeModified),
),
},
{
title: '操作',
key: 'actions',
width: 120,
render: (row) => {
if (row.isFolder) return null
const o = row.obj!
const restoring = o.storageTier === 'Archive' && o.archivalState === 'Restoring'
const archived =
o.storageTier === 'Archive' && o.archivalState !== 'Restored' && !restoring
return h('div', { class: 'flex items-center gap-1' }, [
restoring
? h(
NButton,
{ size: 'tiny', quaternary: true, disabled: true },
{ default: () => '取回中' },
)
: archived
? h(
ConfirmPop,
{
title: '取回 Archive 对象?',
content: '约 1 小时后可下载 (24 小时有效)。',
kind: 'plain',
confirmText: '取回',
onConfirm: () => restore(o.name),
},
{
trigger: () =>
h(NButton, { size: 'tiny', quaternary: true }, { default: () => '恢复' }),
},
)
: h(
NButton,
{ size: 'tiny', quaternary: true, onClick: () => download(o.name, o.size) },
{ default: () => '下载' },
),
h(
ConfirmPop,
{
title: '删除该对象?',
content: '未开版本控制时不可恢复。',
confirmText: '删除',
onConfirm: () => removeObject(o.name),
},
{
trigger: () =>
h(
NButton,
{ size: 'tiny', quaternary: true, type: 'error' },
{ default: () => '删除' },
),
},
),
])
},
},
])
</script>
<template>
<div class="flex flex-col gap-4">
<!-- hero:与租户/VCN 详情同构返回链 + 标题行(徽标/操作)+ meta 栅格(移动可折叠) -->
<div class="panel px-5 py-4">
<button
type="button"
class="mb-2 inline-flex cursor-pointer items-center gap-1.5 text-[13px] text-ink-3 hover:text-ink"
@click="emit('back')"
>
返回存储桶列表
</button>
<div class="flex flex-wrap items-center gap-3">
<h1 class="page-title min-w-0 truncate">{{ bucket }}</h1>
<StatusBadge
v-if="info"
:kind="info.visibility === 'ObjectRead' ? 'prov' : 'check'"
:label="info.visibility === 'ObjectRead' ? '公共读' : '私有'"
:dot="false"
/>
<StatusBadge v-if="info?.versioningOn" kind="run" label="版本控制" :dot="false" />
<div class="flex-1" />
<!-- 操作按钮组:移动端整组独立成行,不随标题换行散落 -->
<div class="flex items-center gap-2 max-md:w-full">
<NButton size="small" @click="openParModal('')">分享桶</NButton>
<NButton size="small" @click="emit('settings')">桶设置</NButton>
<NButton size="small" type="primary" @click="pickFiles">上传对象</NButton>
</div>
<input ref="fileInput" type="file" multiple class="hidden" @change="onFilesPicked" />
</div>
<button
v-if="isMobile"
class="mt-2 flex cursor-pointer items-center gap-1 text-xs text-ink-3"
@click="heroExpanded = !heroExpanded"
>
{{ heroExpanded ? '收起详情' : '展开详情' }}
<svg
class="h-3 w-3 transition-transform"
:class="heroExpanded ? 'rotate-180' : ''"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
>
<path d="m6 9 6 6 6-6" />
</svg>
</button>
<div
v-if="!isMobile || heroExpanded"
class="mt-3 grid grid-cols-4 gap-4 max-lg:grid-cols-2 max-md:grid-cols-1"
>
<div class="min-w-0">
<div class="text-xs text-ink-3">对象数</div>
<div class="mono mt-0.5 text-[13px]">{{ info?.approximateCount ?? '…' }}</div>
</div>
<div class="min-w-0">
<div class="text-xs text-ink-3">已用容量</div>
<div class="mono mt-0.5 text-[13px]">{{ info ? fmtBytes(info.approximateSize) : '…' }}</div>
</div>
<div class="min-w-0">
<div class="text-xs text-ink-3">存储层</div>
<div class="mt-0.5 text-[13px]">{{ info?.storageTier ?? '…' }}</div>
</div>
<div class="min-w-0">
<div class="text-xs text-ink-3">创建时间</div>
<div class="mt-0.5 text-[13px]">{{ info?.timeCreated ? fmtTime(info.timeCreated) : '…' }}</div>
</div>
</div>
</div>
<NTabs v-model:value="tab" type="line">
<NTabPane name="objects" tab="对象" />
<NTabPane name="par" tab="分享链接" />
</NTabs>
<div v-show="tab === 'objects'" class="panel">
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-line-soft px-4.5 py-3 max-md:px-3.5">
<div class="flex min-w-0 flex-wrap items-center gap-1.5 text-[13px] text-ink-3">
<span
class="mono inline-block max-w-48 cursor-pointer truncate align-bottom font-medium text-ink hover:text-accent"
:title="bucket"
@click="enterFolder('')"
>
{{ bucket }}
</span>
<template v-if="foldedOptions.length">
<span>/</span>
<NDropdown trigger="click" :options="foldedOptions" @select="(k: string) => enterFolder(k)">
<span class="cursor-pointer rounded px-1 hover:bg-wash hover:text-ink"></span>
</NDropdown>
</template>
<template v-for="c in visibleCrumbs" :key="c.prefix">
<span>/</span>
<span
class="mono inline-block max-w-40 cursor-pointer truncate align-bottom hover:text-ink"
:title="c.label"
@click="enterFolder(c.prefix)"
>
{{ c.label }}
</span>
</template>
</div>
<div class="flex items-center gap-2 max-md:w-full">
<NInput
v-model:value="filterInput"
size="small"
placeholder="搜索本层对象…"
clearable
class="!w-52 max-md:!w-auto max-md:flex-1"
/>
<NButton size="small" @click="showNewFolder = true">新建文件夹</NButton>
</div>
</div>
<div
v-if="checkedKeys.length"
class="flex items-center gap-2.5 border-b border-line-soft bg-wash/60 px-4.5 py-2 text-[12.5px]"
>
<span class="font-medium">已选 {{ checkedKeys.length }} </span>
<NButton size="tiny" @click="batchDownload">逐个下载</NButton>
<ConfirmPop
:title="`删除选中的 ${checkedKeys.length} 个对象?`"
content="未开版本控制时不可恢复。"
confirm-text="删除"
:on-confirm="batchDelete"
>
<template #trigger>
<NButton size="tiny" type="error" quaternary>删除</NButton>
</template>
</ConfirmPop>
<span class="ml-auto cursor-pointer text-ink-3 hover:text-ink" @click="checkedKeys = []">
清除选择
</span>
</div>
<NDataTable
v-model:checked-row-keys="checkedKeys"
:columns="columns"
:data="rows"
:loading="result.loading.value"
:scroll-x="880"
:row-key="(r: Row) => r.key"
/>
<div
class="flex items-center justify-between gap-3 border-t border-line-soft px-4.5 py-2.5 text-[12.5px] text-ink-3"
>
<span>每页 {{ PAGE_SIZE }} · 文件夹为虚拟层级 · Archive 层需恢复后下载</span>
<span class="flex flex-none items-center gap-1.5">
<NButton size="tiny" :disabled="!cursorStack.length" @click="prevPage">上一页</NButton>
<NButton size="tiny" :disabled="!result.data.value?.nextStartWith" @click="nextPage">
下一页
</NButton>
</span>
</div>
</div>
<ParPanel v-show="tab === 'par'" ref="parPanel" :cfg-id="cfgId" :region="region" :bucket="bucket" />
<!-- 传输列表浮层:上传主色 / 下载 info ,失败红字可重试,可收起 -->
<Teleport to="body">
<div
v-if="transfers.length"
class="fixed right-5 bottom-5 z-40 w-80 max-w-[calc(100vw-24px)] max-md:right-3 max-md:bottom-[calc(64px_+_env(safe-area-inset-bottom))]"
>
<div class="overflow-hidden rounded-lg border border-line bg-card shadow-[0_10px_32px_-8px_rgba(0,0,0,0.22)]">
<div
class="flex items-center gap-2 bg-wash px-3.5 py-2 text-[12.5px]"
:class="transfersCollapsed ? '' : 'border-b border-line-soft'"
>
<span class="font-medium">传输列表</span>
<span v-if="activeCount" class="text-ink-3">{{ activeCount }} 进行中</span>
<div class="ml-auto flex items-center gap-1">
<button
v-if="doneCount"
type="button"
class="cursor-pointer rounded px-1.5 py-0.5 text-xs text-ink-3 hover:bg-wash-deep hover:text-ink"
@click="clearDone"
>
清除已完成
</button>
<button
type="button"
class="cursor-pointer rounded p-1 text-ink-3 hover:bg-wash-deep hover:text-ink"
:title="transfersCollapsed ? '展开' : '收起'"
@click="transfersCollapsed = !transfersCollapsed"
>
<svg
class="h-3.5 w-3.5 transition-transform"
:class="transfersCollapsed ? 'rotate-180' : ''"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"
stroke-linecap="round" stroke-linejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>
</button>
</div>
</div>
<div v-show="!transfersCollapsed" class="max-h-60 overflow-y-auto">
<div
v-for="t in transfers"
:key="t.id"
class="flex items-center gap-2.5 border-b border-line-soft px-3.5 py-2 text-[12.5px] last:border-b-0"
>
<span
class="flex-none font-semibold"
:class="t.status === 'error' ? 'text-err' : t.kind === 'up' ? 'text-accent' : 'text-info'"
>
{{ t.status === 'error' ? '✕' : t.kind === 'up' ? '↑' : '↓' }}
</span>
<div class="min-w-0 flex-1">
<div class="flex items-center justify-between gap-2">
<span class="mono truncate">{{ t.name }}</span>
<span v-if="t.status === 'active'" class="mono flex-none text-xs text-ink-3">
{{ t.percent }}%
</span>
<span v-else-if="t.status === 'done'" class="flex-none text-xs text-ok">完成</span>
</div>
<div v-if="t.status === 'active'" class="mt-1 h-1 overflow-hidden rounded-full bg-line-soft">
<span
class="block h-full rounded-full"
:class="t.kind === 'up' ? 'bg-accent' : 'bg-info'"
:style="{ width: `${t.percent}%` }"
/>
</div>
<div v-else-if="t.status === 'error'" class="mt-0.5 flex items-center gap-2 text-xs">
<span class="min-w-0 truncate text-err" :title="t.error">{{ t.error }}</span>
<span class="flex-none cursor-pointer font-medium text-accent" @click="retryTask(t)">
重试
</span>
</div>
<div v-else-if="t.note" class="mt-0.5 text-xs text-ink-3">{{ t.note }}</div>
</div>
<button
type="button"
class="flex-none cursor-pointer text-ink-3 hover:text-ink"
:title="t.status === 'active' ? '取消' : '移除'"
@click="removeTask(t)"
>
<svg class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
</div>
</Teleport>
<ObjectViewerModal
v-model:show="showViewer"
:cfg-id="cfgId"
:region="region"
:bucket="bucket"
:object="viewerObject"
:versioning-on="info?.versioningOn"
:visibility="info?.visibility"
:namespace="info?.namespace"
@download="download"
@share="openParModal"
@changed="() => void result.run({ silent: true })"
/>
<FormModal
:show="showNewFolder"
title="新建文件夹"
:width="380"
:submitting="creatingFolder"
:submit-disabled="!folderName.trim()"
submit-text="创建"
@update:show="showNewFolder = $event"
@submit="doCreateFolder"
>
<FormField label="文件夹名" hint="以 0 字节对象实现虚拟层级">
<NInput v-model:value="folderName" placeholder="backup" class="mono" />
</FormField>
</FormModal>
<FormModal
:show="showPar"
:title="parIsBucket ? '分享桶' : '分享对象'"
:width="460"
:submitting="parBusy"
:submit-disabled="!!parUrl || !parForm.expiresHours"
submit-text="签发"
@update:show="showPar = $event"
@submit="doCreatePar"
>
<FormField :label="parIsBucket ? '范围' : '对象'">
<span class="mono text-[12.5px]">{{ parForm.objectName || '整桶对象(桶级链接)' }}</span>
</FormField>
<FormField label="权限">
<NRadioGroup v-model:value="parForm.accessType">
<NRadio :value="parIsBucket ? 'AnyObjectRead' : 'ObjectRead'">只读</NRadio>
<NRadio :value="parIsBucket ? 'AnyObjectReadWrite' : 'ObjectReadWrite'">读写</NRadio>
</NRadioGroup>
</FormField>
<FormField label="有效期" hint="OCI 上限 30 天(720 小时)">
<div class="flex flex-wrap items-center gap-1.5">
<AppInputNumber
v-model:value="parForm.expiresHours"
:min="1"
:max="720"
:precision="0"
size="small"
class="!w-24"
/>
<span class="text-[12.5px] text-ink-2">小时</span>
<NButton
v-for="q in QUICK_HOURS"
:key="q.value"
size="tiny"
quaternary
:type="parForm.expiresHours === q.value ? 'primary' : 'default'"
@click="parForm.expiresHours = q.value"
>
{{ q.label }}
</NButton>
</div>
</FormField>
<div
v-if="parUrl"
class="mt-1 flex items-center gap-2 rounded-lg border border-line-soft bg-wash px-3 py-2"
>
<span class="mono min-w-0 flex-1 truncate text-xs">{{ parUrl }}</span>
<NButton size="tiny" @click="copyParUrl">复制</NButton>
</div>
<div v-if="parUrl" class="mt-1 text-xs text-warn">
链接仅本次展示,关闭后无法再次获取,请立即保存
</div>
</FormModal>
</div>
</template>
@@ -0,0 +1,527 @@
<script setup lang="ts">
import { NButton, NInput, NModal, NSpin } from 'naive-ui'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import {
deleteObject,
getObjectContent,
getObjectDetail,
putObjectContent,
renameObject,
} from '@/api/objectstorage'
import { ApiError } from '@/api/request'
import ConfirmPop from '@/components/ConfirmPop.vue'
import { extOf, previewKindOf } from '@/components/objectstorage/codeHighlight'
import { canFormat, formatSource } from '@/components/objectstorage/format'
import FileIcon from '@/components/objectstorage/FileIcon.vue'
import OfficePreview from '@/components/objectstorage/viewer/OfficePreview.vue'
import TextEditPane from '@/components/objectstorage/viewer/TextEditPane.vue'
import TextPreviewPane from '@/components/objectstorage/viewer/TextPreviewPane.vue'
import { fmtBytes, fmtTime } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import { useIsMobile } from '@/composables/useIsMobile'
import { useToast } from '@/composables/useToast'
import { useScopeStore } from '@/stores/scope'
/** :, +
* 内容经面板中转直读直写(不签发 PAR);保存以 If-Match 做并发保护,
* 412 冲突与无版本控制桶走二段确认 */
const props = defineProps<{
show: boolean
cfgId: number | null
region?: string
bucket: string
object: string
/** 桶版本控制状态;未知按未开启保守处理 */
versioningOn?: boolean
/** 桶可见性(NoPublicAccess / ObjectRead);公共读时「复制 URI」变「复制 URL」 */
visibility?: string
/** 桶 namespace,拼公网对象 URL 用 */
namespace?: string
}>()
const emit = defineEmits<{
'update:show': [boolean]
download: [string]
share: [string]
/** 保存/重命名/删除后,列表需要刷新 */
changed: []
}>()
const message = useToast()
/** 移动端全屏(复用 main.css 的 .form-modal-mobile 全局全屏规则) */
const isMobile = useIsMobile()
const modalStyle = computed(() =>
isMobile.value
? { width: '100vw', height: '100dvh', maxWidth: '100vw', margin: '0', borderRadius: '0' }
: { width: '1080px', maxWidth: 'calc(100vw - 24px)' },
)
/** 文本预览/编辑体积上限;更大的文本请下载查看 */
const TEXT_MAX = 1024 * 1024
/** 图片与 office/pdf 的中转上限(与后端 20MB 限制一致) */
const BINARY_MAX = 20 * 1024 * 1024
/** pre 渲染字符上限,超出截断展示 */
const TEXT_SHOW_MAX = 256 * 1024
const detail = useAsync(async () => {
if (!props.cfgId || !props.object) return null
return getObjectDetail(props.cfgId, props.bucket, props.object, props.region)
}, false)
const ext = computed(() => extOf(props.object))
const kind = computed(() => previewKindOf(props.object))
const archived = computed(() => {
const d = detail.data.value
return d?.storageTier === 'Archive' && d.archivalState !== 'Restored'
})
const size = computed(() => detail.data.value?.size ?? 0)
const tooBig = computed(() =>
kind.value === 'text' ? size.value > TEXT_MAX : size.value > BINARY_MAX,
)
const canEdit = computed(() => kind.value === 'text' && !archived.value && !tooBig.value)
const officeKind = computed(() => {
const k = kind.value
return k === 'docx' || k === 'xlsx' || k === 'pdf' || k === 'pptx' ? k : null
})
const blockedReason = computed(() => {
if (kind.value === 'none') return '该格式暂不支持预览,请下载查看'
if (archived.value) return 'Archive 对象需先恢复才能预览'
if (tooBig.value)
return kind.value === 'text' ? '文本超过 1 MB,请下载查看' : '文件超过 20 MB,请下载查看'
return ''
})
// ---- ----
const mode = ref<'preview' | 'edit'>('preview')
const loading = ref(false)
const loadError = ref('')
/** 文本完整内容(编辑基线,不做美化改写) */
const fullText = ref('')
/** 展示文本(json 美化、超长截断) */
const previewText = ref('')
const truncated = ref(false)
const imageUrl = ref('')
const officeData = ref<ArrayBuffer | null>(null)
const officeError = ref('')
const contentEtag = ref('')
const contentType = ref('')
watch(
() => [props.show, props.object],
([show]) => {
if (!show) {
revokeImage()
return
}
reset()
void detail.run().then(() => {
if (!blockedReason.value) void loadContent()
})
},
)
onBeforeUnmount(revokeImage)
function reset() {
mode.value = 'preview'
// ,,
detail.data.value = null
loading.value = false
loadError.value = ''
fullText.value = ''
previewText.value = ''
truncated.value = false
revokeImage()
officeData.value = null
officeError.value = ''
contentEtag.value = ''
contentType.value = ''
renaming.value = false
resetEdit()
}
function revokeImage() {
if (imageUrl.value) URL.revokeObjectURL(imageUrl.value)
imageUrl.value = ''
}
async function loadContent() {
if (!props.cfgId || loading.value) return
loading.value = true
loadError.value = ''
try {
const c = await getObjectContent(props.cfgId, props.bucket, props.object, props.region)
contentEtag.value = c.etag
contentType.value = c.contentType
await applyContent(c.blob)
} catch (e) {
loadError.value = e instanceof Error ? e.message : '内容加载失败'
} finally {
loading.value = false
}
}
async function applyContent(blob: Blob) {
if (kind.value === 'image') {
imageUrl.value = URL.createObjectURL(blob)
return
}
if (kind.value === 'text') {
setText(await blob.text())
return
}
officeData.value = await blob.arrayBuffer()
}
function setText(raw: string) {
fullText.value = raw
const pretty = ext.value === 'json' ? prettyJson(raw) : raw
truncated.value = pretty.length > TEXT_SHOW_MAX
previewText.value = truncated.value ? pretty.slice(0, TEXT_SHOW_MAX) : pretty
}
/** JSON 美化失败时原样展示 */
function prettyJson(s: string): string {
try {
return JSON.stringify(JSON.parse(s), null, 2)
} catch {
return s
}
}
// ---- ----
const editText = ref('')
const saving = ref(false)
/** 非空时保存进入二段确认态,内容为需用户确认的原因 */
const pendingConfirm = ref('')
/** 412 冲突确认后置真:下次保存不带 If-Match,无条件覆盖 */
const overwrite = ref(false)
const editByteSize = computed(() => new Blob([editText.value]).size)
function resetEdit() {
editText.value = ''
saving.value = false
pendingConfirm.value = ''
overwrite.value = false
}
function startEdit() {
editText.value = fullText.value
pendingConfirm.value = ''
overwrite.value = false
mode.value = 'edit'
}
function cancelEdit() {
mode.value = 'preview'
resetEdit()
}
const canBeautify = computed(() => canFormat(ext.value))
/** 一键美化:json 原生,其余 prettier standalone(动态加载);语法错误只提示不改动 */
async function beautify() {
try {
const out = await formatSource(editText.value, ext.value)
if (out === null) return
if (out === editText.value) {
message.success('已是规范格式')
return
}
editText.value = out
message.success('已格式化')
} catch {
message.error('格式化失败:内容存在语法错误')
}
}
async function save() {
if (!props.cfgId || saving.value) return
if (!pendingConfirm.value && !props.versioningOn) {
pendingConfirm.value = '该桶未开启版本控制,保存将直接覆盖原内容,不可恢复。'
return
}
saving.value = true
try {
const { etag } = await putObjectContent(
props.cfgId,
props.bucket,
props.object,
editText.value,
contentType.value || 'text/plain',
overwrite.value ? undefined : contentEtag.value || undefined,
props.region,
)
applySaved(etag)
} catch (e) {
onSaveError(e)
} finally {
saving.value = false
}
}
function applySaved(etag: string) {
contentEtag.value = etag
setText(editText.value)
message.success('已保存')
mode.value = 'preview'
resetEdit()
emit('changed')
void detail.run({ silent: true })
}
function onSaveError(e: unknown) {
if (e instanceof ApiError && e.status === 412) {
overwrite.value = true
pendingConfirm.value = '对象在编辑期间已被修改(ETag 变化),继续保存将覆盖他人的更改。'
return
}
message.error(e instanceof Error ? e.message : '保存失败')
}
// ---- / / ----
const renaming = ref(false)
const newName = ref('')
const renameBusy = ref(false)
function startRename() {
newName.value = props.object
renaming.value = true
}
async function doRename() {
if (!props.cfgId || !newName.value.trim() || newName.value === props.object) return
renameBusy.value = true
try {
await renameObject(props.cfgId, props.bucket, props.object, newName.value.trim(), props.region)
message.success('已重命名')
emit('update:show', false)
emit('changed')
} catch (e) {
message.error(e instanceof Error ? e.message : '重命名失败')
} finally {
renameBusy.value = false
}
}
async function doDelete() {
if (!props.cfgId) return
try {
await deleteObject(props.cfgId, props.bucket, props.object, props.region)
message.success('对象已删除')
emit('update:show', false)
emit('changed')
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败')
}
}
/** Archive 层(任意恢复态):PAR 对其无效,分享一律禁用 */
const isArchiveTier = computed(() => detail.data.value?.storageTier === 'Archive')
/** 公共读桶:对象有公网直链,「复制 URI」升级为「复制 URL」 */
const isPublicBucket = computed(() => props.visibility === 'ObjectRead')
const scope = useScopeStore()
/** 公共读桶对象的公网直链;对象名整体转义(/ → %2F,OCI 控制台同款) */
function publicUrl(): string {
const region = props.region || scope.region
return `https://objectstorage.${region}.oraclecloud.com/n/${props.namespace}/b/${props.bucket}/o/${encodeURIComponent(props.object)}`
}
async function copyUri() {
const pub = isPublicBucket.value
await navigator.clipboard.writeText(pub ? publicUrl() : `oci://${props.bucket}/${props.object}`)
message.success(pub ? 'URL 已复制' : 'URI 已复制')
}
const kvRows = computed(() => {
const d = detail.data.value
if (!d) return []
return [
{ k: '大小', v: `${fmtBytes(d.size)}(${d.size.toLocaleString()} B)` },
{ k: 'Content-Type', v: d.contentType || '—', mono: true },
{ k: 'ETag', v: d.etag || '—', mono: true },
{ k: 'MD5', v: d.contentMd5 || '—', mono: true },
{ k: '存储层', v: d.storageTier || 'Standard' },
{ k: '版本控制', v: props.versioningOn ? '已开启' : '未开启' },
{ k: '修改时间', v: fmtTime(d.timeModified) },
]
})
</script>
<template>
<NModal
:show="show"
preset="card"
:mask-closable="mode !== 'edit'"
:style="modalStyle"
:class="isMobile ? 'form-modal-mobile' : ''"
@update:show="emit('update:show', $event)"
>
<template #header>
<span class="mono flex min-w-0 items-center gap-2 text-[13.5px]">
<FileIcon :name="object" :size="18" />
<span class="truncate" :title="object">{{ object }}</span>
<span
v-if="mode === 'edit'"
class="flex-none rounded bg-wash px-1.5 py-px text-[10.5px] font-medium text-ink-3"
>
编辑
</span>
</span>
</template>
<div class="flex min-h-0 flex-col gap-4 md:flex-row max-md:flex-1 max-md:overflow-y-auto">
<!-- :内容区(移动端全屏形态下压缩预览高度,信息与操作随外层滚动) -->
<div
class="flex h-[65vh] min-w-0 flex-1 flex-col rounded-lg border border-line-soft bg-wash/50 p-3 max-md:h-auto max-md:min-h-[45dvh] max-md:flex-none"
>
<div
v-if="detail.loading.value || loading"
class="flex flex-1 items-center justify-center"
>
<NSpin size="small" />
</div>
<div
v-else-if="blockedReason"
class="flex flex-1 items-center justify-center text-xs text-ink-3"
>
{{ blockedReason }}
</div>
<div v-else-if="loadError" class="flex flex-1 flex-col items-center justify-center gap-2">
<div class="text-xs text-err">{{ loadError }}</div>
<NButton size="small" @click="loadContent">重试</NButton>
</div>
<template v-else-if="mode === 'edit'">
<div
class="relative min-h-0 flex-1 overflow-hidden rounded-lg border border-line bg-white transition-colors focus-within:border-accent"
>
<TextEditPane v-model="editText" :object-name="object" :disabled="saving" />
</div>
<div class="mt-1.5 flex-none text-xs text-ink-3">
UTF-8 文本 · {{ fmtBytes(editByteSize) }} · 保存经面板中转写回,If-Match 防并发覆盖
</div>
</template>
<img
v-else-if="imageUrl"
:src="imageUrl"
:alt="object"
class="mx-auto max-h-full min-h-0 rounded object-contain"
@error="loadError = '图片加载失败,请下载查看'; revokeImage()"
/>
<TextPreviewPane
v-else-if="kind === 'text' && (previewText || truncated || !loading)"
:text="previewText"
:ext="ext"
:truncated="truncated"
/>
<template v-else-if="officeData && officeKind">
<div
v-if="officeError"
class="flex flex-1 items-center justify-center text-xs text-err"
>
{{ officeError }}
</div>
<div v-else class="min-h-0 flex-1 overflow-auto rounded bg-white">
<OfficePreview :kind="officeKind" :data="officeData" @error="officeError = $event" />
</div>
<div v-if="officeKind === 'pptx' && !officeError" class="mt-1.5 flex-none text-xs text-ink-3">
pptx 预览为实验能力,复杂版式可能失真
</div>
</template>
</div>
<!-- :信息与操作 -->
<div class="flex w-full flex-none flex-col gap-3 md:w-72">
<div v-if="detail.loading.value" class="flex justify-center py-10">
<NSpin size="small" />
</div>
<template v-else>
<div class="flex flex-col gap-0.5">
<div
v-for="row in kvRows"
:key="row.k"
class="flex justify-between gap-3 border-b border-line-soft py-1.5 text-[12px]"
>
<span class="flex-none text-ink-3">{{ row.k }}</span>
<span class="min-w-0 text-right break-all" :class="row.mono ? 'mono' : ''">
{{ row.v }}
</span>
</div>
</div>
<template v-if="mode === 'edit'">
<div
v-if="pendingConfirm"
class="rounded-lg bg-warn/12 px-3 py-2 text-xs leading-relaxed text-warn"
>
{{ pendingConfirm }}
</div>
<NButton v-if="canBeautify" size="small" :disabled="saving" @click="beautify">
美化格式
</NButton>
<div class="flex gap-2">
<NButton
size="small"
type="primary"
class="flex-1"
:loading="saving"
@click="save"
>
{{ pendingConfirm ? '确认覆盖并保存' : '保存' }}
</NButton>
<NButton size="small" :disabled="saving" @click="cancelEdit">取消</NButton>
</div>
</template>
<div v-else-if="renaming" class="flex flex-col gap-2">
<NInput v-model:value="newName" size="small" class="mono" />
<div class="flex gap-2">
<NButton size="small" type="primary" :loading="renameBusy" @click="doRename">
确定
</NButton>
<NButton size="small" :disabled="renameBusy" @click="renaming = false">取消</NButton>
</div>
</div>
<template v-else>
<div :title="archived ? 'Archive 对象需先恢复才能下载' : ''">
<NButton
size="small"
type="primary"
block
:disabled="archived"
@click="emit('download', object)"
>
下载
</NButton>
</div>
<div class="grid grid-cols-2 gap-1.5">
<NButton v-if="canEdit" size="small" @click="startEdit">编辑</NButton>
<div :title="isArchiveTier ? 'Archive 层对象不支持预签名分享' : ''">
<NButton size="small" block :disabled="isArchiveTier" @click="emit('share', object)">
分享
</NButton>
</div>
<NButton size="small" @click="copyUri">
{{ isPublicBucket ? '复制 URL' : '复制 URI' }}
</NButton>
<NButton size="small" @click="startRename">重命名</NButton>
</div>
<ConfirmPop
title="删除该对象?"
content="未开版本控制时不可恢复。"
confirm-text="删除"
:on-confirm="doDelete"
>
<template #trigger>
<NButton size="small" type="error" ghost block>删除</NButton>
</template>
</ConfirmPop>
</template>
</template>
</div>
</div>
</NModal>
</template>
+207
View File
@@ -0,0 +1,207 @@
<script setup lang="ts">
import { NButton, NDataTable, type DataTableColumns } from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import { deleteAllPars, deletePar, listPars } from '@/api/objectstorage'
import ConfirmPop from '@/components/ConfirmPop.vue'
import PanelHeader from '@/components/PanelHeader.vue'
import { fmtTime } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import type { Par, ParPage } from '@/types/api'
import { useToast } from '@/composables/useToast'
const props = defineProps<{ cfgId: number | null; region?: string; bucket: string }>()
const message = useToast()
/** 服务端游标分页:几千条 PAR 的桶全量拉取会把浏览器主线程打满数秒 */
const PAGE_SIZE = 100
/** 上页游标栈:后端只回传 next 游标,上一页靠历史栈回放 */
const cursorStack = ref<string[]>([])
const cursor = ref('')
const pars = useAsync<ParPage>(async () => {
if (!props.cfgId) return { items: [], nextPage: '' }
try {
return await listPars(props.cfgId, props.bucket, {
region: props.region,
page: cursor.value || undefined,
limit: PAGE_SIZE,
})
} catch {
return { items: [], nextPage: '' }
}
}, false)
const items = computed(() => pars.data.value?.items ?? [])
watch(
[() => props.cfgId, () => props.bucket],
() => {
cursorStack.value = []
cursor.value = ''
void pars.run()
},
{ immediate: true },
)
function goNext() {
const next = pars.data.value?.nextPage
if (!next) return
cursorStack.value.push(cursor.value)
cursor.value = next
void pars.run()
}
function goPrev() {
cursor.value = cursorStack.value.pop() ?? ''
void pars.run()
}
/** 回到首页重拉;签发新 PAR 后的刷新走这里(新条目排序位置不定,回首页语义最直观) */
function refreshFirstPage(opts?: { silent?: boolean }) {
cursorStack.value = []
cursor.value = ''
void pars.run(opts)
}
defineExpose({ refresh: () => refreshFirstPage({ silent: true }) })
async function remove(row: Par) {
if (!props.cfgId) return
try {
await deletePar(props.cfgId, props.bucket, row.id, props.region)
message.success('分享链接已删除并立即失效')
await pars.run({ silent: true })
// 退
if (!items.value.length && cursorStack.value.length) goPrev()
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败')
}
}
async function removeAll() {
if (!props.cfgId) return
try {
const { deleted } = await deleteAllPars(props.cfgId, props.bucket, props.region)
message.success(`已删除 ${deleted} 条分享链接`)
} catch (e) {
message.error(e instanceof Error ? e.message : '删除失败')
} finally {
refreshFirstPage()
}
}
const ACCESS_LABEL: Record<string, string> = {
ObjectRead: '只读',
ObjectWrite: '只写',
ObjectReadWrite: '读写',
AnyObjectRead: '桶级只读',
AnyObjectWrite: '桶级只写',
AnyObjectReadWrite: '桶级读写',
}
const columns = computed<DataTableColumns<Par>>(() => [
{
title: '目标',
key: 'objectName',
minWidth: 220,
ellipsis: { tooltip: true },
render: (r) => h('span', { class: 'mono text-[12.5px]' }, r.objectName || '(桶级)'),
},
{
title: '权限',
key: 'accessType',
width: 120,
render: (r) =>
h(
'span',
{
class:
'rounded-full bg-wash px-2 py-0.5 text-[11.5px] font-medium whitespace-nowrap text-ink-2',
},
ACCESS_LABEL[r.accessType] ?? r.accessType,
),
},
{
title: '过期时间',
key: 'timeExpires',
width: 160,
render: (r) => h('span', { class: 'text-[13px] text-ink-2' }, fmtTime(r.timeExpires)),
},
{
title: '创建',
key: 'timeCreated',
width: 150,
render: (r) => h('span', { class: 'text-[13px] text-ink-2' }, fmtTime(r.timeCreated)),
},
{
title: '操作',
key: 'actions',
width: 90,
render: (r) =>
h(
ConfirmPop,
{
title: '删除该临时链接?',
content: '删除后链接立即失效。',
confirmText: '删除',
onConfirm: () => remove(r),
},
{
trigger: () =>
h(
NButton,
{ size: 'tiny', quaternary: true, type: 'error' },
{ default: () => '删除' },
),
},
),
},
])
</script>
<template>
<div class="panel">
<PanelHeader
title="分享链接(PAR)"
desc="完整 URL 仅签发时展示一次(OCI 不支持事后取回);删除后链接立即失效"
>
<template #title-extra>
<span class="text-[13px] font-normal text-ink-3">
· 本页 {{ pars.data.value ? items.length : '…' }}{{ pars.data.value?.nextPage ? '+' : '' }}
</span>
</template>
<ConfirmPop
title="删除全部分享链接?"
content="将删除桶内全部分享链接(含未展示分页),删除后全部立即失效。"
confirm-text="全部删除"
:on-confirm="removeAll"
>
<template #trigger>
<NButton size="tiny" type="error" quaternary :disabled="!items.length">
删除全部
</NButton>
</template>
</ConfirmPop>
</PanelHeader>
<NDataTable
:columns="columns"
:data="items"
:loading="pars.loading.value"
:pagination="false"
:scroll-x="740"
:max-height="440"
:row-key="(r: Par) => r.id"
/>
<div
v-if="cursorStack.length || pars.data.value?.nextPage"
class="flex items-center justify-between border-t border-line-soft px-4.5 py-2.5 text-[12.5px] text-ink-3"
>
<span>每页 {{ PAGE_SIZE }} </span>
<span class="flex items-center gap-1.5">
<NButton size="tiny" :disabled="!cursorStack.length" @click="goPrev">上一页</NButton>
<NButton size="tiny" :disabled="!pars.data.value?.nextPage" @click="goNext">下一页</NButton>
</span>
</div>
</div>
</template>
@@ -0,0 +1,94 @@
import type { LanguageFn } from 'highlight.js'
const IMAGE_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif'])
const TEXT_EXT = new Set([
'txt', 'md', 'log', 'json', 'yaml', 'yml', 'ini', 'toml', 'conf', 'cfg', 'csv',
'xml', 'html', 'htm', 'css', 'js', 'ts', 'sh', 'py', 'go', 'env', 'properties', 'sql',
])
/** office/pdf 预览形态(vue-office 渲染);doc/xls/ppt 老格式不支持 */
const OFFICE_KIND: Record<string, 'docx' | 'xlsx' | 'pdf' | 'pptx'> = {
docx: 'docx',
xlsx: 'xlsx',
pdf: 'pdf',
pptx: 'pptx',
}
export type PreviewKind = 'image' | 'text' | 'docx' | 'xlsx' | 'pdf' | 'pptx' | 'none'
export function extOf(name: string): string {
return name.split('.').pop()?.toLowerCase() ?? ''
}
/** 对象是否支持预览及预览形态 */
export function previewKindOf(name: string): PreviewKind {
const ext = extOf(name)
// svg 按文本处理:预览「渲染 ↔ 代码」双态由文本生成,且可在线编辑
if (ext === 'svg') return 'text'
if (IMAGE_EXT.has(ext)) return 'image'
if (TEXT_EXT.has(ext)) return 'text'
return OFFICE_KIND[ext] ?? 'none'
}
/** 扩展名 → highlight.js 语言;不在表内的按纯文本展示 */
const EXT_LANG: Record<string, string> = {
py: 'python',
json: 'json',
yaml: 'yaml',
yml: 'yaml',
ini: 'ini',
toml: 'ini',
conf: 'ini',
cfg: 'ini',
env: 'ini',
properties: 'ini',
xml: 'xml',
html: 'xml',
htm: 'xml',
sh: 'bash',
js: 'javascript',
ts: 'typescript',
go: 'go',
sql: 'sql',
md: 'markdown',
css: 'css',
svg: 'xml',
}
/** 语言按需动态加载,各自成 chunk,不预览不下载 */
const LANG_LOADERS: Record<string, () => Promise<{ default: LanguageFn }>> = {
python: () => import('highlight.js/lib/languages/python'),
json: () => import('highlight.js/lib/languages/json'),
yaml: () => import('highlight.js/lib/languages/yaml'),
ini: () => import('highlight.js/lib/languages/ini'),
xml: () => import('highlight.js/lib/languages/xml'),
bash: () => import('highlight.js/lib/languages/bash'),
javascript: () => import('highlight.js/lib/languages/javascript'),
typescript: () => import('highlight.js/lib/languages/typescript'),
go: () => import('highlight.js/lib/languages/go'),
sql: () => import('highlight.js/lib/languages/sql'),
markdown: () => import('highlight.js/lib/languages/markdown'),
css: () => import('highlight.js/lib/languages/css'),
}
/**
* ;lang (md , python/bash)( py/sh)
* hljs HTML(, v-html); null
*/
export async function highlightCode(code: string, lang: string): Promise<string | null> {
const name = LANG_LOADERS[lang] ? lang : EXT_LANG[lang]
const load = name ? LANG_LOADERS[name] : undefined
if (!name || !load) return null
try {
const { default: hljs } = await import('highlight.js/lib/core')
if (!hljs.getLanguage(name)) hljs.registerLanguage(name, (await load()).default)
return hljs.highlight(code, { language: name }).value
} catch {
return null
}
}
/** 按扩展名高亮整份源码,语义同 highlightCode(ext 分支)。 */
export async function highlightSource(text: string, ext: string): Promise<string | null> {
return highlightCode(text, ext)
}
+60
View File
@@ -0,0 +1,60 @@
// 由 scripts/gen-file-icons.mjs 从 @iconify-json/catppuccin 提取,勿手改;
// 来源:Catppuccin VSCode Icons(MIT),16x16 viewBox。
export const FILE_ICON_BODIES: Record<string, string> = {
"folder":
'<path fill="none" stroke="#cad3f5" stroke-linecap="round" stroke-linejoin="round" d="M4.5 4.5H12c.83 0 1.5.67 1.5 1.5v6c0 .83-.67 1.5-1.5 1.5H2A1.5 1.5 0 0 1 .5 12V3.5a1 1 0 0 1 1-1h5a1 1 0 0 1 1 1v1"/>',
"file":
'<path fill="none" stroke="#cad3f5" stroke-linecap="round" stroke-linejoin="round" d="M13.5 6.5v6a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h4.01m-.01 0l5 5h-4a1 1 0 0 1-1-1z"/>',
"image":
'<g fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="#eed49f" d="M11.5 6A1.5 1.5 0 0 1 10 7.5A1.5 1.5 0 0 1 8.5 6A1.5 1.5 0 0 1 10 4.5A1.5 1.5 0 0 1 11.5 6"/><path stroke="#a6da95" d="M7.5 13.5L11 10c.5-.5 1.5-.5 2 0l1.5 1.5"/><path stroke="#a6da95" d="m1.5 9.5l2-2C4 7 5 7 5.5 7.5l4 4"/><path stroke="#7dc4e4" d="M3 2.5h10c.83 0 1.5.67 1.5 1.5v8c0 .83-.67 1.5-1.5 1.5H3A1.5 1.5 0 0 1 1.5 12V4c0-.83.67-1.5 1.5-1.5"/></g>',
"json":
'<path fill="none" stroke="#eed49f" stroke-linecap="round" stroke-linejoin="round" d="M4.5 2.5H4c-.75 0-1.5.75-1.5 1.5v2c0 1.1-1 2-1.83 2c.83 0 1.83.9 1.83 2v2c0 .75.75 1.5 1.5 1.5h.5m7-11h.5c.75 0 1.5.75 1.5 1.5v2c0 1.1 1 2 1.83 2c-.83 0-1.83.9-1.83 2v2c0 .74-.75 1.5-1.5 1.5h-.5m-6.5-3a.5.5 0 1 0 0-1a.5.5 0 0 0 0 1m3 0a.5.5 0 1 0 0-1a.5.5 0 0 0 0 1m3 0a.5.5 0 1 0 0-1a.5.5 0 0 0 0 1"/>',
"yaml":
'<path fill="none" stroke="#ed8796" stroke-linecap="round" stroke-linejoin="round" d="M2.5 1.5h3l3 4l3-4h3l-9 13h-3L7 8z"/>',
"toml":
'<path fill="none" stroke="#ee99a0" stroke-linecap="round" stroke-linejoin="round" d="M3.5 1.5h-2v13h2m9-13h2v13h-2m-8-11h7v3h-2v6h-3v-6h-2z"/>',
"properties":
'<path fill="none" stroke="#cad3f5" stroke-linecap="round" stroke-linejoin="round" d="M8 1.5c-.87 0-1.17 1.32-2.03 1.63c-.86.3-2.17-.68-2.84 0c-.68.67.3 1.98 0 2.84S1.5 7.13 1.5 8s1.32 1.17 1.63 2.03c.3.86-.68 2.17 0 2.85c.67.67 1.98-.3 2.84 0c.85.3 1.16 1.62 2.03 1.62s1.17-1.32 2.03-1.63c.86-.3 2.17.68 2.85 0c.67-.67-.3-1.98 0-2.84c.3-.85 1.62-1.16 1.62-2.03s-1.32-1.17-1.63-2.03c-.3-.86.68-2.17 0-2.84c-.67-.68-1.98.3-2.84 0S8.87 1.5 8 1.5m0 9a2.5 2.5 0 1 0 0-5a2.5 2.5 0 0 0 0 5"/>',
"python":
'<g fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="#8aadf4" d="M8.5 5.5h-3m6 0V3c0-.8-.7-1.5-1.5-1.5H7c-.8 0-1.5.7-1.5 1.5v2.5H3c-.8 0-1.5.7-1.5 1.5v2c0 .8.7 1.5 1.48 1.5"/><path stroke="#eed49f" d="M10.5 10.5h-3m-3 0V13c0 .8.7 1.5 1.5 1.5h3c.8 0 1.5-.7 1.5-1.5v-2.5H13c.8 0 1.5-.7 1.5-1.5V7c0-.8-.7-1.5-1.48-1.5H11.5c0 1.5 0 2-1 2h-2"/><path stroke="#8aadf4" d="M2.98 10.5H4.5c0-1.5 0-2 1-2h2m0-5"/></g>',
"javascript":
'<g fill="none" stroke="#eed49f" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 11a1.5 1.5 0 0 0 3 0V7.5m5 1.25c0-.69-.537-1.25-1.2-1.25h-.6c-.663 0-1.2.56-1.2 1.25S10.037 10 10.7 10h.6c.663 0 1.2.56 1.2 1.25s-.537 1.25-1.2 1.25h-.6c-.663 0-1.2-.56-1.2-1.25"/><path d="M4 1.5h8c1.385 0 2.5 1.115 2.5 2.5v8c0 1.385-1.115 2.5-2.5 2.5H4A2.495 2.495 0 0 1 1.5 12V4c0-1.385 1.115-2.5 2.5-2.5"/></g>',
"typescript":
'<g fill="none" stroke="#8aadf4" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h8A2.5 2.5 0 0 1 14.5 4v8a2.5 2.5 0 0 1-2.5 2.5H4A2.5 2.5 0 0 1 1.5 12V4A2.5 2.5 0 0 1 4 1.5"/><path d="M12.5 8.75c0-.69-.54-1.25-1.2-1.25h-.6c-.66 0-1.2.56-1.2 1.25S10.04 10 10.7 10h.6c.66 0 1.2.56 1.2 1.25s-.54 1.25-1.2 1.25h-.6c-.66 0-1.2-.56-1.2-1.25m-3-3.75v5M5 7.5h3"/></g>',
"markdown":
'<path fill="none" stroke="#7dc4e4" stroke-linecap="round" stroke-linejoin="round" d="m9.25 8.25l2.25 2.25l2.25-2.25M3.5 11V5.5l2.04 3l1.96-3V11m4-.5V5M1.65 2.5h12.7c.59 0 1.15.49 1.15 1v9c0 .51-.56 1-1.15 1H1.65c-.59 0-1.15-.49-1.15-1V3.58c0-.5.56-1.08 1.15-1.08"/>',
"database":
'<path fill="none" stroke="#eed49f" stroke-linecap="round" stroke-linejoin="round" d="M8 6.5c3.59 0 6.5-1.4 6.5-2.68S11.59 1.5 8 1.5S1.5 2.54 1.5 3.82S4.41 6.5 8 6.5M14.5 8c0 .83-1.24 1.79-3.25 2.2s-4.49.41-6.5 0S1.5 8.83 1.5 8m13 4.18c0 .83-1.24 1.6-3.25 2c-2.01.42-4.49.42-6.5 0c-2.01-.4-3.25-1.17-3.25-2m0-8.3v8.3m13-8.3v8.3"/>',
"bash":
'<g fill="none" stroke="#a6da95" stroke-linecap="round" stroke-linejoin="round"><path d="M2 15.5c-.7 0-1.5-.8-1.5-1.5V5c0-.7.8-1.5 1.5-1.5h9c.7 0 1.5.8 1.5 1.5v9c0 .7-.8 1.5-1.5 1.5z"/><path d="m1.2 3.8l3.04-2.5S5.17.5 5.7.5h8.4c.66 0 1.4.73 1.4 1.4v7.73a2.7 2.7 0 0 1-.7 1.75l-2.68 3.51"/><path d="M6 8.75c0-.69-.54-1.25-1.2-1.25h-.6c-.66 0-1.2.56-1.2 1.25S3.54 10 4.2 10h.6c.66 0 1.2.56 1.2 1.25s-.54 1.25-1.2 1.25h-.6c-.66 0-1.2-.56-1.2-1.25M4.5 6.5v1m0 5v1"/></g>',
"go":
'<path fill="none" stroke="#7dc4e4" stroke-linecap="round" stroke-linejoin="round" d="m15.48 8.06l-4.85.48m4.85-.48a4.98 4.98 0 0 1-4.54 5.42a5 5 0 1 1 2.95-8.66l-1.7 1.84a2.5 2.5 0 0 0-4.18 2.06c.05.57.3 1.1.69 1.51c.25.27 1 .83 1.78.82c.8-.02 1.58-.25 2.07-.81c0 0 .8-.96.68-1.88M2.5 8.5l-2 .01m1.5 2h1.5m-2-3.99l2-.02"/>',
"zip":
'<path fill="none" stroke="#cad3f5" stroke-linejoin="round" d="M5.5 10v1m1-2v1m-1-2v1m1-2v1m-1-2v1m1-2v1m-1-2v1m0-3v1m1 0v1m7 2.5v6a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h4.01m-.01 0l5 5h-4a1 1 0 0 1-1-1z"/>',
"pdf":
'<path fill="none" stroke="#ed8796" stroke-linecap="round" stroke-linejoin="round" d="M2.8 14.34c1.81-1.25 3.02-3.16 3.91-5.5c.9-2.33 1.86-4.33 1.44-6.63c-.06-.36-.57-.73-.83-.7c-1.02.06-.95 1.21-.85 1.9c.24 1.71 1.56 3.7 2.84 5.56c1.27 1.87 2.32 2.16 3.78 2.26c.5.03 1.25-.14 1.37-.58c.77-2.8-9.02-.54-12.28 2.08c-.4.33-.86 1-.6 1.46c.2.36.87.4 1.23.15h0Z"/>',
"video":
'<g fill="none" stroke="#7dc4e4" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2.5h10c.83 0 1.5.67 1.5 1.5v9c0 .83-.67 1.5-1.5 1.5H3A1.5 1.5 0 0 1 1.5 13V4c0-.83.67-1.5 1.5-1.5m-1.5 3h13"/><path d="m3.5 5.5l2-3m1.5 3l2-3m1.5 3l2-3M6.5 8v4l4-2z"/></g>',
"audio":
'<g fill="none" stroke="#ee99a0" stroke-linecap="round" stroke-linejoin="round"><path d="M5.5 12.5a2 2 0 0 1-2 2a2 2 0 0 1-2-2a2 2 0 0 1 2-2a2 2 0 0 1 2 2m9-2a2 2 0 0 1-2 2a2 2 0 0 1-2-2a2 2 0 0 1 2-2a2 2 0 0 1 2 2"/><path d="M5.5 12.5V5c0-.54.44-1.21 1.35-1.5l6.3-2c.9 0 1.35.88 1.35 1.5v7.58m-9-3.08l9-3"/></g>',
"html":
'<g fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="#f5a97f" d="M1.5 1.5h13L13 13l-5 2l-5-2z"/><path stroke="#cad3f5" d="M11 4.5H5l.25 3h5.5l-.25 3l-2.5 1l-2.5-1l-.08-1"/></g>',
"css":
'<g fill="none" stroke="#c6a0f6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 1.5h8A2.5 2.5 0 0 1 14.5 4v8a2.5 2.5 0 0 1-2.5 2.5H4A2.5 2.5 0 0 1 1.5 12V4A2.5 2.5 0 0 1 4 1.5"/><path stroke-width=".814" d="M10.24 11.53c0 .58.438 1.038.96 1.035l.453-.004c.522-.003.949-.451.949-1.033c0-.58-.427-1.065-.95-1.065h-.451c-.523 0-.95-.486-.95-1.066s.427-1.038.95-1.038h.452c.522 0 .951.458.951 1.039M6.8 11.529c0 .58.438 1.04.96 1.036l.465-.004c.523-.003.936-.451.936-1.031s-.409-1.066-.931-1.066h-.47c-.522 0-.949-.485-.949-1.066c0-.58.427-1.037.95-1.037h.451c.523 0 .964.457.964 1.037M3.407 11.53c0 .58.438 1.052.96 1.052h.452c.522 0 .95-.457.95-1.038m.01-2.131c0-.58-.437-1.038-.96-1.038h-.451c-.523 0-.96.468-.96 1.05v2.118"/></g>',
"text":
'<g fill="none" stroke="#cad3f5" stroke-linecap="round" stroke-linejoin="round"><path d="M13.5 6.5v6a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h4.01"/><path d="m8.5 1.5l5 5h-4a1 1 0 0 1-1-1zm-3 10h5m-5-3h5m-5-3h1"/></g>',
"log":
'<g fill="none" stroke="#cad3f5" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 3.5h9v11h-9z"/><path d="M11.5 3.45V1.5h-9v11h1.95m3.05-5h3m-3 3h3"/></g>',
"csv":
'<path fill="none" stroke="#a6da95" stroke-linecap="round" stroke-linejoin="round" d="M1.5 3.5c0-.54.48-1 1.08-1H6.5l1.54 1h5.38c.6 0 1.08.44 1.08.98l-.09 9.04c0 .54-.48.98-1.08.98H2.58c-.6 0-1.08-.44-1.08-.98zm2 4v4m3-4v4m3-4v4m3-4v4m-9 0h9m-9-2h9m-9-2h9"/>',
"xml":
'<path fill="none" stroke="#f5a97f" stroke-linecap="round" stroke-linejoin="round" d="M4.5 4.5L1 8l3.5 3.5m7-7L15 8l-3.5 3.5M9.5 2l-3 12"/>',
"binary":
'<g fill="none" stroke="#cad3f5" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 1.5h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-9a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2"/><path d="M10.5 9.5h1v3.05M6 9.5h1c.28 0 .5.22.5.5v2a.5.5 0 0 1-.5.5H6a.5.5 0 0 1-.5-.5v-2c0-.28.22-.5.5-.5m4-6h1c.28 0 .5.22.5.5v2a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1-.5-.5V4c0-.28.22-.5.5-.5m-4.5 0h1v3.05"/></g>',
"ms-word":
'<g fill="none" stroke="#8aadf4" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 3.13c0-.77.86-1.63 1.62-1.63h9.76c.76 0 1.62.86 1.62 1.63v9.75c0 .76-.86 1.62-1.62 1.62H4.13c-.77 0-1.63-.86-1.63-1.62"/><path d="m.5 5.5l1 5l1-5l1 5l.97-5m3.03 1h4m-4 3h4"/></g>',
"ms-excel":
'<g fill="none" stroke="#a6da95" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 3.13c0-.77.86-1.63 1.62-1.63h9.76c.76 0 1.62.86 1.62 1.63v9.75c0 .76-.86 1.62-1.62 1.62H4.13c-.77 0-1.63-.86-1.63-1.62M.5 5.5l4 5m0-5l-4 5"/><path d="M7.5 5.5h5v5h-5zm2 0v5m-2-3h5"/></g>',
"ms-powerpoint":
'<g fill="none" stroke="#f5a97f" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 3.13c0-.77.86-1.63 1.62-1.63h9.76c.76 0 1.62.86 1.62 1.63v9.75c0 .76-.86 1.62-1.62 1.62H4.13c-.77 0-1.63-.86-1.63-1.62"/><path d="M7.5 5.8L11.88 8L7.5 10.2zm-7-.3v5m0-2H2a1.5 1.5 0 0 0 0-3H.5"/></g>',
}
+61
View File
@@ -0,0 +1,61 @@
import type { Plugin } from 'prettier'
/** prettier 各格式的 parser 与插件加载器;插件按需动态 import,各自成 chunk */
const PRETTIER_CFG: Record<string, { parser: string; plugins: (() => Promise<unknown>)[] }> = {
yaml: { parser: 'yaml', plugins: [() => import('prettier/plugins/yaml')] },
yml: { parser: 'yaml', plugins: [() => import('prettier/plugins/yaml')] },
css: { parser: 'css', plugins: [() => import('prettier/plugins/postcss')] },
md: { parser: 'markdown', plugins: [() => import('prettier/plugins/markdown')] },
html: {
parser: 'html',
plugins: [
() => import('prettier/plugins/html'),
() => import('prettier/plugins/postcss'),
() => import('prettier/plugins/babel'),
() => import('prettier/plugins/estree'),
],
},
htm: {
parser: 'html',
plugins: [
() => import('prettier/plugins/html'),
() => import('prettier/plugins/postcss'),
() => import('prettier/plugins/babel'),
() => import('prettier/plugins/estree'),
],
},
js: {
parser: 'babel',
plugins: [() => import('prettier/plugins/babel'), () => import('prettier/plugins/estree')],
},
ts: {
parser: 'babel-ts',
plugins: [() => import('prettier/plugins/babel'), () => import('prettier/plugins/estree')],
},
xml: { parser: 'xml', plugins: [() => import('@prettier/plugin-xml')] },
svg: { parser: 'xml', plugins: [() => import('@prettier/plugin-xml')] },
}
/** 该扩展名是否支持一键美化 */
export function canFormat(ext: string): boolean {
return ext === 'json' || ext in PRETTIER_CFG
}
/** 解开插件模块的 default 包装(prettier 插件 ESM 互操作) */
function unwrap(m: unknown): Plugin {
const obj = m as { default?: Plugin }
return obj.default ?? (m as Plugin)
}
/**
* ;json JSON , prettier standalone
* null;
*/
export async function formatSource(text: string, ext: string): Promise<string | null> {
if (ext === 'json') return JSON.stringify(JSON.parse(text), null, 2)
const cfg = PRETTIER_CFG[ext]
if (!cfg) return null
const { format } = await import('prettier/standalone')
const plugins = await Promise.all(cfg.plugins.map((p) => p().then(unwrap)))
return format(text, { parser: cfg.parser, plugins })
}
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { computed, defineAsyncComponent } from 'vue'
/** office/pdf 渲染:vue-office 组件按需异步加载,各自独立 chunk,不预览不下载 */
const props = defineProps<{
kind: 'docx' | 'xlsx' | 'pdf' | 'pptx'
data: ArrayBuffer
}>()
const emit = defineEmits<{ error: [string] }>()
const comps = {
docx: defineAsyncComponent(async () => {
await import('@vue-office/docx/lib/index.css')
return (await import('@vue-office/docx')).default
}),
xlsx: defineAsyncComponent(async () => {
await import('@vue-office/excel/lib/index.css')
return (await import('@vue-office/excel')).default
}),
pdf: defineAsyncComponent(() => import('@vue-office/pdf').then((m) => m.default)),
pptx: defineAsyncComponent(() => import('@vue-office/pptx').then((m) => m.default)),
}
const comp = computed(() => comps[props.kind])
</script>
<template>
<component
:is="comp"
:src="data"
class="office-host"
@error="emit('error', '文档渲染失败,请下载查看')"
/>
</template>
<style scoped>
.office-host {
height: 100%;
}
</style>
@@ -0,0 +1,179 @@
<script setup lang="ts">
import { NSpin } from 'naive-ui'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { extOf } from '@/components/objectstorage/codeHighlight'
/** 文本编辑器:CodeMirror 6,行号 / 语法高亮 / 搜索;
* 核心与语言包全部动态 import 独立 chunk,不进编辑不下载
* 须放在定高容器内(内部自滚动) */
const props = defineProps<{
modelValue: string
objectName: string
disabled?: boolean
}>()
const emit = defineEmits<{ 'update:modelValue': [string] }>()
type CmExtension = import('@codemirror/state').Extension
type CmEditorView = typeof import('@codemirror/view').EditorView
const host = ref<HTMLElement | null>(null)
const booting = ref(true)
const bootError = ref('')
let view: import('@codemirror/view').EditorView | null = null
let EV: CmEditorView | null = null
let editableComp: import('@codemirror/state').Compartment | null = null
onMounted(() => void boot())
onBeforeUnmount(() => view?.destroy())
async function boot() {
try {
const [{ basicSetup }, { EditorView }, { Compartment }, lang, theme] = await Promise.all([
import('codemirror'),
import('@codemirror/view'),
import('@codemirror/state'),
loadLanguage(extOf(props.objectName)),
themeExtensions(),
])
EV = EditorView
editableComp = new Compartment()
view = new EditorView({
parent: host.value!,
doc: props.modelValue,
extensions: [
basicSetup,
EditorView.lineWrapping,
...(lang ? [lang] : []),
...theme,
editableComp.of(EditorView.editable.of(!props.disabled)),
EditorView.updateListener.of((u) => {
if (u.docChanged) emit('update:modelValue', u.state.doc.toString())
}),
],
})
} catch (e) {
bootError.value = e instanceof Error ? e.message : '编辑器加载失败'
} finally {
booting.value = false
}
}
/** 主题与语法配色引用设计 token(明暗自适应),语义与全局 .code-hl 一致 */
async function themeExtensions(): Promise<CmExtension[]> {
const [{ HighlightStyle, syntaxHighlighting }, { tags: t }, { EditorView }] = await Promise.all([
import('@codemirror/language'),
import('@lezer/highlight'),
import('@codemirror/view'),
])
const hl = HighlightStyle.define([
{ tag: [t.keyword, t.operatorKeyword, t.modifier], color: 'var(--color-warn)' },
{ tag: [t.string, t.special(t.string), t.regexp], color: 'var(--color-ok)' },
{ tag: [t.number, t.bool, t.null, t.atom], color: 'var(--color-accent)' },
{ tag: [t.comment, t.meta], color: 'var(--color-ink-3)', fontStyle: 'italic' },
{ tag: [t.propertyName, t.attributeName], color: 'var(--color-info)' },
{ tag: [t.typeName, t.className, t.tagName], color: 'var(--color-accent)' },
{ tag: t.heading, color: 'var(--color-ink)', fontWeight: '600' },
{ tag: t.link, color: 'var(--color-accent)' },
])
const theme = EditorView.theme({
'&': { height: '100%', fontSize: '12px', backgroundColor: 'transparent' },
'.cm-scroller': {
fontFamily: "ui-monospace, 'SF Mono', Menlo, Consolas, monospace",
lineHeight: '1.65',
overflow: 'auto',
},
'.cm-gutters': {
backgroundColor: 'var(--color-wash)',
color: 'var(--color-ink-3)',
border: 'none',
},
'.cm-activeLineGutter': { backgroundColor: 'var(--color-wash)' },
'.cm-activeLine': { backgroundColor: 'color-mix(in srgb, var(--color-wash) 55%, transparent)' },
'&.cm-focused': { outline: 'none' },
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground': {
backgroundColor: 'color-mix(in srgb, var(--color-accent) 18%, transparent)',
},
})
// fallback: basicSetup defaultHighlightStyle( fallback)
return [theme, syntaxHighlighting(hl)]
}
/** 扩展名 → CodeMirror 语言扩展;不在表内按纯文本编辑 */
const CM_LANG: Record<string, () => Promise<CmExtension>> = {
json: () => import('@codemirror/lang-json').then((m) => m.json()),
yaml: () => import('@codemirror/lang-yaml').then((m) => m.yaml()),
yml: () => import('@codemirror/lang-yaml').then((m) => m.yaml()),
py: () => import('@codemirror/lang-python').then((m) => m.python()),
js: () => import('@codemirror/lang-javascript').then((m) => m.javascript()),
ts: () => import('@codemirror/lang-javascript').then((m) => m.javascript({ typescript: true })),
xml: () => import('@codemirror/lang-xml').then((m) => m.xml()),
svg: () => import('@codemirror/lang-xml').then((m) => m.xml()),
html: () => import('@codemirror/lang-html').then((m) => m.html()),
htm: () => import('@codemirror/lang-html').then((m) => m.html()),
css: () => import('@codemirror/lang-css').then((m) => m.css()),
md: () => import('@codemirror/lang-markdown').then((m) => m.markdown()),
sql: () => import('@codemirror/lang-sql').then((m) => m.sql()),
go: () => import('@codemirror/lang-go').then((m) => m.go()),
sh: () => import('@codemirror/legacy-modes/mode/shell').then((m) => streamOf(m.shell)),
ini: () => import('@codemirror/legacy-modes/mode/properties').then((m) => streamOf(m.properties)),
conf: () =>
import('@codemirror/legacy-modes/mode/properties').then((m) => streamOf(m.properties)),
cfg: () => import('@codemirror/legacy-modes/mode/properties').then((m) => streamOf(m.properties)),
env: () => import('@codemirror/legacy-modes/mode/properties').then((m) => streamOf(m.properties)),
properties: () =>
import('@codemirror/legacy-modes/mode/properties').then((m) => streamOf(m.properties)),
toml: () => import('@codemirror/legacy-modes/mode/toml').then((m) => streamOf(m.toml)),
}
async function streamOf<T>(def: import('@codemirror/language').StreamParser<T>) {
const { StreamLanguage } = await import('@codemirror/language')
return StreamLanguage.define(def)
}
async function loadLanguage(ext: string): Promise<CmExtension | null> {
const load = CM_LANG[ext]
if (!load) return null
try {
return await load()
} catch {
return null
}
}
watch(
() => props.modelValue,
(v) => {
// (); emit ,
if (view && v !== view.state.doc.toString())
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: v } })
},
)
watch(
() => props.disabled,
(d) => {
if (view && editableComp && EV)
view.dispatch({ effects: editableComp.reconfigure(EV.editable.of(!d)) })
},
)
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<div v-if="booting" class="flex flex-1 items-center justify-center">
<NSpin size="small" />
</div>
<div v-else-if="bootError" class="flex flex-1 items-center justify-center text-xs text-err">
{{ bootError }}
</div>
<div ref="host" class="cm-host min-h-0 flex-1" :class="booting || bootError ? 'hidden' : ''"></div>
</div>
</template>
<style scoped>
.cm-host :deep(.cm-editor) {
height: 100%;
}
</style>
@@ -0,0 +1,184 @@
<script setup lang="ts">
import { NButton } from 'naive-ui'
import { onBeforeUnmount, computed, ref, watch } from 'vue'
import { highlightCode, highlightSource } from '@/components/objectstorage/codeHighlight'
/** 文本类预览:hljs 高亮;md/svg 支持「渲染 ↔ 代码」双形态 */
const props = defineProps<{
text: string
ext: string
truncated?: boolean
}>()
const renderMode = ref<'render' | 'code'>('render')
const mdHtml = ref('')
const hlHtml = ref('')
const svgUrl = ref('')
const switchable = computed(() => props.ext === 'md' || props.ext === 'svg')
watch(() => [props.text, props.ext], () => void refresh(), { immediate: true })
onBeforeUnmount(revokeSvg)
async function refresh() {
renderMode.value = 'render'
mdHtml.value = ''
revokeSvg()
if (props.ext === 'svg')
svgUrl.value = URL.createObjectURL(new Blob([props.text], { type: 'image/svg+xml' }))
if (props.ext === 'md') void renderMd()
hlHtml.value = (await highlightSource(props.text, props.ext)) ?? ''
}
function revokeSvg() {
if (svgUrl.value) URL.revokeObjectURL(svgUrl.value)
svgUrl.value = ''
}
/** markdown 渲染:marked 转 HTML(围栏代码块经 hljs 着色)后 DOMPurify 消毒;库按需加载独立 chunk */
async function renderMd() {
try {
const [{ Marked }, { markedHighlight }, { default: DOMPurify }] = await Promise.all([
import('marked'),
import('marked-highlight'),
import('dompurify'),
])
const md = new Marked(
markedHighlight({
async: true,
// null,退 marked
highlight: (code, lang) => highlightCode(code, lang),
}),
)
mdHtml.value = DOMPurify.sanitize(await md.parse(props.text, { async: true }))
} catch {
renderMode.value = 'code'
}
}
</script>
<template>
<div class="flex h-full min-h-0 flex-col">
<div v-if="switchable" class="mb-2 flex flex-none justify-end gap-1">
<NButton
size="tiny"
:quaternary="renderMode !== 'render'"
:type="renderMode === 'render' ? 'primary' : 'default'"
@click="renderMode = 'render'"
>
渲染
</NButton>
<NButton
size="tiny"
:quaternary="renderMode !== 'code'"
:type="renderMode === 'code' ? 'primary' : 'default'"
@click="renderMode = 'code'"
>
代码
</NButton>
</div>
<div class="min-h-0 flex-1 overflow-auto rounded bg-white">
<img
v-if="ext === 'svg' && renderMode === 'render' && svgUrl"
:src="svgUrl"
alt="svg 预览"
class="mx-auto max-h-full object-contain p-4"
/>
<!-- eslint-disable vue/no-v-html -- mdHtml DOMPurify 消毒;hljs 输出已转义原文本 -->
<div
v-else-if="ext === 'md' && renderMode === 'render' && mdHtml"
class="md-preview code-hl px-4 py-3"
v-html="mdHtml"
></div>
<pre
v-else-if="hlHtml"
class="code-hl mono m-0 p-3 text-xs leading-relaxed break-all whitespace-pre-wrap"
v-html="hlHtml"
></pre>
<!-- eslint-enable vue/no-v-html -->
<pre
v-else
class="mono m-0 p-3 text-xs leading-relaxed break-all whitespace-pre-wrap"
>{{ text }}</pre>
</div>
<div v-if="truncated" class="mt-1.5 flex-none text-xs text-warn">
内容过长已截断,完整内容请下载查看
</div>
</div>
</template>
<style scoped>
/* markdown ; v-html :deep
hljs 高亮配色为全局 .code-hl(main.css),与编辑器共用 */
.md-preview {
font-size: 13px;
line-height: 1.7;
color: var(--color-ink);
}
.md-preview :deep(h1),
.md-preview :deep(h2),
.md-preview :deep(h3),
.md-preview :deep(h4) {
margin: 0.9em 0 0.4em;
font-weight: 600;
line-height: 1.4;
}
.md-preview :deep(h1) {
font-size: 1.3em;
}
.md-preview :deep(h2) {
font-size: 1.15em;
}
.md-preview :deep(h3) {
font-size: 1.05em;
}
.md-preview :deep(p),
.md-preview :deep(ul),
.md-preview :deep(ol),
.md-preview :deep(blockquote),
.md-preview :deep(pre),
.md-preview :deep(table) {
margin: 0.5em 0;
}
.md-preview :deep(ul),
.md-preview :deep(ol) {
padding-left: 1.4em;
list-style: revert;
}
.md-preview :deep(code) {
background: var(--color-wash);
border-radius: 4px;
padding: 0.1em 0.35em;
font-size: 0.92em;
}
.md-preview :deep(pre) {
background: var(--color-wash);
border-radius: 6px;
padding: 10px 12px;
overflow-x: auto;
}
.md-preview :deep(pre code) {
background: none;
padding: 0;
}
.md-preview :deep(blockquote) {
border-left: 3px solid var(--color-line);
padding-left: 0.8em;
color: var(--color-ink-2);
}
.md-preview :deep(a) {
color: var(--color-accent);
text-decoration: underline;
}
.md-preview :deep(table) {
border-collapse: collapse;
}
.md-preview :deep(th),
.md-preview :deep(td) {
border: 1px solid var(--color-line);
padding: 4px 10px;
}
.md-preview :deep(img) {
max-width: 100%;
}
</style>
+25 -23
View File
@@ -3,8 +3,6 @@ import {
NButton,
NDataTable,
NInput,
NModal,
NPopconfirm,
NRadioButton,
NRadioGroup,
type DataTableColumns,
@@ -19,9 +17,11 @@ import {
probeProxy,
updateProxy,
} from '@/api/proxies'
import ConfirmPop from '@/components/ConfirmPop.vue'
import AppInputNumber from '@/components/AppInputNumber.vue'
import FootNote from '@/components/FootNote.vue'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import ProxyTenantsModal from '@/components/proxy/ProxyTenantsModal.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { useAsync } from '@/composables/useAsync'
@@ -190,6 +190,13 @@ function renderGeo(row: ProxyInfo) {
return h('span', { class: 'text-[13px]' }, row.city ? `${row.country}·${row.city}` : row.country)
}
/** 状态单元格:与地区探测同源 —— 探测经该代理链路发起,失败即代理不可用 */
function renderStatus(row: ProxyInfo) {
if (!row.geoAt) return h(StatusBadge, { kind: 'check', label: '检测中' })
const ok = !!row.country
return h(StatusBadge, { kind: ok ? 'run' : 'term', label: ok ? '正常' : '异常' })
}
// / (ProxyListView),
defineExpose({ openCreate, openImport })
@@ -215,6 +222,7 @@ const columns: DataTableColumns<ProxyInfo> = [
render: (row) => h('span', { class: 'mono text-[12.5px] text-ink-2' }, `${row.host}:${row.port}`),
},
{ title: '地区', key: 'geo', minWidth: 120, render: renderGeo },
{ title: '状态', key: 'status', width: 88, render: renderStatus },
{
title: '认证',
key: 'username',
@@ -249,12 +257,11 @@ const columns: DataTableColumns<ProxyInfo> = [
h(NButton, { size: 'tiny', quaternary: true, onClick: () => openTenants(row) }, () => '关联租户'),
h(NButton, { size: 'tiny', quaternary: true, onClick: () => openEdit(row) }, () => '编辑'),
h(
NPopconfirm,
{ onPositiveClick: () => remove(row) },
ConfirmPop,
{ title: '删除该代理?', content: '删除后不可恢复。', confirmText: '删除', onConfirm: () => remove(row) },
{
trigger: () =>
h(NButton, { size: 'tiny', type: 'error', quaternary: true, disabled: row.usedBy > 0 }, () => '删除'),
default: () => '删除后不可恢复,确认?',
},
),
]),
@@ -272,7 +279,7 @@ const columns: DataTableColumns<ProxyInfo> = [
:row-key="(r: ProxyInfo) => r.id"
/>
<FootNote>
支持 SOCKS5 / HTTP / HTTPS;密码 AES 加密存储不回显明文;地区为经代理实测的出口位置(ip-api.com),创建后自动检测;被租户关联的代理不可删除,先解除关联
支持 SOCKS5 / HTTP / HTTPS;被租户关联的代理须先解除关联才可删除
</FootNote>
<ProxyTenantsModal
@@ -281,11 +288,12 @@ const columns: DataTableColumns<ProxyInfo> = [
@saved="void proxies.run({ silent: true })"
/>
<NModal
<FormModal
v-model:show="showForm"
preset="card"
:title="editing ? '编辑代理' : '新增代理'"
:style="{ width: '480px', maxWidth: 'calc(100vw - 24px)' }"
submit-text="保存"
:submitting="saving"
@submit="save"
>
<FormField label="类型">
<NRadioGroup v-model:value="form.type" class="w-full" size="small">
@@ -327,7 +335,7 @@ const columns: DataTableColumns<ProxyInfo> = [
/>
</FormField>
</div>
<div class="mb-3.5 flex items-start gap-2.5 rounded-lg border border-ok/30 bg-ok/10 px-3 py-2.5">
<div class="flex items-start gap-2.5 rounded-lg border border-ok/30 bg-ok/10 px-3 py-2.5">
<svg
class="mt-0.5 h-[15px] w-[15px] flex-none text-ok"
viewBox="0 0 24 24"
@@ -345,17 +353,15 @@ const columns: DataTableColumns<ProxyInfo> = [
</div>
</div>
</div>
<div class="mt-1 flex items-center gap-2">
<NButton size="small" type="primary" :loading="saving" @click="save">保存</NButton>
<NButton size="small" quaternary @click="showForm = false">取消</NButton>
</div>
</NModal>
</FormModal>
<NModal
<FormModal
v-model:show="showImport"
preset="card"
title="批量导入代理"
:style="{ width: '560px', maxWidth: 'calc(100vw - 24px)' }"
submit-text="导入"
:submitting="importing"
:width="560"
@submit="doImport"
>
<FormField label="代理列表">
<NInput
@@ -397,10 +403,6 @@ const columns: DataTableColumns<ProxyInfo> = [
<span class="ml-auto flex-none text-[11.5px] text-ink-2">{{ f.reason }}</span>
</div>
</div>
<div class="mt-1 flex items-center gap-2">
<NButton size="small" type="primary" :loading="importing" @click="doImport">导入</NButton>
<NButton size="small" quaternary @click="showImport = false">关闭</NButton>
</div>
</NModal>
</FormModal>
</div>
</template>
+4 -1
View File
@@ -7,6 +7,7 @@ import { setProxyTenants } from '@/api/proxies'
import FormField from '@/components/FormField.vue'
import TenantPicker from '@/components/TenantPicker.vue'
import { useAsync } from '@/composables/useAsync'
import { useMobileModal } from '@/composables/useMobileModal'
import type { ProxyInfo } from '@/types/api'
import { useToast } from '@/composables/useToast'
@@ -16,6 +17,7 @@ const props = defineProps<{ show: boolean; proxy: ProxyInfo | null }>()
const emit = defineEmits<{ 'update:show': [boolean]; saved: [] }>()
const message = useToast()
const { modalStyle, modalClass } = useMobileModal(480)
const configs = useAsync(listConfigs, false)
const selected = ref<number[]>([])
const saving = ref(false)
@@ -66,7 +68,8 @@ async function save() {
:show="show"
preset="card"
:title="`关联租户 · ${proxy?.name ?? ''}`"
:style="{ width: '480px', maxWidth: 'calc(100vw - 24px)' }"
:style="modalStyle"
:class="modalClass"
@update:show="emit('update:show', $event)"
>
<FormField label="关联租户" hint="选中即关联,取消选中即解除;关联后租户全部 SDK 请求经此代理出站">
+6 -6
View File
@@ -114,17 +114,17 @@ function openRepo() {
<!-- 运行状态:运行时长随查看自增,资源指标为进程自启动累计口径 -->
<div v-if="info?.resources" class="panel">
<div
class="flex items-center justify-between gap-3 border-b border-line-soft px-5 py-3.5 max-md:flex-col max-md:items-start max-md:gap-1"
class="flex items-center justify-between gap-3 border-b border-line-soft px-4.5 py-3.5 max-md:flex-col max-md:items-start max-md:gap-1"
>
<div class="flex items-center gap-2">
<span class="live-dot"></span>
<span class="text-[13px] font-semibold">运行状态</span>
<span class="text-sm font-semibold">运行状态</span>
</div>
<span class="text-xs text-ink-3">
{{ fmtTime(info.startedAt) }} 启动 · 指标为进程自启动累计口径
</span>
</div>
<div class="px-5 pt-[22px] pb-5">
<div class="px-4.5 pt-[22px] pb-5">
<div class="text-xs font-medium text-ink-2">运行时间</div>
<div class="mt-1.5 text-[38px] leading-[1.1] font-semibold tracking-[-0.6px]">
<template v-for="p in uptimeParts" :key="p.u"
@@ -132,9 +132,9 @@ function openRepo() {
>
</div>
</div>
<div class="mx-5 h-px bg-line-soft"></div>
<div class="mx-4.5 h-px bg-line-soft"></div>
<div class="grid grid-cols-4 max-md:grid-cols-2">
<div v-for="c in statCells" :key="c.label" class="statcell flex flex-col gap-[5px] px-5 pt-4 pb-[18px]">
<div v-for="c in statCells" :key="c.label" class="statcell flex flex-col gap-[5px] px-4.5 pt-4 pb-[18px]">
<div class="text-xs font-medium text-ink-2">{{ c.label }}</div>
<div class="text-[26px] leading-[1.15] font-semibold tracking-[-0.3px]">
<span>{{ c.value }}</span
@@ -146,7 +146,7 @@ function openRepo() {
</div>
<!-- GitHub 仓库 -->
<div class="panel flex items-center gap-3.5 px-5 py-4">
<div class="panel flex items-center gap-3.5 px-4.5 py-4">
<span class="flex h-10 w-10 flex-none items-center justify-center rounded-[9px] bg-wash">
<svg class="h-5 w-5" viewBox="0 0 16 16" fill="currentColor">
<path
+27 -13
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { NButton, NInput, NModal, NPopconfirm, NQrCode, NSpin, NSwitch } from 'naive-ui'
import { NButton, NInput, NModal, NQrCode, NSpin, NSwitch } from 'naive-ui'
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
@@ -18,17 +18,22 @@ import {
updateOAuthSettings,
updatePasswordLogin,
} from '@/api/auth'
import ConfirmPop from '@/components/ConfirmPop.vue'
import FormField from '@/components/FormField.vue'
import FormModal from '@/components/FormModal.vue'
import FootNote from '@/components/FootNote.vue'
import { useAsync } from '@/composables/useAsync'
import { useMobileModal } from '@/composables/useMobileModal'
import { useAppStore } from '@/stores/app'
import { darkTokens, tokens } from '@/theme/tokens'
import { useAuthStore } from '@/stores/auth'
import { fmtTime } from '@/composables/useFormat'
import type { SessionRefresh, TotpSetup, UpdateOAuthRequest } from '@/types/api'
import { useToast } from '@/composables/useToast'
const message = useToast()
/** TOTP 启用引导弹窗的移动端全屏形态 */
const { modalStyle, modalClass } = useMobileModal(360)
const router = useRouter()
const auth = useAuthStore()
const app = useAppStore()
@@ -424,7 +429,7 @@ async function deleteProvider(p: ProviderType) {
<div class="min-w-0">
<div class="text-[13px] font-medium">两步验证(TOTP)</div>
<div class="mt-0.5 text-xs text-ink-3">
登录需额外输入验证器动态码;兼容 Google Authenticator / 1Password
登录需额外输入验证器动态码
</div>
</div>
<NSpin v-if="totp.loading.value" size="small" />
@@ -495,12 +500,17 @@ async function deleteProvider(p: ProviderType) {
</div>
<div class="mt-0.5 text-xs text-ink-3">绑定于 {{ fmtTime(it.createdAt) }}</div>
</div>
<NPopconfirm @positive-click="removeIdentity(it.id)">
<ConfirmPop
:title="`解绑 ${displayNameOf(it.provider)} 身份?`"
content="解绑后该身份无法再登录面板。"
kind="plain"
confirm-text="解绑"
:on-confirm="() => removeIdentity(it.id)"
>
<template #trigger>
<NButton size="tiny" type="error" quaternary>解绑</NButton>
</template>
解绑后该身份无法再登录面板,确认?
</NPopconfirm>
</ConfirmPop>
</div>
<div
@@ -575,12 +585,16 @@ async function deleteProvider(p: ProviderType) {
>
{{ row.disabled ? '启用' : '禁用' }}
</NButton>
<NPopconfirm @positive-click="deleteProvider(row.provider)">
<ConfirmPop
title="删除该登录方式?"
content="将清空全部配置(含 Secret),不可恢复。"
confirm-text="删除"
:on-confirm="() => deleteProvider(row.provider)"
>
<template #trigger>
<NButton size="tiny" type="error" quaternary>删除</NButton>
</template>
删除将清空该方式全部配置( Secret),不可恢复;确认?
</NPopconfirm>
</ConfirmPop>
</td>
</tr>
</tbody>
@@ -590,9 +604,8 @@ async function deleteProvider(p: ProviderType) {
尚未配置任何登录方式;点击右上新增登录方式配置 GitHub OIDC
</div>
<FootNote>
IdP / GitHub 应用中填写的授权回调地址(Redirect URI):{{ callbackBase
}}/api/v1/auth/oauth/&lt;github|oidc&gt;/callback;secret ·
需先在网络与地址保存面板地址
IdP / GitHub 应用中填写的授权回调地址:
{{ callbackBase}}/api/v1/auth/oauth/&lt;github|oidc&gt;/callback
</FootNote>
</div>
@@ -736,7 +749,8 @@ async function deleteProvider(p: ProviderType) {
preset="card"
title="启用两步验证"
closable
:style="{ width: '360px', maxWidth: 'calc(100vw - 24px)' }"
:style="modalStyle"
:class="modalClass"
>
<div v-if="totpPending" class="flex flex-col items-center gap-3">
<!-- 亮色下透明融入弹窗底;暗色下保留浅底(黑模块二维码的可扫性要求) -->
@@ -745,7 +759,7 @@ async function deleteProvider(p: ProviderType) {
:value="totpPending.otpauthUri"
:size="160"
:padding="0"
:color="app.dark ? '#f5f4ed' : '#141413'"
:color="app.dark ? darkTokens.ink : tokens.ink"
background-color="transparent"
error-correction-level="M"
/>
+40 -9
View File
@@ -21,6 +21,7 @@ const form = reactive<AiSettings>({
streamGuardKB: 60,
grokWebSearch: true,
grokXSearch: true,
upstreamWaitSeconds: 300,
})
watch(
@@ -58,6 +59,12 @@ function commitGuardKB(v: number | null) {
setField('streamGuardKB', v)
}
/** 上游无响应预算失焦/回车提交 */
function commitUpstreamWait(v: number | null) {
if (v == null || v === form.upstreamWaitSeconds) return
setField('upstreamWaitSeconds', v)
}
const removing = ref(0)
async function doRemove(id: number, name: string) {
removing.value = id
@@ -83,15 +90,15 @@ function onBlacklistChanged() {
<NSpin size="small" />
</div>
<div v-else class="flex max-w-[880px] flex-col gap-4">
<!-- 流式保险丝 -->
<!-- Responses 直通防护 -->
<div class="panel">
<div class="border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">流式保险丝</div>
<div class="text-sm font-semibold">Responses 直通</div>
</div>
<div class="px-4.5">
<div class="flex items-center justify-between gap-3 py-3.5">
<div class="flex items-center justify-between gap-3 border-b border-line-soft py-3.5">
<div class="min-w-0">
<div class="text-[13px] font-medium">instructions + tools 阈值</div>
<div class="text-[13px] font-medium">流式保险丝:instructions + tools 阈值</div>
<div class="mt-0.5 text-xs text-ink-3">
系统提示与工具定义合计超过阈值的流式请求,预防性改走非流式上游并合成
SSE:丢增量输出,保会话不中断
@@ -119,9 +126,34 @@ function onBlacklistChanged() {
/>
</div>
</div>
<div class="flex items-center justify-between gap-3 py-3.5">
<div class="min-w-0">
<div class="text-[13px] font-medium">上游无响应预算</div>
<div class="mt-0.5 text-xs text-ink-3">
非流式为单次尝试总超时,流式为等待响应头上限,响应头到达后不限制流时长;
multi-agent / 搜索类模型单次调用可达 3 分钟,建议 300
</div>
</div>
<div class="flex flex-none items-center gap-3">
<NInputNumber
:value="form.upstreamWaitSeconds"
:min="30"
:max="900"
:show-button="false"
size="small"
class="w-24"
:update-value-on-input="false"
@update:value="commitUpstreamWait"
>
<template #suffix><span class="text-xs text-ink-3"></span></template>
</NInputNumber>
<!-- 隐形开关与上一行等宽占位,保证两行输入框网格对齐 -->
<NSwitch class="invisible" size="small" aria-hidden="true" />
</div>
</div>
</div>
<div class="border-t border-line-soft bg-wash px-4.5 py-2.5 text-xs leading-relaxed text-ink-3">
修改即时生效,无需重启 · 仅作用于 Responses 直通面;Chat / Messages 已有断流自动重做兜底
仅作用于 Responses 直通面;Chat / Messages 已有断流自动重做兜底
</div>
</div>
@@ -130,8 +162,7 @@ function onBlacklistChanged() {
<div class="border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">grok 服务端搜索工具</div>
<div class="mt-0.5 text-xs text-ink-3">
仅对 <span class="mono">xai.</span> 前缀模型的对话请求生效;请求 tools
已包含同名工具时保持原样,不覆盖参数
仅对 <span class="mono">xai.</span> 前缀模型的对话请求生效
</div>
</div>
<div class="px-4.5">
@@ -166,7 +197,7 @@ function onBlacklistChanged() {
<div class="min-w-0">
<div class="text-[13px] font-medium">过滤弃用模型</div>
<div class="mt-0.5 text-xs text-ink-3">
开启后,已宣布弃用(即使未退役)的模型从模型列表与路由中排除;关闭恢复展示
开启后,已宣布弃用(即使未退役)的模型从模型列表与路由中排除
</div>
</div>
<NSwitch
@@ -180,7 +211,7 @@ function onBlacklistChanged() {
<div class="min-w-0">
<div class="text-[13px] font-medium">模型黑名单</div>
<div class="mt-0.5 text-xs text-ink-3">
命中的模型从模型列表与路由排除,重新同步渠道后移出才恢复
命中的模型从模型列表与路由排除
</div>
</div>
<NButton size="tiny" quaternary type="primary" @click="showAdd = true"> 添加模型</NButton>
@@ -3,6 +3,7 @@ import { NInput, NModal } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { addAiBlacklist, listAiModelCatalog } from '@/api/aigateway'
import { useMobileModal } from '@/composables/useMobileModal'
import { useToast } from '@/composables/useToast'
import type { AiCatalogModel } from '@/types/api'
@@ -10,6 +11,7 @@ const props = defineProps<{ show: boolean; blacklisted: string[] }>()
const emit = defineEmits<{ 'update:show': [boolean]; changed: [] }>()
const toast = useToast()
const { modalStyle, modalClass } = useMobileModal(640)
const rows = ref<AiCatalogModel[]>([])
const loading = ref(false)
@@ -78,7 +80,8 @@ async function doBan(name: string) {
<NModal
:show="show"
preset="card"
:style="{ width: '640px', maxWidth: 'calc(100vw - 24px)' }"
:style="modalStyle"
:class="modalClass"
@update:show="emit('update:show', $event)"
>
<template #header>
@@ -3,6 +3,7 @@ import { NButton, NInput, NModal } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { testNotifyTemplate, updateNotifyTemplate } from '@/api/settings'
import { useMobileModal } from '@/composables/useMobileModal'
import type { NotifyTemplateItem } from '@/types/api'
import { useToast } from '@/composables/useToast'
@@ -20,6 +21,7 @@ const emit = defineEmits<{
}>()
const message = useToast()
const { modalStyle, modalClass } = useMobileModal(600)
const draft = ref('')
const saving = ref(false)
const testing = ref(false)
@@ -104,7 +106,8 @@ async function sendTest() {
v-model:show="visible"
preset="card"
closable
:style="{ width: '600px', maxWidth: 'calc(100vw - 24px)' }"
:style="modalStyle"
:class="modalClass"
>
<template #header>
<div class="flex flex-col gap-1">
+106 -29
View File
@@ -1,20 +1,25 @@
<script setup lang="ts">
import { NButton, NDataTable, NModal, type DataTableColumns } from 'naive-ui'
import { computed, h, onMounted, reactive, ref } from 'vue'
import { NButton, NDataTable, NInput, NInputGroup, NInputGroupLabel, NModal, type DataTableColumns } from 'naive-ui'
import { computed, h, onMounted, reactive, ref, watch } from 'vue'
import { getAuditEventDetail, listAuditEvents } from '@/api/tenant'
import DetailFieldList, { type DetailRow } from '@/components/DetailFieldList.vue'
import DetailHero, { type HeroChip } from '@/components/DetailHero.vue'
import EmptyCard from '@/components/EmptyCard.vue'
import FootNote from '@/components/FootNote.vue'
import JsonBlock from '@/components/JsonBlock.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import { eventLabel } from '@/composables/useEventLabel'
import { fmtTime } from '@/composables/useFormat'
import { useIsMobile } from '@/composables/useIsMobile'
import { useMobileModal } from '@/composables/useMobileModal'
import type { AuditEvent } from '@/types/api'
import { useToast } from '@/composables/useToast'
const props = defineProps<{ cfgId: number }>()
const message = useToast()
const isMobile = useIsMobile()
const { modalStyle, modalClass } = useMobileModal(720)
const loading = ref(false)
const loadingMore = ref(false)
@@ -23,23 +28,78 @@ const rows = ref<AuditEvent[]>([])
// : exhausted 365
const cursor = ref('')
const exhausted = ref(false)
// ;
const q = ref('')
// (),
const scannedThrough = ref('')
// :/,
let gen = 0
let qTimer: ReturnType<typeof setTimeout> | undefined
// ;/,
let loadedQ: string | null = null
// :,
let autoFills = 0
const maxAutoFills = 2
// : 500ms ;/
watch(q, () => {
clearTimeout(qTimer)
if (q.value.trim() === loadedQ) return
qTimer = setTimeout(() => void load(), 500)
})
/** 回车/清空的即时提交:关键字未变则不发起重复搜索 */
function submitSearch() {
clearTimeout(qTimer)
if (q.value.trim() !== loadedQ) void load()
}
const pageCount = computed(() => Math.max(1, Math.ceil(rows.value.length / pagination.pageSize)))
const hasMore = computed(() => cursor.value !== '' && !exhausted.value)
/** = min(, ):,
* 直接展示会显示成当前时刻;两者取更早才反映真实扫描位置 */
const scanProgress = computed(() => {
const oldest = rows.value.length ? (rows.value[rows.value.length - 1].eventTime ?? '') : ''
if (!scannedThrough.value || !oldest) return scannedThrough.value || oldest
return scannedThrough.value < oldest ? scannedThrough.value : oldest
})
/** 受控分页:字面量对象会在重渲染时被重建导致页大小切换失效 */
const pagination = reactive({
page: 1,
pageSize: 20,
showSizePicker: true,
pageSizes: [20, 50, 100],
prefix: () =>
`已加载 ${rows.value.length} 条 · ` +
(loadingMore.value ? '正在加载更早…' : exhausted.value ? '已到 365 天保留期尽头' : '翻到末页自动加载更早'),
// , simple ( n/ )
get simple() {
return isMobile.value
},
/** :/;,
* 自动补批封顶后由用户显式接力,不会无人值守扫完整个保留期 */
prefix: () => {
const parts = [`已加载 ${rows.value.length}`]
if (scanProgress.value && !exhausted.value) parts.push(`已回溯至 ${fmtTime(scanProgress.value)}`)
if (exhausted.value) parts.push('已到 365 天保留期尽头')
const text = parts.join(' · ')
if (loadingMore.value) return `${text} · 正在加载更早…`
if (!hasMore.value) return text
return h('span', { class: 'inline-flex items-center gap-1.5' }, [
`${text} ·`,
h(
NButton,
{ size: 'tiny', quaternary: true, type: 'primary', onClick: () => { autoFills = 0; void fetchBatch() } },
{ default: () => '加载更早' },
),
])
},
onUpdatePage: (p: number) => {
pagination.page = p
// :
if (p >= pageCount.value) void fetchBatch()
// :(,)
if (p >= pageCount.value) {
autoFills = 0
void fetchBatch()
}
},
onUpdatePageSize: (ps: number) => {
pagination.pageSize = ps
@@ -47,35 +107,45 @@ const pagination = reactive({
},
})
/** 重置信息流:回到最新一批 */
/** 重置信息流:回到最新一批(刷新按钮与关键字变化共用) */
async function load() {
clearTimeout(qTimer)
const g = ++gen
loadedQ = q.value.trim()
autoFills = 0
loading.value = true
error.value = ''
rows.value = []
cursor.value = ''
exhausted.value = false
scannedThrough.value = ''
pagination.page = 1
try {
await fetchBatch(true)
} finally {
loading.value = false
if (g === gen) loading.value = false
}
}
/** (~100 ):;
* 末页不满且还有更早数据时自动补一批,避免首屏残页 */
/** (~200 ):;
* 末页不满且还有更早数据时自动补一批,避免首屏残页;
* 代次不符的在途响应直接丢弃,防止旧关键字结果混入新信息流 */
async function fetchBatch(first = false) {
if (loadingMore.value || (!first && !hasMore.value)) return
if (!first && (loadingMore.value || !hasMore.value)) return
const g = gen
loadingMore.value = true
try {
const r = await listAuditEvents(props.cfgId, { cursor: cursor.value || undefined })
const r = await listAuditEvents(props.cfgId, { cursor: cursor.value || undefined, q: q.value.trim() || undefined })
if (g !== gen) return
const seen = new Set(rows.value.map((e) => e.eventId))
rows.value = [...rows.value, ...r.items.filter((e) => !seen.has(e.eventId))].sort((a, b) =>
(b.eventTime ?? '').localeCompare(a.eventTime ?? ''),
)
cursor.value = r.cursor ?? ''
exhausted.value = r.exhausted
scannedThrough.value = r.scannedThrough ?? ''
} catch (e) {
if (g !== gen) return
if (first) {
error.value = e instanceof Error ? e.message : '查询失败'
} else {
@@ -83,9 +153,13 @@ async function fetchBatch(first = false) {
message.error(e instanceof Error ? e.message : '继续加载失败,请刷新重新查询')
}
} finally {
loadingMore.value = false
if (g === gen) loadingMore.value = false
}
// : maxAutoFills ,
if (g === gen && hasMore.value && rows.value.length < pagination.pageSize && autoFills < maxAutoFills) {
autoFills++
void fetchBatch()
}
if (hasMore.value && rows.value.length < pagination.pageSize) void fetchBatch()
}
onMounted(() => void load())
@@ -202,19 +276,24 @@ const columns: DataTableColumns<AuditEvent> = [
<template>
<div class="panel">
<div class="flex flex-wrap items-center gap-2.5 border-b border-line-soft px-4.5 py-3">
<div class="flex flex-wrap items-center gap-2.5 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">审计日志</div>
<StatusBadge v-if="exhausted" kind="run" label="已加载全部保留期数据" :dot="false" />
<div class="flex-1" />
<NButton size="small" :loading="loading" @click="load()">刷新</NButton>
<NInputGroup class="!w-76 max-lg:!w-full">
<NInputGroupLabel size="small">搜索</NInputGroupLabel>
<NInput
v-model:value="q"
size="small"
clearable
placeholder="事件 / 资源 / 操作者,支持 *"
@keydown.enter="submitSearch()"
@clear="submitSearch()"
/>
</NInputGroup>
</div>
<div
v-if="error"
class="px-5 py-10 text-center text-[13px] text-ink-3"
>
{{ error }}
</div>
<EmptyCard v-if="error" title="审计日志加载失败" :note="error" />
<NDataTable
v-else
:columns="columns"
@@ -225,13 +304,11 @@ const columns: DataTableColumns<AuditEvent> = [
:row-props="rowProps"
/>
<FootNote>
OCI Audit 免费且默认开启事件保留 365 无需在云端做任何配置 ·
实时查询不入库事件通常延迟数分钟可见 ·
已默认过滤遥测噪声SummarizeMetricsData与内网地址发起的服务互调 ·
从最新事件起每批约 100 翻到末页自动向更早加载空档期自动扩窗回溯 · 点击行查看完整详情
事件通常延迟数分钟可见 ·
从最新事件起每批约 200 翻到末页自动向更早加载命中较少时自动补两批后停驻
</FootNote>
<NModal v-model:show="showDetail" preset="card" closable :style="{ width: '720px', maxWidth: 'calc(100vw - 24px)' }">
<NModal v-model:show="showDetail" preset="card" closable :style="modalStyle" :class="modalClass">
<template #header>
<DetailHero
v-if="detail"
@@ -254,7 +331,7 @@ const columns: DataTableColumns<AuditEvent> = [
v-if="detailRaw"
:value="detailRaw"
title="原始 JSON"
meta="来自 Audit SDK"
meta="来自 OCI 审计日志"
max-height="36vh"
wide
/>
+141 -41
View File
@@ -2,49 +2,122 @@
import { NSelect, NSpin } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { getCosts } from '@/api/analytics'
import { getCosts, type CostQuery } from '@/api/analytics'
import CostChart from '@/components/CostChart.vue'
import EmptyCard from '@/components/EmptyCard.vue'
import FootNote from '@/components/FootNote.vue'
import { useAsync } from '@/composables/useAsync'
const props = defineProps<{ cfgId: number }>()
const rangeDays = ref(14)
/** 'today' 走小时粒度(本地零点起);数字为最近 N 天(天粒度) */
const range = ref<'today' | 14 | 30>(14)
const rangeOptions = [
{ label: '今天', value: 'today' as const },
{ label: '近 14 天', value: 14 },
{ label: '近 30 天', value: 30 },
]
const costs = useAsync(() => getCosts(props.cfgId, { granularity: 'DAILY', groupBy: 'service' }))
watch(rangeDays, () => void costs.run())
const daily = computed(() => {
const byDay = new Map<string, number>()
for (const item of costs.data.value ?? []) {
const day = item.timeStart.slice(5, 10)
byDay.set(day, (byDay.get(day) ?? 0) + item.computedAmount)
/** 一次复合分组查询(service,skuName):总额/曲线/服务/产品全部本地聚合,不加请求 */
function buildQuery(): CostQuery {
const q: CostQuery = { groupBy: 'service,skuName' }
if (range.value === 'today') {
const midnight = new Date()
midnight.setHours(0, 0, 0, 0)
q.granularity = 'HOURLY'
q.startTime = midnight.toISOString()
} else {
q.granularity = 'DAILY'
q.startTime = new Date(Date.now() - range.value * 86400e3).toISOString()
}
const labels = [...byDay.keys()].sort()
return { labels, values: labels.map((l) => +(byDay.get(l) ?? 0).toFixed(2)) }
return q
}
const costs = useAsync(() => getCosts(props.cfgId, buildQuery()))
watch(range, () => void costs.run())
/** 时间桶标签:今天按本地小时(HH:00),天粒度按 MM-DD(UTC 日) */
function bucketLabel(timeStart: string): string {
if (range.value !== 'today') return timeStart.slice(5, 10)
return `${String(new Date(timeStart).getHours()).padStart(2, '0')}:00`
}
/** 完整时间轴:Usage API 对无出账记录的时段不返回行,不补零桶会断轴缺刻度 */
function fullLabels(): string[] {
if (range.value === 'today') {
const hours = new Date().getHours()
return Array.from({ length: hours + 1 }, (_, h) => `${String(h).padStart(2, '0')}:00`)
}
const days = range.value
return Array.from({ length: days + 1 }, (_, i) =>
new Date(Date.now() - (days - i) * 86400e3).toISOString().slice(5, 10),
)
}
const series = computed(() => {
const byBucket = new Map<string, number>()
for (const item of costs.data.value ?? []) {
const key = bucketLabel(item.timeStart)
byBucket.set(key, (byBucket.get(key) ?? 0) + item.computedAmount)
}
const labels = fullLabels()
return { labels, values: labels.map((l) => +(byBucket.get(l) ?? 0).toFixed(2)) }
})
const total = computed(() => daily.value.values.reduce((s, v) => s + v, 0))
const total = computed(() => series.value.values.reduce((s, v) => s + v, 0))
const byService = computed(() => {
const map = new Map<string, number>()
interface ProductRow {
name: string
amount: number
pct: number
}
interface ServiceRow {
name: string
amount: number
pct: number
barWidth: string
products: ProductRow[]
}
/** 服务榜单 + 各服务内产品(SKU)明细,均按金额倒序 */
const byService = computed<ServiceRow[]>(() => {
const svcTotal = new Map<string, number>()
const skuTotal = new Map<string, Map<string, number>>()
for (const item of costs.data.value ?? []) {
map.set(item.groupValue, (map.get(item.groupValue) ?? 0) + item.computedAmount)
const svc = item.groupValue || '(未知服务)'
svcTotal.set(svc, (svcTotal.get(svc) ?? 0) + item.computedAmount)
const skus = skuTotal.get(svc) ?? new Map<string, number>()
const sku = item.subValue || '(未细分)'
skus.set(sku, (skus.get(sku) ?? 0) + item.computedAmount)
skuTotal.set(svc, skus)
}
const rows = [...map.entries()].sort((a, b) => b[1] - a[1])
const rows = [...svcTotal.entries()].sort((a, b) => b[1] - a[1])
const max = rows[0]?.[1] ?? 1
return rows.map(([name, amount]) => ({
name,
amount,
pct: total.value ? Math.round((amount / total.value) * 100) : 0,
barWidth: `${Math.round((amount / max) * 100)}%`,
products: [...(skuTotal.get(name) ?? new Map<string, number>()).entries()]
.sort((a, b) => b[1] - a[1])
.map(([sku, amt]) => ({
name: sku,
amount: amt,
pct: amount ? Math.round((amt / amount) * 100) : 0,
})),
}))
})
// ---- :, ----
const expanded = ref(new Set<string>())
watch(range, () => (expanded.value = new Set()))
function toggle(name: string) {
const next = new Set(expanded.value)
if (next.has(name)) next.delete(name)
else next.add(name)
expanded.value = next
}
</script>
<template>
@@ -53,7 +126,7 @@ const byService = computed(() => {
<div class="text-sm font-semibold">成本分析</div>
<div class="flex-1" />
<div class="w-28">
<NSelect v-model:value="rangeDays" size="small" :options="rangeOptions" />
<NSelect v-model:value="range" size="small" :options="rangeOptions" />
</div>
</div>
@@ -64,43 +137,70 @@ const byService = computed(() => {
<div class="flex flex-wrap items-baseline gap-2.5 px-4.5 pt-3.5">
<div class="text-[26px] font-semibold tabular-nums">${{ total.toFixed(2) }}</div>
<div class="text-[12.5px] text-ink-3">
{{ daily.labels[0] }} {{ daily.labels.at(-1) }} 合计
{{
range === 'today'
? '今天 0 点至今合计(小时粒度)'
: `${series.labels[0]}${series.labels.at(-1)} 合计`
}}
</div>
</div>
<div class="px-3 pb-1">
<CostChart :labels="daily.labels" :values="daily.values" />
<CostChart :labels="series.labels" :values="series.values" />
</div>
<div class="border-t border-line-soft px-4.5 py-3">
<div class="mb-2 flex items-center justify-between">
<div class="text-[13px] font-semibold">按服务拆分</div>
<div class="text-[12.5px] text-ink-3">本期合计 ${{ total.toFixed(2) }}</div>
<div class="text-[12.5px] text-ink-3">点击服务行展开产品 · 本期合计 ${{ total.toFixed(2) }}</div>
</div>
<div
v-for="svc in byService"
:key="svc.name"
class="flex items-center gap-3 py-1.5 max-md:gap-2"
>
<div class="w-32 flex-none truncate text-[13px] max-md:w-24" :title="svc.name">
{{ svc.name }}
<template v-for="svc in byService" :key="svc.name">
<div
class="flex cursor-pointer items-center gap-3 rounded py-1.5 select-none hover:bg-wash/70 max-md:gap-2"
@click="toggle(svc.name)"
>
<span
class="w-3 flex-none text-center text-[10px] text-ink-3 transition-transform"
:class="expanded.has(svc.name) ? 'rotate-90' : ''"
>
</span>
<div class="w-32 flex-none truncate text-[13px] max-md:w-24" :title="svc.name">
{{ svc.name }}
</div>
<div class="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-line-soft">
<div class="h-full rounded-full bg-chart" :style="{ width: svc.barWidth }" />
</div>
<div class="w-17 flex-none text-right text-[13px] tabular-nums">
${{ svc.amount.toFixed(2) }}
</div>
<div class="w-10 flex-none text-right text-xs tabular-nums text-ink-3">
{{ svc.pct }}%
</div>
</div>
<div class="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-line-soft">
<div class="h-full rounded-full bg-chart" :style="{ width: svc.barWidth }" />
<div v-if="expanded.has(svc.name)" class="mb-1 ml-3 border-l border-line-soft pl-4">
<div
v-for="p in svc.products"
:key="p.name"
class="flex items-center gap-3 py-1 max-md:gap-2"
>
<div class="min-w-0 flex-1 truncate text-[12.5px] text-ink-2" :title="p.name">
{{ p.name }}
</div>
<div class="w-17 flex-none text-right text-[12.5px] tabular-nums">
${{ p.amount.toFixed(2) }}
</div>
<div class="w-10 flex-none text-right text-xs tabular-nums text-ink-3">
{{ p.pct }}%
</div>
</div>
</div>
<div class="w-17 flex-none text-right text-[13px] tabular-nums">
${{ svc.amount.toFixed(2) }}
</div>
<div class="w-10 flex-none text-right text-xs tabular-nums text-ink-3">{{ svc.pct }}%</div>
</div>
</template>
</div>
</template>
<EmptyCard
v-else
title="暂无成本数据"
note="试用租户无消费时成本为空;Usage API 数据通常延迟数小时至一天"
:title="range === 'today' ? '今天暂无成本数据' : '暂无成本数据'"
note="试用租户无消费时成本为空;Usage API 数据通常延迟数小时至一天,「今天」视图可能滞后"
/>
<FootNote>
每日 03:30 自动同步 Usage API · 本地快照 · 免费类别租户不参与成本同步 · 点击刷新可即时拉取
</FootNote>
</div>
</template>
+10 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { NButton, NDataTable, NPopconfirm, NSwitch, useDialog, type DataTableColumns } from 'naive-ui'
import { NButton, NDataTable, NSwitch, useDialog, type DataTableColumns } from 'naive-ui'
import { h, ref } from 'vue'
import {
@@ -16,6 +16,7 @@ import StatusBadge from '@/components/StatusBadge.vue'
import IdpFormModal from '@/components/tenant/IdpFormModal.vue'
import { useAsync } from '@/composables/useAsync'
import type { IdentityProvider, SignOnRule } from '@/types/api'
import ConfirmPop from '@/components/ConfirmPop.vue'
import { useToast } from '@/composables/useToast'
const props = defineProps<{ cfgId: number; domainId?: string }>()
@@ -121,15 +122,17 @@ const ruleColumns: DataTableColumns<SignOnRule> = [
row.builtIn
? h('span', { class: 'text-xs text-ink-3' }, '内置')
: h(
NPopconfirm,
ConfirmPop,
{
onPositiveClick: () =>
title: '删除该免 MFA 规则?',
content: '删除后经此 IdP 登录将重新要求 MFA。',
confirmText: '删除',
onConfirm: () =>
act(() => deleteSignOnExemption(props.cfgId, row.id, props.domainId), '已删除免 MFA 规则并恢复优先级'),
},
{
trigger: () =>
h(NButton, { size: 'tiny', quaternary: true, type: 'error' }, { default: () => '删除' }),
default: () => '删除该免 MFA 规则?删除后经此 IdP 登录将重新要求 MFA',
},
),
},
@@ -175,7 +178,7 @@ function addExemption() {
<template>
<div class="flex flex-col gap-4">
<div class="panel">
<div class="flex items-center justify-between border-b border-line-soft px-4.5 py-3.5">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">SAML 身份提供商</div>
<div class="flex items-center gap-2">
<NButton size="small" @click="doDownloadMetadata">下载 SP 元数据</NButton>
@@ -190,13 +193,12 @@ function addExemption() {
:row-key="(r: IdentityProvider) => r.id"
/>
<FootNote>
推荐流程下载 SP SAML 元数据导入 IdP 创建 IdP 激活自动显示到登录页 建免 MFA
规则停用与删除会先将 IdP 移出登录页
流程下载 SP 元数据导入 IdP 创建 激活登录页 建免 MFA 规则停用 / 删除自动移出登录页
</FootNote>
</div>
<div class="panel">
<div class="flex items-center justify-between border-b border-line-soft px-4.5 py-3.5">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">Sign-on 策略 MFA 规则</div>
<NButton size="small" @click="addExemption">为已启用 IdP 创建免 MFA 规则</NButton>
</div>
@@ -0,0 +1,132 @@
<script setup lang="ts">
import { NButton, NModal, NSpin } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { fetchInvoicePdf, listInvoiceLines, saveInvoicePdf } from '@/api/billing'
import StatusBadge from '@/components/StatusBadge.vue'
import { useToast } from '@/composables/useToast'
import { invoiceDate, invoiceStatusMeta } from '@/components/tenant/invoiceStatus'
import { useAsync } from '@/composables/useAsync'
import { fmtMoney } from '@/composables/useFormat'
import { useMobileModal } from '@/composables/useMobileModal'
import type { Invoice } from '@/types/api'
/** 发票明细弹窗:费用行 + 合计 + 付款/PDF 入口 */
const props = defineProps<{ show: boolean; cfgId: number; invoice: Invoice | null }>()
const emit = defineEmits<{ 'update:show': [boolean]; pay: [Invoice] }>()
const message = useToast()
const { modalStyle, modalClass } = useMobileModal(640)
const lines = useAsync(async () => {
const inv = props.invoice
return inv ? listInvoiceLines(props.cfgId, inv.internalId) : []
}, false)
watch(
() => props.show,
(v) => {
if (v && props.invoice) void lines.run()
},
)
const meta = computed(() => (props.invoice ? invoiceStatusMeta(props.invoice) : null))
const total = computed(() => (lines.data.value ?? []).reduce((s, l) => s + l.total, 0))
const payable = computed(() => !!props.invoice && props.invoice.isPayable && !props.invoice.isPaid)
const downloading = ref(false)
async function onPdf() {
const inv = props.invoice
if (!inv) return
downloading.value = true
try {
saveInvoicePdf(await fetchInvoicePdf(props.cfgId, inv.internalId), inv.number || inv.internalId)
} catch (e) {
message.error(e instanceof Error ? e.message : 'PDF 下载失败')
} finally {
downloading.value = false
}
}
</script>
<template>
<NModal
:show="show"
preset="card"
:title="invoice ? `发票 ${invoice.number || invoice.id}` : '发票明细'"
:style="modalStyle"
:class="modalClass"
@update:show="emit('update:show', $event)"
>
<template v-if="invoice">
<div class="rounded-md bg-wash px-4 py-3">
<div class="flex items-baseline justify-between gap-3">
<div class="text-[24px] font-semibold tabular-nums">
{{ fmtMoney(invoice.amount, invoice.currency) }}
</div>
<StatusBadge v-if="meta" :kind="meta.kind" :label="meta.label" />
</div>
<div class="mt-1.5 text-xs text-ink-3">
{{ invoice.type || 'USAGE' }} · 开票 {{ invoiceDate(invoice.timeInvoice) }} · 到期
{{ invoiceDate(invoice.timeDue) }}
</div>
<div v-if="invoice.isPaymentFailed" class="mt-1.5 text-xs text-err">
上次自动扣款失败,请检查付款方式后手动支付
</div>
</div>
<div class="mt-4 mb-1.5 text-[13px] font-semibold">费用明细</div>
<div class="max-h-[46vh] overflow-y-auto">
<div v-if="lines.loading.value" class="flex items-center justify-center py-10">
<NSpin size="small" />
</div>
<div v-else-if="lines.error.value" class="py-6 text-center text-xs text-err">
{{ lines.error.value }}
</div>
<template v-else>
<div
v-for="(l, i) in lines.data.value ?? []"
:key="i"
class="flex items-center gap-3 border-b border-line-soft py-2 last:border-b-0"
>
<div class="min-w-0 flex-1">
<div class="truncate text-[13px]" :title="l.product">{{ l.product }}</div>
<div class="mt-0.5 text-xs text-ink-3">
{{ invoiceDate(l.timeStart) }} ~ {{ invoiceDate(l.timeEnd) }}
</div>
</div>
<div class="flex-none text-right text-xs text-ink-3 tabular-nums">
{{ l.quantity.toLocaleString() }} × {{ l.unitPrice }}
</div>
<div class="w-20 flex-none text-right text-[13px] tabular-nums">
{{ fmtMoney(l.total, l.currency || invoice.currency) }}
</div>
</div>
<div v-if="!lines.data.value?.length" class="py-6 text-center text-xs text-ink-3">
该发票暂无费用行
</div>
</template>
</div>
<div
v-if="lines.data.value?.length"
class="flex items-center justify-between border-t border-line pt-2.5 text-[13px] font-semibold"
>
<span>合计</span>
<span class="tabular-nums">{{ fmtMoney(total, invoice.currency) }}</span>
</div>
</template>
<template #footer>
<div class="flex justify-end gap-2.5">
<NButton size="small" :loading="downloading" @click="onPdf">下载 PDF</NButton>
<NButton
v-if="payable && invoice"
size="small"
type="primary"
@click="emit('pay', invoice)"
>
立即付款
</NButton>
</div>
</template>
</NModal>
</template>
+100
View File
@@ -0,0 +1,100 @@
<script setup lang="ts">
import { NInput } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { payInvoice } from '@/api/billing'
import FormModal from '@/components/FormModal.vue'
import { useToast } from '@/composables/useToast'
import { invoiceDate } from '@/components/tenant/invoiceStatus'
import { fmtMoney } from '@/composables/useFormat'
import type { Invoice, PaymentMethod } from '@/types/api'
/** : OSP Gateway PayInvoice ;
* email API 必填项(接收付款回执),在此向用户收集 */
const props = defineProps<{
show: boolean
cfgId: number
invoice: Invoice | null
methods: PaymentMethod[] | null
}>()
const emit = defineEmits<{ 'update:show': [boolean]; paid: [] }>()
const message = useToast()
const email = ref('')
const paying = ref(false)
const emailOk = computed(() => /.+@.+\..+/.test(email.value.trim()))
/** 扣款方式展示:优先第一张信用卡,其次任一登记方式 */
const payVia = computed(() => {
const ms = props.methods ?? []
const m = ms.find((x) => x.method === 'CREDIT_CARD') ?? ms[0]
if (!m) return '订阅默认付款方式'
if (m.method === 'CREDIT_CARD') return `${m.cardType || '银行卡'} •••• ${m.lastDigits}`
return `PayPal(${m.email})`
})
watch(
() => props.show,
(v) => {
if (v) paying.value = false
},
)
async function doPay() {
const inv = props.invoice
if (!inv || !emailOk.value) return
paying.value = true
try {
await payInvoice(props.cfgId, inv.internalId, email.value.trim())
message.success('付款已提交,发票状态稍后更新')
emit('update:show', false)
emit('paid')
} catch (e) {
message.error(e instanceof Error ? e.message : '付款失败')
} finally {
paying.value = false
}
}
</script>
<template>
<FormModal
:show="show"
title="支付发票"
:width="440"
submit-text="确认支付"
:submitting="paying"
:submit-disabled="!emailOk"
@update:show="emit('update:show', $event)"
@submit="doPay"
>
<template v-if="invoice">
<div class="rounded-md bg-wash px-4 py-3">
<div class="text-xs text-ink-3">应付金额</div>
<div class="mt-1 text-[24px] font-semibold tabular-nums">
{{ fmtMoney(invoice.amountDue || invoice.amount, invoice.currency) }}
</div>
<div class="mt-1 text-xs text-ink-3">
发票 {{ invoice.number }} · 到期 {{ invoiceDate(invoice.timeDue) }}
</div>
</div>
<div
class="mt-3 flex items-center justify-between rounded-md border border-line-soft px-4 py-2.5 text-[13px]"
>
<span class="text-ink-3">扣款方式</span>
<span class="font-medium">{{ payVia }}</span>
</div>
<div class="mt-3">
<div class="mb-1 text-xs text-ink-3">回执邮箱(必填)</div>
<NInput v-model:value="email" placeholder="billing@example.com" />
</div>
<div class="mt-3 text-xs leading-relaxed text-ink-3">
确认后经 OCI 支付网关按上述方式即时扣款,回执发送至邮箱;提交后发票转入处理中,
入账通常需要数分钟,期间请勿重复支付
</div>
</template>
</FormModal>
</template>
+81
View File
@@ -0,0 +1,81 @@
<script setup lang="ts">
import { NButton, NModal, NSpin } from 'naive-ui'
import { ref, watch } from 'vue'
import { fetchInvoicePdf, saveInvoicePdf } from '@/api/billing'
import OfficePreview from '@/components/objectstorage/viewer/OfficePreview.vue'
import { useMobileModal } from '@/composables/useMobileModal'
import type { Invoice } from '@/types/api'
/** 发票 PDF 预览弹窗:面板代理拉取后 vue-office 渲染,预览框内可下载 */
const props = defineProps<{ show: boolean; cfgId: number; invoice: Invoice | null }>()
const emit = defineEmits<{ 'update:show': [boolean] }>()
const { modalStyle, modalClass } = useMobileModal(860)
const loading = ref(false)
const loadError = ref('')
const pdfData = ref<ArrayBuffer | null>(null)
let blob: Blob | null = null
watch(
() => props.show,
(v) => {
if (v) void load()
},
)
async function load() {
const inv = props.invoice
if (!inv) return
loading.value = true
loadError.value = ''
pdfData.value = null
try {
blob = await fetchInvoicePdf(props.cfgId, inv.internalId)
pdfData.value = await blob.arrayBuffer()
} catch (e) {
loadError.value = e instanceof Error ? e.message : 'PDF 加载失败'
} finally {
loading.value = false
}
}
function download() {
const inv = props.invoice
if (blob && inv) saveInvoicePdf(blob, inv.number || inv.internalId)
}
</script>
<template>
<NModal
:show="show"
preset="card"
:title="invoice ? `发票 ${invoice.number || invoice.id} · PDF` : 'PDF 预览'"
:style="modalStyle"
:class="modalClass"
@update:show="emit('update:show', $event)"
>
<!-- 全屏形态下预览区吃满内容区剩余高度(内容区为 flex column) -->
<div class="h-[70vh] overflow-auto rounded-lg border border-line-soft bg-wash/50 max-md:h-auto max-md:min-h-0 max-md:flex-1">
<div v-if="loading" class="flex h-full items-center justify-center">
<NSpin size="small" />
</div>
<div
v-else-if="loadError"
class="flex h-full flex-col items-center justify-center gap-2 text-xs text-err"
>
{{ loadError }}
<NButton size="small" @click="load">重试</NButton>
</div>
<div v-else-if="pdfData" class="min-h-full bg-white">
<OfficePreview kind="pdf" :data="pdfData" @error="loadError = $event" />
</div>
</div>
<template #footer>
<div class="flex justify-end">
<NButton size="small" type="primary" :disabled="!pdfData" @click="download">下载</NButton>
</div>
</template>
</NModal>
</template>
+346
View File
@@ -0,0 +1,346 @@
<script setup lang="ts">
import { NButton, NDataTable, NSpin, type DataTableColumns } from 'naive-ui'
import { computed, h, ref } from 'vue'
import { listInvoices, listPaymentMethods } from '@/api/billing'
import { ApiError } from '@/api/request'
import EmptyCard from '@/components/EmptyCard.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import InvoiceDetailModal from '@/components/tenant/InvoiceDetailModal.vue'
import InvoicePayModal from '@/components/tenant/InvoicePayModal.vue'
import InvoicePdfModal from '@/components/tenant/InvoicePdfModal.vue'
import PaymentMethodsModal from '@/components/tenant/PaymentMethodsModal.vue'
import { invoiceDate, invoiceStatusMeta } from '@/components/tenant/invoiceStatus'
import { useAsync } from '@/composables/useAsync'
import { useToast } from '@/composables/useToast'
import { fmtMoney } from '@/composables/useFormat'
import type { Invoice } from '@/types/api'
const props = defineProps<{ cfgId: number }>()
const message = useToast()
// ---- :(),, 2 ----
const thisYear = new Date().getFullYear()
const EMPTY_STOP = 2
const rows = ref<Invoice[]>([])
/** 下一个待加载的自然年 */
const nextYear = ref(thisYear)
const exhausted = ref(false)
const initialLoading = ref(true)
const loadingMore = ref(false)
/** 无 osp-gateway 权限时整 tab 转受限卡,不当作普通错误 */
const forbidden = ref(false)
/** 组织被 OCI 账单平台排除(巴西等本地结算体系注册地),账单能力整体不适用 */
const excluded = ref(false)
const loadError = ref('')
let emptyStreak = 0
/** 拉一个自然年并入列表 */
async function loadYear(year: number) {
const batch = await listInvoices(props.cfgId, year)
nextYear.value = year - 1
if (batch.length) {
emptyStreak = 0
rows.value = [...rows.value, ...batch]
} else if (++emptyStreak >= EMPTY_STOP) {
exhausted.value = true
}
}
async function init() {
initialLoading.value = true
forbidden.value = false
excluded.value = false
loadError.value = ''
rows.value = []
nextYear.value = thisYear
exhausted.value = false
emptyStreak = 0
try {
// ,
while (!exhausted.value && !rows.value.length) await loadYear(nextYear.value)
} catch (e) {
// ociCode 403: 403 ,
if (e instanceof ApiError && e.ociCode === 'OrganizationExclusionError') excluded.value = true
else if (e instanceof ApiError && e.status === 403) forbidden.value = true
else loadError.value = e instanceof Error ? e.message : String(e)
} finally {
initialLoading.value = false
}
}
void init()
async function loadMore() {
loadingMore.value = true
try {
await loadYear(nextYear.value)
} catch (e) {
message.error(e instanceof Error ? e.message : '加载失败')
} finally {
loadingMore.value = false
}
}
/** 付款后静默重拉已加载的年份区间,不闪加载态 */
async function refreshSilent() {
const years: number[] = []
for (let y = thisYear; y > nextYear.value; y--) years.push(y)
try {
const batches = await Promise.all(years.map((y) => listInvoices(props.cfgId, y)))
rows.value = batches.flat()
} catch {
/* 静默失败,保留现有数据 */
}
}
/** 非 PAYG 计划(如年度合约/内部账号)没有自助付款方式,单独提示而非报错 */
const methodsUnsupported = ref(false)
/** 付款方式受同一 policy 管制,其余失败静默置空(受限卡已说明原因) */
const methods = useAsync(() =>
listPaymentMethods(props.cfgId).catch((e) => {
if (e instanceof ApiError && e.ociCode === 'InvalidPlanType') methodsUnsupported.value = true
return []
}),
)
// ---- ----
/** API 返回序不保证,统一按开票时间倒序 */
const list = computed(() =>
[...rows.value].sort((a, b) => (b.timeInvoice ?? '').localeCompare(a.timeInvoice ?? '')),
)
const currency = computed(() => list.value[0]?.currency || 'USD')
/** 未付余额只计还可操作的欠款;「处理中」已提交扣款,不再计入 */
const unpaidDue = computed(() =>
list.value
.filter((i) => !i.isPaid && (i.status === 'OPEN' || i.status === 'PAST_DUE'))
.reduce((s, i) => s + i.amountDue, 0),
)
const yearTotal = computed(() =>
list.value
.filter((i) => (i.timeInvoice ?? '').startsWith(String(thisYear)))
.reduce((s, i) => s + i.amount, 0),
)
const lastPaid = computed(() => list.value.find((i) => i.isPaid) ?? null)
const methodBrief = computed(() => {
if (methodsUnsupported.value) return '不适用(非 PAYG'
const m = (methods.data.value ?? [])[0]
if (!m) return '未登记'
return m.method === 'CREDIT_CARD' ? `${m.cardType || '银行卡'} •••• ${m.lastDigits}` : 'PayPal'
})
// ---- ----
const detailInv = ref<Invoice | null>(null)
const showDetail = ref(false)
const payInv = ref<Invoice | null>(null)
const showPay = ref(false)
const pdfInv = ref<Invoice | null>(null)
const showPdf = ref(false)
const showMethods = ref(false)
function openDetail(inv: Invoice) {
detailInv.value = inv
showDetail.value = true
}
function openPay(inv: Invoice) {
payInv.value = inv
showPay.value = true
}
function openPdf(inv: Invoice) {
pdfInv.value = inv
showPdf.value = true
}
/** 明细弹窗里点付款:先关明细再开付款确认 */
function payFromDetail(inv: Invoice) {
showDetail.value = false
openPay(inv)
}
const columns = computed<DataTableColumns<Invoice>>(() => [
{
title: '发票号',
key: 'number',
render: (r) =>
h('div', [
h('div', { class: 'text-[13px] font-medium tabular-nums' }, r.number || r.id),
h('div', { class: 'mt-0.5 text-xs text-ink-3' }, r.type || 'USAGE'),
]),
},
{ title: '开票日期', key: 'timeInvoice', width: 110, render: (r) => invoiceDate(r.timeInvoice) },
{
title: '到期日期',
key: 'timeDue',
width: 110,
render: (r) =>
h('span', { class: r.status === 'PAST_DUE' ? 'text-err' : '' }, invoiceDate(r.timeDue)),
},
{
title: '金额',
key: 'amount',
width: 110,
align: 'right',
render: (r) => h('span', { class: 'tabular-nums' }, fmtMoney(r.amount, r.currency)),
},
{
title: '状态',
key: 'status',
width: 100,
render: (r) => {
const m = invoiceStatusMeta(r)
return h(StatusBadge, { kind: m.kind, label: m.label })
},
},
{
title: '操作',
key: 'actions',
width: 170,
align: 'right',
render: (r) =>
h('div', { class: 'flex justify-end gap-1' }, [
r.isPayable && !r.isPaid
? h(
NButton,
{ size: 'tiny', type: 'primary', onClick: (e: MouseEvent) => { e.stopPropagation(); openPay(r) } },
{ default: () => '付款' },
)
: null,
h(
NButton,
{ size: 'tiny', quaternary: true, onClick: (e: MouseEvent) => { e.stopPropagation(); openDetail(r) } },
{ default: () => '明细' },
),
h(
NButton,
{ size: 'tiny', quaternary: true, onClick: (e: MouseEvent) => { e.stopPropagation(); openPdf(r) } },
{ default: () => 'PDF' },
),
]),
},
])
const rowProps = (row: Invoice) => ({
style: 'cursor: pointer',
onClick: () => openDetail(row),
})
</script>
<template>
<div class="flex flex-col gap-4">
<div v-if="initialLoading" class="panel flex items-center justify-center py-16">
<NSpin size="small" />
</div>
<div v-else-if="forbidden" class="panel">
<EmptyCard
title="无账单访问权限"
note="当前 API Key 所属用户无 OSP Gateway 权限;需要租户管理员授予 policy:Allow group Administrators to manage osp-gateway in tenancy"
/>
</div>
<div v-else-if="excluded" class="panel">
<EmptyCard
title="账单服务不适用于该租户"
note="OCI 账单平台(OSP Gateway)排除了该租户所属组织(OrganizationExclusionError),常见于巴西等采用当地结算体系的注册地;发票请前往 Oracle 官方控制台或当地结算渠道查询"
/>
</div>
<div v-else-if="loadError" class="panel flex items-center gap-2 px-4.5 py-3 text-xs text-err">
<span class="min-w-0 flex-1 truncate" :title="loadError">{{ loadError }}</span>
<NButton size="tiny" quaternary @click="init">重试</NButton>
</div>
<div v-else-if="!list.length" class="panel">
<EmptyCard
title="暂无发票"
note="Free Tier / Always Free 用量不产生发票;升级为付费账户后,月度发票将在此展示"
/>
</div>
<template v-else>
<div class="grid grid-cols-4 gap-3 max-md:grid-cols-2">
<div class="panel px-4 py-3">
<div class="text-xs text-ink-3">未付余额</div>
<div class="mt-1 text-[20px] font-semibold text-accent tabular-nums">
{{ fmtMoney(unpaidDue, currency) }}
</div>
</div>
<div class="panel px-4 py-3">
<div class="text-xs text-ink-3">本年已开票</div>
<div class="mt-1 text-[20px] font-semibold tabular-nums">
{{ fmtMoney(yearTotal, currency) }}
</div>
</div>
<div class="panel px-4 py-3">
<div class="text-xs text-ink-3">上期已付发票</div>
<div class="mt-1 text-[20px] font-semibold tabular-nums">
{{ lastPaid ? fmtMoney(lastPaid.amount, lastPaid.currency) : '—' }}
</div>
</div>
<div
class="panel cursor-pointer px-4 py-3 transition-colors hover:border-accent/45"
title="查看付款方式"
@click="showMethods = true"
>
<div class="flex items-center justify-between text-xs text-ink-3">
<span>默认付款方式</span>
<span class="text-ink-3"></span>
</div>
<div class="mt-1 truncate text-[15px] font-semibold">{{ methodBrief }}</div>
</div>
</div>
<div class="panel">
<div class="flex items-center gap-2.5 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">发票</div>
<div class="text-xs text-ink-3">已加载 {{ list.length }} ,点击行查看费用明细</div>
</div>
<NDataTable
:columns="columns"
:data="list"
:bordered="false"
:bottom-bordered="false"
:row-props="rowProps"
:row-key="(r: Invoice) => r.id"
:scroll-x="720"
size="small"
/>
<div class="flex justify-center border-t border-line-soft py-2">
<NButton
v-if="!exhausted"
size="tiny"
quaternary
:loading="loadingMore"
@click="loadMore"
>
加载 {{ nextYear }} 年发票
</NButton>
<span v-else class="text-xs text-ink-3">已加载全部发票</span>
</div>
</div>
</template>
<InvoiceDetailModal
v-model:show="showDetail"
:cfg-id="cfgId"
:invoice="detailInv"
@pay="payFromDetail"
/>
<InvoicePayModal
v-model:show="showPay"
:cfg-id="cfgId"
:invoice="payInv"
:methods="methods.data.value"
@paid="refreshSilent"
/>
<InvoicePdfModal v-model:show="showPdf" :cfg-id="cfgId" :invoice="pdfInv" />
<PaymentMethodsModal
v-model:show="showMethods"
:methods="methods.data.value"
:loading="methods.loading.value"
:unsupported="methodsUnsupported"
/>
</div>
</template>
+20 -14
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { NButton, NDynamicTags, NPopconfirm, NSpin, NSwitch } from 'naive-ui'
import { NButton, NDynamicTags, NSpin, NSwitch } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import {
@@ -17,6 +17,7 @@ import {
updateIdentitySetting,
updateNotificationRecipients,
} from '@/api/tenant'
import ConfirmPop from '@/components/ConfirmPop.vue'
import FootNote from '@/components/FootNote.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import PolicyEditModal from '@/components/tenant/PolicyEditModal.vue'
@@ -205,14 +206,17 @@ function policyDesc(p: PasswordPolicy): string {
<span class="h-1.5 w-1.5 rounded-full" :class="relayChip.dot" />
{{ relayChip.label }}
</span>
<NPopconfirm v-if="relayBuilt" @positive-click="destroyRelay">
<ConfirmPop
v-if="relayBuilt"
title="销毁回传链路?"
content="将删除租户内的 Connector、Policy、订阅与 Topic 并撤销回调地址。"
confirm-text="销毁"
:on-confirm="destroyRelay"
>
<template #trigger>
<NButton size="tiny" type="error" quaternary :loading="tearingRelay">
销毁链路
</NButton>
<NButton size="tiny" type="error" quaternary>销毁链路</NButton>
</template>
将删除租户内的 ConnectorPolicy订阅与 Topic 并撤销回调地址,确认销毁?
</NPopconfirm>
</ConfirmPop>
<NButton
v-else
size="small"
@@ -264,14 +268,16 @@ function policyDesc(p: PasswordPolicy): string {
{{ webhook.data.value.webhook?.path }}
</span>
<NButton size="tiny" quaternary class="flex-none" @click="copyWebhookPath">复制</NButton>
<NPopconfirm @positive-click="removeWebhook">
<ConfirmPop
title="撤销 Webhook 地址?"
content="撤销后旧回调地址立即 404,OCI 侧订阅将投递失败。"
confirm-text="撤销"
:on-confirm="removeWebhook"
>
<template #trigger>
<NButton size="tiny" type="error" quaternary class="flex-none" :loading="savingWebhook">
撤销
</NButton>
<NButton size="tiny" type="error" quaternary class="flex-none">撤销</NButton>
</template>
撤销后旧回调地址立即 404,OCI 侧订阅将投递失败,确认撤销?
</NPopconfirm>
</ConfirmPop>
</div>
<div v-else class="mx-4.5 mt-3 flex flex-wrap items-center gap-2.5 rounded-md bg-wash px-3 py-2">
<span class="min-w-0 flex-1 text-xs text-ink-3">
@@ -306,7 +312,7 @@ function policyDesc(p: PasswordPolicy): string {
<div class="grid grid-cols-2 items-start gap-4 max-lg:grid-cols-1">
<!-- 密码策略与身份 -->
<div class="panel">
<div class="flex items-center justify-between border-b border-line-soft px-4.5 py-3.5">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">密码策略与身份</div>
<div class="text-[12.5px] text-ink-3">Default 身份域 · IAM 规则</div>
</div>
@@ -0,0 +1,86 @@
<script setup lang="ts">
import { NModal, NSpin } from 'naive-ui'
import type { PaymentMethod } from '@/types/api'
/** :
* OSP Gateway 不提供删卡 API,加卡/换卡走 OCI 托管付款页(面板不经手卡号),
* 故这里只展示并引导到 Billing Center */
defineProps<{
show: boolean
methods: PaymentMethod[] | null
loading: boolean
/** 非 PAYG 计划(InvalidPlanType):没有自助付款方式,与「未登记」区分展示 */
unsupported?: boolean
}>()
const emit = defineEmits<{ 'update:show': [boolean] }>()
function iconText(m: PaymentMethod): string {
if (m.method !== 'CREDIT_CARD') return 'PP'
return (m.cardType || 'CARD').slice(0, 4)
}
function title(m: PaymentMethod): string {
if (m.method === 'CREDIT_CARD') return `${m.cardType || '银行卡'} •••• ${m.lastDigits || '????'}`
return m.email || 'PayPal 账户'
}
function subtitle(m: PaymentMethod): string {
if (m.method === 'CREDIT_CARD') {
const exp = m.timeExpiration ? `到期 ${m.timeExpiration.slice(0, 7)}` : ''
return [m.nameOnCard, exp].filter(Boolean).join(' · ')
}
const ba = m.billingAgreement ? `扣款协议 ${m.billingAgreement}` : ''
return [m.payerName, ba].filter(Boolean).join(' · ')
}
</script>
<template>
<NModal
:show="show"
preset="card"
title="付款方式"
:style="{ width: '480px', maxWidth: 'calc(100vw - 24px)' }"
@update:show="emit('update:show', $event)"
>
<div class="-mt-1 mb-2 text-xs text-ink-3">自动扣款与在线付款按订阅默认方式执行</div>
<div v-if="loading" class="flex items-center justify-center py-10">
<NSpin size="small" />
</div>
<template v-else-if="methods?.length">
<div
v-for="(m, i) in methods"
:key="i"
class="flex items-center gap-3 border-b border-line-soft py-3 last:border-b-0"
>
<div
class="flex h-8 w-12 flex-none items-center justify-center rounded border border-line-soft bg-wash text-[10px] font-bold tracking-wide text-ink-2"
>
{{ iconText(m) }}
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-[13px] font-medium">{{ title(m) }}</div>
<div class="mt-0.5 truncate text-xs text-ink-3">{{ subtitle(m) }}</div>
</div>
<span
class="flex-none rounded border border-line-soft px-1.5 py-0.5 text-[10.5px] text-ink-3"
>
{{ m.method }}
</span>
</div>
</template>
<div v-else-if="unsupported" class="py-8 text-center text-[12.5px] text-ink-3">
当前订阅计划不属于 PAYG(InvalidPlanType),无自助付款方式;
合约/伙伴结算账号的付款安排请联系 Oracle 销售或查看合同条款
</div>
<div v-else class="py-8 text-center text-[12.5px] text-ink-3">
未登记付款方式
</div>
<div class="mt-3 rounded-lg bg-wash px-3 py-2.5 text-xs leading-relaxed text-ink-3">
加换卡片请在 OCI 控制台Billing &amp;
Cost Management Payment Methods操作
</div>
</NModal>
</template>
+64 -47
View File
@@ -12,12 +12,15 @@ import { computed, h, reactive, ref, watch } from 'vue'
import { listCachedRegions } from '@/api/configs'
import { listLimitServices, listLimits } from '@/api/tenant'
import FilterBar from '@/components/FilterBar.vue'
import FootNote from '@/components/FootNote.vue'
import { regionCity, shortAd } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import { useIsMobile } from '@/composables/useIsMobile'
import type { LimitItem } from '@/types/api'
const props = defineProps<{ cfgId: number }>()
const isMobile = useIsMobile()
const service = ref('compute')
const name = ref('')
@@ -90,6 +93,10 @@ const pagination = reactive({
pageSize: 10,
showSizePicker: true,
pageSizes: [10, 20, 50],
// , simple ( n/ )
get simple() {
return isMobile.value
},
onUpdatePage: (p: number) => {
pagination.page = p
},
@@ -127,19 +134,29 @@ const baseColumns: DataTableColumns<LimitItem> = [
},
]
/** 字节类配额可达百亿级,列宽须容纳千分位全量数值,禁止折行 */
const availColumns: DataTableColumns<LimitItem> = [
{
title: '已用',
key: 'used',
width: 80,
render: (r) => h('span', { class: 'tabular-nums' }, r.used === undefined ? '—' : String(r.used)),
width: 120,
render: (r) =>
h(
'span',
{ class: 'tabular-nums whitespace-nowrap' },
r.used === undefined ? '—' : r.used.toLocaleString('en-US'),
),
},
{
title: '可用',
key: 'available',
width: 80,
width: 120,
render: (r) =>
h('span', { class: 'tabular-nums' }, r.available === undefined ? '—' : String(r.available)),
h(
'span',
{ class: 'tabular-nums whitespace-nowrap' },
r.available === undefined ? '—' : r.available.toLocaleString('en-US'),
),
},
{
title: '用量',
@@ -174,59 +191,59 @@ const columns = computed(() => (withAvail.value ? [...baseColumns, ...availColum
<template>
<div class="panel">
<div class="flex flex-wrap items-center gap-2 px-4.5 py-3">
<div class="flex flex-col gap-2.5 px-4.5 py-3">
<div class="text-sm font-semibold">服务配额</div>
<div class="flex-1" />
<NInputGroup class="!w-60 max-md:!w-full">
<NInputGroupLabel size="small">区域</NInputGroupLabel>
<NSelect
v-model:value="region"
size="small"
filterable
:options="regionOptions"
:loading="regions.loading.value"
:consistent-menu-width="false"
/>
</NInputGroup>
<NInputGroup class="!w-72 max-lg:!w-60 max-md:!w-full">
<NInputGroupLabel size="small">服务</NInputGroupLabel>
<NSelect
v-model:value="service"
size="small"
filterable
:options="serviceOptions"
:loading="services.loading.value"
/>
</NInputGroup>
<NInputGroup class="!w-52 max-lg:!w-44 max-md:!w-full">
<NInputGroupLabel size="small">作用域</NInputGroupLabel>
<NSelect v-model:value="scopeType" size="small" :options="scopeOptions" />
</NInputGroup>
<NInputGroup class="!w-56 max-lg:!w-44 max-md:!w-full">
<NInputGroupLabel size="small">配额名</NInputGroupLabel>
<NInput
v-model:value="name"
size="small"
placeholder="如 core-count"
clearable
@keyup.enter="limits.run()"
@clear="limits.run()"
/>
</NInputGroup>
<NCheckbox v-model:checked="hideZero" size="small">忽略 0 配额</NCheckbox>
<NCheckbox v-model:checked="withAvail" size="small">查用量</NCheckbox>
<FilterBar>
<NInputGroup class="!w-60">
<NInputGroupLabel size="small">区域</NInputGroupLabel>
<NSelect
v-model:value="region"
size="small"
filterable
:options="regionOptions"
:loading="regions.loading.value"
:consistent-menu-width="false"
/>
</NInputGroup>
<NInputGroup class="!w-72 max-lg:!w-60">
<NInputGroupLabel size="small">服务</NInputGroupLabel>
<NSelect
v-model:value="service"
size="small"
filterable
:options="serviceOptions"
:loading="services.loading.value"
/>
</NInputGroup>
<NInputGroup class="!w-56 max-lg:!w-48">
<NInputGroupLabel size="small">作用域</NInputGroupLabel>
<NSelect v-model:value="scopeType" size="small" :options="scopeOptions" />
</NInputGroup>
<NInputGroup class="!w-56 max-lg:!w-48">
<NInputGroupLabel size="small">配额名</NInputGroupLabel>
<NInput
v-model:value="name"
size="small"
placeholder="如 core-count"
clearable
@keyup.enter="limits.run()"
@clear="limits.run()"
/>
</NInputGroup>
<NCheckbox v-model:checked="hideZero" size="small">忽略 0 配额</NCheckbox>
<NCheckbox v-model:checked="withAvail" size="small">查用量</NCheckbox>
</FilterBar>
</div>
<NDataTable
:columns="columns"
:data="rows"
:loading="limits.loading.value"
:pagination="pagination"
:scroll-x="withAvail ? 660 : 380"
:scroll-x="withAvail ? 980 : 560"
:row-key="(r: LimitItem) => r.name + (r.availabilityDomain ?? '')"
/>
<FootNote>
勾选查用量单次限 100 超出请用配额名 / 作用域过滤收窄配合忽略 0
配额服务端过滤可大幅释放名额不支持用量查询的配额自动跳过并显示无用量数据
查用量单次限 100 用筛选与忽略 0 配额收窄不支持的配额显示无用量数据
</FootNote>
</div>
</template>
+5 -7
View File
@@ -5,6 +5,7 @@ import { computed, h, ref } from 'vue'
import { listRegionSubscriptions, listRegions } from '@/api/configs'
import { getSubscription, listLimits, listSubscriptions } from '@/api/tenant'
import AccountTypeBadge from '@/components/AccountTypeBadge.vue'
import EmptyCard from '@/components/EmptyCard.vue'
import FootNote from '@/components/FootNote.vue'
import StatusBadge from '@/components/StatusBadge.vue'
import SubscribeRegionModal from '@/components/tenant/SubscribeRegionModal.vue'
@@ -196,15 +197,12 @@ function subLabel(d: SubscriptionDetail): string {
<NSpin size="small" />
</div>
<div
v-else-if="!subs.data.value?.length"
class="panel px-4.5 py-10 text-center text-[13px] text-ink-3"
>
未获取到订阅信息Organizations API 可能对该租户不可用
<div v-else-if="!subs.data.value?.length" class="panel">
<EmptyCard title="未获取到订阅信息" note="Organizations API 可能对该租户不可用" />
</div>
<div v-for="d in subs.data.value" v-else :key="d.id" class="panel">
<div class="flex items-center justify-between border-b border-line-soft px-4.5 py-3.5">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">云订阅</div>
<div class="text-[12.5px] text-ink-3">{{ subLabel(d) }} · 账户类别数据来源</div>
</div>
@@ -260,7 +258,7 @@ function subLabel(d: SubscriptionDetail): string {
</div>
<div class="panel min-w-0">
<div class="flex items-center justify-between border-b border-line-soft px-4.5 py-3.5">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">区域订阅</div>
<div class="text-[12.5px] text-ink-3">
已订阅 {{ subscribedCount }} ·
+14 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { NButton, NDataTable, NPopconfirm, useDialog, type DataTableColumns } from 'naive-ui'
import { NButton, NDataTable, useDialog, type DataTableColumns } from 'naive-ui'
import { h, ref } from 'vue'
import { clearUserMfa, deleteUser, deleteUserApiKeys, listUsers, resetUserPassword } from '@/api/tenant'
@@ -9,6 +9,7 @@ import UserFormModal from '@/components/tenant/UserFormModal.vue'
import { fmtTime } from '@/composables/useFormat'
import { useAsync } from '@/composables/useAsync'
import type { IamUser } from '@/types/api'
import ConfirmPop from '@/components/ConfirmPop.vue'
import { useToast } from '@/composables/useToast'
const props = defineProps<{ cfgId: number; domainId?: string }>()
@@ -117,25 +118,30 @@ const columns: DataTableColumns<IamUser> = [
h(NButton, { size: 'tiny', quaternary: true, onClick: () => openEdit(row) }, { default: () => '修改' }),
h(NButton, { size: 'tiny', quaternary: true, onClick: () => resetPwd(row) }, { default: () => '重置密码' }),
h(
NPopconfirm,
ConfirmPop,
{
onPositiveClick: () =>
title: '清除全部 MFA 因子?',
content: `${row.name} 下次登录需重新注册 MFA。`,
kind: 'warn',
confirmText: '清除',
onConfirm: () =>
act(() => clearUserMfa(props.cfgId, row.id, props.domainId), `已清除 ${row.name} 的全部 MFA`),
},
{
trigger: () => h(NButton, { size: 'tiny', quaternary: true }, { default: () => '清 MFA' }),
default: () => '清除该用户全部 MFA 因子?',
},
),
h(
NPopconfirm,
ConfirmPop,
{
onPositiveClick: () =>
title: '删除全部 API Key',
content: '跳过当前配置使用中的指纹。',
confirmText: '删除',
onConfirm: () =>
act(() => deleteUserApiKeys(props.cfgId, row.id), `已删除 ${row.name} 的 API Key`),
},
{
trigger: () => h(NButton, { size: 'tiny', quaternary: true }, { default: () => '删 Key' }),
default: () => '删除该用户全部 API Key(跳过当前配置使用中的指纹)?',
},
),
row.isCurrentUser
@@ -152,7 +158,7 @@ const columns: DataTableColumns<IamUser> = [
<template>
<div class="panel">
<div class="flex items-center justify-between border-b border-line-soft px-4.5 py-3.5">
<div class="flex flex-wrap items-center justify-between gap-y-2 border-b border-line-soft px-4.5 py-3.5">
<div class="text-sm font-semibold">IAM 用户</div>
<NButton size="small" type="primary" @click="openCreate">添加用户</NButton>
</div>
+18
View File
@@ -0,0 +1,18 @@
import type { Invoice } from '@/types/api'
/** 发票状态 → 徽章形态与中文标签(isPaid 优先于 status 判定) */
export function invoiceStatusMeta(inv: Invoice): {
kind: 'warn' | 'term' | 'prov' | 'run' | 'check'
label: string
} {
if (inv.isPaid || inv.status === 'CLOSED') return { kind: 'run', label: '已付' }
if (inv.status === 'PAST_DUE') return { kind: 'term', label: '逾期' }
if (inv.status === 'PAYMENT_SUBMITTED') return { kind: 'prov', label: '处理中' }
if (inv.status === 'OPEN') return { kind: 'warn', label: '未付' }
return { kind: 'check', label: inv.status || '未知' }
}
/** ISO 时间取日期段;发票的开票/到期语义是日期,不做时区换算 */
export function invoiceDate(iso: string | null): string {
return iso ? iso.slice(0, 10) : '—'
}
+22
View File
@@ -32,6 +32,21 @@ const exact: Record<string, string> = {
'POST /api/v1/oci-configs/:id/instances/:instanceId/ipv6-addresses': '添加 IPv6 地址',
'DELETE /api/v1/oci-configs/:id/instances/:instanceId/ipv6-addresses': '删除 IPv6 地址',
'POST /api/v1/oci-configs/:id/instances/:instanceId/replace-boot-volume': '更换引导卷',
'PUT /api/v1/oci-configs/:id/buckets/:bucket/objects/content': '保存对象内容',
'POST /api/v1/oci-configs/:id/buckets/:bucket/objects/rename': '重命名对象',
'POST /api/v1/oci-configs/:id/buckets/:bucket/objects/restore': '恢复归档对象',
'DELETE /api/v1/oci-configs/:id/reserved-ips/:publicIpId': '释放预留公网 IP',
'POST /api/v1/oci-configs/:id/vnics/:vnicId/change-public-ip': '更换公网 IP',
'POST /api/v1/oci-configs/:id/vnics/:vnicId/ipv6-addresses': '添加 IPv6 地址',
'POST /api/v1/oci-configs/:id/instances/:instanceId/vnics': '附加 VNIC',
'DELETE /api/v1/oci-configs/:id/vnic-attachments/:attachmentId': '分离 VNIC',
'POST /api/v1/oci-configs/:id/instances/:instanceId/volume-attachments': '挂载块卷',
'DELETE /api/v1/oci-configs/:id/volume-attachments/:attachmentId': '分离块卷',
'POST /api/v1/oci-configs/:id/instances/:instanceId/boot-volume-attachments': '挂载引导卷',
'DELETE /api/v1/oci-configs/:id/boot-volume-attachments/:attachmentId': '分离引导卷',
'POST /api/v1/oci-configs/:id/invoices/:internalId/pay': '支付账单',
'POST /api/v1/oci-configs/:id/vcns/:vcnId/enable-ipv6': '启用 VCN IPv6',
'POST /api/v1/oci-configs/:id/identity-providers/:idpId/activate': '激活身份提供方',
'POST /api/v1/oci-configs/:id/users': '创建租户用户',
'PUT /api/v1/oci-configs/:id/users/:userId': '修改租户用户',
'DELETE /api/v1/oci-configs/:id/users/:userId': '删除租户用户',
@@ -85,6 +100,13 @@ const nouns: Record<string, string> = {
'identity-providers': '身份提供方',
'sign-on-exemptions': 'MFA 豁免',
proxies: '代理',
buckets: '桶',
objects: '对象',
pars: '分享链接',
'reserved-ips': '预留公网 IP',
vnics: 'VNIC',
'vnic-attachments': 'VNIC 挂载',
invoices: '账单',
}
const verbs: Record<string, string> = { POST: '创建', PUT: '修改', DELETE: '删除' }
+8
View File
@@ -27,6 +27,14 @@ export function fmtBytes(n: number): string {
return `${(n / 2 ** (10 * i)).toFixed(1)} ${units[i]}`
}
/** 金额展示:千分位 + 2 位小数,常见币种转符号前缀,其余保留币种码 */
export function fmtMoney(n: number, currency = 'USD'): string {
const sym: Record<string, string> = { USD: '$', EUR: '€', GBP: '£', JPY: '¥', CNY: '¥' }
const s = n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
const p = sym[currency]
return p ? p + s : `${currency} ${s}`.trim()
}
/** OCID 中段省略:ocid1.instance.oc1..aaaa…mc25a */
export function truncOcid(ocid: string, head = 24, tail = 6): string {
if (!ocid || ocid.length <= head + tail + 1) return ocid
+22
View File
@@ -0,0 +1,22 @@
import { readonly, ref } from 'vue'
/** 移动/桌面切换线与 CSS 断点同源:≤767px 为移动形态(Tailwind md 之下) */
const QUERY = '(max-width: 767px)'
const isMobile = ref(false)
let started = false
/** 模块级单例监听:任意组件首次调用时启动,全应用共享一个 matchMedia */
function ensureWatcher() {
if (started || typeof window === 'undefined') return
started = true
const mq = window.matchMedia(QUERY)
isMobile.value = mq.matches
mq.addEventListener('change', (e) => (isMobile.value = e.matches))
}
/** 响应式返回「当前是否移动形态」;JS 层条件渲染(表格换卡片、弹窗全屏)用它 */
export function useIsMobile() {
ensureWatcher()
return readonly(isMobile)
}
+17
View File
@@ -0,0 +1,17 @@
import { computed } from 'vue'
import { useIsMobile } from './useIsMobile'
/** :, 100vw/100dvh
class main.css .form-modal-mobile ,
FormModal ; NModal */
export function useMobileModal(width: number) {
const isMobile = useIsMobile()
const modalStyle = computed(() =>
isMobile.value
? { width: '100vw', height: '100dvh', maxWidth: '100vw', margin: '0', borderRadius: '0' }
: { width: `${width}px`, maxWidth: 'calc(100vw - 24px)' },
)
const modalClass = computed(() => (isMobile.value ? 'form-modal-mobile' : ''))
return { modalStyle, modalClass }
}
+24 -7
View File
@@ -1,13 +1,16 @@
<script setup lang="ts">
import { NPopselect } from 'naive-ui'
import { computed } from 'vue'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MobileTabBar from './MobileTabBar.vue'
import MoreSheet from './MoreSheet.vue'
import SidebarNav from './SidebarNav.vue'
import { logout as logoutApi } from '@/api/auth'
import SerialConsolePanel from '@/components/instance/SerialConsolePanel.vue'
import TenantPicker from '@/components/TenantPicker.vue'
import { regionCity } from '@/composables/useFormat'
import { useIsMobile } from '@/composables/useIsMobile'
import { useRegionAlias } from '@/composables/useRegionAlias'
import { useAppStore } from '@/stores/app'
import { useAuthStore } from '@/stores/auth'
@@ -22,6 +25,10 @@ const route = useRoute()
const router = useRouter()
const { alias } = useRegionAlias()
/** ≤767px:侧栏让位于底部导航 + 「更多」抽屉(设计稿定稿形态) */
const isMobile = useIsMobile()
const showMore = ref(false)
/** 胶囊内区域只显城市短名(友好名括号内文字),完整名留在菜单与悬浮提示 */
const regionFull = computed(() => alias(scope.region))
const regionShort = computed(() => regionCity(regionFull.value))
@@ -40,6 +47,7 @@ const crumbTitle = computed(() => {
network: '网络',
'vcn-detail': '网络',
'boot-volumes': '存储 / 引导卷',
'object-storage': '对象存储',
tasks: '任务',
proxies: '代理',
logs: '日志',
@@ -58,14 +66,15 @@ async function logout() {
<template>
<div class="flex min-h-screen">
<SidebarNav :collapsed="app.sidebarCollapsed" @logout="logout" />
<SidebarNav v-if="!isMobile" :collapsed="app.sidebarCollapsed" @logout="logout" />
<main class="flex min-w-0 flex-1 flex-col">
<header
class="flex h-14 flex-none items-center justify-between gap-3 border-b border-line pr-6 pl-4"
class="flex h-14 flex-none items-center justify-between gap-3 border-b border-line pr-6 pl-4 max-md:pr-3"
>
<div class="flex min-w-0 items-center gap-2.5">
<button
v-if="!isMobile"
class="flex h-8 w-8 flex-none cursor-pointer items-center justify-center rounded-md text-ink-2 hover:bg-wash hover:text-ink"
title="收起 / 展开侧栏"
aria-label="收起或展开侧栏"
@@ -146,7 +155,7 @@ async function logout() {
>
<path d="M3 21h18M5 21V7l7-4 7 4v14M9 21v-6h6v6" />
</svg>
<span class="max-w-[200px] truncate text-[13px] max-lg:max-w-[120px] max-md:hidden">
<span class="max-w-[200px] truncate text-[13px] max-lg:max-w-[120px] max-md:max-w-[84px]">
{{ scope.currentConfig?.alias ?? '选择租户' }}
</span>
<svg
@@ -193,7 +202,7 @@ async function logout() {
<circle cx="12" cy="12" r="10" />
<path d="M2 12h20M12 2a15.3 15.3 0 0 1 0 20 15.3 15.3 0 0 1 0-20" />
</svg>
<span class="max-w-[160px] truncate text-[13px] max-md:hidden">
<span class="max-w-[160px] truncate text-[13px] max-md:max-w-[72px]">
{{ regionShort }}
</span>
<svg
@@ -212,12 +221,20 @@ async function logout() {
</div>
</header>
<!-- 内容区限宽居中避免超宽屏下的空置感 -->
<div class="mx-auto w-full max-w-[1560px]">
<!-- 内容区限宽居中避免超宽屏下的空置感;移动端为底栏预留高度 -->
<div
class="mx-auto w-full max-w-[1560px]"
:style="isMobile ? { paddingBottom: 'calc(66px + env(safe-area-inset-bottom))' } : undefined"
>
<RouterView />
</div>
</main>
<template v-if="isMobile">
<MobileTabBar @more="showMore = true" />
<MoreSheet v-model:show="showMore" />
</template>
<!-- 串行控制台全局挂载切换路由不断开会话 -->
<SerialConsolePanel
v-model:show="consoleStore.show"
+65
View File
@@ -0,0 +1,65 @@
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { findNavItem, mobileMoreNames, mobileTabNames, navIcon } from './navItems'
/** 移动端底部导航:高频四项直达 + 「更多」唤起抽屉(设计稿 ①) */
const emit = defineEmits<{ more: [] }>()
const route = useRoute()
const router = useRouter()
const tabs = mobileTabNames.map((name) => {
const item = findNavItem(name)
return { ...item, icon: navIcon(item.iconPaths, 'h-[22px] w-[22px] flex-none') }
})
const moreIcon = navIcon(
'<circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/>',
'h-[22px] w-[22px] flex-none',
)
const activeName = computed(() => {
const current = String(route.name)
return tabs.find((t) => t.activeNames.includes(current))?.name ?? ''
})
/** 当前路由属「更多」内页面时高亮更多槽 */
const moreActive = computed(() => {
const current = String(route.name)
return mobileMoreNames.some((n) => findNavItem(n).activeNames.includes(current))
})
function go(name: string) {
if (name !== String(route.name)) void router.push({ name })
}
</script>
<template>
<nav
class="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg px-1 pt-1.5"
style="padding-bottom: env(safe-area-inset-bottom)"
>
<div class="flex">
<button
v-for="t in tabs"
:key="t.name"
class="flex min-h-[52px] flex-1 cursor-pointer flex-col items-center justify-center gap-0.5 rounded-md pb-1"
:class="activeName === t.name ? 'text-accent' : 'text-ink-3'"
@click="go(t.name)"
>
<component :is="t.icon" />
<span class="text-[10px] font-medium">{{ t.label }}</span>
</button>
<button
class="flex min-h-[52px] flex-1 cursor-pointer flex-col items-center justify-center gap-0.5 rounded-md pb-1"
:class="moreActive ? 'text-accent' : 'text-ink-3'"
@click="emit('more')"
>
<component :is="moreIcon" />
<span class="text-[10px] font-medium">更多</span>
</button>
</div>
</nav>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup lang="ts">
import { NDrawer } from 'naive-ui'
import { useRoute, useRouter } from 'vue-router'
import { findNavItem, mobileMoreNames, navIcon } from './navItems'
/** 「更多」底部抽屉:收纳低频七项(设计稿 ④) */
const props = defineProps<{ show: boolean }>()
const emit = defineEmits<{ 'update:show': [boolean] }>()
const route = useRoute()
const router = useRouter()
const items = mobileMoreNames.map((name) => {
const item = findNavItem(name)
return { ...item, icon: navIcon(item.iconPaths, 'h-[22px] w-[22px] flex-none') }
})
function go(name: string) {
emit('update:show', false)
if (name !== String(route.name)) void router.push({ name })
}
function isActive(activeNames: string[]): boolean {
return props.show && activeNames.includes(String(route.name))
}
</script>
<template>
<NDrawer
:show="show"
placement="bottom"
height="auto"
:auto-focus="false"
@update:show="emit('update:show', $event)"
>
<div class="bg-bg px-4 pt-2" style="padding-bottom: calc(16px + env(safe-area-inset-bottom))">
<div class="mx-auto mb-3 mt-1 h-1 w-9 rounded-full bg-ink/20"></div>
<div class="grid grid-cols-3 gap-2">
<button
v-for="it in items"
:key="it.name"
class="flex cursor-pointer flex-col items-center gap-1.5 rounded-md border border-line bg-card py-3.5"
:class="isActive(it.activeNames) ? 'text-accent' : 'text-ink-2'"
@click="go(it.name)"
>
<component :is="it.icon" />
<span class="text-[11.5px] text-ink">{{ it.label }}</span>
</button>
</div>
</div>
</NDrawer>
</template>
+17 -125
View File
@@ -1,8 +1,9 @@
<script setup lang="ts">
import { h, type Component } from 'vue'
import { type Component } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import AppLogo from '@/components/AppLogo.vue'
import { navGroups, navIcon } from './navItems'
defineProps<{ collapsed: boolean }>()
const emit = defineEmits<{ logout: [] }>()
@@ -21,120 +22,17 @@ interface NavGroup {
items: NavItem[]
}
function icon(paths: string): Component {
return () =>
h('svg', {
class: 'h-4 w-4 flex-none',
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
'stroke-width': '1.5',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
innerHTML: paths,
})
}
/** 条目定义共享自 navItems.ts(与移动端底栏 / 「更多」抽屉同源) */
const groups: NavGroup[] = navGroups.map((g) => ({
label: g.label,
items: g.items.map((i) => ({
name: i.name,
label: i.label,
activeNames: i.activeNames,
icon: navIcon(i.iconPaths),
})),
}))
const groups: NavGroup[] = [
{
label: '概览',
items: [
{
name: 'overview',
label: '总览',
activeNames: ['overview'],
icon: icon(
'<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/>',
),
},
],
},
{
label: '资源',
items: [
{
name: 'tenants',
label: '租户',
activeNames: ['tenants', 'tenant-detail'],
icon: icon(
'<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
),
},
{
name: 'instances',
label: '实例',
activeNames: ['instances', 'instance-detail'],
icon: icon(
'<rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/>',
),
},
{
name: 'network',
label: '网络',
activeNames: ['network', 'vcn-detail'],
icon: icon(
'<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
),
},
{
name: 'boot-volumes',
label: '存储',
activeNames: ['boot-volumes'],
icon: icon(
'<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/>',
),
},
],
},
{
label: '自动化',
items: [
{
name: 'tasks',
label: '任务',
activeNames: ['tasks'],
icon: icon('<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>'),
},
{
name: 'ai-gateway',
label: 'AI 网关',
activeNames: ['ai-gateway'],
icon: icon(
'<path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"/><path d="M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"/>',
),
},
],
},
{
label: '系统',
items: [
{
name: 'proxies',
label: '代理',
activeNames: ['proxies'],
icon: icon(
'<path d="m16 3 4 4-4 4"/><path d="M20 7H4"/><path d="m8 21-4-4 4-4"/><path d="M4 17h16"/>',
),
},
{
name: 'logs',
label: '日志',
activeNames: ['logs'],
icon: icon(
'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>',
),
},
{
name: 'settings',
label: '设置',
activeNames: ['settings'],
icon: icon(
'<line x1="21" y1="4" x2="14" y2="4"/><line x1="10" y1="4" x2="3" y2="4"/><line x1="21" y1="12" x2="12" y2="12"/><line x1="8" y1="12" x2="3" y2="12"/><line x1="21" y1="20" x2="16" y2="20"/><line x1="12" y1="20" x2="3" y2="20"/><line x1="14" y1="2" x2="14" y2="6"/><line x1="8" y1="10" x2="8" y2="14"/><line x1="16" y1="18" x2="16" y2="22"/>',
),
},
],
},
]
function isActive(item: NavItem): boolean {
return item.activeNames.includes(String(route.name))
@@ -159,7 +57,7 @@ function itemClass(item: NavItem): string {
:class="collapsed ? 'justify-center px-0!' : ''"
>
<AppLogo :size="24" class="flex-none" />
<span v-if="!collapsed" class="font-serif text-lg font-semibold max-md:hidden">
<span v-if="!collapsed" class="font-serif text-lg font-semibold">
OCI Portal
</span>
</div>
@@ -168,7 +66,7 @@ function itemClass(item: NavItem): string {
<template v-for="group in groups" :key="group.label">
<div
v-if="!collapsed"
class="px-2 pt-3.5 pb-1.5 text-[11px] font-semibold tracking-wider whitespace-nowrap text-ink-3 max-md:hidden"
class="px-2 pt-3.5 pb-1.5 text-[11px] font-semibold tracking-wider whitespace-nowrap text-ink-3"
>
{{ group.label }}
</div>
@@ -182,12 +80,11 @@ function itemClass(item: NavItem): string {
<template #default="{ navigate }">
<div
:class="[itemClass(item), collapsed ? 'justify-center gap-0 px-0' : '']"
class="max-md:justify-center max-md:gap-0 max-md:px-0"
:title="item.label"
@click="navigate"
>
<component :is="item.icon" />
<span v-if="!collapsed" class="max-md:hidden">{{ item.label }}</span>
<span v-if="!collapsed">{{ item.label }}</span>
</div>
</template>
</RouterLink>
@@ -204,13 +101,13 @@ function itemClass(item: NavItem): string {
>
A
</div>
<div v-if="!collapsed" class="min-w-0 flex-1 max-md:hidden">
<div v-if="!collapsed" class="min-w-0 flex-1">
<div class="text-[13px] font-medium">admin</div>
<div class="text-[11.5px] text-ink-3">管理员</div>
</div>
<button
v-if="!collapsed"
class="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-ink-2 hover:bg-wash hover:text-ink max-md:hidden"
class="flex h-8 w-8 cursor-pointer items-center justify-center rounded-md text-ink-2 hover:bg-wash hover:text-ink"
title="退出登录"
aria-label="退出登录"
@click="emit('logout')"
@@ -232,9 +129,4 @@ function itemClass(item: NavItem): string {
.sb-aside.collapsed {
width: 64px;
}
@media (max-width: 768px) {
.sb-aside {
width: 64px !important;
}
}
</style>
+149
View File
@@ -0,0 +1,149 @@
import { h, type Component } from 'vue'
/** 侧栏 / 底栏 / 「更多」抽屉共享的导航条目定义(唯一来源) */
export interface NavItem {
name: string
label: string
iconPaths: string
activeNames: string[]
}
export interface NavGroup {
label: string
items: NavItem[]
}
/** 细线风格图标工厂:paths 为 24 viewBox 下的 svg 内部标记 */
export function navIcon(paths: string, cls = 'h-4 w-4 flex-none'): Component {
return () =>
h('svg', {
class: cls,
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
'stroke-width': '1.5',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
innerHTML: paths,
})
}
export const navGroups: NavGroup[] = [
{
label: '概览',
items: [
{
name: 'overview',
label: '总览',
activeNames: ['overview'],
iconPaths:
'<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/>',
},
],
},
{
label: '资源',
items: [
{
name: 'tenants',
label: '租户',
activeNames: ['tenants', 'tenant-detail'],
iconPaths:
'<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
},
{
name: 'instances',
label: '实例',
activeNames: ['instances', 'instance-detail'],
iconPaths:
'<rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/>',
},
{
name: 'network',
label: '网络',
activeNames: ['network', 'vcn-detail'],
iconPaths:
'<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
},
{
name: 'boot-volumes',
label: '存储',
activeNames: ['boot-volumes'],
iconPaths:
'<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/>',
},
{
name: 'object-storage',
label: '对象存储',
activeNames: ['object-storage'],
iconPaths:
'<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><path d="M3.3 7 12 12l8.7-5"/><path d="M12 22V12"/>',
},
],
},
{
label: '自动化',
items: [
{
name: 'tasks',
label: '任务',
activeNames: ['tasks'],
iconPaths: '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',
},
{
name: 'ai-gateway',
label: 'AI 网关',
activeNames: ['ai-gateway'],
iconPaths:
'<path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"/><path d="M18.5 15.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2-2.2-.8 2.2-.8z"/>',
},
],
},
{
label: '系统',
items: [
{
name: 'proxies',
label: '代理',
activeNames: ['proxies'],
iconPaths:
'<path d="m16 3 4 4-4 4"/><path d="M20 7H4"/><path d="m8 21-4-4 4-4"/><path d="M4 17h16"/>',
},
{
name: 'logs',
label: '日志',
activeNames: ['logs'],
iconPaths:
'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>',
},
{
name: 'settings',
label: '设置',
activeNames: ['settings'],
iconPaths:
'<line x1="21" y1="4" x2="14" y2="4"/><line x1="10" y1="4" x2="3" y2="4"/><line x1="21" y1="12" x2="12" y2="12"/><line x1="8" y1="12" x2="3" y2="12"/><line x1="21" y1="20" x2="16" y2="20"/><line x1="12" y1="20" x2="3" y2="20"/><line x1="14" y1="2" x2="14" y2="6"/><line x1="8" y1="10" x2="8" y2="14"/><line x1="16" y1="18" x2="16" y2="22"/>',
},
],
},
]
const allItems = navGroups.flatMap((g) => g.items)
export function findNavItem(name: string): NavItem {
const item = allItems.find((i) => i.name === name)
if (!item) throw new Error(`unknown nav item: ${name}`)
return item
}
/** 移动端底栏高频四项;其余进「更多」抽屉 */
export const mobileTabNames = ['overview', 'tenants', 'instances', 'logs']
export const mobileMoreNames = [
'network',
'boot-volumes',
'object-storage',
'tasks',
'ai-gateway',
'proxies',
'settings',
]
+5
View File
@@ -49,6 +49,11 @@ const router = createRouter({
name: 'boot-volumes',
component: () => import('@/views/BootVolumeListView.vue'),
},
{
path: 'storage/objects',
name: 'object-storage',
component: () => import('@/views/ObjectStorageView.vue'),
},
{ path: 'tasks', name: 'tasks', component: () => import('@/views/TaskListView.vue') },
{
path: 'ai-gateway',
+2 -5
View File
@@ -136,15 +136,12 @@ export const useScopeStore = defineStore('scope', () => {
}))
})
/** 区间树根节点标签,供 CompartmentSelect 使用 */
const rootLabel = computed(() =>
currentConfig.value?.tenancyName
? `${currentConfig.value.tenancyName}(根)`
: '根 compartment',
)
const compOptions = computed(() => [
{ label: rootLabel.value, value: '' },
...(compartments.data.value ?? []).map((c) => ({ label: c.name, value: c.id })),
])
/** 未开启多区域 / 多区间支持:对应选择器禁用,锁定默认值 */
const regionDisabled = computed(() => !currentConfig.value?.multiRegion)
@@ -179,7 +176,7 @@ export const useScopeStore = defineStore('scope', () => {
compartments,
cfgOptions,
regionOptions,
compOptions,
rootLabel,
regionDisabled,
compDisabled,
}

Some files were not shown because too many files have changed in this diff Show More