更新uniapp和platform
This commit is contained in:
1 parent
31ae07175d
commit
7f9a66da0f
47 files changed
+5088
-1855
No files matched your search
@@ -0,0 +1,43 @@
|
|||||||
|
import request from "@/utils/request";
|
||||||
|
|
||||||
|
/** 当前租户附件空间用量(基础额度 / 生效套餐 / 已用) */
|
||||||
|
export function getStorageInfo() {
|
||||||
|
return request({
|
||||||
|
url: "/backend/tenant/storageInfo",
|
||||||
|
method: "get",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 可购买的附件空间套餐 */
|
||||||
|
export function getStoragePackages() {
|
||||||
|
return request({
|
||||||
|
url: "/backend/tenant/storagePackages",
|
||||||
|
method: "get",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 创建附件空间订单并拉起支付 */
|
||||||
|
export function createStorageOrder(data) {
|
||||||
|
return request({
|
||||||
|
url: "/backend/tenant/storage/order",
|
||||||
|
method: "post",
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 我的购买记录 */
|
||||||
|
export function getStorageOrders(params = {}) {
|
||||||
|
return request({
|
||||||
|
url: "/backend/tenant/storage/orders",
|
||||||
|
method: "get",
|
||||||
|
params,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 订单详情(支付后轮询) */
|
||||||
|
export function getStorageOrder(orderNo) {
|
||||||
|
return request({
|
||||||
|
url: `/backend/tenant/storage/order/${orderNo}`,
|
||||||
|
method: "get",
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
<el-menu
|
<el-menu
|
||||||
:collapse="isCollapse"
|
:collapse="isCollapse"
|
||||||
:collapse-transition="false"
|
:collapse-transition="false"
|
||||||
class="el-menu-vertical-demo"
|
class="el-menu-vertical-demo aside-root-menu"
|
||||||
popper-class="common-aside-popper"
|
popper-class="common-aside-popper"
|
||||||
:unique-opened="true"
|
:unique-opened="true"
|
||||||
:default-active="route.path"
|
:default-active="route.path"
|
||||||
@@ -169,10 +169,15 @@ onUnmounted(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
.common-aside {
|
// 用 aside.common-aside 提权:Main.vue 里 :deep(.el-aside) 也是 !important,
|
||||||
|
// 权重相同时会被后加载的规则覆盖,导致 flex 布局失效、菜单无法滚动。
|
||||||
|
aside.common-aside {
|
||||||
--aside-footer-height: 0px;
|
--aside-footer-height: 0px;
|
||||||
position: relative;
|
position: relative;
|
||||||
|
display: flex !important;
|
||||||
|
flex-direction: column;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--yz-aside-bg);
|
background: var(--yz-aside-bg);
|
||||||
border-right: 1px solid var(--yz-border);
|
border-right: 1px solid var(--yz-border);
|
||||||
@@ -224,11 +229,16 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
:deep(.el-menu) {
|
// 只作用于「侧栏根菜单」:flex / overflow / padding 不能写到 :deep(.el-menu) 上,
|
||||||
|
// 否则展开出来的 el-menu--inline 也会命中,导致子菜单宽度、缩进、箭头定位全部错乱。
|
||||||
|
.aside-root-menu {
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
height: calc(100% - var(--aside-footer-height) - 52px);
|
flex: 1 1 auto;
|
||||||
padding: 16px 10px 12px;
|
min-height: 0;
|
||||||
|
height: auto;
|
||||||
|
// 底部留出折叠按钮(约 52px)与小程序码区域
|
||||||
|
padding: 16px 10px calc(64px + var(--aside-footer-height));
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
border-right: none !important;
|
border-right: none !important;
|
||||||
@@ -275,20 +285,10 @@ onUnmounted(() => {
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 展开出来的子菜单背景透明;缩进交给 Element Plus 自身(--el-menu-level)计算,
|
||||||
|
// 不能在这里写 padding-left,否则多级子菜单的缩进与图标间距会被叠坏。
|
||||||
.el-menu--inline {
|
.el-menu--inline {
|
||||||
background: transparent !important;
|
background: transparent !important;
|
||||||
padding-top: 0 !important;
|
|
||||||
padding-bottom: 0 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.el-menu--inline > .el-menu-item,
|
|
||||||
.el-menu--inline > .el-sub-menu > .el-sub-menu__title {
|
|
||||||
padding-left: 26px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.el-menu--inline .el-menu--inline > .el-menu-item,
|
|
||||||
.el-menu--inline .el-menu--inline > .el-sub-menu > .el-sub-menu__title {
|
|
||||||
padding-left: 44px !important;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.is-locked {
|
.is-locked {
|
||||||
@@ -302,7 +302,7 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
:deep(.el-menu.el-menu--collapse) {
|
.aside-root-menu.el-menu--collapse {
|
||||||
width: 100% !important;
|
width: 100% !important;
|
||||||
padding-left: 0;
|
padding-left: 0;
|
||||||
padding-right: 0;
|
padding-right: 0;
|
||||||
@@ -320,7 +320,7 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
:deep(.el-menu--collapse .menu-icon) {
|
.aside-root-menu.el-menu--collapse :deep(.menu-icon) {
|
||||||
margin-right: 0 !important;
|
margin-right: 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -475,8 +475,8 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
:deep(.el-menu) {
|
.aside-root-menu {
|
||||||
padding: 12px 6px;
|
padding: 12px 6px calc(56px + var(--aside-footer-height));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -620,9 +620,13 @@ const canCloseRight = computed(() => {
|
|||||||
background-color: var(--bg-color-page);
|
background-color: var(--bg-color-page);
|
||||||
transition: background-color 0.3s ease;
|
transition: background-color 0.3s ease;
|
||||||
:deep(.el-aside) {
|
:deep(.el-aside) {
|
||||||
display: block !important;
|
// 侧栏内部是「菜单 + 底部小程序码」的纵向布局:
|
||||||
|
// 必须是 flex 列容器,菜单才能 flex:1 收缩并在内部滚动;写成 block 会溢出裁剪。
|
||||||
|
display: flex !important;
|
||||||
|
flex-direction: column;
|
||||||
visibility: visible !important;
|
visibility: visible !important;
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
|
min-height: 0;
|
||||||
}
|
}
|
||||||
.main-header {
|
.main-header {
|
||||||
background-color: var(--header-bg-color, #3973ff);
|
background-color: var(--header-bg-color, #3973ff);
|
||||||
|
|||||||
@@ -38,22 +38,9 @@
|
|||||||
/>
|
/>
|
||||||
<el-button type="primary" :icon="Search" @click="applyFilters">查询</el-button>
|
<el-button type="primary" :icon="Search" @click="applyFilters">查询</el-button>
|
||||||
<el-button :icon="RefreshLeft" @click="resetFilters">重置</el-button>
|
<el-button :icon="RefreshLeft" @click="resetFilters">重置</el-button>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="content-card">
|
<!-- 统计周期:切换后重新拉取汇总,展开的明细按新周期加载 -->
|
||||||
<!-- ==================== 考勤汇总(可折叠,默认收起) ==================== -->
|
<div class="period-switch">
|
||||||
<el-collapse v-model="summaryPanels" class="summary-collapse">
|
|
||||||
<el-collapse-item name="overview">
|
|
||||||
<template #title>
|
|
||||||
<div class="collapse-title">
|
|
||||||
<span class="ct-title">{{ periodTitle }}</span>
|
|
||||||
<span class="ct-sub">{{ summary.label }}</span>
|
|
||||||
<span class="ct-rate">出勤率 {{ summary.stats.attendance_rate || 0 }}%</span>
|
|
||||||
<span class="ct-hint">{{ summary.startDate }} 至 {{ summary.endDate }}</span>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<div class="period-bar">
|
|
||||||
<el-radio-group v-model="summary.period" @change="onPeriodChange">
|
<el-radio-group v-model="summary.period" @change="onPeriodChange">
|
||||||
<el-radio-button value="month">月度</el-radio-button>
|
<el-radio-button value="month">月度</el-radio-button>
|
||||||
<el-radio-button value="quarter">季度</el-radio-button>
|
<el-radio-button value="quarter">季度</el-radio-button>
|
||||||
@@ -64,71 +51,10 @@
|
|||||||
<span class="year-text">{{ summary.year }} 年</span>
|
<span class="year-text">{{ summary.year }} 年</span>
|
||||||
<el-button :icon="ArrowRight" text @click="shiftYear(1)" />
|
<el-button :icon="ArrowRight" text @click="shiftYear(1)" />
|
||||||
</div>
|
</div>
|
||||||
<span class="period-tip">格子里为「已打卡 / 应出勤」,颜色按当日出勤率</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="sum-metrics">
|
|
||||||
<div class="sum-metric">
|
|
||||||
<span class="sm-label">应出勤</span>
|
|
||||||
<span class="sm-value">{{ summary.stats.scheduled || 0 }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="sum-metric">
|
|
||||||
<span class="sm-label">已打卡</span>
|
|
||||||
<span class="sm-value is-ok">{{ summary.stats.clocked || 0 }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="sum-metric">
|
|
||||||
<span class="sm-label">迟到</span>
|
|
||||||
<span class="sm-value is-warn">{{ summary.stats.late || 0 }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="sum-metric">
|
|
||||||
<span class="sm-label">早退</span>
|
|
||||||
<span class="sm-value is-warn">{{ summary.stats.early || 0 }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="sum-metric">
|
|
||||||
<span class="sm-label">缺卡</span>
|
|
||||||
<span class="sm-value is-danger">{{ summary.stats.missing || 0 }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="sum-metric">
|
|
||||||
<span class="sm-label">无排班</span>
|
|
||||||
<span class="sm-value is-info">{{ summary.stats.noschedule || 0 }}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-loading="summary.loading" class="calendar-wrap" :class="'cols-' + calendarColumns">
|
<div class="content-card">
|
||||||
<div v-for="cal in summaryCalendars" :key="cal.key" class="cal-month">
|
|
||||||
<div class="cal-month-head">
|
|
||||||
<span class="cal-month-title">{{ cal.month }} 月</span>
|
|
||||||
<span class="cal-month-rate">{{ cal.rate }}%</span>
|
|
||||||
</div>
|
|
||||||
<div class="cal-week">
|
|
||||||
<span v-for="week in WEEK_HEAD" :key="week">{{ week }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="cal-grid">
|
|
||||||
<div
|
|
||||||
v-for="cell in cal.cells"
|
|
||||||
:key="cell.key"
|
|
||||||
class="cal-cell"
|
|
||||||
:class="[cell.status, { 'is-blank': cell.blank, 'is-today': cell.isToday, 'is-future': cell.future }]"
|
|
||||||
:title="cell.tip"
|
|
||||||
>
|
|
||||||
<span v-if="!cell.blank" class="cal-day">{{ cell.day }}</span>
|
|
||||||
<span v-if="cell.stat && cell.stat.scheduled" class="cal-num">
|
|
||||||
{{ cell.stat.clocked }}/{{ cell.stat.scheduled }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="cal-legend">
|
|
||||||
<span class="legend-item"><i class="dot is-ok" />出勤率 ≥ 90%</span>
|
|
||||||
<span class="legend-item"><i class="dot is-warn" />70% ~ 90%</span>
|
|
||||||
<span class="legend-item"><i class="dot is-danger" />低于 70%</span>
|
|
||||||
<span class="legend-item"><i class="dot is-info" />无排班打卡</span>
|
|
||||||
<span class="legend-item"><i class="dot is-off" />无排班</span>
|
|
||||||
</div>
|
|
||||||
</el-collapse-item>
|
|
||||||
</el-collapse>
|
|
||||||
|
|
||||||
<!-- ==================== 人员考勤(点姓名展开明细) ==================== -->
|
<!-- ==================== 人员考勤(点姓名展开明细) ==================== -->
|
||||||
<div class="list-head">
|
<div class="list-head">
|
||||||
@@ -146,17 +72,80 @@
|
|||||||
empty-text="当前范围内没有员工"
|
empty-text="当前范围内没有员工"
|
||||||
style="width: 100%"
|
style="width: 100%"
|
||||||
@expand-change="onExpandChange"
|
@expand-change="onExpandChange"
|
||||||
|
@row-click="onRowClick"
|
||||||
>
|
>
|
||||||
<el-table-column type="expand" width="38">
|
<el-table-column type="expand" width="38">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<div class="row-detail">
|
<div class="row-detail">
|
||||||
<div class="rd-head">
|
<div class="rd-head">
|
||||||
<span class="rd-name">{{ row.employee_name || '未绑定员工' }}</span>
|
<span class="rd-name">{{ row.employee_name || '未绑定员工' }}</span>
|
||||||
<span class="rd-meta">
|
<span class="rd-meta">{{ row.employee_account || '—' }}</span>
|
||||||
应出勤 {{ row.scheduled_days }} 天 · 打卡 {{ row.clocked_days }} 天 · 迟到 {{ row.late_count }} ·
|
<span class="rd-range">{{ summary.label }} · {{ summary.startDate }} 至 {{ summary.endDate }}</span>
|
||||||
早退 {{ row.early_count }} · 缺卡 {{ row.missing_days }}
|
</div>
|
||||||
</span>
|
|
||||||
<span class="rd-range">{{ summary.label }}</span>
|
<!-- 个人汇总指标 -->
|
||||||
|
<div class="sum-metrics rd-metrics">
|
||||||
|
<div class="sum-metric">
|
||||||
|
<span class="sm-label">应出勤</span>
|
||||||
|
<span class="sm-value">{{ row.scheduled_days || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sum-metric">
|
||||||
|
<span class="sm-label">已打卡</span>
|
||||||
|
<span class="sm-value is-ok">{{ row.clocked_days || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sum-metric">
|
||||||
|
<span class="sm-label">迟到</span>
|
||||||
|
<span class="sm-value is-warn">{{ row.late_count || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sum-metric">
|
||||||
|
<span class="sm-label">早退</span>
|
||||||
|
<span class="sm-value is-warn">{{ row.early_count || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sum-metric">
|
||||||
|
<span class="sm-label">缺卡</span>
|
||||||
|
<span class="sm-value is-danger">{{ row.missing_days || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sum-metric">
|
||||||
|
<span class="sm-label">无排班</span>
|
||||||
|
<span class="sm-value is-info">{{ row.noschedule_count || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 个人打卡日历:格子里为「已打卡 / 应出勤」,颜色按当日结果 -->
|
||||||
|
<div
|
||||||
|
v-loading="rowDetail(row).loading"
|
||||||
|
class="calendar-wrap rd-calendar"
|
||||||
|
:class="'cols-' + calendarColumns"
|
||||||
|
>
|
||||||
|
<div v-for="cal in employeeMonths(row)" :key="cal.key" class="cal-month">
|
||||||
|
<div class="cal-month-head">
|
||||||
|
<span class="cal-month-title">{{ cal.month }} 月</span>
|
||||||
|
<span class="cal-month-rate">{{ cal.rate }}%</span>
|
||||||
|
</div>
|
||||||
|
<div class="cal-week">
|
||||||
|
<span v-for="week in WEEK_HEAD" :key="week">{{ week }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="cal-grid">
|
||||||
|
<div
|
||||||
|
v-for="cell in cal.cells"
|
||||||
|
:key="cell.key"
|
||||||
|
class="cal-cell"
|
||||||
|
:class="[cell.status, { 'is-blank': cell.blank, 'is-today': cell.isToday, 'is-future': cell.future }]"
|
||||||
|
:title="cell.tip"
|
||||||
|
>
|
||||||
|
<span v-if="!cell.blank" class="cal-day">{{ cell.day }}</span>
|
||||||
|
<span v-if="cell.stat" class="cal-num">{{ cell.stat.clocked }}/{{ cell.stat.scheduled }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cal-legend">
|
||||||
|
<span class="legend-item"><i class="dot is-ok" />正常</span>
|
||||||
|
<span class="legend-item"><i class="dot is-warn" />迟到 / 早退</span>
|
||||||
|
<span class="legend-item"><i class="dot is-danger" />缺卡</span>
|
||||||
|
<span class="legend-item"><i class="dot is-info" />无排班打卡</span>
|
||||||
|
<span class="legend-item"><i class="dot is-off" />休息 / 无排班</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<el-table
|
<el-table
|
||||||
@@ -242,8 +231,7 @@
|
|||||||
<el-table-column label="员工" min-width="170">
|
<el-table-column label="员工" min-width="170">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<div class="emp-cell">
|
<div class="emp-cell">
|
||||||
<span class="emp-name is-clickable" @click.stop="toggleRow(row)">
|
<span class="emp-name">
|
||||||
<el-icon class="expand-caret" :class="{ 'is-open': isExpanded(row) }"><ArrowRight /></el-icon>
|
|
||||||
{{ row.employee_name || '未绑定员工' }}
|
{{ row.employee_name || '未绑定员工' }}
|
||||||
<el-tag v-if="!row.bound" size="small" type="info" effect="plain">未绑定档案</el-tag>
|
<el-tag v-if="!row.bound" size="small" type="info" effect="plain">未绑定档案</el-tag>
|
||||||
</span>
|
</span>
|
||||||
@@ -402,9 +390,6 @@ function unwrap(res) {
|
|||||||
|
|
||||||
const filters = reactive({ org_id: 0, include_child: true, keyword: '' })
|
const filters = reactive({ org_id: 0, include_child: true, keyword: '' })
|
||||||
|
|
||||||
// 汇总面板默认收起,点标题展开日历
|
|
||||||
const summaryPanels = ref([])
|
|
||||||
|
|
||||||
const summary = reactive({
|
const summary = reactive({
|
||||||
period: 'month',
|
period: 'month',
|
||||||
anchor: todayString(),
|
anchor: todayString(),
|
||||||
@@ -426,12 +411,6 @@ const summary = reactive({
|
|||||||
const orgTree = ref([])
|
const orgTree = ref([])
|
||||||
const orgFilterTree = computed(() => [{ id: 0, org_name: '全部', children: orgTree.value }])
|
const orgFilterTree = computed(() => [{ id: 0, org_name: '全部', children: orgTree.value }])
|
||||||
|
|
||||||
const periodTitle = computed(() => {
|
|
||||||
if (summary.period === 'year') return '年度考勤'
|
|
||||||
if (summary.period === 'quarter') return '季度考勤'
|
|
||||||
return '月度考勤'
|
|
||||||
})
|
|
||||||
|
|
||||||
// 月度 1 张、季度 3 张、年度 12 张日历
|
// 月度 1 张、季度 3 张、年度 12 张日历
|
||||||
const calendarColumns = computed(() => {
|
const calendarColumns = computed(() => {
|
||||||
if (summary.period === 'year') return 4
|
if (summary.period === 'year') return 4
|
||||||
@@ -451,25 +430,45 @@ const summaryMonthList = computed(() => {
|
|||||||
return [{ year, month: startMonth }]
|
return [{ year, month: startMonth }]
|
||||||
})
|
})
|
||||||
|
|
||||||
const summaryCalendarMap = computed(() => {
|
// 后端「当日结果」枚举 → 日历颜色:1正常 2迟到 3早退 4缺卡 5无排班 6时段异常 7未签退 8休息
|
||||||
const map = {}
|
const DAY_STATUS_COLOR = {
|
||||||
;(summary.calendar || []).forEach((item) => {
|
1: 'is-ok',
|
||||||
map[item.date] = item
|
2: 'is-warn',
|
||||||
})
|
3: 'is-warn',
|
||||||
return map
|
4: 'is-danger',
|
||||||
})
|
5: 'is-info',
|
||||||
|
6: 'is-warn',
|
||||||
|
7: 'is-warn',
|
||||||
|
8: 'is-off'
|
||||||
|
}
|
||||||
|
|
||||||
const summaryCalendars = computed(() =>
|
/** 某个员工在当前统计周期内的日历(月度 1 张 / 季度 3 张 / 年度 12 张) */
|
||||||
summaryMonthList.value.map((item) => ({
|
function employeeMonths(row) {
|
||||||
|
const list = rowDetail(row).list || []
|
||||||
|
const byDate = {}
|
||||||
|
list.forEach((item) => {
|
||||||
|
if (item.attend_date) byDate[item.attend_date] = item
|
||||||
|
})
|
||||||
|
return summaryMonthList.value.map((item) => {
|
||||||
|
const cells = buildEmployeeMonthGrid(item.year, item.month, byDate)
|
||||||
|
let scheduled = 0
|
||||||
|
let clocked = 0
|
||||||
|
cells.forEach((cell) => {
|
||||||
|
if (cell.blank || !cell.stat) return
|
||||||
|
scheduled += cell.stat.scheduled
|
||||||
|
clocked += cell.stat.clocked
|
||||||
|
})
|
||||||
|
return {
|
||||||
key: `${item.year}-${item.month}`,
|
key: `${item.year}-${item.month}`,
|
||||||
month: item.month,
|
month: item.month,
|
||||||
rate: (summary.cards.months[item.month - 1] || {}).attendance_rate || 0,
|
rate: scheduled > 0 ? Math.round((clocked / scheduled) * 100) : 0,
|
||||||
cells: buildMonthGrid(item.year, item.month)
|
cells
|
||||||
}))
|
}
|
||||||
)
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/** 生成某月日历格子:空白占位 + 每日考勤色块 */
|
/** 生成某员工某月的日历格子:空白占位 + 每日打卡色块 */
|
||||||
function buildMonthGrid(year, month) {
|
function buildEmployeeMonthGrid(year, month, byDate) {
|
||||||
const firstDay = new Date(year, month - 1, 1)
|
const firstDay = new Date(year, month - 1, 1)
|
||||||
const leading = (firstDay.getDay() + 6) % 7 // 周一为第一列
|
const leading = (firstDay.getDay() + 6) % 7 // 周一为第一列
|
||||||
const daysInMonth = new Date(year, month, 0).getDate()
|
const daysInMonth = new Date(year, month, 0).getDate()
|
||||||
@@ -481,28 +480,36 @@ function buildMonthGrid(year, month) {
|
|||||||
}
|
}
|
||||||
for (let day = 1; day <= daysInMonth; day += 1) {
|
for (let day = 1; day <= daysInMonth; day += 1) {
|
||||||
const date = `${year}-${pad2(month)}-${pad2(day)}`
|
const date = `${year}-${pad2(month)}-${pad2(day)}`
|
||||||
const stat = summaryCalendarMap.value[date]
|
const rec = byDate[date]
|
||||||
let status = 'is-off'
|
let status = 'is-off'
|
||||||
if (stat) {
|
let scheduled = 0
|
||||||
if (stat.scheduled > 0) {
|
let clocked = 0
|
||||||
if (stat.attendance_rate >= 90) status = 'is-ok'
|
let tip = '休息 / 无排班'
|
||||||
else if (stat.attendance_rate >= 70) status = 'is-warn'
|
|
||||||
else status = 'is-danger'
|
if (rec) {
|
||||||
} else if (stat.clocked > 0) {
|
clocked = rec.clock_in_hm ? 1 : 0
|
||||||
status = 'is-info'
|
// 休息(8) 与 无排班(5) 不算应出勤
|
||||||
}
|
scheduled = rec.day_status === 5 || rec.day_status === 8 ? 0 : 1
|
||||||
|
status = DAY_STATUS_COLOR[rec.day_status] || 'is-off'
|
||||||
|
if (scheduled > 0 && clocked === 0) status = 'is-danger'
|
||||||
|
if (scheduled === 0 && clocked > 0) status = 'is-info'
|
||||||
|
|
||||||
|
const parts = [rec.day_status_text || '']
|
||||||
|
if (rec.shift_name) parts.push(rec.shift_name)
|
||||||
|
if (rec.clock_in_hm) parts.push(`签到 ${rec.clock_in_hm}`)
|
||||||
|
if (rec.clock_out_hm) parts.push(`签退 ${rec.clock_out_hm}`)
|
||||||
|
tip = parts.filter(Boolean).join(' · ')
|
||||||
}
|
}
|
||||||
|
|
||||||
cells.push({
|
cells.push({
|
||||||
key: date,
|
key: date,
|
||||||
day,
|
day,
|
||||||
date,
|
date,
|
||||||
stat,
|
|
||||||
status,
|
status,
|
||||||
|
stat: scheduled > 0 ? { scheduled, clocked } : null,
|
||||||
future: date > today,
|
future: date > today,
|
||||||
isToday: date === today,
|
isToday: date === today,
|
||||||
tip: stat
|
tip
|
||||||
? `应出勤 ${stat.scheduled} · 已打卡 ${stat.clocked} · 缺卡 ${stat.missing} · 迟到 ${stat.late} · 早退 ${stat.early}`
|
|
||||||
: '无排班'
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return cells
|
return cells
|
||||||
@@ -517,14 +524,16 @@ function rowDetail(row) {
|
|||||||
return rowDetailMap.value[row.key] || { loading: false, loaded: false, list: [], total: 0 }
|
return rowDetailMap.value[row.key] || { loading: false, loaded: false, list: [], total: 0 }
|
||||||
}
|
}
|
||||||
|
|
||||||
function isExpanded(row) {
|
|
||||||
return expandedKeys.value.includes(row.key)
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleRow(row) {
|
function toggleRow(row) {
|
||||||
tableRef.value?.toggleRowExpansion(row)
|
tableRef.value?.toggleRowExpansion(row)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 点击整行展开/收起明细;展开箭头列自身已处理,跳过避免重复切换 */
|
||||||
|
function onRowClick(row, column) {
|
||||||
|
if (column && column.type === 'expand') return
|
||||||
|
toggleRow(row)
|
||||||
|
}
|
||||||
|
|
||||||
function onExpandChange(row, expandedRows) {
|
function onExpandChange(row, expandedRows) {
|
||||||
const rows = Array.isArray(expandedRows) ? expandedRows : []
|
const rows = Array.isArray(expandedRows) ? expandedRows : []
|
||||||
expandedKeys.value = rows.map((item) => item.key)
|
expandedKeys.value = rows.map((item) => item.key)
|
||||||
@@ -533,6 +542,32 @@ function onExpandChange(row, expandedRows) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 后端明细接口单次最多查询 92 天,季度/年度需要按区间切片后合并 */
|
||||||
|
const ATTENDANCE_MAX_SPAN_DAYS = 92
|
||||||
|
|
||||||
|
function toDateStr(date) {
|
||||||
|
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把 [start, end] 按最多 maxDays 天切成若干段(闭区间) */
|
||||||
|
function splitDateRange(start, end, maxDays = ATTENDANCE_MAX_SPAN_DAYS) {
|
||||||
|
const ranges = []
|
||||||
|
if (!start || !end) return ranges
|
||||||
|
let cursor = new Date(`${start}T00:00:00`)
|
||||||
|
const stop = new Date(`${end}T00:00:00`)
|
||||||
|
if (Number.isNaN(cursor.getTime()) || Number.isNaN(stop.getTime()) || cursor > stop) return ranges
|
||||||
|
|
||||||
|
while (cursor <= stop) {
|
||||||
|
const next = new Date(cursor)
|
||||||
|
next.setDate(next.getDate() + maxDays - 1)
|
||||||
|
const chunkEnd = next > stop ? stop : next
|
||||||
|
ranges.push([toDateStr(cursor), toDateStr(chunkEnd)])
|
||||||
|
cursor = new Date(chunkEnd)
|
||||||
|
cursor.setDate(cursor.getDate() + 1)
|
||||||
|
}
|
||||||
|
return ranges
|
||||||
|
}
|
||||||
|
|
||||||
/** 展开某人的明细:按当前汇总周期取该员工的考勤记录 */
|
/** 展开某人的明细:按当前汇总周期取该员工的考勤记录 */
|
||||||
async function loadRowDetail(row) {
|
async function loadRowDetail(row) {
|
||||||
const key = row.key
|
const key = row.key
|
||||||
@@ -542,20 +577,31 @@ async function loadRowDetail(row) {
|
|||||||
}
|
}
|
||||||
rowDetailMap.value = { ...rowDetailMap.value, [key]: { loading: true, loaded: false, list: [], total: 0 } }
|
rowDetailMap.value = { ...rowDetailMap.value, [key]: { loading: true, loaded: false, list: [], total: 0 } }
|
||||||
try {
|
try {
|
||||||
const data =
|
const ranges = splitDateRange(summary.startDate, summary.endDate)
|
||||||
unwrap(
|
const responses = await Promise.all(
|
||||||
await getAttendanceRecords({
|
ranges.map(([startDate, endDate]) =>
|
||||||
|
getAttendanceRecords({
|
||||||
page: 1,
|
page: 1,
|
||||||
pageSize: 100,
|
pageSize: 200,
|
||||||
start_date: summary.startDate,
|
start_date: startDate,
|
||||||
end_date: summary.endDate,
|
end_date: endDate,
|
||||||
employee_id: row.bound ? row.employee_id : '',
|
employee_id: row.bound ? row.employee_id : '',
|
||||||
uid: row.bound ? '' : row.uid
|
uid: row.bound ? '' : row.uid
|
||||||
})
|
})
|
||||||
) || {}
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
const list = []
|
||||||
|
let total = 0
|
||||||
|
responses.forEach((res) => {
|
||||||
|
const data = unwrap(res) || {}
|
||||||
|
list.push(...(data.list || []))
|
||||||
|
total += Number(data.total || 0)
|
||||||
|
})
|
||||||
|
|
||||||
rowDetailMap.value = {
|
rowDetailMap.value = {
|
||||||
...rowDetailMap.value,
|
...rowDetailMap.value,
|
||||||
[key]: { loading: false, loaded: true, list: data.list || [], total: data.total || 0 }
|
[key]: { loading: false, loaded: true, list, total }
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
rowDetailMap.value = { ...rowDetailMap.value, [key]: { loading: false, loaded: false, list: [], total: 0 } }
|
rowDetailMap.value = { ...rowDetailMap.value, [key]: { loading: false, loaded: false, list: [], total: 0 } }
|
||||||
@@ -610,10 +656,6 @@ async function loadSummary() {
|
|||||||
|
|
||||||
function onPeriodChange() {
|
function onPeriodChange() {
|
||||||
summary.page = 1
|
summary.page = 1
|
||||||
// 切换维度时自动展开日历,避免以为没数据
|
|
||||||
if (!summaryPanels.value.includes('overview')) {
|
|
||||||
summaryPanels.value = ['overview']
|
|
||||||
}
|
|
||||||
loadSummary()
|
loadSummary()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -794,7 +836,7 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
p {
|
p {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -810,14 +852,21 @@ onMounted(async () => {
|
|||||||
gap: 12px;
|
gap: 12px;
|
||||||
padding: 14px 16px;
|
padding: 14px 16px;
|
||||||
margin-bottom: 14px;
|
margin-bottom: 14px;
|
||||||
background: #fff;
|
background: var(--el-bg-color);
|
||||||
border: 1px solid #ebeef5;
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
}
|
}
|
||||||
|
// 周期切换靠右,与筛选条件同一行
|
||||||
|
.period-switch {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
.content-card {
|
.content-card {
|
||||||
padding: 8px 16px 16px;
|
padding: 8px 16px 16px;
|
||||||
background: #fff;
|
background: var(--el-bg-color);
|
||||||
border: 1px solid #ebeef5;
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -825,7 +874,7 @@ onMounted(async () => {
|
|||||||
.summary-collapse {
|
.summary-collapse {
|
||||||
margin-top: 6px;
|
margin-top: 6px;
|
||||||
border-top: none;
|
border-top: none;
|
||||||
border-bottom: 1px solid #ebeef5;
|
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||||
|
|
||||||
:deep(.el-collapse-item__header) {
|
:deep(.el-collapse-item__header) {
|
||||||
height: auto;
|
height: auto;
|
||||||
@@ -852,20 +901,20 @@ onMounted(async () => {
|
|||||||
.ct-title {
|
.ct-title {
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
.ct-sub {
|
.ct-sub {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
color: #606266;
|
color: var(--el-text-color-regular);
|
||||||
}
|
}
|
||||||
.ct-rate {
|
.ct-rate {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #409eff;
|
color: var(--el-color-primary);
|
||||||
}
|
}
|
||||||
.ct-hint {
|
.ct-hint {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ============ 周期切换 ============ */
|
/* ============ 周期切换 ============ */
|
||||||
@@ -884,12 +933,12 @@ onMounted(async () => {
|
|||||||
.year-text {
|
.year-text {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
min-width: 62px;
|
min-width: 62px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
.period-tip {
|
.period-tip {
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -903,32 +952,39 @@ onMounted(async () => {
|
|||||||
.sum-metric {
|
.sum-metric {
|
||||||
flex: 1 0 110px;
|
flex: 1 0 110px;
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
background: #f7f8fa;
|
background: var(--el-fill-color-light);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
|
// 展开明细内的指标条:与上方姓名行、下方日历的间距收紧
|
||||||
|
.rd-metrics {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
}
|
||||||
|
.rd-calendar {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
.sm-label {
|
.sm-label {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
.sm-value {
|
.sm-value {
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
|
|
||||||
&.is-ok {
|
&.is-ok {
|
||||||
color: #67c23a;
|
color: var(--el-color-success);
|
||||||
}
|
}
|
||||||
&.is-warn {
|
&.is-warn {
|
||||||
color: #e6a23c;
|
color: var(--el-color-warning);
|
||||||
}
|
}
|
||||||
&.is-danger {
|
&.is-danger {
|
||||||
color: #f56c6c;
|
color: var(--el-color-danger);
|
||||||
}
|
}
|
||||||
&.is-info {
|
&.is-info {
|
||||||
color: #409eff;
|
color: var(--el-color-primary);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -957,9 +1013,9 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
.cal-month {
|
.cal-month {
|
||||||
padding: 10px 12px 12px;
|
padding: 10px 12px 12px;
|
||||||
border: 1px solid #ebeef5;
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
background: #fff;
|
background: var(--el-bg-color);
|
||||||
}
|
}
|
||||||
.cal-month-head {
|
.cal-month-head {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -970,11 +1026,11 @@ onMounted(async () => {
|
|||||||
.cal-month-title {
|
.cal-month-title {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
.cal-month-rate {
|
.cal-month-rate {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
.cal-week,
|
.cal-week,
|
||||||
.cal-grid {
|
.cal-grid {
|
||||||
@@ -988,7 +1044,7 @@ onMounted(async () => {
|
|||||||
span {
|
span {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
color: #c0c4cc;
|
color: var(--el-text-color-placeholder);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.cal-cell {
|
.cal-cell {
|
||||||
@@ -996,7 +1052,7 @@ onMounted(async () => {
|
|||||||
min-height: 34px;
|
min-height: 34px;
|
||||||
padding: 3px 4px 2px;
|
padding: 3px 4px 2px;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
background: #f7f8fa;
|
background: var(--el-fill-color-light);
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
@@ -1013,35 +1069,35 @@ onMounted(async () => {
|
|||||||
background: transparent;
|
background: transparent;
|
||||||
}
|
}
|
||||||
&.is-ok {
|
&.is-ok {
|
||||||
background: #ecfdf3;
|
background: var(--el-color-success-light-9);
|
||||||
}
|
}
|
||||||
&.is-warn {
|
&.is-warn {
|
||||||
background: #fef7e6;
|
background: var(--el-color-warning-light-9);
|
||||||
}
|
}
|
||||||
&.is-danger {
|
&.is-danger {
|
||||||
background: #fef0f0;
|
background: var(--el-color-danger-light-9);
|
||||||
}
|
}
|
||||||
&.is-info {
|
&.is-info {
|
||||||
background: #eff6ff;
|
background: var(--el-color-primary-light-9);
|
||||||
}
|
}
|
||||||
&.is-off {
|
&.is-off {
|
||||||
background: #f7f8fa;
|
background: var(--el-fill-color-light);
|
||||||
}
|
}
|
||||||
&.is-future {
|
&.is-future {
|
||||||
opacity: 0.45;
|
opacity: 0.45;
|
||||||
}
|
}
|
||||||
&.is-today {
|
&.is-today {
|
||||||
box-shadow: inset 0 0 0 1.5px #409eff;
|
box-shadow: inset 0 0 0 1.5px var(--el-color-primary);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.cal-day {
|
.cal-day {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
color: #606266;
|
color: var(--el-text-color-regular);
|
||||||
line-height: 1.2;
|
line-height: 1.2;
|
||||||
}
|
}
|
||||||
.cal-num {
|
.cal-num {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
line-height: 1.2;
|
line-height: 1.2;
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
}
|
}
|
||||||
@@ -1052,7 +1108,7 @@ onMounted(async () => {
|
|||||||
gap: 16px;
|
gap: 16px;
|
||||||
margin-top: 12px;
|
margin-top: 12px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
.legend-item {
|
.legend-item {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -1066,19 +1122,19 @@ onMounted(async () => {
|
|||||||
display: inline-block;
|
display: inline-block;
|
||||||
|
|
||||||
&.is-ok {
|
&.is-ok {
|
||||||
background: #67c23a;
|
background: var(--el-color-success);
|
||||||
}
|
}
|
||||||
&.is-warn {
|
&.is-warn {
|
||||||
background: #e6a23c;
|
background: var(--el-color-warning);
|
||||||
}
|
}
|
||||||
&.is-danger {
|
&.is-danger {
|
||||||
background: #f56c6c;
|
background: var(--el-color-danger);
|
||||||
}
|
}
|
||||||
&.is-info {
|
&.is-info {
|
||||||
background: #409eff;
|
background: var(--el-color-primary);
|
||||||
}
|
}
|
||||||
&.is-off {
|
&.is-off {
|
||||||
background: #dcdfe6;
|
background: var(--el-border-color);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1093,11 +1149,11 @@ onMounted(async () => {
|
|||||||
.list-title {
|
.list-title {
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
.list-sub {
|
.list-sub {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
.emp-cell {
|
.emp-cell {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -1109,37 +1165,22 @@ onMounted(async () => {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
|
}
|
||||||
&.is-clickable {
|
// 点击整行即可展开/收起明细
|
||||||
|
:deep(.el-table__body tr.el-table__row) {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
user-select: none;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
color: #409eff;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.expand-caret {
|
|
||||||
font-size: 12px;
|
|
||||||
color: #909399;
|
|
||||||
transition: transform 0.2s ease;
|
|
||||||
|
|
||||||
&.is-open {
|
|
||||||
transform: rotate(90deg);
|
|
||||||
color: #409eff;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
.emp-meta {
|
.emp-meta {
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ============ 展开的明细 ============ */
|
/* ============ 展开的明细 ============ */
|
||||||
.row-detail {
|
.row-detail {
|
||||||
padding: 8px 12px 12px;
|
padding: 8px 12px 12px;
|
||||||
background: #fafbfc;
|
background: var(--el-fill-color-lighter);
|
||||||
border-left: 3px solid #409eff;
|
border-left: 3px solid var(--el-color-primary);
|
||||||
}
|
}
|
||||||
.rd-head {
|
.rd-head {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -1151,21 +1192,21 @@ onMounted(async () => {
|
|||||||
.rd-name {
|
.rd-name {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
.rd-meta {
|
.rd-meta {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #606266;
|
color: var(--el-text-color-regular);
|
||||||
}
|
}
|
||||||
.rd-range {
|
.rd-range {
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
.rd-more {
|
.rd-more {
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
}
|
}
|
||||||
.date-cell {
|
.date-cell {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -1173,7 +1214,7 @@ onMounted(async () => {
|
|||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
.weekday {
|
.weekday {
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
.shift-cell {
|
.shift-cell {
|
||||||
@@ -1193,10 +1234,10 @@ onMounted(async () => {
|
|||||||
gap: 2px;
|
gap: 2px;
|
||||||
}
|
}
|
||||||
.shift-name {
|
.shift-name {
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
.shift-time {
|
.shift-time {
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
.punch-cell {
|
.punch-cell {
|
||||||
@@ -1206,13 +1247,13 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
.punch-time {
|
.punch-time {
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: #303133;
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
.note-text {
|
.note-text {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
color: #e6a23c;
|
color: var(--el-color-warning);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
}
|
}
|
||||||
@@ -1220,19 +1261,19 @@ onMounted(async () => {
|
|||||||
display: inline-block;
|
display: inline-block;
|
||||||
margin-top: 2px;
|
margin-top: 2px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: #606266;
|
color: var(--el-text-color-regular);
|
||||||
}
|
}
|
||||||
.is-warn {
|
.is-warn {
|
||||||
color: #e6a23c;
|
color: var(--el-color-warning);
|
||||||
}
|
}
|
||||||
.is-danger {
|
.is-danger {
|
||||||
color: #f56c6c;
|
color: var(--el-color-danger);
|
||||||
}
|
}
|
||||||
.is-info {
|
.is-info {
|
||||||
color: #409eff;
|
color: var(--el-color-primary);
|
||||||
}
|
}
|
||||||
.muted {
|
.muted {
|
||||||
color: #c0c4cc;
|
color: var(--el-text-color-placeholder);
|
||||||
}
|
}
|
||||||
.pager {
|
.pager {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -1246,12 +1287,12 @@ onMounted(async () => {
|
|||||||
margin-bottom: 12px;
|
margin-bottom: 12px;
|
||||||
}
|
}
|
||||||
.missing-tip {
|
.missing-tip {
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
.missing-count {
|
.missing-count {
|
||||||
margin-right: auto;
|
margin-right: auto;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
.remark-head {
|
.remark-head {
|
||||||
|
|||||||
@@ -416,7 +416,7 @@ onMounted(loadList)
|
|||||||
}
|
}
|
||||||
p {
|
p {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -430,9 +430,11 @@ onMounted(loadList)
|
|||||||
}
|
}
|
||||||
.table-card {
|
.table-card {
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
background: #fff;
|
// 跟随主题:暗色模式下使用 Element Plus 暗色变量,避免白底块
|
||||||
border: 1px solid #ebeef5;
|
background: var(--el-bg-color);
|
||||||
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
|
transition: background-color 0.3s ease, border-color 0.3s ease;
|
||||||
}
|
}
|
||||||
.name-cell {
|
.name-cell {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -446,9 +448,9 @@ onMounted(loadList)
|
|||||||
gap: 4px;
|
gap: 4px;
|
||||||
|
|
||||||
.is-default {
|
.is-default {
|
||||||
color: #e6a23c;
|
color: var(--el-color-warning);
|
||||||
border-color: #f3d19e;
|
border-color: var(--el-color-warning-light-5);
|
||||||
background: #fdf6ec;
|
background: var(--el-color-warning-light-9);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.model-editor {
|
.model-editor {
|
||||||
@@ -464,7 +466,7 @@ onMounted(loadList)
|
|||||||
}
|
}
|
||||||
.form-tip {
|
.form-tip {
|
||||||
margin-left: 10px;
|
margin-left: 10px;
|
||||||
color: #909399;
|
color: var(--el-text-color-secondary);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
.test-results {
|
.test-results {
|
||||||
@@ -480,7 +482,7 @@ onMounted(loadList)
|
|||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
.test-error {
|
.test-error {
|
||||||
color: #f56c6c;
|
color: var(--el-color-danger);
|
||||||
word-break: break-all;
|
word-break: break-all;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
<template>
|
||||||
|
<div class="container-box storage-page" v-loading="loading">
|
||||||
|
<!-- 空间概览 -->
|
||||||
|
<div class="overview-card">
|
||||||
|
<div class="overview-head">
|
||||||
|
<div class="overview-title">
|
||||||
|
<el-icon><Coin /></el-icon>
|
||||||
|
<span>附件空间</span>
|
||||||
|
</div>
|
||||||
|
<el-button link type="primary" @click="openOrders">购买记录</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="overview-usage">
|
||||||
|
<span class="used">{{ formatSize(info.used_bytes) }}</span>
|
||||||
|
<span class="total">/ {{ formatSize(info.quota_bytes) }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-progress
|
||||||
|
:percentage="progressPercent"
|
||||||
|
:status="progressStatus"
|
||||||
|
:stroke-width="10"
|
||||||
|
:show-text="false"
|
||||||
|
class="overview-progress"
|
||||||
|
/>
|
||||||
|
<div class="overview-foot">
|
||||||
|
<span>已用 {{ info.used_percent || 0 }}%,剩余 {{ formatSize(info.remaining_bytes) }}</span>
|
||||||
|
<span v-if="info.expire_time" class="expire">
|
||||||
|
套餐 {{ info.package_name }} 到期:{{ formatDate(info.expire_time) }}(剩 {{ info.days_remaining }} 天)
|
||||||
|
</span>
|
||||||
|
<span v-else class="expire">当前为基础额度 {{ info.base_quota_mb || 500 }}MB</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 套餐 -->
|
||||||
|
<div class="section-title">
|
||||||
|
<h3>扩容套餐</h3>
|
||||||
|
<span class="tip">购买后立即生效;换规格会替换当前套餐,同规格续费到期时间顺延</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="packages.length" class="package-grid">
|
||||||
|
<div v-for="pkg in packages" :key="pkg.id" class="package-card">
|
||||||
|
<div class="package-name">{{ pkg.name }}</div>
|
||||||
|
<div class="package-capacity">{{ formatCapacity(pkg.capacity_mb) }}</div>
|
||||||
|
<div class="package-price">
|
||||||
|
<span class="symbol">¥</span>
|
||||||
|
<span class="amount">{{ Number(pkg.price || 0).toFixed(2) }}</span>
|
||||||
|
<span class="unit">/ {{ durationText(pkg.duration_days) }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="pkg.remark" class="package-remark">{{ pkg.remark }}</div>
|
||||||
|
<el-button
|
||||||
|
type="primary"
|
||||||
|
class="package-btn"
|
||||||
|
:loading="buyingId === pkg.id"
|
||||||
|
@click="handleBuy(pkg)"
|
||||||
|
>
|
||||||
|
购买
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<el-empty v-else description="暂无可购买的扩容套餐" />
|
||||||
|
|
||||||
|
<!-- 支付弹窗 -->
|
||||||
|
<el-dialog v-model="payVisible" title="扫码支付" width="420px" :close-on-click-modal="false">
|
||||||
|
<div v-if="payParams?.code_url" class="pay-body">
|
||||||
|
<canvas ref="qrRef" class="pay-qr"></canvas>
|
||||||
|
<p class="pay-tip">请使用{{ currentChannelName }}扫码支付</p>
|
||||||
|
<p class="pay-amount">¥{{ Number(payAmount || 0).toFixed(2) }}</p>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="payParams?.redirect_url" class="pay-body">
|
||||||
|
<p class="pay-tip">正在跳转{{ currentChannelName }}收银台…</p>
|
||||||
|
<el-button type="primary" @click="openPayUrl(payParams.redirect_url)">重新打开支付页</el-button>
|
||||||
|
</div>
|
||||||
|
<p class="pay-status">{{ payStatusText }}</p>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="handleCancelPay">取消支付</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
|
<!-- 购买记录 -->
|
||||||
|
<el-drawer v-model="ordersVisible" title="购买记录" size="640px">
|
||||||
|
<el-table :data="orders" v-loading="ordersLoading" size="small">
|
||||||
|
<el-table-column prop="order_no" label="订单号" min-width="180" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="package_name" label="套餐" width="120" />
|
||||||
|
<el-table-column label="容量" width="100">
|
||||||
|
<template #default="{ row }">{{ formatCapacity(row.capacity_mb) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="金额" width="90">
|
||||||
|
<template #default="{ row }">¥{{ Number(row.amount || 0).toFixed(2) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="状态" width="90">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag size="small" :type="storageOrderStatusType(row.status)">
|
||||||
|
{{ storageOrderStatusText(row.status) }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="有效期" min-width="190">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span v-if="row.end_time">{{ formatDate(row.start_time) }} ~ {{ formatDate(row.end_time) }}</span>
|
||||||
|
<span v-else>-</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-drawer>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";
|
||||||
|
import { ElMessage } from "element-plus";
|
||||||
|
import { Coin } from "@element-plus/icons-vue";
|
||||||
|
import QRCode from "qrcode";
|
||||||
|
import { getPaymentChannels } from "@/api/product";
|
||||||
|
import {
|
||||||
|
createStorageOrder,
|
||||||
|
getStorageInfo,
|
||||||
|
getStorageOrder,
|
||||||
|
getStorageOrders,
|
||||||
|
getStoragePackages,
|
||||||
|
} from "@/api/storage";
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const info = ref<Record<string, any>>({});
|
||||||
|
const packages = ref<any[]>([]);
|
||||||
|
|
||||||
|
const buyingId = ref<number | null>(null);
|
||||||
|
const payVisible = ref(false);
|
||||||
|
const payParams = ref<any>(null);
|
||||||
|
const payStatusText = ref("");
|
||||||
|
const payAmount = ref(0);
|
||||||
|
const currentChannelName = ref("");
|
||||||
|
const qrRef = ref<HTMLCanvasElement | null>(null);
|
||||||
|
|
||||||
|
const ordersVisible = ref(false);
|
||||||
|
const orders = ref<any[]>([]);
|
||||||
|
const ordersLoading = ref(false);
|
||||||
|
|
||||||
|
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let pollCount = 0;
|
||||||
|
|
||||||
|
const progressPercent = computed(() => {
|
||||||
|
const p = Number(info.value.used_percent) || 0;
|
||||||
|
return Math.min(100, Math.max(0, Math.round(p * 10) / 10));
|
||||||
|
});
|
||||||
|
|
||||||
|
const progressStatus = computed(() => {
|
||||||
|
const p = progressPercent.value;
|
||||||
|
if (p >= 95) return "exception";
|
||||||
|
if (p >= 80) return "warning";
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
|
||||||
|
const formatSize = (bytes: any) => {
|
||||||
|
const n = Number(bytes) || 0;
|
||||||
|
if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;
|
||||||
|
if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;
|
||||||
|
if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||||
|
return `${n} B`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCapacity = (mb: any) => {
|
||||||
|
const n = Number(mb) || 0;
|
||||||
|
return n >= 1024 ? `${(n / 1024).toFixed(n % 1024 === 0 ? 0 : 1)} GB` : `${n} MB`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDate = (value: any) => {
|
||||||
|
if (!value) return "-";
|
||||||
|
const d = new Date(value);
|
||||||
|
if (Number.isNaN(d.getTime())) return String(value).slice(0, 10);
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const durationText = (days: any) => {
|
||||||
|
const n = Number(days) || 0;
|
||||||
|
if (n === 365) return "年";
|
||||||
|
if (n === 180) return "半年";
|
||||||
|
if (n === 90) return "季";
|
||||||
|
if (n === 30) return "月";
|
||||||
|
return `${n} 天`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const storageOrderStatusText = (s: string) =>
|
||||||
|
({ pending: "待支付", paid: "已支付", cancelled: "已取消", replaced: "已替换" }[s] || s);
|
||||||
|
|
||||||
|
const storageOrderStatusType = (s: string) =>
|
||||||
|
({ pending: "warning", paid: "success", cancelled: "info", replaced: "info" }[s] || "info");
|
||||||
|
|
||||||
|
const loadInfo = async () => {
|
||||||
|
const res = await getStorageInfo();
|
||||||
|
if (res?.code === 200) info.value = res.data || {};
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadPackages = async () => {
|
||||||
|
const res = await getStoragePackages();
|
||||||
|
if (res?.code === 200) packages.value = res.data?.list || [];
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadAll = async () => {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
await Promise.all([loadInfo(), loadPackages()]);
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || "加载空间信息失败");
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderQR = async () => {
|
||||||
|
if (!payParams.value?.code_url) return;
|
||||||
|
await nextTick();
|
||||||
|
if (!qrRef.value) return;
|
||||||
|
try {
|
||||||
|
await QRCode.toCanvas(qrRef.value, payParams.value.code_url, { width: 200, margin: 1 });
|
||||||
|
} catch (e) {
|
||||||
|
console.error("二维码生成失败:", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openPayUrl = (url: string) => {
|
||||||
|
if (url) window.open(url, "_blank");
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopPolling = () => {
|
||||||
|
if (pollTimer) {
|
||||||
|
clearInterval(pollTimer);
|
||||||
|
pollTimer = null;
|
||||||
|
}
|
||||||
|
pollCount = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
const startPolling = (orderNo: string) => {
|
||||||
|
stopPolling();
|
||||||
|
pollTimer = setInterval(async () => {
|
||||||
|
pollCount += 1;
|
||||||
|
if (pollCount > 100) {
|
||||||
|
stopPolling();
|
||||||
|
payStatusText.value = "支付结果确认超时,请稍后在购买记录中查看";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await getStorageOrder(orderNo);
|
||||||
|
if (res?.code !== 200) return;
|
||||||
|
const status = res.data?.status;
|
||||||
|
if (status === "paid") {
|
||||||
|
stopPolling();
|
||||||
|
payStatusText.value = "支付成功,空间已扩容";
|
||||||
|
ElMessage.success("支付成功,附件空间已扩容");
|
||||||
|
payVisible.value = false;
|
||||||
|
await loadInfo();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 网络抖动继续轮询
|
||||||
|
}
|
||||||
|
}, 3000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBuy = async (pkg: any) => {
|
||||||
|
buyingId.value = pkg.id;
|
||||||
|
try {
|
||||||
|
const channelRes = await getPaymentChannels();
|
||||||
|
const channels = channelRes?.code === 200 ? channelRes.data?.list || [] : [];
|
||||||
|
const channel = channels.length ? channels[0].channel : "";
|
||||||
|
|
||||||
|
const res = await createStorageOrder({
|
||||||
|
package_id: pkg.id,
|
||||||
|
channel,
|
||||||
|
pay_type: "",
|
||||||
|
return_url: window.location.origin + window.location.pathname,
|
||||||
|
});
|
||||||
|
if (res?.code !== 200) {
|
||||||
|
ElMessage.error(res?.msg || "下单失败");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.data?.free) {
|
||||||
|
ElMessage.success("套餐已开通");
|
||||||
|
await loadInfo();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
payParams.value = res.data?.pay_params || null;
|
||||||
|
payAmount.value = Number(res.data?.amount || pkg.price || 0);
|
||||||
|
currentChannelName.value = channels.find((x: any) => x.channel === channel)?.name || channel;
|
||||||
|
payStatusText.value = "请在有效期内完成支付,支付成功后空间自动扩容";
|
||||||
|
payVisible.value = true;
|
||||||
|
await renderQR();
|
||||||
|
if (payParams.value?.redirect_url) openPayUrl(payParams.value.redirect_url);
|
||||||
|
startPolling(res.data.order_no);
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || "下单失败");
|
||||||
|
} finally {
|
||||||
|
buyingId.value = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancelPay = () => {
|
||||||
|
stopPolling();
|
||||||
|
payVisible.value = false;
|
||||||
|
payParams.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const openOrders = async () => {
|
||||||
|
ordersVisible.value = true;
|
||||||
|
ordersLoading.value = true;
|
||||||
|
try {
|
||||||
|
const res = await getStorageOrders({ page: 1, pageSize: 50 });
|
||||||
|
orders.value = res?.code === 200 ? res.data?.list || [] : [];
|
||||||
|
} catch (e) {
|
||||||
|
orders.value = [];
|
||||||
|
} finally {
|
||||||
|
ordersLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(loadAll);
|
||||||
|
onUnmounted(stopPolling);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped lang="less">
|
||||||
|
.storage-page {
|
||||||
|
.overview-card {
|
||||||
|
padding: 20px 22px;
|
||||||
|
border: 1px solid var(--yz-border, #e8edf7);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--yz-card-bg, #fff);
|
||||||
|
box-shadow: var(--yz-shadow, 0 2px 12px rgba(31, 61, 130, 0.06));
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
|
||||||
|
.overview-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-usage {
|
||||||
|
margin-top: 18px;
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 6px;
|
||||||
|
|
||||||
|
.used {
|
||||||
|
font-size: 28px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.total {
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-progress {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-foot {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
|
||||||
|
.expire {
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 10px;
|
||||||
|
margin: 26px 0 14px;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tip {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-card {
|
||||||
|
padding: 20px;
|
||||||
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--el-bg-color);
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
border-color: var(--el-color-primary-light-7);
|
||||||
|
box-shadow: 0 8px 24px rgba(47, 107, 255, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-name {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-capacity {
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-price {
|
||||||
|
margin-top: 6px;
|
||||||
|
color: var(--el-text-color-regular);
|
||||||
|
|
||||||
|
.symbol {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount {
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.unit {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-remark {
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.package-btn {
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 14px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.pay-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
|
||||||
|
.pay-qr {
|
||||||
|
width: 200px;
|
||||||
|
height: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pay-tip {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pay-amount {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--el-color-danger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.pay-status {
|
||||||
|
margin: 12px 0 0;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -46,9 +46,12 @@
|
|||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { ref, computed } from "vue";
|
import { ref, computed } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
import { ElMessage, ElMessageBox } from "element-plus";
|
import { ElMessage, ElMessageBox } from "element-plus";
|
||||||
import { UploadFilled } from "@element-plus/icons-vue";
|
import { UploadFilled } from "@element-plus/icons-vue";
|
||||||
import { uploadFile } from "@/api/file";
|
import { uploadFile } from "@/api/file";
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
import type { UploadInstance, UploadFile, UploadFiles } from "element-plus";
|
import type { UploadInstance, UploadFile, UploadFiles } from "element-plus";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -240,6 +243,28 @@ const submitUpload = async () => {
|
|||||||
ElMessage.success(message);
|
ElMessage.success(message);
|
||||||
}
|
}
|
||||||
if (failCount > 0) {
|
if (failCount > 0) {
|
||||||
|
// 附件空间不足(后端业务码 4032):引导购买扩容
|
||||||
|
const quotaRejected = results.find(
|
||||||
|
(r) =>
|
||||||
|
r.status === "rejected" &&
|
||||||
|
Number(r.reason?.error?.response?.data?.code) === 4032,
|
||||||
|
);
|
||||||
|
if (quotaRejected) {
|
||||||
|
const quotaMsg =
|
||||||
|
quotaRejected.reason?.error?.response?.data?.msg ||
|
||||||
|
"附件空间不足,请购买扩容后再上传";
|
||||||
|
ElMessageBox.confirm(quotaMsg, "附件空间不足", {
|
||||||
|
confirmButtonText: "去扩容",
|
||||||
|
cancelButtonText: "知道了",
|
||||||
|
type: "warning",
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
handleClose();
|
||||||
|
router.push("/basicSettings/storage");
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
ElMessage.warning(`${failCount} 个文件上传失败`);
|
ElMessage.warning(`${failCount} 个文件上传失败`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,24 @@
|
|||||||
<el-icon><Folder /></el-icon>
|
<el-icon><Folder /></el-icon>
|
||||||
文件管理系统
|
文件管理系统
|
||||||
</span>
|
</span>
|
||||||
|
<div class="header-right">
|
||||||
|
<!-- 附件空间用量:点击进入扩容页 -->
|
||||||
|
<div class="storage-usage" title="附件空间用量,点击扩容" @click="goStorage">
|
||||||
|
<el-progress
|
||||||
|
:percentage="storagePercent"
|
||||||
|
:status="storageStatus"
|
||||||
|
:stroke-width="6"
|
||||||
|
:show-text="false"
|
||||||
|
class="storage-bar"
|
||||||
|
/>
|
||||||
|
<span class="storage-text">
|
||||||
|
空间 {{ storageText }}
|
||||||
|
<span v-if="storagePercent >= 90" class="storage-warn">(即将用尽)</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<el-button :icon="Refresh" @click="refushData"> 刷新 </el-button>
|
<el-button :icon="Refresh" @click="refushData"> 刷新 </el-button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<el-row :gutter="20">
|
<el-row :gutter="20">
|
||||||
@@ -457,6 +473,7 @@
|
|||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { ref, computed, onMounted } from "vue";
|
import { ref, computed, onMounted } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
import { ElMessage, ElMessageBox } from "element-plus";
|
import { ElMessage, ElMessageBox } from "element-plus";
|
||||||
import {
|
import {
|
||||||
Folder,
|
Folder,
|
||||||
@@ -496,9 +513,49 @@ import UploadFile from "./components/uploadFile.vue";
|
|||||||
import MoveFile from "./components/moveFile.vue";
|
import MoveFile from "./components/moveFile.vue";
|
||||||
import RenameCategory from "./components/renameCategory.vue";
|
import RenameCategory from "./components/renameCategory.vue";
|
||||||
import CreateCategory from "./components/createCategory.vue";
|
import CreateCategory from "./components/createCategory.vue";
|
||||||
|
import { getStorageInfo } from "@/api/storage";
|
||||||
// 日期显示统一为:YYYY-MM-DD
|
// 日期显示统一为:YYYY-MM-DD
|
||||||
import { formatDate } from "@/utils/datetime";
|
import { formatDate } from "@/utils/datetime";
|
||||||
|
|
||||||
|
// ---------- 附件空间用量 ----------
|
||||||
|
const router = useRouter();
|
||||||
|
const storageInfo = ref<Record<string, any>>({});
|
||||||
|
|
||||||
|
const storagePercent = computed(() => {
|
||||||
|
const p = Number(storageInfo.value.used_percent) || 0;
|
||||||
|
return Math.min(100, Math.max(0, Math.round(p * 10) / 10));
|
||||||
|
});
|
||||||
|
|
||||||
|
const storageStatus = computed(() => {
|
||||||
|
if (storagePercent.value >= 95) return "exception";
|
||||||
|
if (storagePercent.value >= 80) return "warning";
|
||||||
|
return "";
|
||||||
|
});
|
||||||
|
|
||||||
|
const formatStorageSize = (bytes: any) => {
|
||||||
|
const n = Number(bytes) || 0;
|
||||||
|
if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)}GB`;
|
||||||
|
if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)}MB`;
|
||||||
|
if (n >= 1024) return `${(n / 1024).toFixed(1)}KB`;
|
||||||
|
return `${n}B`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const storageText = computed(
|
||||||
|
() =>
|
||||||
|
`${formatStorageSize(storageInfo.value.used_bytes)} / ${formatStorageSize(storageInfo.value.quota_bytes)}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadStorageInfo = async () => {
|
||||||
|
try {
|
||||||
|
const res = await getStorageInfo();
|
||||||
|
if (res?.code === 200) storageInfo.value = res.data || {};
|
||||||
|
} catch {
|
||||||
|
// 空间用量属于辅助信息,失败不影响文件管理
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const goStorage = () => router.push("/basicSettings/storage");
|
||||||
|
|
||||||
// 分组相关
|
// 分组相关
|
||||||
interface Group {
|
interface Group {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -1247,6 +1304,7 @@ const handleBatchDeletePermanently = () => {
|
|||||||
// 初始化
|
// 初始化
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
getUserCateData();
|
getUserCateData();
|
||||||
|
loadStorageInfo();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -1270,6 +1328,39 @@ onMounted(() => {
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
color: var(--el-text-color-placeholder);
|
color: var(--el-text-color-placeholder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.header-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 附件空间用量(点击进入扩容页)
|
||||||
|
.storage-usage {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
min-width: 190px;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover .storage-text {
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-bar {
|
||||||
|
width: 190px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-text {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
transition: color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-warn {
|
||||||
|
color: var(--el-color-danger);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.group-card,
|
.group-card,
|
||||||
|
|||||||
@@ -272,6 +272,15 @@ func (c *AppOaController) uploadTenantImage() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 附件空间校验:OA 附件同样占用租户额度
|
||||||
|
if qerr := services.EnsureTenantStorageQuota(tid, uint64(staged.Size)); qerr != nil {
|
||||||
|
if respondStorageQuotaError(&c.Controller, qerr) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.oaErr(500, 500, "附件空间校验失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
result, err := storage.Commit(staged, ctx)
|
result, err := storage.Commit(staged, ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.oaErr(500, 500, "上传失败,请重试")
|
c.oaErr(500, 500, "上传失败,请重试")
|
||||||
|
|||||||
@@ -575,6 +575,16 @@ func (c *BackendFileController) UploadFile() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2.1 附件空间校验:重复文件不占空间,所以放在查重之后、落盘之前。
|
||||||
|
// 平台端上传(source=platform)不占租户额度,这里只管租户端上传。
|
||||||
|
if qerr := services.EnsureTenantStorageQuota(tid, uint64(staged.Size)); qerr != nil {
|
||||||
|
if respondStorageQuotaError(&c.Controller, qerr) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.jsonErr(500, 500, "附件空间校验失败: "+qerr.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 3. 提交到正式目录:backend/{tid}[/{tuid}]/yyyy/MM/dd/
|
// 3. 提交到正式目录:backend/{tid}[/{tuid}]/yyyy/MM/dd/
|
||||||
result, err := storageService.Commit(staged, ctx)
|
result, err := storageService.Commit(staged, ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -976,6 +986,15 @@ func (c *BackendFileController) UploadAvatar() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 头像也占用租户附件空间(计入文件台账)
|
||||||
|
if qerr := services.EnsureTenantStorageQuota(tid, uint64(staged.Size)); qerr != nil {
|
||||||
|
if respondStorageQuotaError(&c.Controller, qerr) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.jsonErr(500, 500, "附件空间校验失败: "+qerr.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
result, err := storageService.Commit(staged, upCtx)
|
result, err := storageService.Commit(staged, upCtx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.jsonErr(500, 500, "上传头像失败: "+err.Error())
|
c.jsonErr(500, 500, "上传头像失败: "+err.Error())
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"server/models"
|
||||||
|
"server/pkg/identity"
|
||||||
|
"server/pkg/jwtutil"
|
||||||
|
"server/services"
|
||||||
|
"server/services/payment"
|
||||||
|
|
||||||
|
beego "github.com/beego/beego/v2/server/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BackendStorageController 租户端附件空间:用量 / 套餐 / 下单 / 购买记录
|
||||||
|
type BackendStorageController struct {
|
||||||
|
beego.Controller
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BackendStorageController) claims() (*jwtutil.Claims, error) {
|
||||||
|
return identity.Claims(c.Ctx.Request.Header.Get("Authorization"), identity.EndBackend)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BackendStorageController) fail(httpStatus, bizCode int, msg string) {
|
||||||
|
c.Ctx.Output.SetStatus(httpStatus)
|
||||||
|
c.Data["json"] = map[string]any{"code": bizCode, "msg": msg}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BackendStorageController) ok(data any) {
|
||||||
|
c.Data["json"] = map[string]any{"code": 200, "msg": "success", "data": data}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// storageOperator 下单人(账号),用于订单审计
|
||||||
|
func storageOperator(claims *jwtutil.Claims) string {
|
||||||
|
if claims == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(claims.Username)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *BackendStorageController) tenantID() (uint64, error) {
|
||||||
|
claims, err := c.claims()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if claims.TenantId <= 0 {
|
||||||
|
return 0, fmt.Errorf("当前账号未归属企业")
|
||||||
|
}
|
||||||
|
return uint64(claims.TenantId), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StorageInfo GET /backend/tenant/storageInfo
|
||||||
|
// 附件空间使用情况:基础额度、生效套餐、已用/剩余、到期时间。
|
||||||
|
func (c *BackendStorageController) StorageInfo() {
|
||||||
|
tid, err := c.tenantID()
|
||||||
|
if err != nil {
|
||||||
|
c.fail(401, 401, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
info, err := services.GetTenantStorageInfo(tid)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "获取空间信息失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Packages GET /backend/tenant/storagePackages
|
||||||
|
// 可购买的附件空间套餐(上架中)。
|
||||||
|
func (c *BackendStorageController) Packages() {
|
||||||
|
if _, err := c.tenantID(); err != nil {
|
||||||
|
c.fail(401, 401, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var rows []models.SystemTenantStoragePackage
|
||||||
|
_, err := models.Orm.QueryTable(new(models.SystemTenantStoragePackage)).
|
||||||
|
Filter("status", 1).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
OrderBy("sort", "id").
|
||||||
|
All(&rows)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "获取套餐失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
list := make([]map[string]any, 0, len(rows))
|
||||||
|
for i := range rows {
|
||||||
|
list = append(list, map[string]any{
|
||||||
|
"id": rows[i].ID,
|
||||||
|
"name": rows[i].Name,
|
||||||
|
"code": rows[i].Code,
|
||||||
|
"capacity_mb": rows[i].CapacityMB,
|
||||||
|
"price": rows[i].Price,
|
||||||
|
"duration_days": rows[i].DurationDays,
|
||||||
|
"remark": rows[i].Remark,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.ok(map[string]any{"list": list})
|
||||||
|
}
|
||||||
|
|
||||||
|
type storageOrderPayload struct {
|
||||||
|
PackageID uint64 `json:"package_id"`
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
PayType string `json:"pay_type"`
|
||||||
|
ReturnURL string `json:"return_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateOrder POST /backend/tenant/storage/order
|
||||||
|
// 创建附件空间订单并拉起支付;返回支付参数供前端调起渠道。
|
||||||
|
func (c *BackendStorageController) CreateOrder() {
|
||||||
|
tid, err := c.tenantID()
|
||||||
|
if err != nil {
|
||||||
|
c.fail(401, 401, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
claims, _ := c.claims()
|
||||||
|
|
||||||
|
var p storageOrderPayload
|
||||||
|
if err := c.BindJSON(&p); err != nil {
|
||||||
|
c.fail(400, 400, "参数错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.PackageID == 0 {
|
||||||
|
c.fail(400, 400, "请选择要购买的套餐")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var pkg models.SystemTenantStoragePackage
|
||||||
|
if err := models.Orm.QueryTable(new(models.SystemTenantStoragePackage)).
|
||||||
|
Filter("id", p.PackageID).
|
||||||
|
Filter("status", 1).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
One(&pkg); err != nil {
|
||||||
|
c.fail(404, 404, "套餐不存在或已下架")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if pkg.CapacityMB <= 0 {
|
||||||
|
c.fail(400, 400, "套餐容量配置异常")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 租户名称(支付单展示)
|
||||||
|
tenantName := ""
|
||||||
|
var tenant models.SystemTenant
|
||||||
|
if err := models.Orm.QueryTable(new(models.SystemTenant)).Filter("id", tid).One(&tenant); err == nil {
|
||||||
|
tenantName = tenant.TenantName
|
||||||
|
}
|
||||||
|
|
||||||
|
orderNo := services.BuildStorageOrderNo(tid)
|
||||||
|
order := &models.SystemTenantStorageOrder{
|
||||||
|
OrderNo: orderNo,
|
||||||
|
Tid: tid,
|
||||||
|
PackageID: pkg.ID,
|
||||||
|
PackageName: pkg.Name,
|
||||||
|
CapacityMB: pkg.CapacityMB,
|
||||||
|
DurationDays: pkg.DurationDays,
|
||||||
|
Amount: pkg.Price,
|
||||||
|
Status: models.StorageOrderPending,
|
||||||
|
Operator: storageOperator(claims),
|
||||||
|
}
|
||||||
|
if _, err := models.Orm.Insert(order); err != nil {
|
||||||
|
c.fail(500, 500, "创建订单失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 免费套餐:直接激活,不拉起支付
|
||||||
|
if pkg.Price <= 0 {
|
||||||
|
if err := services.ActivateStorageOrder(orderNo, ""); err != nil {
|
||||||
|
c.fail(500, 500, "开通失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(map[string]any{"order_no": orderNo, "free": true, "amount": 0})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
channel := strings.TrimSpace(p.Channel)
|
||||||
|
if channel == "" {
|
||||||
|
c.fail(400, 400, "请选择支付渠道")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
amountFen := int64(math.Round(pkg.Price * 100))
|
||||||
|
payOrder, params, err := payment.CreatePayment(
|
||||||
|
c.Ctx.Request.Context(),
|
||||||
|
payment.CreateInput{
|
||||||
|
OutTradeNo: orderNo,
|
||||||
|
OrderType: "tenant_storage",
|
||||||
|
TenantID: strconv.FormatUint(tid, 10),
|
||||||
|
TenantName: tenantName,
|
||||||
|
Amount: amountFen,
|
||||||
|
Channel: channel,
|
||||||
|
Subject: "附件空间-" + pkg.Name,
|
||||||
|
ClientIP: c.Ctx.Input.IP(),
|
||||||
|
PayType: strings.TrimSpace(p.PayType),
|
||||||
|
ReturnURL: strings.TrimSpace(p.ReturnURL),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "发起支付失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.ok(map[string]any{
|
||||||
|
"order_no": orderNo,
|
||||||
|
"pay_no": payOrder.PayNo,
|
||||||
|
"amount": pkg.Price,
|
||||||
|
"pay_params": params,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Orders GET /backend/tenant/storage/orders?page=&pageSize=
|
||||||
|
func (c *BackendStorageController) Orders() {
|
||||||
|
tid, err := c.tenantID()
|
||||||
|
if err != nil {
|
||||||
|
c.fail(401, 401, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
page, _ := strconv.Atoi(c.GetString("page", "1"))
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
pageSize, _ := strconv.Atoi(c.GetString("pageSize", "10"))
|
||||||
|
if pageSize <= 0 || pageSize > 100 {
|
||||||
|
pageSize = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
qs := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("tid", tid).
|
||||||
|
Filter("delete_time__isnull", true)
|
||||||
|
total, err := qs.Count()
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "查询失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []models.SystemTenantStorageOrder
|
||||||
|
_, err = qs.OrderBy("-id").Offset((page - 1) * pageSize).Limit(pageSize).All(&rows)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "查询失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
list := make([]map[string]any, 0, len(rows))
|
||||||
|
for i := range rows {
|
||||||
|
r := &rows[i]
|
||||||
|
list = append(list, map[string]any{
|
||||||
|
"order_no": r.OrderNo,
|
||||||
|
"package_id": r.PackageID,
|
||||||
|
"package_name": r.PackageName,
|
||||||
|
"capacity_mb": r.CapacityMB,
|
||||||
|
"duration_days": r.DurationDays,
|
||||||
|
"amount": r.Amount,
|
||||||
|
"status": r.Status,
|
||||||
|
"pay_no": r.PayNo,
|
||||||
|
"start_time": r.StartTime,
|
||||||
|
"end_time": r.EndTime,
|
||||||
|
"create_time": r.CreateTime,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.ok(map[string]any{"list": list, "total": total, "page": page, "pageSize": pageSize})
|
||||||
|
}
|
||||||
|
|
||||||
|
// OrderDetail GET /backend/tenant/storage/order/:orderNo
|
||||||
|
// 支付后轮询用:返回订单状态与最新空间信息。
|
||||||
|
func (c *BackendStorageController) OrderDetail() {
|
||||||
|
tid, err := c.tenantID()
|
||||||
|
if err != nil {
|
||||||
|
c.fail(401, 401, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
orderNo := strings.TrimSpace(c.Ctx.Input.Param(":orderNo"))
|
||||||
|
if orderNo == "" {
|
||||||
|
c.fail(400, 400, "订单号不能为空")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var order models.SystemTenantStorageOrder
|
||||||
|
if err := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("order_no", orderNo).
|
||||||
|
Filter("tid", tid).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
One(&order); err != nil {
|
||||||
|
c.fail(404, 404, "订单不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
info, _ := services.GetTenantStorageInfo(tid)
|
||||||
|
c.ok(map[string]any{
|
||||||
|
"order_no": order.OrderNo,
|
||||||
|
"status": order.Status,
|
||||||
|
"pay_no": order.PayNo,
|
||||||
|
"capacity_mb": order.CapacityMB,
|
||||||
|
"amount": order.Amount,
|
||||||
|
"start_time": order.StartTime,
|
||||||
|
"end_time": order.EndTime,
|
||||||
|
"storage_info": info,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/models"
|
||||||
|
"server/services"
|
||||||
|
"server/services/payment"
|
||||||
|
|
||||||
|
"github.com/beego/beego/v2/client/orm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 支付成功 -> 附件空间订单同步:
|
||||||
|
// 渠道回调(或主动查询)把支付单置为 paid 时,支付服务会调用这里注册的钩子,
|
||||||
|
// 自动把附件空间订单置为已支付并计算生效区间(续费顺延 / 换规格替换)。
|
||||||
|
func init() {
|
||||||
|
payment.RegisterOrderSyncHook(syncStorageOrderFromPayment)
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncStorageOrderFromPayment(_ context.Context, payOrder *models.PlatformPaymentOrder) error {
|
||||||
|
if payOrder == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
orderNo := strings.TrimSpace(payOrder.OutTradeNo)
|
||||||
|
if orderNo == "" || !strings.HasPrefix(orderNo, "ST") {
|
||||||
|
// 不是附件空间订单,交给其他钩子处理
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var order models.SystemTenantStorageOrder
|
||||||
|
err := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("order_no", orderNo).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
One(&order)
|
||||||
|
if err == orm.ErrNoRows {
|
||||||
|
// 下单链路先建支付单、后落业务订单,回调可能抢先到达:
|
||||||
|
// 10 分钟内保留重试,超过窗口视为非本模块订单。
|
||||||
|
if time.Since(payOrder.CreateTime) < 10*time.Minute {
|
||||||
|
return fmt.Errorf("附件空间订单 %s 尚未入库,等待重试", orderNo)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if order.Status == models.StorageOrderPaid {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return services.ActivateStorageOrder(orderNo, payOrder.PayNo)
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/models"
|
||||||
|
"server/pkg/identity"
|
||||||
|
|
||||||
|
"github.com/beego/beego/v2/client/orm"
|
||||||
|
beego "github.com/beego/beego/v2/server/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PlatformAnalyticsController 平台端数据统计(真实数据,不做任何模拟)
|
||||||
|
type PlatformAnalyticsController struct {
|
||||||
|
beego.Controller
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *PlatformAnalyticsController) analyticsFail(httpStatus, bizCode int, msg string) {
|
||||||
|
c.Ctx.Output.SetStatus(httpStatus)
|
||||||
|
c.Data["json"] = map[string]any{"code": bizCode, "msg": msg}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Users GET /platform/analytics/users
|
||||||
|
//
|
||||||
|
// 统计租户端(backend)真实的用户与租户数据:
|
||||||
|
// - 用户:yz_system_tenant_user(不含已删除)
|
||||||
|
// - 租户:yz_system_tenant(不含已删除)
|
||||||
|
// - 活跃:yz_system_login_log 近 30 天成功登录的去重用户 / 今日登录次数
|
||||||
|
//
|
||||||
|
// 返回:总量、今日/本月新增、近 14 天新增趋势、各租户用户数分布。
|
||||||
|
func (c *PlatformAnalyticsController) Users() {
|
||||||
|
if _, err := requirePlatform(&c.Controller); err != nil {
|
||||||
|
code := identity.Status(err)
|
||||||
|
c.analyticsFail(code, code, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||||
|
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
|
||||||
|
lastMonthStart := monthStart.AddDate(0, -1, 0)
|
||||||
|
trendStart := today.AddDate(0, 0, -13) // 含今天共 14 天
|
||||||
|
activeSince := now.AddDate(0, 0, -30)
|
||||||
|
|
||||||
|
userQuery := func() orm.QuerySeter {
|
||||||
|
return models.Orm.QueryTable(new(models.SystemTenantUser)).
|
||||||
|
Filter("delete_time__isnull", true)
|
||||||
|
}
|
||||||
|
tenantQuery := func() orm.QuerySeter {
|
||||||
|
return models.Orm.QueryTable(new(models.SystemTenant)).
|
||||||
|
Filter("delete_time__isnull", true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 用户 =====
|
||||||
|
totalUsers, _ := userQuery().Count()
|
||||||
|
activeUsers, _ := userQuery().Filter("status", 1).Count()
|
||||||
|
todayNewUsers, _ := userQuery().Filter("create_time__gte", today).Count()
|
||||||
|
monthNewUsers, _ := userQuery().Filter("create_time__gte", monthStart).Count()
|
||||||
|
lastMonthNewUsers, _ := userQuery().
|
||||||
|
Filter("create_time__gte", lastMonthStart).
|
||||||
|
Filter("create_time__lt", monthStart).
|
||||||
|
Count()
|
||||||
|
|
||||||
|
// ===== 租户 =====
|
||||||
|
totalTenants, _ := tenantQuery().Count()
|
||||||
|
activeTenants, _ := tenantQuery().Filter("status", 1).Count()
|
||||||
|
todayNewTenants, _ := tenantQuery().Filter("create_time__gte", today).Count()
|
||||||
|
monthNewTenants, _ := tenantQuery().Filter("create_time__gte", monthStart).Count()
|
||||||
|
|
||||||
|
// ===== 活跃用户(近 30 天成功登录)=====
|
||||||
|
var loginLogs []models.SystemLoginLog
|
||||||
|
_, _ = models.Orm.QueryTable(new(models.SystemLoginLog)).
|
||||||
|
Filter("create_time__gte", activeSince).
|
||||||
|
Filter("status", 1).
|
||||||
|
All(&loginLogs)
|
||||||
|
|
||||||
|
activeUserSet := make(map[uint64]struct{}, len(loginLogs))
|
||||||
|
todayLogins := 0
|
||||||
|
for _, log := range loginLogs {
|
||||||
|
if log.UserID > 0 {
|
||||||
|
activeUserSet[log.UserID] = struct{}{}
|
||||||
|
}
|
||||||
|
if !log.CreateTime.Before(today) {
|
||||||
|
todayLogins++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 近 14 天新增趋势 =====
|
||||||
|
const trendDays = 14
|
||||||
|
days := make([]string, trendDays)
|
||||||
|
dayUsers := make([]int, trendDays)
|
||||||
|
dayTenants := make([]int, trendDays)
|
||||||
|
dayIndex := make(map[string]int, trendDays)
|
||||||
|
for i := 0; i < trendDays; i++ {
|
||||||
|
d := trendStart.AddDate(0, 0, i)
|
||||||
|
key := d.Format("2006-01-02")
|
||||||
|
dayIndex[key] = i
|
||||||
|
days[i] = d.Format("01-02")
|
||||||
|
}
|
||||||
|
|
||||||
|
var recentUsers []models.SystemTenantUser
|
||||||
|
_, _ = userQuery().Filter("create_time__gte", trendStart).All(&recentUsers)
|
||||||
|
for _, u := range recentUsers {
|
||||||
|
if i, ok := dayIndex[u.CreateTime.Format("2006-01-02")]; ok {
|
||||||
|
dayUsers[i]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var recentTenants []models.SystemTenant
|
||||||
|
_, _ = tenantQuery().Filter("create_time__gte", trendStart).All(&recentTenants)
|
||||||
|
for _, t := range recentTenants {
|
||||||
|
if i, ok := dayIndex[t.CreateTime.Format("2006-01-02")]; ok {
|
||||||
|
dayTenants[i]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 各租户用户数分布(Top 8 + 其他)=====
|
||||||
|
var allUsers []models.SystemTenantUser
|
||||||
|
_, _ = userQuery().All(&allUsers)
|
||||||
|
countByTid := make(map[uint64]int, len(allUsers))
|
||||||
|
for _, u := range allUsers {
|
||||||
|
countByTid[u.Tid]++
|
||||||
|
}
|
||||||
|
|
||||||
|
var allTenants []models.SystemTenant
|
||||||
|
_, _ = tenantQuery().All(&allTenants)
|
||||||
|
tenantName := make(map[uint64]string, len(allTenants))
|
||||||
|
for _, t := range allTenants {
|
||||||
|
tenantName[t.ID] = t.TenantName
|
||||||
|
}
|
||||||
|
|
||||||
|
type tenantUserCount struct {
|
||||||
|
ID uint64
|
||||||
|
Name string
|
||||||
|
Value int
|
||||||
|
}
|
||||||
|
dist := make([]tenantUserCount, 0, len(countByTid))
|
||||||
|
for tid, count := range countByTid {
|
||||||
|
name := tenantName[tid]
|
||||||
|
if name == "" {
|
||||||
|
name = "未归属租户"
|
||||||
|
}
|
||||||
|
dist = append(dist, tenantUserCount{ID: tid, Name: name, Value: count})
|
||||||
|
}
|
||||||
|
sort.Slice(dist, func(i, j int) bool {
|
||||||
|
if dist[i].Value != dist[j].Value {
|
||||||
|
return dist[i].Value > dist[j].Value
|
||||||
|
}
|
||||||
|
return dist[i].ID < dist[j].ID
|
||||||
|
})
|
||||||
|
|
||||||
|
const topN = 8
|
||||||
|
tenantUserTop := make([]map[string]any, 0, topN+1)
|
||||||
|
otherCount := 0
|
||||||
|
for i, item := range dist {
|
||||||
|
if i < topN {
|
||||||
|
tenantUserTop = append(tenantUserTop, map[string]any{
|
||||||
|
"name": item.Name,
|
||||||
|
"value": item.Value,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
otherCount += item.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if otherCount > 0 {
|
||||||
|
tenantUserTop = append(tenantUserTop, map[string]any{
|
||||||
|
"name": "其他",
|
||||||
|
"value": otherCount,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 环比(本月新增 vs 上月新增)=====
|
||||||
|
growthPct := 0.0
|
||||||
|
growthUp := true
|
||||||
|
if lastMonthNewUsers > 0 {
|
||||||
|
growthPct = float64(monthNewUsers-lastMonthNewUsers) / float64(lastMonthNewUsers) * 100
|
||||||
|
growthUp = monthNewUsers >= lastMonthNewUsers
|
||||||
|
} else if monthNewUsers > 0 {
|
||||||
|
growthPct = 100
|
||||||
|
}
|
||||||
|
growthPct = math.Round(math.Abs(growthPct)*10) / 10
|
||||||
|
|
||||||
|
c.Data["json"] = map[string]any{
|
||||||
|
"code": 200,
|
||||||
|
"msg": "success",
|
||||||
|
"data": map[string]any{
|
||||||
|
"totalUsers": totalUsers,
|
||||||
|
"activeUsers": activeUsers,
|
||||||
|
"todayNewUsers": todayNewUsers,
|
||||||
|
"monthNewUsers": monthNewUsers,
|
||||||
|
"lastMonthNewUsers": lastMonthNewUsers,
|
||||||
|
"totalTenants": totalTenants,
|
||||||
|
"activeTenants": activeTenants,
|
||||||
|
"todayNewTenants": todayNewTenants,
|
||||||
|
"monthNewTenants": monthNewTenants,
|
||||||
|
"activeUsers30d": len(activeUserSet),
|
||||||
|
"todayLogins": todayLogins,
|
||||||
|
"userGrowthPct": growthPct,
|
||||||
|
"userGrowthUp": growthUp,
|
||||||
|
"tenantUserTop": tenantUserTop,
|
||||||
|
"trend": map[string]any{
|
||||||
|
"days": days,
|
||||||
|
"users": dayUsers,
|
||||||
|
"tenants": dayTenants,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
@@ -0,0 +1,354 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/models"
|
||||||
|
"server/pkg/identity"
|
||||||
|
"server/services"
|
||||||
|
|
||||||
|
beego "github.com/beego/beego/v2/server/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PlatformStorageController 平台端附件空间管理:
|
||||||
|
// 套餐维护、租户空间用量与基础额度调整、订单查询。
|
||||||
|
type PlatformStorageController struct {
|
||||||
|
beego.Controller
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *PlatformStorageController) fail(httpStatus, bizCode int, msg string) {
|
||||||
|
c.Ctx.Output.SetStatus(httpStatus)
|
||||||
|
c.Data["json"] = map[string]any{"code": bizCode, "msg": msg}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *PlatformStorageController) ok(data any) {
|
||||||
|
c.Data["json"] = map[string]any{"code": 200, "msg": "success", "data": data}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *PlatformStorageController) auth() bool {
|
||||||
|
if _, err := requirePlatform(&c.Controller); err != nil {
|
||||||
|
code := identity.Status(err)
|
||||||
|
c.fail(code, code, err.Error())
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type storagePackagePayload struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
CapacityMB int `json:"capacity_mb"`
|
||||||
|
Price *float64 `json:"price"`
|
||||||
|
DurationDays int `json:"duration_days"`
|
||||||
|
Sort int `json:"sort"`
|
||||||
|
Status *int8 `json:"status"`
|
||||||
|
Remark string `json:"remark"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Packages GET /platform/storage/packages 套餐列表(含下架)
|
||||||
|
func (c *PlatformStorageController) Packages() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []models.SystemTenantStoragePackage
|
||||||
|
_, err := models.Orm.QueryTable(new(models.SystemTenantStoragePackage)).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
OrderBy("sort", "id").
|
||||||
|
All(&rows)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "查询失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list := make([]map[string]any, 0, len(rows))
|
||||||
|
for i := range rows {
|
||||||
|
r := &rows[i]
|
||||||
|
list = append(list, map[string]any{
|
||||||
|
"id": r.ID,
|
||||||
|
"name": r.Name,
|
||||||
|
"code": r.Code,
|
||||||
|
"capacity_mb": r.CapacityMB,
|
||||||
|
"price": r.Price,
|
||||||
|
"duration_days": r.DurationDays,
|
||||||
|
"sort": r.Sort,
|
||||||
|
"status": r.Status,
|
||||||
|
"remark": r.Remark,
|
||||||
|
"create_time": r.CreateTime,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.ok(map[string]any{"list": list})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreatePackage POST /platform/storage/package/create
|
||||||
|
func (c *PlatformStorageController) CreatePackage() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var p storagePackagePayload
|
||||||
|
if err := c.BindJSON(&p); err != nil {
|
||||||
|
c.fail(400, 400, "参数错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strings.TrimSpace(p.Name)
|
||||||
|
if name == "" {
|
||||||
|
c.fail(400, 400, "请填写套餐名称")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.CapacityMB <= 0 {
|
||||||
|
c.fail(400, 400, "容量必须大于 0")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status := int8(1)
|
||||||
|
if p.Status != nil {
|
||||||
|
status = *p.Status
|
||||||
|
}
|
||||||
|
duration := p.DurationDays
|
||||||
|
if duration <= 0 {
|
||||||
|
duration = 365
|
||||||
|
}
|
||||||
|
price := 0.0
|
||||||
|
if p.Price != nil && *p.Price > 0 {
|
||||||
|
price = *p.Price
|
||||||
|
}
|
||||||
|
|
||||||
|
row := &models.SystemTenantStoragePackage{
|
||||||
|
Name: name,
|
||||||
|
Code: strings.TrimSpace(p.Code),
|
||||||
|
CapacityMB: p.CapacityMB,
|
||||||
|
Price: price,
|
||||||
|
DurationDays: duration,
|
||||||
|
Sort: p.Sort,
|
||||||
|
Status: status,
|
||||||
|
Remark: strings.TrimSpace(p.Remark),
|
||||||
|
}
|
||||||
|
id, err := models.Orm.Insert(row)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "创建失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(map[string]any{"id": id})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePackage POST /platform/storage/package/:id
|
||||||
|
func (c *PlatformStorageController) UpdatePackage() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.fail(400, 400, "无效的套餐ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var p storagePackagePayload
|
||||||
|
if err := c.BindJSON(&p); err != nil {
|
||||||
|
c.fail(400, 400, "参数错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
update := map[string]any{"update_time": time.Now()}
|
||||||
|
if name := strings.TrimSpace(p.Name); name != "" {
|
||||||
|
update["name"] = name
|
||||||
|
}
|
||||||
|
if p.Code != "" {
|
||||||
|
update["code"] = strings.TrimSpace(p.Code)
|
||||||
|
}
|
||||||
|
if p.CapacityMB > 0 {
|
||||||
|
update["capacity_mb"] = p.CapacityMB
|
||||||
|
}
|
||||||
|
if p.Price != nil {
|
||||||
|
update["price"] = *p.Price
|
||||||
|
}
|
||||||
|
if p.DurationDays > 0 {
|
||||||
|
update["duration_days"] = p.DurationDays
|
||||||
|
}
|
||||||
|
update["sort"] = p.Sort
|
||||||
|
if p.Status != nil {
|
||||||
|
update["status"] = *p.Status
|
||||||
|
}
|
||||||
|
update["remark"] = strings.TrimSpace(p.Remark)
|
||||||
|
|
||||||
|
n, err := models.Orm.QueryTable(new(models.SystemTenantStoragePackage)).
|
||||||
|
Filter("id", id).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
Update(update)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "更新失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
c.fail(404, 404, "套餐不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TogglePackage POST /platform/storage/package/:id/status body: {"status":0|1}
|
||||||
|
func (c *PlatformStorageController) TogglePackage() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.fail(400, 400, "无效的套餐ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var p struct {
|
||||||
|
Status int8 `json:"status"`
|
||||||
|
}
|
||||||
|
if err := c.BindJSON(&p); err != nil {
|
||||||
|
c.fail(400, 400, "参数错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.Status != 0 && p.Status != 1 {
|
||||||
|
c.fail(400, 400, "状态值不合法")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = models.Orm.QueryTable(new(models.SystemTenantStoragePackage)).
|
||||||
|
Filter("id", id).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
Update(map[string]any{"status": p.Status, "update_time": time.Now()})
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "更新失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletePackage DELETE /platform/storage/package/:id
|
||||||
|
func (c *PlatformStorageController) DeletePackage() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.fail(400, 400, "无效的套餐ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n, err := models.Orm.QueryTable(new(models.SystemTenantStoragePackage)).
|
||||||
|
Filter("id", id).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
Update(map[string]any{"delete_time": time.Now(), "update_time": time.Now()})
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "删除失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
c.fail(404, 404, "套餐不存在")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TenantInfo GET /platform/storage/tenant/:tid 租户空间用量
|
||||||
|
func (c *PlatformStorageController) TenantInfo() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tid, err := strconv.ParseUint(c.Ctx.Input.Param(":tid"), 10, 64)
|
||||||
|
if err != nil || tid == 0 {
|
||||||
|
c.fail(400, 400, "无效的租户ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
info, err := services.GetTenantStorageInfo(tid)
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "获取失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ok(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateTenantQuota POST /platform/storage/tenant/:tid/quota body: {"storage_quota_mb": 500}
|
||||||
|
// 平台直接调整租户基础额度(赠送 / 降级),不影响已购买的套餐。
|
||||||
|
func (c *PlatformStorageController) UpdateTenantQuota() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tid, err := strconv.ParseUint(c.Ctx.Input.Param(":tid"), 10, 64)
|
||||||
|
if err != nil || tid == 0 {
|
||||||
|
c.fail(400, 400, "无效的租户ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var p struct {
|
||||||
|
StorageQuotaMB int `json:"storage_quota_mb"`
|
||||||
|
}
|
||||||
|
if err := c.BindJSON(&p); err != nil {
|
||||||
|
c.fail(400, 400, "参数错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.StorageQuotaMB < 0 {
|
||||||
|
c.fail(400, 400, "额度不能为负数")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if p.StorageQuotaMB == 0 {
|
||||||
|
p.StorageQuotaMB = services.DefaultTenantStorageMB
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = models.Orm.QueryTable(new(models.SystemTenant)).
|
||||||
|
Filter("id", tid).
|
||||||
|
Update(map[string]any{"storage_quota_mb": p.StorageQuotaMB})
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "更新失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
info, _ := services.GetTenantStorageInfo(tid)
|
||||||
|
c.ok(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Orders GET /platform/storage/orders?tid=&status=&page=&pageSize=
|
||||||
|
func (c *PlatformStorageController) Orders() {
|
||||||
|
if !c.auth() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, _ := strconv.Atoi(c.GetString("page", "1"))
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
pageSize, _ := strconv.Atoi(c.GetString("pageSize", "10"))
|
||||||
|
if pageSize <= 0 || pageSize > 100 {
|
||||||
|
pageSize = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
qs := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("delete_time__isnull", true)
|
||||||
|
if tid, err := strconv.ParseUint(strings.TrimSpace(c.GetString("tid")), 10, 64); err == nil && tid > 0 {
|
||||||
|
qs = qs.Filter("tid", tid)
|
||||||
|
}
|
||||||
|
if st := strings.TrimSpace(c.GetString("status")); st != "" {
|
||||||
|
qs = qs.Filter("status", st)
|
||||||
|
}
|
||||||
|
|
||||||
|
total, err := qs.Count()
|
||||||
|
if err != nil {
|
||||||
|
c.fail(500, 500, "查询失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []models.SystemTenantStorageOrder
|
||||||
|
if _, err := qs.OrderBy("-id").Offset((page - 1) * pageSize).Limit(pageSize).All(&rows); err != nil {
|
||||||
|
c.fail(500, 500, "查询失败: "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
list := make([]map[string]any, 0, len(rows))
|
||||||
|
for i := range rows {
|
||||||
|
r := &rows[i]
|
||||||
|
list = append(list, map[string]any{
|
||||||
|
"order_no": r.OrderNo,
|
||||||
|
"tid": r.Tid,
|
||||||
|
"package_id": r.PackageID,
|
||||||
|
"package_name": r.PackageName,
|
||||||
|
"capacity_mb": r.CapacityMB,
|
||||||
|
"duration_days": r.DurationDays,
|
||||||
|
"amount": r.Amount,
|
||||||
|
"status": r.Status,
|
||||||
|
"pay_no": r.PayNo,
|
||||||
|
"start_time": r.StartTime,
|
||||||
|
"end_time": r.EndTime,
|
||||||
|
"operator": r.Operator,
|
||||||
|
"create_time": r.CreateTime,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
c.ok(map[string]any{"list": list, "total": total, "page": page, "pageSize": pageSize})
|
||||||
|
}
|
||||||
@@ -40,6 +40,8 @@ type tenantDTO struct {
|
|||||||
DaysRemaining int `json:"days_remaining"`
|
DaysRemaining int `json:"days_remaining"`
|
||||||
UserQuota int `json:"user_quota"`
|
UserQuota int `json:"user_quota"`
|
||||||
UserUsed int `json:"user_used"`
|
UserUsed int `json:"user_used"`
|
||||||
|
// StorageQuotaMB 附件空间基础额度(MB)
|
||||||
|
StorageQuotaMB int `json:"storage_quota_mb"`
|
||||||
Remark string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
CreateTime *time.Time `json:"create_time,omitempty"`
|
CreateTime *time.Time `json:"create_time,omitempty"`
|
||||||
UpdateTime *time.Time `json:"update_time,omitempty"`
|
UpdateTime *time.Time `json:"update_time,omitempty"`
|
||||||
@@ -109,6 +111,7 @@ func toTenantDTO(t models.SystemTenant) tenantDTO {
|
|||||||
PackageExpireTime: t.PackageExpireTime,
|
PackageExpireTime: t.PackageExpireTime,
|
||||||
DaysRemaining: daysRemaining,
|
DaysRemaining: daysRemaining,
|
||||||
UserQuota: t.UserQuota,
|
UserQuota: t.UserQuota,
|
||||||
|
StorageQuotaMB: t.StorageQuotaMB,
|
||||||
Remark: stringValue(t.Remark),
|
Remark: stringValue(t.Remark),
|
||||||
CreateTime: &ct,
|
CreateTime: &ct,
|
||||||
UpdateTime: &ut,
|
UpdateTime: &ut,
|
||||||
@@ -235,6 +238,8 @@ type tenantPayload struct {
|
|||||||
// 套餐与用户数上限(可选)
|
// 套餐与用户数上限(可选)
|
||||||
PackageID *uint64 `json:"package_id"`
|
PackageID *uint64 `json:"package_id"`
|
||||||
UserQuota *int `json:"user_quota"`
|
UserQuota *int `json:"user_quota"`
|
||||||
|
// StorageQuotaMB 附件空间基础额度(MB,可选)
|
||||||
|
StorageQuotaMB *int `json:"storage_quota_mb"`
|
||||||
Remark string `json:"remark"`
|
Remark string `json:"remark"`
|
||||||
|
|
||||||
// 指定租户管理员(可选):把已有认证身份绑定为该租户管理员。
|
// 指定租户管理员(可选):把已有认证身份绑定为该租户管理员。
|
||||||
@@ -274,6 +279,11 @@ func (c *PlatformTenantController) parseTenantPayload() (tenantPayload, error) {
|
|||||||
p.UserQuota = &v
|
p.UserQuota = &v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if s := strings.TrimSpace(c.GetString("storage_quota_mb")); s != "" {
|
||||||
|
if v, err := strconv.Atoi(s); err == nil {
|
||||||
|
p.StorageQuotaMB = &v
|
||||||
|
}
|
||||||
|
}
|
||||||
if s := strings.TrimSpace(c.GetString("admin_identity_id")); s != "" {
|
if s := strings.TrimSpace(c.GetString("admin_identity_id")); s != "" {
|
||||||
if v, err := strconv.ParseUint(s, 10, 64); err == nil {
|
if v, err := strconv.ParseUint(s, 10, 64); err == nil {
|
||||||
p.AdminIdentityID = v
|
p.AdminIdentityID = v
|
||||||
@@ -430,6 +440,11 @@ func (c *PlatformTenantController) CreateTenant() {
|
|||||||
if userQuota <= 0 {
|
if userQuota <= 0 {
|
||||||
userQuota = services.DefaultTenantUserQuota
|
userQuota = services.DefaultTenantUserQuota
|
||||||
}
|
}
|
||||||
|
// 附件空间基础额度:未显式指定时按 500MB
|
||||||
|
storageQuota := services.DefaultTenantStorageMB
|
||||||
|
if p.StorageQuotaMB != nil && *p.StorageQuotaMB > 0 {
|
||||||
|
storageQuota = *p.StorageQuotaMB
|
||||||
|
}
|
||||||
|
|
||||||
t := models.SystemTenant{
|
t := models.SystemTenant{
|
||||||
TenantCode: p.TenantCode,
|
TenantCode: p.TenantCode,
|
||||||
@@ -443,6 +458,7 @@ func (c *PlatformTenantController) CreateTenant() {
|
|||||||
PackageID: packageID,
|
PackageID: packageID,
|
||||||
PackageExpireTime: packageExpire,
|
PackageExpireTime: packageExpire,
|
||||||
UserQuota: userQuota,
|
UserQuota: userQuota,
|
||||||
|
StorageQuotaMB: storageQuota,
|
||||||
Remark: stringPtr(p.Remark),
|
Remark: stringPtr(p.Remark),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -536,6 +552,14 @@ func (c *PlatformTenantController) EditTenant() {
|
|||||||
update["user_quota"] = quota
|
update["user_quota"] = quota
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if p.StorageQuotaMB != nil {
|
||||||
|
// 附件空间基础额度:允许平台赠送/降级;0 视为恢复默认 500MB
|
||||||
|
storageQuota := *p.StorageQuotaMB
|
||||||
|
if storageQuota <= 0 {
|
||||||
|
storageQuota = services.DefaultTenantStorageMB
|
||||||
|
}
|
||||||
|
update["storage_quota_mb"] = storageQuota
|
||||||
|
}
|
||||||
|
|
||||||
_, err = models.Orm.QueryTable(new(models.SystemTenant)).Filter("id", id).Update(update)
|
_, err = models.Orm.QueryTable(new(models.SystemTenant)).Filter("id", id).Update(update)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"server/models"
|
"server/models"
|
||||||
|
"server/pkg/identity"
|
||||||
"server/pkg/passwordutil"
|
"server/pkg/passwordutil"
|
||||||
"server/services"
|
"server/services"
|
||||||
authsvc "server/services/auth"
|
authsvc "server/services/auth"
|
||||||
@@ -95,6 +96,45 @@ type tenantUserPayload struct {
|
|||||||
Remark *string `json:"remark"`
|
Remark *string `json:"remark"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetTenantOrganizations GET /platform/tenantUser/orgs?tid=1
|
||||||
|
// 平台端代租户加用户时,部门下拉必须取「该租户」的组织架构;
|
||||||
|
// 平台自己的组织与租户无关,直接查会一直是空列表。
|
||||||
|
func (c *PlatformTenantUserController) GetTenantOrganizations() {
|
||||||
|
if _, err := requirePlatform(&c.Controller); err != nil {
|
||||||
|
code := identity.Status(err)
|
||||||
|
c.Data["json"] = map[string]interface{}{"code": code, "msg": err.Error()}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tid, _ := c.GetUint64("tid")
|
||||||
|
list := make([]map[string]interface{}, 0)
|
||||||
|
if tid > 0 {
|
||||||
|
var rows []models.BackendOrganization
|
||||||
|
_, _ = models.Orm.QueryTable(new(models.BackendOrganization)).
|
||||||
|
Filter("tid", tid).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
OrderBy("sort", "id").
|
||||||
|
All(&rows)
|
||||||
|
for i := range rows {
|
||||||
|
list = append(list, map[string]interface{}{
|
||||||
|
"id": rows[i].ID,
|
||||||
|
"org_name": rows[i].OrgName,
|
||||||
|
"parent_id": rows[i].ParentID,
|
||||||
|
"sort": rows[i].Sort,
|
||||||
|
"status": rows[i].Status,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = map[string]interface{}{
|
||||||
|
"code": 200,
|
||||||
|
"msg": "success",
|
||||||
|
"data": map[string]interface{}{"list": list},
|
||||||
|
}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
// GetTenantUserList 获取绑定列表(支持按 tid / uid 过滤,keyword 对姓名/手机/邮箱/账号模糊匹配)
|
// GetTenantUserList 获取绑定列表(支持按 tid / uid 过滤,keyword 对姓名/手机/邮箱/账号模糊匹配)
|
||||||
// GET /platform/tenantUser/list?tid=1&uid=2&keyword=xxx
|
// GET /platform/tenantUser/list?tid=1&uid=2&keyword=xxx
|
||||||
func (c *PlatformTenantUserController) GetTenantUserList() {
|
func (c *PlatformTenantUserController) GetTenantUserList() {
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"server/services"
|
||||||
|
|
||||||
|
beego "github.com/beego/beego/v2/server/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StorageQuotaExceededBizCode 附件空间不足的业务码。
|
||||||
|
// 前端据此弹「空间不足,去扩容」,而不是普通错误提示。
|
||||||
|
const StorageQuotaExceededBizCode = 4032
|
||||||
|
|
||||||
|
// respondStorageQuotaError 输出「附件空间不足」响应。
|
||||||
|
// 返回 true 表示已写入响应,调用方必须立即 return。
|
||||||
|
func respondStorageQuotaError(c *beego.Controller, err error) bool {
|
||||||
|
quotaErr, ok := err.(*services.StorageQuotaExceededError)
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
c.Ctx.Output.SetStatus(403)
|
||||||
|
c.Data["json"] = map[string]interface{}{
|
||||||
|
"code": StorageQuotaExceededBizCode,
|
||||||
|
"msg": quotaErr.Error(),
|
||||||
|
"data": map[string]interface{}{
|
||||||
|
"used_bytes": quotaErr.UsedBytes,
|
||||||
|
"quota_bytes": quotaErr.QuotaBytes,
|
||||||
|
"required_bytes": quotaErr.RequiredBytes,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
_ = c.ServeJSON()
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- 租户附件空间(配额 + 单独计费的存储套餐)
|
||||||
|
--
|
||||||
|
-- 1) yz_system_tenant 增加基础额度 storage_quota_mb(默认 500MB)
|
||||||
|
-- 2) 存储套餐表 yz_system_tenant_storage_package(平台自由维护)
|
||||||
|
-- 3) 存储订单表 yz_system_tenant_storage_order(接支付,支付成功自动开通)
|
||||||
|
-- 4) 菜单:租户端「存储空间」、平台端「存储套餐」
|
||||||
|
--
|
||||||
|
-- 说明:
|
||||||
|
-- 1. ALTER 语句不可重复执行;若报「Duplicate column name」说明已加过,可忽略。
|
||||||
|
-- 2. CREATE TABLE 使用 IF NOT EXISTS,可重复执行。
|
||||||
|
-- 3. 菜单按 path 判重,可重复执行。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- ---------- 1. 租户基础额度 ----------
|
||||||
|
ALTER TABLE yz_system_tenant
|
||||||
|
ADD COLUMN storage_quota_mb INT NOT NULL DEFAULT 500
|
||||||
|
COMMENT '基础附件空间MB(不含已购存储套餐;实际可用=max(本值, 生效套餐容量))';
|
||||||
|
|
||||||
|
-- 存量租户初始化为 500MB(新增列默认值即可,这里兜底一次)
|
||||||
|
UPDATE yz_system_tenant SET storage_quota_mb = 500 WHERE storage_quota_mb IS NULL OR storage_quota_mb = 0;
|
||||||
|
|
||||||
|
-- ---------- 2. 存储套餐 ----------
|
||||||
|
CREATE TABLE IF NOT EXISTS yz_system_tenant_storage_package (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
name VARCHAR(64) NOT NULL DEFAULT '' COMMENT '套餐名称,如 5GB / 20GB',
|
||||||
|
code VARCHAR(64) NOT NULL DEFAULT '' COMMENT '套餐编码(可选)',
|
||||||
|
capacity_mb INT NOT NULL DEFAULT 0 COMMENT '容量(MB)',
|
||||||
|
price DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '价格(元/周期)',
|
||||||
|
duration_days INT NOT NULL DEFAULT 365 COMMENT '有效天数',
|
||||||
|
sort INT NOT NULL DEFAULT 0 COMMENT '排序(升序)',
|
||||||
|
status TINYINT NOT NULL DEFAULT 1 COMMENT '1 上架 0 下架',
|
||||||
|
remark VARCHAR(255) NOT NULL DEFAULT '' COMMENT '备注',
|
||||||
|
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
update_time DATETIME NULL,
|
||||||
|
delete_time DATETIME NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
KEY idx_status_sort (status, sort)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='租户附件空间套餐';
|
||||||
|
|
||||||
|
-- ---------- 3. 存储订单 ----------
|
||||||
|
CREATE TABLE IF NOT EXISTS yz_system_tenant_storage_order (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
order_no VARCHAR(64) NOT NULL COMMENT '业务订单号(支付 out_trade_no)',
|
||||||
|
tid BIGINT UNSIGNED NOT NULL COMMENT '租户ID',
|
||||||
|
package_id BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '套餐ID',
|
||||||
|
package_name VARCHAR(64) NOT NULL DEFAULT '' COMMENT '套餐名称快照',
|
||||||
|
capacity_mb INT NOT NULL DEFAULT 0 COMMENT '容量快照(MB)',
|
||||||
|
duration_days INT NOT NULL DEFAULT 365 COMMENT '时长快照(天)',
|
||||||
|
amount DECIMAL(10,2) NOT NULL DEFAULT 0 COMMENT '金额(元)',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/paid/cancelled/replaced',
|
||||||
|
pay_no VARCHAR(40) NOT NULL DEFAULT '' COMMENT '支付单号',
|
||||||
|
start_time DATETIME NULL COMMENT '生效时间',
|
||||||
|
end_time DATETIME NULL COMMENT '到期时间',
|
||||||
|
operator VARCHAR(64) NOT NULL DEFAULT '' COMMENT '下单人',
|
||||||
|
remark VARCHAR(255) NOT NULL DEFAULT '' COMMENT '备注',
|
||||||
|
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
update_time DATETIME NULL,
|
||||||
|
delete_time DATETIME NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
UNIQUE KEY uk_order_no (order_no),
|
||||||
|
KEY idx_tid_status (tid, status),
|
||||||
|
KEY idx_tid_end (tid, end_time)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='租户附件空间订单';
|
||||||
|
|
||||||
|
-- 文件表补索引:按租户统计已用空间(SUM(size))
|
||||||
|
-- 已存在同名索引时报 Duplicate key name,可忽略。
|
||||||
|
ALTER TABLE yz_system_files ADD INDEX idx_tid_source_size (tid, source, size);
|
||||||
|
|
||||||
|
-- ---------- 4. 菜单 ----------
|
||||||
|
-- 4.1 租户端「存储空间」:挂到租户端「基础设置」下
|
||||||
|
INSERT INTO yz_system_menu
|
||||||
|
(pid, title, path, component_path, icon, sort, status, is_visible, views, type, creater, remark)
|
||||||
|
SELECT
|
||||||
|
(SELECT id FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings' AND delete_time IS NULL ORDER BY id LIMIT 1) b),
|
||||||
|
'存储空间', '/basicSettings/storage', '/basicSettings/storage/index.vue',
|
||||||
|
'Coin', 95, 1, 1, '[2]', 2, 'system',
|
||||||
|
'附件空间用量、套餐购买与购买记录'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings' AND delete_time IS NULL) b)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings/storage' AND delete_time IS NULL) e);
|
||||||
|
|
||||||
|
INSERT INTO yz_system_menu
|
||||||
|
(pid, title, path, component_path, icon, sort, status, is_visible, views, type, creater, remark)
|
||||||
|
SELECT 0, '存储空间', '/basicSettings/storage', '/basicSettings/storage/index.vue',
|
||||||
|
'Coin', 95, 1, 1, '[2]', 2, 'system',
|
||||||
|
'附件空间用量、套餐购买与购买记录'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings' AND delete_time IS NULL) b)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings/storage' AND delete_time IS NULL) e);
|
||||||
|
|
||||||
|
-- 4.2 平台端「存储套餐」:挂到平台端「基础设置」下
|
||||||
|
INSERT INTO yz_system_menu
|
||||||
|
(pid, title, path, component_path, icon, sort, status, is_visible, views, type, creater, remark)
|
||||||
|
SELECT
|
||||||
|
(SELECT id FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings' AND delete_time IS NULL ORDER BY id LIMIT 1) b),
|
||||||
|
'存储套餐', '/basicSettings/storagePackage', '/basicSettings/storagePackage/index.vue',
|
||||||
|
'Coin', 96, 1, 1, '[1]', 2, 'system',
|
||||||
|
'附件空间套餐维护:容量 / 价格 / 时长'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings' AND delete_time IS NULL) b)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings/storagePackage' AND delete_time IS NULL) e);
|
||||||
|
|
||||||
|
INSERT INTO yz_system_menu
|
||||||
|
(pid, title, path, component_path, icon, sort, status, is_visible, views, type, creater, remark)
|
||||||
|
SELECT 0, '存储套餐', '/basicSettings/storagePackage', '/basicSettings/storagePackage/index.vue',
|
||||||
|
'Coin', 96, 1, 1, '[1]', 2, 'system',
|
||||||
|
'附件空间套餐维护:容量 / 价格 / 时长'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings' AND delete_time IS NULL) b)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_menu WHERE path = '/basicSettings/storagePackage' AND delete_time IS NULL) e);
|
||||||
|
|
||||||
|
-- ---------- 5. 预置套餐(价格请按实际调整;同 code 重复执行不会插入) ----------
|
||||||
|
INSERT INTO yz_system_tenant_storage_package
|
||||||
|
(name, code, capacity_mb, price, duration_days, sort, status, remark)
|
||||||
|
SELECT '5GB', 'storage_5g', 5120, 100.00, 365, 1, 1, '5GB / 年'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_tenant_storage_package WHERE code = 'storage_5g' AND delete_time IS NULL) e);
|
||||||
|
|
||||||
|
INSERT INTO yz_system_tenant_storage_package
|
||||||
|
(name, code, capacity_mb, price, duration_days, sort, status, remark)
|
||||||
|
SELECT '20GB', 'storage_20g', 20480, 300.00, 365, 2, 1, '20GB / 年'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_tenant_storage_package WHERE code = 'storage_20g' AND delete_time IS NULL) e);
|
||||||
|
|
||||||
|
INSERT INTO yz_system_tenant_storage_package
|
||||||
|
(name, code, capacity_mb, price, duration_days, sort, status, remark)
|
||||||
|
SELECT '50GB', 'storage_50g', 51200, 600.00, 365, 3, 1, '50GB / 年'
|
||||||
|
FROM DUAL
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM (SELECT id FROM yz_system_tenant_storage_package WHERE code = 'storage_50g' AND delete_time IS NULL) e);
|
||||||
@@ -40,6 +40,9 @@ func Init(_ string) {
|
|||||||
new(SystemTenantPackageModule),
|
new(SystemTenantPackageModule),
|
||||||
new(SystemTenantUserQuotaPackage),
|
new(SystemTenantUserQuotaPackage),
|
||||||
new(SystemTenantQuotaOrder),
|
new(SystemTenantQuotaOrder),
|
||||||
|
// 租户附件空间套餐 / 订单(docs/sql/create_tenant_storage.sql)
|
||||||
|
new(SystemTenantStoragePackage),
|
||||||
|
new(SystemTenantStorageOrder),
|
||||||
// 产品定价(docs/sql/create_platform_product_pricing.sql)
|
// 产品定价(docs/sql/create_platform_product_pricing.sql)
|
||||||
new(PlatformProduct),
|
new(PlatformProduct),
|
||||||
new(PlatformProductFeature),
|
new(PlatformProductFeature),
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ type SystemTenant struct {
|
|||||||
PackageExpireTime *time.Time `orm:"column(package_expire_time);type(datetime);null" json:"package_expire_time"`
|
PackageExpireTime *time.Time `orm:"column(package_expire_time);type(datetime);null" json:"package_expire_time"`
|
||||||
// UserQuota 用户数上限:默认 20,增购后累加。租户用户数达到上限后不允许再新增账号。
|
// UserQuota 用户数上限:默认 20,增购后累加。租户用户数达到上限后不允许再新增账号。
|
||||||
UserQuota int `orm:"column(user_quota);default(20)" json:"user_quota"`
|
UserQuota int `orm:"column(user_quota);default(20)" json:"user_quota"`
|
||||||
|
// StorageQuotaMB 基础附件空间(MB),默认 500。
|
||||||
|
// 租户实际可用空间 = max(StorageQuotaMB, 生效中的附件空间套餐容量)。
|
||||||
|
StorageQuotaMB int `orm:"column(storage_quota_mb);default(500)" json:"storage_quota_mb"`
|
||||||
Remark *string `orm:"column(remark);size(512);null" json:"remark"`
|
Remark *string `orm:"column(remark);size(512);null" json:"remark"`
|
||||||
CreateTime time.Time `orm:"column(create_time);auto_now_add;type(datetime)" json:"create_time"`
|
CreateTime time.Time `orm:"column(create_time);auto_now_add;type(datetime)" json:"create_time"`
|
||||||
UpdateTime time.Time `orm:"column(update_time);auto_now;type(datetime)" json:"update_time"`
|
UpdateTime time.Time `orm:"column(update_time);auto_now;type(datetime)" json:"update_time"`
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// 附件空间订单状态
|
||||||
|
const (
|
||||||
|
StorageOrderPending = "pending" // 待支付
|
||||||
|
StorageOrderPaid = "paid" // 已支付(生效中)
|
||||||
|
StorageOrderCancelled = "cancelled" // 已取消
|
||||||
|
StorageOrderReplaced = "replaced" // 被新套餐替换
|
||||||
|
)
|
||||||
|
|
||||||
|
// SystemTenantStoragePackage 租户附件空间套餐 yz_system_tenant_storage_package
|
||||||
|
//
|
||||||
|
// 与功能套餐(yz_system_tenant_package)相互独立:
|
||||||
|
// 功能套餐决定可用模块与用户数;附件空间套餐只决定容量,单独计费、单独计时长。
|
||||||
|
type SystemTenantStoragePackage struct {
|
||||||
|
ID uint64 `orm:"column(id);pk;auto" json:"id"`
|
||||||
|
Name string `orm:"column(name);size(64)" json:"name"`
|
||||||
|
Code string `orm:"column(code);size(64)" json:"code"`
|
||||||
|
CapacityMB int `orm:"column(capacity_mb);default(0)" json:"capacity_mb"` // 容量(MB)
|
||||||
|
Price float64 `orm:"column(price);digits(10);decimals(2)" json:"price"` // 价格(元/周期)
|
||||||
|
DurationDays int `orm:"column(duration_days);default(365)" json:"duration_days"`
|
||||||
|
Sort int `orm:"column(sort);default(0)" json:"sort"`
|
||||||
|
Status int8 `orm:"column(status);default(1)" json:"status"` // 1上架 0下架
|
||||||
|
Remark string `orm:"column(remark);size(255)" json:"remark"`
|
||||||
|
CreateTime time.Time `orm:"column(create_time);type(datetime);auto_now_add" json:"create_time"`
|
||||||
|
UpdateTime *time.Time `orm:"column(update_time);type(datetime);null" json:"update_time"`
|
||||||
|
DeleteTime *time.Time `orm:"column(delete_time);type(datetime);null" json:"delete_time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *SystemTenantStoragePackage) TableName() string {
|
||||||
|
return "yz_system_tenant_storage_package"
|
||||||
|
}
|
||||||
|
|
||||||
|
// SystemTenantStorageOrder 租户附件空间订单 yz_system_tenant_storage_order
|
||||||
|
//
|
||||||
|
// 一条已支付且未过期的订单即一份生效套餐。
|
||||||
|
// 「只保留最大的一个」:购买不同规格时,旧的已支付订单置为 replaced;
|
||||||
|
// 续费同规格时在现有到期时间上顺延。
|
||||||
|
type SystemTenantStorageOrder struct {
|
||||||
|
ID uint64 `orm:"column(id);pk;auto" json:"id"`
|
||||||
|
OrderNo string `orm:"column(order_no);size(64)" json:"order_no"`
|
||||||
|
Tid uint64 `orm:"column(tid)" json:"tid"`
|
||||||
|
PackageID uint64 `orm:"column(package_id);default(0)" json:"package_id"`
|
||||||
|
PackageName string `orm:"column(package_name);size(64)" json:"package_name"`
|
||||||
|
CapacityMB int `orm:"column(capacity_mb);default(0)" json:"capacity_mb"`
|
||||||
|
DurationDays int `orm:"column(duration_days);default(365)" json:"duration_days"`
|
||||||
|
Amount float64 `orm:"column(amount);digits(10);decimals(2)" json:"amount"`
|
||||||
|
Status string `orm:"column(status);size(20);default(pending)" json:"status"`
|
||||||
|
PayNo string `orm:"column(pay_no);size(40)" json:"pay_no"`
|
||||||
|
StartTime *time.Time `orm:"column(start_time);type(datetime);null" json:"start_time"`
|
||||||
|
EndTime *time.Time `orm:"column(end_time);type(datetime);null" json:"end_time"`
|
||||||
|
Operator string `orm:"column(operator);size(64)" json:"operator"`
|
||||||
|
Remark string `orm:"column(remark);size(255)" json:"remark"`
|
||||||
|
CreateTime time.Time `orm:"column(create_time);type(datetime);auto_now_add" json:"create_time"`
|
||||||
|
UpdateTime *time.Time `orm:"column(update_time);type(datetime);null" json:"update_time"`
|
||||||
|
DeleteTime *time.Time `orm:"column(delete_time);type(datetime);null" json:"delete_time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *SystemTenantStorageOrder) TableName() string {
|
||||||
|
return "yz_system_tenant_storage_order"
|
||||||
|
}
|
||||||
@@ -157,6 +157,13 @@ func RegisterAuthRoutes() {
|
|||||||
beego.Router("/backend/uploadavatar/:id", &controllers.BackendFileController{}, "post:UpdateAvatar")
|
beego.Router("/backend/uploadavatar/:id", &controllers.BackendFileController{}, "post:UpdateAvatar")
|
||||||
beego.Router("/backend/batchdeletefiles", &controllers.BackendFileController{}, "post:BatchDeleteFiles")
|
beego.Router("/backend/batchdeletefiles", &controllers.BackendFileController{}, "post:BatchDeleteFiles")
|
||||||
beego.Router("/backend/batchDeleteFilesPermanently", &controllers.BackendFileController{}, "post:BatchDeleteFilesPermanently")
|
beego.Router("/backend/batchDeleteFilesPermanently", &controllers.BackendFileController{}, "post:BatchDeleteFilesPermanently")
|
||||||
|
|
||||||
|
// 附件空间:用量 / 可购套餐 / 下单支付 / 购买记录
|
||||||
|
beego.Router("/backend/tenant/storageInfo", &controllers.BackendStorageController{}, "get:StorageInfo")
|
||||||
|
beego.Router("/backend/tenant/storagePackages", &controllers.BackendStorageController{}, "get:Packages")
|
||||||
|
beego.Router("/backend/tenant/storage/order", &controllers.BackendStorageController{}, "post:CreateOrder")
|
||||||
|
beego.Router("/backend/tenant/storage/orders", &controllers.BackendStorageController{}, "get:Orders")
|
||||||
|
beego.Router("/backend/tenant/storage/order/:orderNo", &controllers.BackendStorageController{}, "get:OrderDetail")
|
||||||
beego.Router("/backend/batchMoveFiles", &controllers.BackendFileController{}, "post:BatchMoveFiles")
|
beego.Router("/backend/batchMoveFiles", &controllers.BackendFileController{}, "post:BatchMoveFiles")
|
||||||
|
|
||||||
// 模块接口
|
// 模块接口
|
||||||
|
|||||||
@@ -71,6 +71,19 @@ func Register() {
|
|||||||
beego.Router("/platform/register", &controllers.PlatformAuthController{}, "post:Register")
|
beego.Router("/platform/register", &controllers.PlatformAuthController{}, "post:Register")
|
||||||
beego.Router("/platform/sendRegisterCode", &controllers.PlatformAuthController{}, "post:SendRegisterCode")
|
beego.Router("/platform/sendRegisterCode", &controllers.PlatformAuthController{}, "post:SendRegisterCode")
|
||||||
|
|
||||||
|
// 数据统计(租户端用户 / 租户真实数据)
|
||||||
|
beego.Router("/platform/analytics/users", &controllers.PlatformAnalyticsController{}, "get:Users")
|
||||||
|
|
||||||
|
// 附件空间:套餐维护 / 租户额度 / 订单
|
||||||
|
beego.Router("/platform/storage/packages", &controllers.PlatformStorageController{}, "get:Packages")
|
||||||
|
beego.Router("/platform/storage/package/create", &controllers.PlatformStorageController{}, "post:CreatePackage")
|
||||||
|
beego.Router("/platform/storage/package/:id", &controllers.PlatformStorageController{}, "post:UpdatePackage")
|
||||||
|
beego.Router("/platform/storage/package/:id/status", &controllers.PlatformStorageController{}, "post:TogglePackage")
|
||||||
|
beego.Router("/platform/storage/package/:id/delete", &controllers.PlatformStorageController{}, "delete:DeletePackage")
|
||||||
|
beego.Router("/platform/storage/tenant/:tid", &controllers.PlatformStorageController{}, "get:TenantInfo")
|
||||||
|
beego.Router("/platform/storage/tenant/:tid/quota", &controllers.PlatformStorageController{}, "post:UpdateTenantQuota")
|
||||||
|
beego.Router("/platform/storage/orders", &controllers.PlatformStorageController{}, "get:Orders")
|
||||||
|
|
||||||
// 平台菜单配置相关
|
// 平台菜单配置相关
|
||||||
beego.Router("/platform/menu/:id", &controllers.AdminMenuController{}, "get:GetMenu")
|
beego.Router("/platform/menu/:id", &controllers.AdminMenuController{}, "get:GetMenu")
|
||||||
beego.Router("/platform/allmenu", &controllers.AdminMenuController{}, "get:GetAllMenus")
|
beego.Router("/platform/allmenu", &controllers.AdminMenuController{}, "get:GetAllMenus")
|
||||||
@@ -96,6 +109,7 @@ func Register() {
|
|||||||
// 平台租户用户绑定相关
|
// 平台租户用户绑定相关
|
||||||
beego.Router("/platform/getTenantUsers/:tid", &controllers.PlatformTenantUserController{}, "get:GetTenantUsersByTid")
|
beego.Router("/platform/getTenantUsers/:tid", &controllers.PlatformTenantUserController{}, "get:GetTenantUsersByTid")
|
||||||
beego.Router("/platform/tenantUser/list", &controllers.PlatformTenantUserController{}, "get:GetTenantUserList")
|
beego.Router("/platform/tenantUser/list", &controllers.PlatformTenantUserController{}, "get:GetTenantUserList")
|
||||||
|
beego.Router("/platform/tenantUser/orgs", &controllers.PlatformTenantUserController{}, "get:GetTenantOrganizations")
|
||||||
beego.Router("/platform/tenantUser/detail/:id", &controllers.PlatformTenantUserController{}, "get:GetTenantUserDetail")
|
beego.Router("/platform/tenantUser/detail/:id", &controllers.PlatformTenantUserController{}, "get:GetTenantUserDetail")
|
||||||
beego.Router("/platform/tenantUser/create", &controllers.PlatformTenantUserController{}, "post:CreateTenantUser")
|
beego.Router("/platform/tenantUser/create", &controllers.PlatformTenantUserController{}, "post:CreateTenantUser")
|
||||||
beego.Router("/platform/tenantUser/edit/:id", &controllers.PlatformTenantUserController{}, "post:EditTenantUser")
|
beego.Router("/platform/tenantUser/edit/:id", &controllers.PlatformTenantUserController{}, "post:EditTenantUser")
|
||||||
|
|||||||
@@ -723,6 +723,8 @@ func ApproveCreateApply(applyID, reviewerID uint64, reviewerName string) (tid ui
|
|||||||
if tenant.UserQuota <= 0 {
|
if tenant.UserQuota <= 0 {
|
||||||
tenant.UserQuota = DefaultTenantUserQuota
|
tenant.UserQuota = DefaultTenantUserQuota
|
||||||
}
|
}
|
||||||
|
// 附件空间默认额度:500MB,超出需购买扩容套餐
|
||||||
|
tenant.StorageQuotaMB = DefaultTenantStorageMB
|
||||||
newID, err := models.Orm.Insert(tenant)
|
newID, err := models.Orm.Insert(tenant)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, errors.New("创建租户失败:" + err.Error())
|
return 0, errors.New("创建租户失败:" + err.Error())
|
||||||
|
|||||||
@@ -31,12 +31,33 @@ type OrderSyncFunc func(ctx context.Context, order *models.PlatformPaymentOrder)
|
|||||||
type PromoterResolveFunc func(ctx context.Context, order *models.PlatformPaymentOrder) (promoterID, promoterName, promoterType string, ok bool)
|
type PromoterResolveFunc func(ctx context.Context, order *models.PlatformPaymentOrder) (promoterID, promoterName, promoterType string, ok bool)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
orderSyncHook OrderSyncFunc
|
// 业务订单同步钩子可以有多个(产品订单、附件空间订单等),
|
||||||
|
// 逐个执行;任何一个失败都会保留 order_synced=0 由补偿任务重试。
|
||||||
|
orderSyncHooks []OrderSyncFunc
|
||||||
promoterResolve PromoterResolveFunc
|
promoterResolve PromoterResolveFunc
|
||||||
)
|
)
|
||||||
|
|
||||||
// RegisterOrderSyncHook 注册业务订单同步钩子(在业务模块 init 时调用)
|
// RegisterOrderSyncHook 注册业务订单同步钩子(在业务模块 init 时调用)
|
||||||
func RegisterOrderSyncHook(fn OrderSyncFunc) { orderSyncHook = fn }
|
// 支持多个模块分别注册,互不覆盖。
|
||||||
|
func RegisterOrderSyncHook(fn OrderSyncFunc) {
|
||||||
|
if fn != nil {
|
||||||
|
orderSyncHooks = append(orderSyncHooks, fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runOrderSyncHooks 依次执行所有业务同步钩子,返回第一个错误(便于补偿重试)
|
||||||
|
func runOrderSyncHooks(ctx context.Context, order *models.PlatformPaymentOrder) error {
|
||||||
|
var firstErr error
|
||||||
|
for _, fn := range orderSyncHooks {
|
||||||
|
if fn == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := fn(ctx, order); err != nil && firstErr == nil {
|
||||||
|
firstErr = err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return firstErr
|
||||||
|
}
|
||||||
|
|
||||||
// RegisterPromoterResolver 注册推广方解析钩子
|
// RegisterPromoterResolver 注册推广方解析钩子
|
||||||
func RegisterPromoterResolver(fn PromoterResolveFunc) { promoterResolve = fn }
|
func RegisterPromoterResolver(fn PromoterResolveFunc) { promoterResolve = fn }
|
||||||
@@ -374,11 +395,11 @@ func applyChannelState(ctx context.Context, order *models.PlatformPaymentOrder,
|
|||||||
LogStateChange(order.PayNo, models.PayStatusPaying, models.PayStatusPaid, operator, note)
|
LogStateChange(order.PayNo, models.PayStatusPaying, models.PayStatusPaid, operator, note)
|
||||||
|
|
||||||
// 1. 同步业务订单状态(钩子;失败保留 order_synced=0 由补偿任务重试)
|
// 1. 同步业务订单状态(钩子;失败保留 order_synced=0 由补偿任务重试)
|
||||||
if orderSyncHook == nil {
|
if len(orderSyncHooks) == 0 {
|
||||||
_, _ = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
_, _ = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||||
Filter("id", order.ID).
|
Filter("id", order.ID).
|
||||||
Update(orm.Params{"order_synced": 1, "update_time": time.Now()})
|
Update(orm.Params{"order_synced": 1, "update_time": time.Now()})
|
||||||
} else if serr := orderSyncHook(ctx, order); serr != nil {
|
} else if serr := runOrderSyncHooks(ctx, order); serr != nil {
|
||||||
LogStateChange(order.PayNo, models.PayStatusPaid, models.PayStatusPaid, operator, "业务订单同步失败:"+serr.Error())
|
LogStateChange(order.PayNo, models.PayStatusPaid, models.PayStatusPaid, operator, "业务订单同步失败:"+serr.Error())
|
||||||
} else {
|
} else {
|
||||||
_, _ = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
_, _ = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||||
@@ -559,7 +580,7 @@ func CloseExpiredOrders(ctx context.Context) (int, error) {
|
|||||||
|
|
||||||
// SyncPendingOrders 重试同步「已支付但业务订单未更新」的支付单(补偿任务),返回处理数量
|
// SyncPendingOrders 重试同步「已支付但业务订单未更新」的支付单(补偿任务),返回处理数量
|
||||||
func SyncPendingOrders(ctx context.Context) (int, error) {
|
func SyncPendingOrders(ctx context.Context) (int, error) {
|
||||||
if orderSyncHook == nil {
|
if len(orderSyncHooks) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
var orders []models.PlatformPaymentOrder
|
var orders []models.PlatformPaymentOrder
|
||||||
@@ -573,7 +594,7 @@ func SyncPendingOrders(ctx context.Context) (int, error) {
|
|||||||
}
|
}
|
||||||
done := 0
|
done := 0
|
||||||
for i := range orders {
|
for i := range orders {
|
||||||
if serr := orderSyncHook(ctx, &orders[i]); serr != nil {
|
if serr := runOrderSyncHooks(ctx, &orders[i]); serr != nil {
|
||||||
beelog.Warn("支付单 %s 业务订单同步重试失败: %v", orders[i].PayNo, serr)
|
beelog.Warn("支付单 %s 业务订单同步重试失败: %v", orders[i].PayNo, serr)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,278 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"server/models"
|
||||||
|
|
||||||
|
"github.com/beego/beego/v2/client/orm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultTenantStorageMB 租户默认附件空间(MB)。
|
||||||
|
// 未配置基础额度、也没买套餐时按 500MB 兜底。
|
||||||
|
const DefaultTenantStorageMB = 500
|
||||||
|
|
||||||
|
const bytesPerMB = 1024 * 1024
|
||||||
|
|
||||||
|
// StorageQuotaExceededError 附件空间不足
|
||||||
|
type StorageQuotaExceededError struct {
|
||||||
|
UsedBytes uint64
|
||||||
|
QuotaBytes uint64
|
||||||
|
RequiredBytes uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *StorageQuotaExceededError) Error() string {
|
||||||
|
return fmt.Sprintf(
|
||||||
|
"附件空间不足:已用 %.2fMB / 共 %.2fMB,本次需要 %.2fMB,请购买扩容",
|
||||||
|
float64(e.UsedBytes)/bytesPerMB,
|
||||||
|
float64(e.QuotaBytes)/bytesPerMB,
|
||||||
|
float64(e.RequiredBytes)/bytesPerMB,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TenantStorageInfo 租户附件空间使用情况
|
||||||
|
type TenantStorageInfo struct {
|
||||||
|
Tid uint64 `json:"tid"`
|
||||||
|
|
||||||
|
BaseQuotaMB int `json:"base_quota_mb"` // 基础额度(租户字段,默认 500)
|
||||||
|
PackageQuotaMB int `json:"package_quota_mb"` // 生效套餐容量(无套餐为 0)
|
||||||
|
QuotaMB int `json:"quota_mb"` // 实际可用 = max(基础, 套餐)
|
||||||
|
UsedBytes uint64 `json:"used_bytes"`
|
||||||
|
QuotaBytes uint64 `json:"quota_bytes"`
|
||||||
|
RemainingBytes uint64 `json:"remaining_bytes"`
|
||||||
|
UsedPercent float64 `json:"used_percent"`
|
||||||
|
|
||||||
|
PackageID uint64 `json:"package_id"`
|
||||||
|
PackageName string `json:"package_name"`
|
||||||
|
ExpireTime *time.Time `json:"expire_time"`
|
||||||
|
DaysRemaining int `json:"days_remaining"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SumTenantStorageUsed 统计租户已用附件空间(字节)。
|
||||||
|
//
|
||||||
|
// 注意:这里**不过滤 delete_time**。
|
||||||
|
// 软删除只是标记 delete_time(回收站),记录仍然存在、磁盘仍然占用;
|
||||||
|
// 只有「彻底删除」才会物理删行,此时统计自然减少 —— 即“彻底删除才释放空间”。
|
||||||
|
// 只统计租户端上传(source=backend)的文件:平台端上传不占租户额度。
|
||||||
|
func SumTenantStorageUsed(tid uint64) (uint64, error) {
|
||||||
|
if tid == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
var rows []orm.Params
|
||||||
|
_, err := models.Orm.Raw(
|
||||||
|
"SELECT COALESCE(SUM(size), 0) AS total FROM yz_system_files WHERE tid = ? AND source = ?",
|
||||||
|
tid, models.FileSourceBackend,
|
||||||
|
).Values(&rows)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
return toUint64(rows[0]["total"]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// toUint64 兼容驱动返回的 int64 / uint64 / []byte / string
|
||||||
|
func toUint64(v interface{}) uint64 {
|
||||||
|
switch n := v.(type) {
|
||||||
|
case int64:
|
||||||
|
if n < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return uint64(n)
|
||||||
|
case uint64:
|
||||||
|
return n
|
||||||
|
case int:
|
||||||
|
if n < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return uint64(n)
|
||||||
|
case []byte:
|
||||||
|
var out uint64
|
||||||
|
_, _ = fmt.Sscan(string(n), &out)
|
||||||
|
return out
|
||||||
|
case string:
|
||||||
|
var out uint64
|
||||||
|
_, _ = fmt.Sscan(n, &out)
|
||||||
|
return out
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetActiveStorageOrder 取租户当前生效的附件空间订单。
|
||||||
|
// 正常情况下同一时刻只有一条(购买不同规格时旧的会被置为 replaced),
|
||||||
|
// 这里按容量倒序取第一条,兼容历史数据。
|
||||||
|
func GetActiveStorageOrder(tid uint64) (*models.SystemTenantStorageOrder, error) {
|
||||||
|
if tid == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
var order models.SystemTenantStorageOrder
|
||||||
|
err := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("tid", tid).
|
||||||
|
Filter("status", models.StorageOrderPaid).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
Filter("end_time__gt", now).
|
||||||
|
OrderBy("-capacity_mb", "-id").
|
||||||
|
One(&order)
|
||||||
|
if err == orm.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &order, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTenantStorageInfo 查询租户附件空间使用情况
|
||||||
|
func GetTenantStorageInfo(tid uint64) (*TenantStorageInfo, error) {
|
||||||
|
info := &TenantStorageInfo{Tid: tid, BaseQuotaMB: DefaultTenantStorageMB}
|
||||||
|
|
||||||
|
var tenant models.SystemTenant
|
||||||
|
if err := models.Orm.QueryTable(new(models.SystemTenant)).
|
||||||
|
Filter("id", tid).
|
||||||
|
One(&tenant); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if tenant.StorageQuotaMB > 0 {
|
||||||
|
info.BaseQuotaMB = tenant.StorageQuotaMB
|
||||||
|
}
|
||||||
|
|
||||||
|
order, err := GetActiveStorageOrder(tid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if order != nil {
|
||||||
|
info.PackageID = order.PackageID
|
||||||
|
info.PackageName = order.PackageName
|
||||||
|
info.PackageQuotaMB = order.CapacityMB
|
||||||
|
info.ExpireTime = order.EndTime
|
||||||
|
if order.EndTime != nil {
|
||||||
|
days := int(math.Ceil(order.EndTime.Sub(time.Now()).Hours() / 24))
|
||||||
|
if days < 0 {
|
||||||
|
days = 0
|
||||||
|
}
|
||||||
|
info.DaysRemaining = days
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
info.QuotaMB = info.BaseQuotaMB
|
||||||
|
if info.PackageQuotaMB > info.QuotaMB {
|
||||||
|
info.QuotaMB = info.PackageQuotaMB
|
||||||
|
}
|
||||||
|
|
||||||
|
used, err := SumTenantStorageUsed(tid)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
info.UsedBytes = used
|
||||||
|
info.QuotaBytes = uint64(info.QuotaMB) * bytesPerMB
|
||||||
|
if info.UsedBytes >= info.QuotaBytes {
|
||||||
|
info.RemainingBytes = 0
|
||||||
|
} else {
|
||||||
|
info.RemainingBytes = info.QuotaBytes - info.UsedBytes
|
||||||
|
}
|
||||||
|
if info.QuotaBytes > 0 {
|
||||||
|
info.UsedPercent = math.Round(float64(info.UsedBytes)/float64(info.QuotaBytes)*1000) / 10
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureTenantStorageQuota 上传前校验:已用 + 本次大小不得超过可用额度。
|
||||||
|
// 超限返回 *StorageQuotaExceededError,调用方据此返回 403。
|
||||||
|
func EnsureTenantStorageQuota(tid uint64, addBytes uint64) error {
|
||||||
|
if tid == 0 || addBytes == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
info, err := GetTenantStorageInfo(tid)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if info.QuotaBytes > 0 && info.UsedBytes+addBytes > info.QuotaBytes {
|
||||||
|
return &StorageQuotaExceededError{
|
||||||
|
UsedBytes: info.UsedBytes,
|
||||||
|
QuotaBytes: info.QuotaBytes,
|
||||||
|
RequiredBytes: addBytes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildStorageOrderNo 生成附件空间订单号
|
||||||
|
func BuildStorageOrderNo(tid uint64) string {
|
||||||
|
return fmt.Sprintf("ST%d%s%s", tid, time.Now().Format("20060102150405"), randomHex(4))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActivateStorageOrder 支付成功后激活附件空间订单。
|
||||||
|
//
|
||||||
|
// 规则(与产品确认一致):
|
||||||
|
// - 同一套餐续费:在现有到期时间上顺延,容量不变;
|
||||||
|
// - 购买不同规格:新套餐立即生效,旧的已支付订单置为 replaced(只保留一个);
|
||||||
|
// - 幂等:订单已是 paid 时直接返回。
|
||||||
|
func ActivateStorageOrder(orderNo, payNo string) error {
|
||||||
|
orderNo = strings.TrimSpace(orderNo)
|
||||||
|
if orderNo == "" {
|
||||||
|
return errors.New("订单号不能为空")
|
||||||
|
}
|
||||||
|
|
||||||
|
var order models.SystemTenantStorageOrder
|
||||||
|
err := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("order_no", orderNo).
|
||||||
|
Filter("delete_time__isnull", true).
|
||||||
|
One(&order)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("附件空间订单 %s 不存在: %w", orderNo, err)
|
||||||
|
}
|
||||||
|
if order.Status == models.StorageOrderPaid {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if order.Status == models.StorageOrderCancelled || order.Status == models.StorageOrderReplaced {
|
||||||
|
return fmt.Errorf("订单 %s 状态为 %s,不能激活", orderNo, order.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
start := now
|
||||||
|
end := now.AddDate(0, 0, order.DurationDays)
|
||||||
|
|
||||||
|
// 同规格续费:从原到期时间顺延
|
||||||
|
var sameOrder models.SystemTenantStorageOrder
|
||||||
|
sameErr := models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("tid", order.Tid).
|
||||||
|
Filter("package_id", order.PackageID).
|
||||||
|
Filter("status", models.StorageOrderPaid).
|
||||||
|
Filter("end_time__gt", now).
|
||||||
|
Filter("order_no__ne", order.OrderNo).
|
||||||
|
OrderBy("-end_time").
|
||||||
|
One(&sameOrder)
|
||||||
|
if sameErr == nil && sameOrder.EndTime != nil && sameOrder.EndTime.After(now) {
|
||||||
|
start = *sameOrder.EndTime
|
||||||
|
end = start.AddDate(0, 0, order.DurationDays)
|
||||||
|
} else {
|
||||||
|
// 不同规格:旧的生效订单作废(只保留最大的一个)
|
||||||
|
_, _ = models.Orm.QueryTable(new(models.SystemTenantStorageOrder)).
|
||||||
|
Filter("tid", order.Tid).
|
||||||
|
Filter("status", models.StorageOrderPaid).
|
||||||
|
Filter("order_no__ne", order.OrderNo).
|
||||||
|
Update(orm.Params{
|
||||||
|
"status": models.StorageOrderReplaced,
|
||||||
|
"update_time": now,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
order.Status = models.StorageOrderPaid
|
||||||
|
if payNo != "" {
|
||||||
|
order.PayNo = payNo
|
||||||
|
}
|
||||||
|
order.StartTime = &start
|
||||||
|
order.EndTime = &end
|
||||||
|
order.UpdateTime = &now
|
||||||
|
if _, err := models.Orm.Update(&order, "Status", "PayNo", "StartTime", "EndTime", "UpdateTime"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Vendored
+2
@@ -11,6 +11,7 @@ export {}
|
|||||||
/* prettier-ignore */
|
/* prettier-ignore */
|
||||||
declare module 'vue' {
|
declare module 'vue' {
|
||||||
export interface GlobalComponents {
|
export interface GlobalComponents {
|
||||||
|
AsideMenuItem: typeof import('./src/components/AsideMenuItem.vue')['default']
|
||||||
CommonAside: typeof import('./src/components/CommonAside.vue')['default']
|
CommonAside: typeof import('./src/components/CommonAside.vue')['default']
|
||||||
CommonHeader: typeof import('./src/components/CommonHeader.vue')['default']
|
CommonHeader: typeof import('./src/components/CommonHeader.vue')['default']
|
||||||
ElAlert: typeof import('element-plus/es')['ElAlert']
|
ElAlert: typeof import('element-plus/es')['ElAlert']
|
||||||
@@ -79,6 +80,7 @@ declare module 'vue' {
|
|||||||
ElTreeSelect: typeof import('element-plus/es')['ElTreeSelect']
|
ElTreeSelect: typeof import('element-plus/es')['ElTreeSelect']
|
||||||
ElUpload: typeof import('element-plus/es')['ElUpload']
|
ElUpload: typeof import('element-plus/es')['ElUpload']
|
||||||
FlowCanvas: typeof import('./src/components/approval/FlowCanvas.vue')['default']
|
FlowCanvas: typeof import('./src/components/approval/FlowCanvas.vue')['default']
|
||||||
|
MenuIcon: typeof import('./src/components/MenuIcon.vue')['default']
|
||||||
RouterLink: typeof import('vue-router')['RouterLink']
|
RouterLink: typeof import('vue-router')['RouterLink']
|
||||||
RouterView: typeof import('vue-router')['RouterView']
|
RouterView: typeof import('vue-router')['RouterView']
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,9 @@
|
|||||||
// 数据统计相关API
|
|
||||||
import request from "@/utils/request";
|
import request from "@/utils/request";
|
||||||
|
|
||||||
// 获取内容统计
|
// 用户 / 租户统计(真实数据,取自租户端用户表、租户表与登录日志)
|
||||||
export function getContentStats() {
|
export function getPlatformUserAnalytics() {
|
||||||
return request({
|
return request({
|
||||||
url: "/platform/contentstats",
|
url: "/platform/analytics/users",
|
||||||
method: "get",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取用户统计
|
|
||||||
export function getUserStats() {
|
|
||||||
return request({
|
|
||||||
url: "/platform/usersstats",
|
|
||||||
method: "get",
|
method: "get",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import request from "@/utils/request";
|
||||||
|
|
||||||
|
// ==================== 附件空间套餐(平台端维护) ====================
|
||||||
|
|
||||||
|
export function getStoragePackages() {
|
||||||
|
return request({
|
||||||
|
url: "/platform/storage/packages",
|
||||||
|
method: "get",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createStoragePackage(data) {
|
||||||
|
return request({
|
||||||
|
url: "/platform/storage/package/create",
|
||||||
|
method: "post",
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateStoragePackage(id, data) {
|
||||||
|
return request({
|
||||||
|
url: `/platform/storage/package/${id}`,
|
||||||
|
method: "post",
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toggleStoragePackage(id, status) {
|
||||||
|
return request({
|
||||||
|
url: `/platform/storage/package/${id}/status`,
|
||||||
|
method: "post",
|
||||||
|
data: { status },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteStoragePackage(id) {
|
||||||
|
return request({
|
||||||
|
url: `/platform/storage/package/${id}/delete`,
|
||||||
|
method: "delete",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 租户空间用量 / 基础额度 ====================
|
||||||
|
|
||||||
|
export function getTenantStorageInfo(tid) {
|
||||||
|
return request({
|
||||||
|
url: `/platform/storage/tenant/${tid}`,
|
||||||
|
method: "get",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateTenantStorageQuota(tid, storageQuotaMB) {
|
||||||
|
return request({
|
||||||
|
url: `/platform/storage/tenant/${tid}/quota`,
|
||||||
|
method: "post",
|
||||||
|
data: { storage_quota_mb: storageQuotaMB },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 购买记录 ====================
|
||||||
|
|
||||||
|
export function getStorageOrders(params = {}) {
|
||||||
|
return request({
|
||||||
|
url: "/platform/storage/orders",
|
||||||
|
method: "get",
|
||||||
|
params,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -35,3 +35,12 @@ export function deleteTenantUser(id) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 查询指定租户的组织架构(部门下拉用) */
|
||||||
|
export function getTenantOrganizations(tid) {
|
||||||
|
return request({
|
||||||
|
url: "/platform/tenantUser/orgs",
|
||||||
|
method: "get",
|
||||||
|
params: { tid },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,12 +1,51 @@
|
|||||||
// Element Plus Message z-index
|
// 全局主题:浅蓝白后台框架
|
||||||
|
// 自定义变量供顶栏 / 侧栏 / 内容区统一取色,Element Plus 主色同步收敛。
|
||||||
:root {
|
:root {
|
||||||
--el-message-z-index: 9999;
|
--el-message-z-index: 9999;
|
||||||
|
|
||||||
|
--el-color-primary: #2f6bff;
|
||||||
|
--el-color-primary-light-3: #6f97ff;
|
||||||
|
--el-color-primary-light-5: #97b5ff;
|
||||||
|
--el-color-primary-light-7: #c5d8ff;
|
||||||
|
--el-color-primary-light-8: #dce7ff;
|
||||||
|
--el-color-primary-light-9: #eef4ff;
|
||||||
|
--el-color-primary-dark-2: #2555cc;
|
||||||
|
|
||||||
|
--yz-primary: #2f6bff;
|
||||||
|
--yz-primary-soft: #eef4ff;
|
||||||
|
--yz-primary-softer: #f6f9ff;
|
||||||
|
--yz-header-bg: #ffffff;
|
||||||
|
--yz-aside-bg: #ffffff;
|
||||||
|
--yz-page-bg: #f4f7fd;
|
||||||
|
--yz-card-bg: #ffffff;
|
||||||
|
--yz-border: #e8edf7;
|
||||||
|
--yz-text: #24304a;
|
||||||
|
--yz-text-regular: #5b6785;
|
||||||
|
--yz-text-muted: #93a0b8;
|
||||||
|
--yz-shadow: 0 2px 12px rgba(31, 61, 130, 0.06);
|
||||||
|
--yz-header-height: 64px;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暗色模式:只覆盖框架自定义变量,Element Plus 变量交给官方 dark css-vars
|
||||||
|
html.dark {
|
||||||
|
--yz-primary: #6f97ff;
|
||||||
|
--yz-primary-soft: rgba(64, 110, 220, 0.2);
|
||||||
|
--yz-primary-softer: rgba(64, 110, 220, 0.12);
|
||||||
|
--yz-header-bg: #1b1f2b;
|
||||||
|
--yz-aside-bg: #1b1f2b;
|
||||||
|
--yz-page-bg: #131720;
|
||||||
|
--yz-card-bg: #1f2431;
|
||||||
|
--yz-border: #2c3344;
|
||||||
|
--yz-text: #e8ecf6;
|
||||||
|
--yz-text-regular: #b9c2d6;
|
||||||
|
--yz-text-muted: #8692ac;
|
||||||
|
--yz-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
|
||||||
}
|
}
|
||||||
|
|
||||||
// body 样式
|
// body 样式
|
||||||
body {
|
body {
|
||||||
// background-color: #f5f7fa;
|
color: var(--yz-text);
|
||||||
color: #303133;
|
background-color: var(--yz-page-bg);
|
||||||
transition: background-color 0.3s ease, color 0.3s ease;
|
transition: background-color 0.3s ease, color 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<template>
|
||||||
|
<el-menu-item
|
||||||
|
v-if="!item.children || item.children.length === 0"
|
||||||
|
:index="item.path || String(item.id)"
|
||||||
|
:class="{ 'is-locked': item.locked }"
|
||||||
|
>
|
||||||
|
<MenuIcon :icon="item.icon" />
|
||||||
|
<template #title>
|
||||||
|
<span>{{ item.title }}</span>
|
||||||
|
<i v-if="item.locked" class="fa-solid fa-lock lock-badge"></i>
|
||||||
|
</template>
|
||||||
|
</el-menu-item>
|
||||||
|
|
||||||
|
<el-sub-menu
|
||||||
|
v-else
|
||||||
|
:index="item.path || String(item.id)"
|
||||||
|
teleported
|
||||||
|
:class="{ 'is-locked': item.locked }"
|
||||||
|
>
|
||||||
|
<template #title>
|
||||||
|
<MenuIcon :icon="item.icon" />
|
||||||
|
<span>{{ item.title }}</span>
|
||||||
|
<i v-if="item.locked" class="fa-solid fa-lock lock-badge"></i>
|
||||||
|
</template>
|
||||||
|
<AsideMenuItem
|
||||||
|
v-for="child in item.children"
|
||||||
|
:key="child.id"
|
||||||
|
:item="child"
|
||||||
|
/>
|
||||||
|
</el-sub-menu>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import MenuIcon from "@/components/MenuIcon.vue";
|
||||||
|
|
||||||
|
defineOptions({ name: "AsideMenuItem" });
|
||||||
|
|
||||||
|
defineProps({
|
||||||
|
item: { type: Object, required: true },
|
||||||
|
});
|
||||||
|
</script>
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
|||||||
|
<template>
|
||||||
|
<i v-if="isFontAwesome" :class="icon" class="menu-icon"></i>
|
||||||
|
<el-icon v-else class="menu-icon">
|
||||||
|
<component :is="elementIconName" />
|
||||||
|
</el-icon>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, getCurrentInstance } from "vue";
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
icon: { type: String, default: "" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const instance = getCurrentInstance();
|
||||||
|
const isFontAwesome = computed(() => /fa-|(^|\s)fa[srlb]?\s/.test(props.icon || ""));
|
||||||
|
|
||||||
|
// main.js 已把所有 Element Plus 图标全局注册;数据库里存的是图标组件名,
|
||||||
|
// 未能识别时统一回退到 Grid,避免渲染出空白图标。
|
||||||
|
const elementIconName = computed(() => {
|
||||||
|
const name = props.icon || "Grid";
|
||||||
|
const components = instance?.appContext?.components || {};
|
||||||
|
return components[name] ? name : "Grid";
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.menu-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-right: 8px;
|
||||||
|
font-size: 16px;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
text-align: center;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -104,7 +104,7 @@ const staticMainChildren = [
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
// 静态路由:登录页独立、home 导航门户独立、404 页面独立
|
// 静态路由:登录页独立、404 页面独立(Main 布局路由单独定义,见 mainRoute)
|
||||||
const staticRoutes = [
|
const staticRoutes = [
|
||||||
{
|
{
|
||||||
path: "/login",
|
path: "/login",
|
||||||
@@ -129,27 +129,43 @@ const staticRoutes = [
|
|||||||
{
|
{
|
||||||
path: "/apps/erp/dashborad",
|
path: "/apps/erp/dashborad",
|
||||||
redirect: "/apps/erp/dashboard"
|
redirect: "/apps/erp/dashboard"
|
||||||
},
|
}
|
||||||
{
|
];
|
||||||
|
|
||||||
|
const notFoundRoute = {
|
||||||
path: "/:pathMatch(.*)*",
|
path: "/:pathMatch(.*)*",
|
||||||
name: "NotFound",
|
name: "NotFound",
|
||||||
component: () => import("@/views/404/404.vue"),
|
component: () => import("@/views/404/404.vue"),
|
||||||
meta: { requiresAuth: false }
|
meta: { requiresAuth: false }
|
||||||
}
|
};
|
||||||
];
|
|
||||||
|
// 主布局路由必须随应用一起注册:/home、/user/userProfile 等静态页面
|
||||||
|
// 不能等菜单接口返回后才存在。否则菜单接口失败或返回空数组时,
|
||||||
|
// 登录后跳转 /home 会命中 404 兜底路由(URL 停在 /#/home)。
|
||||||
|
const mainRoute = {
|
||||||
|
path: "/",
|
||||||
|
name: "Main",
|
||||||
|
component: () => import("@/views/Main.vue"),
|
||||||
|
redirect: "/home",
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
children: [...staticMainChildren]
|
||||||
|
};
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createWebHashHistory(),
|
history: createWebHashHistory(),
|
||||||
routes: staticRoutes
|
routes: [...staticRoutes, mainRoute, notFoundRoute]
|
||||||
});
|
});
|
||||||
|
|
||||||
let dynamicRoutesAdded = false;
|
let dynamicRoutesAdded = false;
|
||||||
let dynamicRoutesData = [];
|
let dynamicRoutesData = [];
|
||||||
let routesLoadingPromise = null;
|
let routesLoadingPromise = null;
|
||||||
|
// 加载代数:登录/登出时自增,用于丢弃「上一账号」发起但已过期的加载结果
|
||||||
|
let routesGeneration = 0;
|
||||||
|
|
||||||
export function resetDynamicRoutes() {
|
export function resetDynamicRoutes() {
|
||||||
dynamicRoutesAdded = false;
|
dynamicRoutesAdded = false;
|
||||||
routesLoadingPromise = null;
|
routesLoadingPromise = null;
|
||||||
|
routesGeneration += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadAndAddDynamicRoutes() {
|
export async function loadAndAddDynamicRoutes() {
|
||||||
@@ -161,26 +177,33 @@ export async function loadAndAddDynamicRoutes() {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const generation = routesGeneration;
|
||||||
routesLoadingPromise = (async () => {
|
routesLoadingPromise = (async () => {
|
||||||
try {
|
try {
|
||||||
const { useMenuStore } = await import("@/stores/menu");
|
const { useMenuStore } = await import("@/stores/menu");
|
||||||
const menuStore = useMenuStore();
|
const menuStore = useMenuStore();
|
||||||
const menuData = await menuStore.fetchMenus();
|
const menuData = await menuStore.fetchMenus();
|
||||||
|
|
||||||
|
// 等待期间已切换账号(resetDynamicRoutes 被调用):
|
||||||
|
// 丢弃这批旧结果,避免用上一个会话的菜单覆盖路由表。
|
||||||
|
if (generation !== routesGeneration) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (menuData && menuData.length > 0) {
|
if (menuData && menuData.length > 0) {
|
||||||
addDynamicRoutes(menuData);
|
addDynamicRoutes(menuData);
|
||||||
dynamicRoutesAdded = true;
|
|
||||||
routesLoadingPromise = null;
|
|
||||||
return Promise.resolve();
|
|
||||||
} else {
|
|
||||||
dynamicRoutesAdded = true;
|
|
||||||
routesLoadingPromise = null;
|
|
||||||
return Promise.resolve();
|
|
||||||
}
|
}
|
||||||
|
// 菜单为空也要标记完成(/home 等静态页面已在初始路由表中,不受影响),
|
||||||
|
// 避免每次导航都重复请求空菜单接口。
|
||||||
|
dynamicRoutesAdded = true;
|
||||||
|
routesLoadingPromise = null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('加载动态路由失败:', error);
|
console.error('加载动态路由失败:', error);
|
||||||
dynamicRoutesAdded = true;
|
// 关键:失败时不要置 dynamicRoutesAdded,否则同一会话内重新登录
|
||||||
|
// 后不会再加载路由表,业务菜单会全部落到 404;保留重试机会。
|
||||||
|
if (generation === routesGeneration) {
|
||||||
routesLoadingPromise = null;
|
routesLoadingPromise = null;
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
@@ -188,6 +211,20 @@ export async function loadAndAddDynamicRoutes() {
|
|||||||
return routesLoadingPromise;
|
return routesLoadingPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安全的动态路由加载:从不抛错,返回是否加载成功。
|
||||||
|
* 失败仅记录日志,由路由守卫决定放行静态页面还是重新登录。
|
||||||
|
*/
|
||||||
|
async function ensureDynamicRoutes() {
|
||||||
|
try {
|
||||||
|
await loadAndAddDynamicRoutes();
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('动态路由加载失败:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 核心修改:移除扁平化,直接使用嵌套菜单生成路由
|
// 核心修改:移除扁平化,直接使用嵌套菜单生成路由
|
||||||
function addDynamicRoutes(menus) {
|
function addDynamicRoutes(menus) {
|
||||||
if (!menus?.length) {
|
if (!menus?.length) {
|
||||||
@@ -203,11 +240,7 @@ function addDynamicRoutes(menus) {
|
|||||||
|
|
||||||
// 重新添加主路由,合并静态子路由和动态路由
|
// 重新添加主路由,合并静态子路由和动态路由
|
||||||
router.addRoute({
|
router.addRoute({
|
||||||
path: "/",
|
...mainRoute,
|
||||||
name: "Main",
|
|
||||||
component: () => import("@/views/Main.vue"),
|
|
||||||
redirect: "/home",
|
|
||||||
meta: { requiresAuth: true },
|
|
||||||
children: [...staticMainChildren, ...dynamicRoutes] // 合并静态和动态子路由
|
children: [...staticMainChildren, ...dynamicRoutes] // 合并静态和动态子路由
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -251,7 +284,9 @@ router.beforeEach(async (to, from, next) => {
|
|||||||
if (publicPaths.includes(to.path)) {
|
if (publicPaths.includes(to.path)) {
|
||||||
if (token) {
|
if (token) {
|
||||||
if (!dynamicRoutesAdded) {
|
if (!dynamicRoutesAdded) {
|
||||||
await loadAndAddDynamicRoutes();
|
// 已在登录页且带 token:加载失败也要放行(静态路由已就绪),
|
||||||
|
// 不能因为一次接口失败卡在登录页或落到 404。
|
||||||
|
await ensureDynamicRoutes();
|
||||||
}
|
}
|
||||||
next({ path: "/home" });
|
next({ path: "/home" });
|
||||||
} else {
|
} else {
|
||||||
@@ -261,25 +296,25 @@ router.beforeEach(async (to, from, next) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
next({ path: "/login", query: { redirect: to.path } });
|
next({ path: "/login", query: { redirect: to.fullPath || to.path } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!dynamicRoutesAdded) {
|
if (!dynamicRoutesAdded) {
|
||||||
try {
|
const loaded = await ensureDynamicRoutes();
|
||||||
await loadAndAddDynamicRoutes();
|
// 加载过程中请求被判 401,拦截器已清掉 token,直接回登录页
|
||||||
} catch (error) {
|
if (!localStorage.getItem("token")) {
|
||||||
console.error('动态路由加载失败:', error);
|
|
||||||
// token 无效时跳转登录
|
|
||||||
if (error?.message === 'token无效' || error?.response?.status === 401) {
|
|
||||||
next({ path: '/login' });
|
next({ path: '/login' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
if (loaded) {
|
||||||
// 路由加载后重新导航,确保路由匹配正确
|
// 路由表刚变化,重新解析目标地址,避免命中兜底 404
|
||||||
next({ path: to.path, replace: true });
|
next({ path: to.path, query: to.query, hash: to.hash, replace: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// 加载失败但 token 仍有效:静态页面(/home 等)照常放行,
|
||||||
|
// 下次导航会再次尝试加载业务路由。
|
||||||
|
}
|
||||||
|
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,11 +15,25 @@ export const useAllDataStore = defineStore('allData', () => {
|
|||||||
function increment() {
|
function increment() {
|
||||||
count.value++;
|
count.value++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 是否为手机端(≤768px),通过 matchMedia 响应式监听
|
||||||
|
const mobileQuery = window.matchMedia('(max-width: 768px)');
|
||||||
|
const isMobile = ref(mobileQuery.matches);
|
||||||
|
const handleMobileQueryChange = (e) => {
|
||||||
|
isMobile.value = e.matches;
|
||||||
|
};
|
||||||
|
if (typeof mobileQuery.addEventListener === 'function') {
|
||||||
|
mobileQuery.addEventListener('change', handleMobileQueryChange);
|
||||||
|
} else {
|
||||||
|
mobileQuery.addListener(handleMobileQueryChange);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
count,
|
count,
|
||||||
doubleCount,
|
doubleCount,
|
||||||
increment,
|
increment,
|
||||||
|
isMobile,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -37,14 +51,13 @@ import { ref as vueRef } from 'vue';
|
|||||||
* }
|
* }
|
||||||
*/
|
*/
|
||||||
export const useTabsStore = defineTabsStore('tabs', () => {
|
export const useTabsStore = defineTabsStore('tabs', () => {
|
||||||
// 固定首页tab
|
// 固定首页 tab:/home 是数据概览页
|
||||||
const defaultDashboardPath = '/home';
|
const defaultDashboardPath = '/home';
|
||||||
|
|
||||||
// 从 localStorage 恢复 tabs 状态
|
// 从 localStorage 恢复 tabs 状态
|
||||||
function loadTabsFromStorage() {
|
function loadTabsFromStorage() {
|
||||||
try {
|
try {
|
||||||
const savedTabs = localStorage.getItem('tabs_list');
|
const savedTabs = localStorage.getItem('tabs_list');
|
||||||
const savedActiveTab = localStorage.getItem('active_tab');
|
|
||||||
if (savedTabs) {
|
if (savedTabs) {
|
||||||
const tabs = JSON.parse(savedTabs);
|
const tabs = JSON.parse(savedTabs);
|
||||||
// 确保至少包含首页
|
// 确保至少包含首页
|
||||||
@@ -88,6 +101,7 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
|
|
||||||
// 删除指定tab并切换激活tab
|
// 删除指定tab并切换激活tab
|
||||||
function removeTab(fullPath) {
|
function removeTab(fullPath) {
|
||||||
|
if (fullPath === defaultDashboardPath) return;
|
||||||
const idx = tabList.value.findIndex((t) => t.fullPath === fullPath);
|
const idx = tabList.value.findIndex((t) => t.fullPath === fullPath);
|
||||||
if (idx > -1) {
|
if (idx > -1) {
|
||||||
tabList.value.splice(idx, 1);
|
tabList.value.splice(idx, 1);
|
||||||
@@ -118,7 +132,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
function closeLeft(targetFullPath) {
|
function closeLeft(targetFullPath) {
|
||||||
const targetIndex = tabList.value.findIndex((t) => t.fullPath === targetFullPath);
|
const targetIndex = tabList.value.findIndex((t) => t.fullPath === targetFullPath);
|
||||||
if (targetIndex > -1) {
|
if (targetIndex > -1) {
|
||||||
// 保留首页和目标tab及其右侧的所有tab
|
|
||||||
const beforeIndex = tabList.value.slice(0, targetIndex);
|
const beforeIndex = tabList.value.slice(0, targetIndex);
|
||||||
const hasCloseableLeft = beforeIndex.some(t => t.fullPath !== defaultDashboardPath);
|
const hasCloseableLeft = beforeIndex.some(t => t.fullPath !== defaultDashboardPath);
|
||||||
|
|
||||||
@@ -126,7 +139,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
tabList.value = tabList.value.filter((t, index) =>
|
tabList.value = tabList.value.filter((t, index) =>
|
||||||
t.fullPath === defaultDashboardPath || index >= targetIndex
|
t.fullPath === defaultDashboardPath || index >= targetIndex
|
||||||
);
|
);
|
||||||
// 如果关闭的tab中包含了当前激活的tab,则激活目标tab
|
|
||||||
if (!tabList.value.find(t => t.fullPath === activeTab.value)) {
|
if (!tabList.value.find(t => t.fullPath === activeTab.value)) {
|
||||||
activeTab.value = targetFullPath;
|
activeTab.value = targetFullPath;
|
||||||
}
|
}
|
||||||
@@ -139,7 +151,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
function closeRight(targetFullPath) {
|
function closeRight(targetFullPath) {
|
||||||
const targetIndex = tabList.value.findIndex((t) => t.fullPath === targetFullPath);
|
const targetIndex = tabList.value.findIndex((t) => t.fullPath === targetFullPath);
|
||||||
if (targetIndex > -1) {
|
if (targetIndex > -1) {
|
||||||
// 保留首页和目标tab及其左侧的所有tab
|
|
||||||
const afterIndex = tabList.value.slice(targetIndex + 1);
|
const afterIndex = tabList.value.slice(targetIndex + 1);
|
||||||
const hasCloseableRight = afterIndex.length > 0;
|
const hasCloseableRight = afterIndex.length > 0;
|
||||||
|
|
||||||
@@ -147,7 +158,6 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
tabList.value = tabList.value.filter((t, index) =>
|
tabList.value = tabList.value.filter((t, index) =>
|
||||||
t.fullPath === defaultDashboardPath || index <= targetIndex
|
t.fullPath === defaultDashboardPath || index <= targetIndex
|
||||||
);
|
);
|
||||||
// 如果关闭的tab中包含了当前激活的tab,则激活目标tab
|
|
||||||
if (!tabList.value.find(t => t.fullPath === activeTab.value)) {
|
if (!tabList.value.find(t => t.fullPath === activeTab.value)) {
|
||||||
activeTab.value = targetFullPath;
|
activeTab.value = targetFullPath;
|
||||||
}
|
}
|
||||||
@@ -171,9 +181,8 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
|
|
||||||
// 重置 tabs store 到初始状态(登出时使用)
|
// 重置 tabs store 到初始状态(登出时使用)
|
||||||
function resetTabs() {
|
function resetTabs() {
|
||||||
tabList.value = [{ title: '首页', fullPath: defaultDashboardPath, name: 'Dashboard' }];
|
tabList.value = [{ title: '首页', fullPath: defaultDashboardPath, name: 'Home' }];
|
||||||
activeTab.value = defaultDashboardPath;
|
activeTab.value = defaultDashboardPath;
|
||||||
// 清除 localStorage 中的 tabs 数据
|
|
||||||
localStorage.removeItem('tabs_list');
|
localStorage.removeItem('tabs_list');
|
||||||
localStorage.removeItem('active_tab');
|
localStorage.removeItem('active_tab');
|
||||||
}
|
}
|
||||||
@@ -181,6 +190,7 @@ export const useTabsStore = defineTabsStore('tabs', () => {
|
|||||||
return {
|
return {
|
||||||
tabList,
|
tabList,
|
||||||
activeTab,
|
activeTab,
|
||||||
|
defaultDashboardPath,
|
||||||
addTab,
|
addTab,
|
||||||
removeTab,
|
removeTab,
|
||||||
closeOthers,
|
closeOthers,
|
||||||
|
|||||||
@@ -16,13 +16,16 @@ export const useMenuStore = defineStore('menu', () => {
|
|||||||
// 正在加载的 Promise(用于避免重复请求)
|
// 正在加载的 Promise(用于避免重复请求)
|
||||||
let loadingPromise = null;
|
let loadingPromise = null;
|
||||||
|
|
||||||
// 菜单缓存 key(基于用户类型和角色ID)
|
// 菜单缓存 key(基于用户类型、角色ID、用户ID)
|
||||||
|
// 必须带上用户ID:同一浏览器换账号登录时,若只看角色ID会复用上一个账号的菜单,
|
||||||
|
// 导致新账号进入后菜单/路由与权限不匹配。
|
||||||
const getCacheKey = () => {
|
const getCacheKey = () => {
|
||||||
try {
|
try {
|
||||||
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
|
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
|
||||||
const loginType = userInfo.type || 'user';
|
const loginType = userInfo.type || 'user';
|
||||||
const roleId = userInfo.rid || 0;
|
const roleId = userInfo.rid || 0;
|
||||||
return `menu_cache_${loginType}_${roleId}`;
|
const userId = userInfo.id || 0;
|
||||||
|
return `menu_cache_${loginType}_${roleId}_${userId}`;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return 'menu_cache_default';
|
return 'menu_cache_default';
|
||||||
}
|
}
|
||||||
@@ -59,13 +62,17 @@ export const useMenuStore = defineStore('menu', () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 清除菜单缓存
|
// 清除菜单缓存(含历史 key 格式与其他账号遗留的缓存)
|
||||||
const clearCache = () => {
|
const clearCache = () => {
|
||||||
try {
|
try {
|
||||||
const cacheKey = getCacheKey();
|
const cacheKeys = [];
|
||||||
localStorage.removeItem(cacheKey);
|
for (let i = 0; i < localStorage.length; i++) {
|
||||||
// 也清除其他可能的缓存key(兼容旧代码)
|
const key = localStorage.key(i);
|
||||||
localStorage.removeItem('menu_cache');
|
if (key && key.indexOf('menu_cache') === 0) {
|
||||||
|
cacheKeys.push(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cacheKeys.forEach((key) => localStorage.removeItem(key));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('清除菜单缓存失败:', e);
|
console.warn('清除菜单缓存失败:', e);
|
||||||
}
|
}
|
||||||
|
|||||||
+274
-249
@@ -4,16 +4,54 @@ import CommonHeader from '@/components/CommonHeader.vue';
|
|||||||
import { useTabsStore } from '@/stores';
|
import { useTabsStore } from '@/stores';
|
||||||
import { useDictStore } from '@/stores/dict';
|
import { useDictStore } from '@/stores/dict';
|
||||||
import { useRouter, useRoute } from 'vue-router';
|
import { useRouter, useRoute } from 'vue-router';
|
||||||
import { ref, watch, reactive, nextTick, onMounted, computed } from 'vue';
|
import { ref, watch, reactive, nextTick, onMounted, onBeforeUnmount, computed } from 'vue';
|
||||||
import { More, Close, CircleClose, ArrowUp } from '@element-plus/icons-vue';
|
import { More, ArrowUp, Fold, Expand } from '@element-plus/icons-vue';
|
||||||
import { ElMessage } from 'element-plus';
|
import { ElMessage } from 'element-plus';
|
||||||
|
|
||||||
const tabsStore = useTabsStore();
|
const tabsStore = useTabsStore();
|
||||||
const dictStore = useDictStore();
|
const dictStore = useDictStore();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const asideRef = ref(null);
|
|
||||||
const defaultDashboardPath = '/home';
|
// 固定首页(数据概览)作为不可关闭的默认标签
|
||||||
|
const defaultDashboardPath = computed(
|
||||||
|
() => tabsStore.defaultDashboardPath || '/home'
|
||||||
|
);
|
||||||
|
|
||||||
|
// ========== 手机端侧栏抽屉控制 ==========
|
||||||
|
const MOBILE_QUERY = '(max-width: 768px)';
|
||||||
|
const mobileMedia = window.matchMedia(MOBILE_QUERY);
|
||||||
|
const isMobile = ref(mobileMedia.matches);
|
||||||
|
const sidebarVisible = ref(false);
|
||||||
|
|
||||||
|
const handleMobileMediaChange = (e) => {
|
||||||
|
isMobile.value = e.matches;
|
||||||
|
if (!e.matches) {
|
||||||
|
sidebarVisible.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof mobileMedia.addEventListener === 'function') {
|
||||||
|
mobileMedia.addEventListener('change', handleMobileMediaChange);
|
||||||
|
} else {
|
||||||
|
mobileMedia.addListener(handleMobileMediaChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
if (typeof mobileMedia.removeEventListener === 'function') {
|
||||||
|
mobileMedia.removeEventListener('change', handleMobileMediaChange);
|
||||||
|
} else {
|
||||||
|
mobileMedia.removeListener(handleMobileMediaChange);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const toggleMobileSidebar = () => {
|
||||||
|
sidebarVisible.value = !sidebarVisible.value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeMobileSidebar = () => {
|
||||||
|
sidebarVisible.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
// 根据当前路由恢复 tab(刷新时使用)
|
// 根据当前路由恢复 tab(刷新时使用)
|
||||||
function restoreTabFromRoute() {
|
function restoreTabFromRoute() {
|
||||||
@@ -21,12 +59,9 @@ function restoreTabFromRoute() {
|
|||||||
const currentName = route.name;
|
const currentName = route.name;
|
||||||
const currentMeta = route.meta || {};
|
const currentMeta = route.meta || {};
|
||||||
|
|
||||||
// 如果当前路径不在 tabList 中,添加它
|
|
||||||
const existTab = tabsStore.tabList.find(t => t.fullPath === currentPath);
|
const existTab = tabsStore.tabList.find(t => t.fullPath === currentPath);
|
||||||
if (!existTab) {
|
if (!existTab) {
|
||||||
// 从路由 meta 获取标题,如果没有则使用路由 name 或路径
|
|
||||||
const title = currentMeta.title || currentName || '页面';
|
const title = currentMeta.title || currentName || '页面';
|
||||||
// 使用 addTab 会自动保存到 localStorage
|
|
||||||
tabsStore.addTab({
|
tabsStore.addTab({
|
||||||
title: title,
|
title: title,
|
||||||
fullPath: currentPath,
|
fullPath: currentPath,
|
||||||
@@ -34,49 +69,25 @@ function restoreTabFromRoute() {
|
|||||||
icon: currentMeta.icon
|
icon: currentMeta.icon
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// 如果已存在,只激活它(不触发路由跳转)
|
|
||||||
tabsStore.setActiveTab(currentPath);
|
tabsStore.setActiveTab(currentPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 组件挂载后,根据当前路由恢复 tab
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
// 进入后台后把库里所有字典预热到缓存(失败不影响按需加载)
|
|
||||||
dictStore.loadAll();
|
dictStore.loadAll();
|
||||||
|
|
||||||
// 等待路由完全加载后再恢复
|
|
||||||
nextTick(() => {
|
nextTick(() => {
|
||||||
// 刷新时,localStorage 中已保存的 tabs 会在 store 初始化时恢复
|
|
||||||
// 这里只需要确保当前路由对应的 tab 存在并激活
|
|
||||||
restoreTabFromRoute();
|
restoreTabFromRoute();
|
||||||
|
|
||||||
// 为 tabs 容器添加右键事件监听(使用事件委托)
|
|
||||||
const tabsWrapper = document.querySelector('.multi-tabs-wrapper');
|
const tabsWrapper = document.querySelector('.multi-tabs-wrapper');
|
||||||
if (tabsWrapper) {
|
if (tabsWrapper) {
|
||||||
tabsWrapper.addEventListener('contextmenu', (e) => {
|
tabsWrapper.addEventListener('contextmenu', (e) => {
|
||||||
// 排除编辑器相关区域,避免影响编辑器功能
|
const insideEditor =
|
||||||
// 如果点击在编辑器区域内,完全不做任何处理(优先检查)
|
e.target.closest?.('.tiptap-editor-wrapper') ||
|
||||||
const editorWrapper = e.target.closest?.('.tiptap-editor-wrapper');
|
e.target.closest?.('.tiptap-toolbar') ||
|
||||||
if (editorWrapper) {
|
e.target.closest?.('[class*="tiptap-"]');
|
||||||
// 在编辑器区域内,不处理右键菜单,也不阻止事件
|
if (insideEditor) return;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查其他编辑器元素(工具栏、下拉面板等)
|
|
||||||
const editorElements = [
|
|
||||||
'.tiptap-toolbar',
|
|
||||||
'.tiptap',
|
|
||||||
'[class*="tiptap-"]'
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const selector of editorElements) {
|
|
||||||
if (e.target.closest && e.target.closest(selector)) {
|
|
||||||
// 在编辑器元素内,不处理右键菜单
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 只有在非编辑器区域的 tab item 上才处理右键菜单
|
|
||||||
const tabItem = e.target.closest('.el-tabs__item');
|
const tabItem = e.target.closest('.el-tabs__item');
|
||||||
if (tabItem) {
|
if (tabItem) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -94,22 +105,23 @@ watch(
|
|||||||
(newPath) => {
|
(newPath) => {
|
||||||
if (newPath) {
|
if (newPath) {
|
||||||
restoreTabFromRoute();
|
restoreTabFromRoute();
|
||||||
|
if (isMobile.value) sidebarVisible.value = false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ immediate: false }
|
{ immediate: false }
|
||||||
);
|
);
|
||||||
|
|
||||||
// 1. 侧栏菜单点击:加入/激活Tab并切换路由
|
// 侧栏/顶栏菜单点击:加入/激活 Tab 并切换路由
|
||||||
const handleAsideMenuClick = async (menuItem) => {
|
const handleAsideMenuClick = async (menuItem) => {
|
||||||
const targetPath = menuItem.path;
|
const targetPath = menuItem.path;
|
||||||
|
if (!targetPath) return;
|
||||||
|
|
||||||
if (targetPath === '/home' || targetPath === defaultDashboardPath) {
|
if (targetPath === '/home') {
|
||||||
tabsStore.closeAll();
|
tabsStore.closeAll();
|
||||||
router.push(defaultDashboardPath);
|
router.push('/home');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 先添加tab
|
|
||||||
tabsStore.addTab({
|
tabsStore.addTab({
|
||||||
title: menuItem.title,
|
title: menuItem.title,
|
||||||
fullPath: targetPath,
|
fullPath: targetPath,
|
||||||
@@ -117,42 +129,40 @@ const handleAsideMenuClick = async (menuItem) => {
|
|||||||
icon: menuItem.icon
|
icon: menuItem.icon
|
||||||
});
|
});
|
||||||
|
|
||||||
// 如果当前路由已经是目标路由,不需要跳转
|
if (router.currentRoute.value.fullPath === targetPath) return;
|
||||||
if (router.currentRoute.value.fullPath === targetPath) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
router.push(targetPath).catch(err => {
|
router.push(targetPath).catch(err => {
|
||||||
if (err.name !== 'NavigationDuplicated') {
|
if (err.name !== 'NavigationDuplicated') {
|
||||||
|
ElMessage.warning(`路由 ${targetPath} 不存在,请刷新缓存后重试`);
|
||||||
console.error('路由跳转失败:', err);
|
console.error('路由跳转失败:', err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const tabsCloseTab = (targetKey) => {
|
const tabsCloseTab = (targetKey) => {
|
||||||
tabsStore.removeTab(targetKey);
|
tabsStore.removeTab(targetKey);
|
||||||
if (route.fullPath !== tabsStore.activeTab) {
|
if (route.fullPath !== tabsStore.activeTab) {
|
||||||
router.push(tabsStore.activeTab);
|
router.push(tabsStore.activeTab);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeOthers = () => {
|
const closeOthers = () => {
|
||||||
tabsStore.closeOthers();
|
tabsStore.closeOthers();
|
||||||
if (!tabsStore.tabList.find(tab => tab.fullPath === route.fullPath)) {
|
if (!tabsStore.tabList.find(tab => tab.fullPath === route.fullPath)) {
|
||||||
router.push(tabsStore.activeTab);
|
router.push(tabsStore.activeTab);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeAll = () => {
|
const closeAll = () => {
|
||||||
tabsStore.closeAll();
|
tabsStore.closeAll();
|
||||||
router.push(defaultDashboardPath);
|
router.push(defaultDashboardPath.value || route.fullPath);
|
||||||
};
|
};
|
||||||
// 主动监听tab激活,保证切tab时内容区切换(仅用于tab点击切换,菜单点击由handleAsideMenuClick处理)
|
|
||||||
// 使用 immediate: false 避免初始化时触发,使用 flush: 'post' 确保在 DOM 更新后执行
|
// 主动监听 tab 激活,保证切 tab 时内容区切换
|
||||||
watch(
|
watch(
|
||||||
() => tabsStore.activeTab,
|
() => tabsStore.activeTab,
|
||||||
(newVal, oldVal) => {
|
(newVal, oldVal) => {
|
||||||
if (newVal && oldVal !== undefined && router.currentRoute.value.fullPath !== newVal) {
|
if (newVal && oldVal !== undefined && router.currentRoute.value.fullPath !== newVal) {
|
||||||
if (newVal === defaultDashboardPath) {
|
|
||||||
tabsStore.closeAll();
|
|
||||||
}
|
|
||||||
nextTick(() => {
|
nextTick(() => {
|
||||||
router.push(newVal).catch(err => {
|
router.push(newVal).catch(err => {
|
||||||
if (err.name !== 'NavigationDuplicated') {
|
if (err.name !== 'NavigationDuplicated') {
|
||||||
@@ -165,25 +175,21 @@ watch(
|
|||||||
{ flush: 'post' }
|
{ flush: 'post' }
|
||||||
);
|
);
|
||||||
|
|
||||||
// ========== 右键菜单逻辑 ========== //
|
// ========== 右键菜单逻辑 ==========
|
||||||
const contextMenu = reactive({
|
const contextMenu = reactive({
|
||||||
visible: false,
|
visible: false,
|
||||||
x: 0,
|
x: 0,
|
||||||
y: 0,
|
y: 0,
|
||||||
tab: null,
|
tab: null,
|
||||||
});
|
});
|
||||||
const contextDropdownRef = ref(null);
|
|
||||||
|
|
||||||
// 处理 tabs 容器的右键事件
|
|
||||||
const handleTabsContextMenu = (event) => {
|
const handleTabsContextMenu = (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
|
||||||
// 找到点击的 tab item 元素(el-tabs__item)
|
|
||||||
let target = event.target;
|
let target = event.target;
|
||||||
let tabItem = null;
|
let tabItem = null;
|
||||||
|
|
||||||
// 向上查找 el-tabs__item 元素
|
|
||||||
while (target && target !== event.currentTarget) {
|
while (target && target !== event.currentTarget) {
|
||||||
if (target.classList && target.classList.contains('el-tabs__item')) {
|
if (target.classList && target.classList.contains('el-tabs__item')) {
|
||||||
tabItem = target;
|
tabItem = target;
|
||||||
@@ -191,10 +197,8 @@ const handleTabsContextMenu = (event) => {
|
|||||||
}
|
}
|
||||||
target = target.parentElement;
|
target = target.parentElement;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!tabItem) return;
|
if (!tabItem) return;
|
||||||
|
|
||||||
// Element Plus 的 tab item 的 id 格式通常是 "tab-{name}",其中 name 是 tab-pane 的 name 属性
|
|
||||||
const tabId = tabItem.id;
|
const tabId = tabItem.id;
|
||||||
if (tabId && tabId.startsWith('tab-')) {
|
if (tabId && tabId.startsWith('tab-')) {
|
||||||
const tabName = tabId.replace('tab-', '');
|
const tabName = tabId.replace('tab-', '');
|
||||||
@@ -205,183 +209,150 @@ const handleTabsContextMenu = (event) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果通过 id 找不到,尝试通过 aria-controls 或其他属性
|
|
||||||
const ariaControls = tabItem.getAttribute('aria-controls');
|
const ariaControls = tabItem.getAttribute('aria-controls');
|
||||||
if (ariaControls) {
|
if (ariaControls) {
|
||||||
const tabName = ariaControls.replace('pane-', '');
|
const tabName = ariaControls.replace('pane-', '');
|
||||||
const matchedTab = tabsStore.tabList.find(t => t.fullPath === tabName);
|
const matchedTab = tabsStore.tabList.find(t => t.fullPath === tabName);
|
||||||
if (matchedTab) {
|
if (matchedTab) showContextMenu(event, matchedTab);
|
||||||
showContextMenu(event, matchedTab);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 显示右键菜单
|
|
||||||
const showContextMenu = (event, tab) => {
|
const showContextMenu = (event, tab) => {
|
||||||
// 使用 nextTick 确保在下一个事件循环中更新状态,避免在渲染过程中触发更新
|
|
||||||
nextTick(() => {
|
nextTick(() => {
|
||||||
contextMenu.visible = true;
|
contextMenu.visible = true;
|
||||||
contextMenu.x = event.clientX;
|
contextMenu.x = event.clientX;
|
||||||
contextMenu.y = event.clientY;
|
contextMenu.y = event.clientY;
|
||||||
contextMenu.tab = tab;
|
contextMenu.tab = tab;
|
||||||
|
|
||||||
// 延迟添加事件监听器,确保菜单已渲染
|
|
||||||
// 关键:完全排除编辑器区域,确保编辑器的事件不被干扰
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const hideMenuHandler = (e) => {
|
const hideMenuHandler = (e) => {
|
||||||
// 如果右键菜单已经隐藏,直接返回
|
if (!contextMenu.visible) return;
|
||||||
if (!contextMenu.visible) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const target = e.target;
|
const target = e.target;
|
||||||
if (!target) {
|
if (!target) {
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (target.closest?.('.context-menu')) return;
|
||||||
// 检查点击是否在右键菜单本身上
|
if (
|
||||||
if (target.closest?.('.context-menu')) {
|
target.closest?.('.tiptap-toolbar') ||
|
||||||
return; // 点击在菜单上,不隐藏
|
target.closest?.('.tiptap-editor-wrapper')
|
||||||
}
|
) {
|
||||||
|
|
||||||
// ========== 关键修复:优先检查编辑器区域 ==========
|
|
||||||
// 如果在编辑器区域内,立即返回,不执行任何操作,让编辑器的事件正常处理
|
|
||||||
|
|
||||||
// 先检查是否在编辑器包装器内(最快判断)
|
|
||||||
const tiptapEditorWrapper = target.closest?.('.tiptap-editor-wrapper');
|
|
||||||
if (tiptapEditorWrapper) {
|
|
||||||
// 在编辑器包装器内,完全不做任何处理,让编辑器正常处理
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查所有可能的编辑器元素(包括工具栏、下拉面板、模态框等)
|
|
||||||
const editorSelectors = [
|
|
||||||
'.tiptap-toolbar',
|
|
||||||
'.tiptap',
|
|
||||||
'.editor-container',
|
|
||||||
'[class*="tiptap-"]'
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const selector of editorSelectors) {
|
|
||||||
if (target.closest?.(selector)) {
|
|
||||||
// 在编辑器区域内,完全不做任何处理,让编辑器的事件正常处理
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 其他区域点击,隐藏菜单
|
|
||||||
hideContextMenu();
|
|
||||||
};
|
|
||||||
|
|
||||||
// 关键修复:使用 capture: false 在冒泡阶段处理,并且延迟注册
|
|
||||||
// 这样可以确保编辑器的监听器(通常在目标元素上)先处理事件
|
|
||||||
// 然后再处理我们的监听器(在 body 上)
|
|
||||||
// 注意:只有在右键菜单显示时才注册,并且排除编辑器区域
|
|
||||||
setTimeout(() => {
|
|
||||||
// 再次检查右键菜单是否仍然可见
|
|
||||||
if (contextMenu.visible) {
|
|
||||||
document.body.addEventListener('click', hideMenuHandler, { once: true, capture: false, passive: true });
|
|
||||||
}
|
|
||||||
}, 100); // 延迟注册,确保编辑器的事件监听器已经注册并可以正常处理
|
|
||||||
|
|
||||||
const hideContextMenuHandler = (e) => {
|
|
||||||
const target = e.target;
|
|
||||||
if (!target) {
|
|
||||||
hideContextMenu();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 排除编辑器区域和右键菜单本身
|
|
||||||
if (target.closest?.('.tiptap-toolbar') || target.closest?.('.context-menu') || target.closest?.('.tiptap-editor-wrapper')) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
};
|
};
|
||||||
|
document.body.addEventListener('click', hideMenuHandler, { once: true });
|
||||||
document.body.addEventListener('contextmenu', hideContextMenuHandler, { once: true });
|
document.body.addEventListener('contextmenu', hideMenuHandler, { once: true });
|
||||||
}, 0);
|
}, 0);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
function hideContextMenu() {
|
function hideContextMenu() {
|
||||||
contextMenu.visible = false;
|
contextMenu.visible = false;
|
||||||
contextMenu.tab = null;
|
contextMenu.tab = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeTabContextTab() {
|
function closeTabContextTab() {
|
||||||
if (contextMenu.tab && contextMenu.tab.fullPath !== defaultDashboardPath) {
|
if (contextMenu.tab && contextMenu.tab.fullPath !== defaultDashboardPath.value) {
|
||||||
tabsStore.removeTab(contextMenu.tab.fullPath);
|
tabsStore.removeTab(contextMenu.tab.fullPath);
|
||||||
|
if (route.fullPath !== tabsStore.activeTab) {
|
||||||
|
router.push(tabsStore.activeTab);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
}
|
}
|
||||||
// 关闭左侧
|
|
||||||
function closeLeftContextTab() {
|
function closeLeftContextTab() {
|
||||||
if (contextMenu.tab) {
|
if (contextMenu.tab) {
|
||||||
tabsStore.closeLeft(contextMenu.tab.fullPath);
|
tabsStore.closeLeft(contextMenu.tab.fullPath);
|
||||||
// 如果当前路由对应的tab被关闭了,跳转到激活的tab
|
if (!tabsStore.tabList.find(t => t.fullPath === route.fullPath)) {
|
||||||
if (!tabsStore.tabList.find(tab => tab.fullPath === route.fullPath)) {
|
|
||||||
router.push(tabsStore.activeTab);
|
router.push(tabsStore.activeTab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 关闭右侧
|
|
||||||
function closeRightContextTab() {
|
function closeRightContextTab() {
|
||||||
if (contextMenu.tab) {
|
if (contextMenu.tab) {
|
||||||
tabsStore.closeRight(contextMenu.tab.fullPath);
|
tabsStore.closeRight(contextMenu.tab.fullPath);
|
||||||
// 如果当前路由对应的tab被关闭了,跳转到激活的tab
|
if (!tabsStore.tabList.find(t => t.fullPath === route.fullPath)) {
|
||||||
if (!tabsStore.tabList.find(tab => tab.fullPath === route.fullPath)) {
|
|
||||||
router.push(tabsStore.activeTab);
|
router.push(tabsStore.activeTab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 关闭其他
|
|
||||||
function closeOthersContextTab() {
|
function closeOthersContextTab() {
|
||||||
if (contextMenu.tab) {
|
if (contextMenu.tab) {
|
||||||
tabsStore.setActiveTab(contextMenu.tab.fullPath);
|
tabsStore.addTab(contextMenu.tab);
|
||||||
tabsStore.closeOthers();
|
tabsStore.closeOthers();
|
||||||
if (!tabsStore.tabList.find(tab => tab.fullPath === route.fullPath)) {
|
router.push(contextMenu.tab.fullPath);
|
||||||
router.push(tabsStore.activeTab);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 关闭全部
|
|
||||||
function closeAllTabs() {
|
function closeAllTabs() {
|
||||||
tabsStore.closeAll();
|
tabsStore.closeAll();
|
||||||
|
router.push(defaultDashboardPath.value || route.fullPath);
|
||||||
hideContextMenu();
|
hideContextMenu();
|
||||||
router.push(defaultDashboardPath);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 计算是否可以关闭左侧/右侧
|
|
||||||
const canCloseLeft = computed(() => {
|
const canCloseLeft = computed(() => {
|
||||||
if (!contextMenu.tab) return false;
|
if (!contextMenu.tab) return false;
|
||||||
const targetIndex = tabsStore.tabList.findIndex(t => t.fullPath === contextMenu.tab.fullPath);
|
const targetIndex = tabsStore.tabList.findIndex(
|
||||||
// 至少左侧有一个可关闭的tab(排除首页)
|
t => t.fullPath === contextMenu.tab.fullPath
|
||||||
return targetIndex > 0 && tabsStore.tabList.slice(0, targetIndex).some(t => t.fullPath !== defaultDashboardPath);
|
);
|
||||||
|
return (
|
||||||
|
targetIndex > 0 &&
|
||||||
|
tabsStore.tabList
|
||||||
|
.slice(0, targetIndex)
|
||||||
|
.some(t => t.fullPath !== defaultDashboardPath.value)
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const canCloseRight = computed(() => {
|
const canCloseRight = computed(() => {
|
||||||
if (!contextMenu.tab) return false;
|
if (!contextMenu.tab) return false;
|
||||||
const targetIndex = tabsStore.tabList.findIndex(t => t.fullPath === contextMenu.tab.fullPath);
|
const targetIndex = tabsStore.tabList.findIndex(
|
||||||
// 右侧至少有一个tab
|
t => t.fullPath === contextMenu.tab.fullPath
|
||||||
return targetIndex < tabsStore.tabList.length - 1;
|
);
|
||||||
|
return targetIndex > -1 && targetIndex < tabsStore.tabList.length - 1;
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="common-layout">
|
<div class="common-layout">
|
||||||
<el-container class="main-container">
|
<!-- 手机端汉堡菜单按钮(仅 ≤768px 显示,CSS 控制) -->
|
||||||
<div class="aside-wrapper">
|
<button
|
||||||
<common-aside ref="asideRef" @menu-click="handleAsideMenuClick" />
|
class="mobile-menu-btn"
|
||||||
</div>
|
:aria-label="sidebarVisible ? '关闭菜单' : '打开菜单'"
|
||||||
<el-container>
|
@click="toggleMobileSidebar"
|
||||||
|
>
|
||||||
|
<el-icon :size="20">
|
||||||
|
<Expand v-if="sidebarVisible" />
|
||||||
|
<Fold v-else />
|
||||||
|
</el-icon>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- 手机端遮罩层,点击关闭侧栏 -->
|
||||||
|
<transition name="mask-fade">
|
||||||
|
<div
|
||||||
|
v-if="isMobile && sidebarVisible"
|
||||||
|
class="mobile-sidebar-mask"
|
||||||
|
@click="closeMobileSidebar"
|
||||||
|
></div>
|
||||||
|
</transition>
|
||||||
|
|
||||||
|
<el-container class="main-container" direction="vertical">
|
||||||
|
<!-- 顶栏全宽:logo 位于页面真正的左上角 -->
|
||||||
<el-header class="main-header">
|
<el-header class="main-header">
|
||||||
<common-header @collapse="() => asideRef?.toggleMobile()" />
|
<common-header @menu-click="handleAsideMenuClick" />
|
||||||
</el-header>
|
</el-header>
|
||||||
|
<el-container class="main-body">
|
||||||
|
<common-aside
|
||||||
|
class="common-aside-wrapper"
|
||||||
|
:class="{ 'mobile-open': sidebarVisible }"
|
||||||
|
@menu-click="handleAsideMenuClick"
|
||||||
|
/>
|
||||||
<el-main class="right-main">
|
<el-main class="right-main">
|
||||||
<div class="multi-tabs-wrapper">
|
<div class="multi-tabs-wrapper">
|
||||||
<el-tabs
|
<el-tabs
|
||||||
@@ -483,44 +454,37 @@ const canCloseRight = computed(() => {
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
.common-layout, .main-container {
|
.common-layout,
|
||||||
|
.main-container {
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
background-color: var(--bg-color-page);
|
background-color: var(--yz-page-bg);
|
||||||
transition: background-color 0.3s ease;
|
transition: background-color 0.3s ease;
|
||||||
|
|
||||||
:deep(.el-aside) {
|
:deep(.el-aside) {
|
||||||
display: block !important;
|
// 侧栏内部是「菜单 + 底部装饰」的纵向布局:
|
||||||
|
// 必须是 flex 列容器,菜单才能 flex:1 收缩并在内部滚动。
|
||||||
|
// 不能写成 display:block,否则 el-menu 的高度会撑开、溢出被裁剪且无法滚动。
|
||||||
|
display: flex !important;
|
||||||
|
flex-direction: column;
|
||||||
visibility: visible !important;
|
visibility: visible !important;
|
||||||
height: 100vh;
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.aside-wrapper {
|
|
||||||
flex-shrink: 0;
|
|
||||||
position: relative;
|
|
||||||
transition: width 0.3s;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
.aside-wrapper {
|
|
||||||
width: 0 !important;
|
|
||||||
overflow: visible;
|
|
||||||
}
|
|
||||||
.right-main {
|
|
||||||
padding: 12px 8px !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.main-header {
|
.main-header {
|
||||||
background-color: var(--header-bg-color, #3973ff);
|
background-color: var(--yz-header-bg);
|
||||||
transition: background-color 0.3s ease;
|
transition: background-color 0.3s ease;
|
||||||
height: 80px;
|
height: var(--yz-header-height);
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.right-main {
|
.right-main {
|
||||||
background-color: var(--el-bg-color-page);
|
background-color: var(--yz-page-bg);
|
||||||
color: var(--el-text-color-primary);
|
color: var(--yz-text);
|
||||||
transition: background-color 0.3s ease, color 0.3s ease;
|
transition: background-color 0.3s ease, color 0.3s ease;
|
||||||
padding: 20px;
|
padding: 16px 20px 20px;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
|
|
||||||
.multi-tabs-wrapper {
|
.multi-tabs-wrapper {
|
||||||
@@ -528,12 +492,12 @@ const canCloseRight = computed(() => {
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
margin-bottom: 16px;
|
margin-bottom: 14px;
|
||||||
background: var(--el-bg-color);
|
background: var(--yz-card-bg);
|
||||||
border-radius: 8px;
|
border-radius: 12px;
|
||||||
padding: 8px 12px;
|
padding: 6px 10px;
|
||||||
border: 1px solid var(--el-border-color-lighter);
|
border: 1px solid var(--yz-border);
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
|
box-shadow: var(--yz-shadow);
|
||||||
}
|
}
|
||||||
|
|
||||||
.multi-tabs {
|
.multi-tabs {
|
||||||
@@ -549,7 +513,7 @@ const canCloseRight = computed(() => {
|
|||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
overflow-y: hidden;
|
overflow-y: hidden;
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
scrollbar-color: var(--el-border-color) transparent;
|
scrollbar-color: var(--yz-border) transparent;
|
||||||
|
|
||||||
&::-webkit-scrollbar {
|
&::-webkit-scrollbar {
|
||||||
height: 4px;
|
height: 4px;
|
||||||
@@ -560,44 +524,39 @@ const canCloseRight = computed(() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
&::-webkit-scrollbar-thumb {
|
&::-webkit-scrollbar-thumb {
|
||||||
background: var(--el-border-color);
|
background: var(--yz-border);
|
||||||
border-radius: 2px;
|
border-radius: 2px;
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background: var(--el-border-color-darker);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
:deep(.el-tabs__item) {
|
:deep(.el-tabs__item) {
|
||||||
border: 1px solid var(--el-border-color-lighter);
|
border: 1px solid transparent;
|
||||||
border-radius: 6px;
|
border-radius: 8px;
|
||||||
margin-right: 8px;
|
margin-right: 6px;
|
||||||
padding: 8px 16px;
|
padding: 8px 16px;
|
||||||
height: 36px;
|
height: 36px;
|
||||||
line-height: 20px;
|
line-height: 20px;
|
||||||
color: var(--el-text-color-regular);
|
color: var(--yz-text-regular);
|
||||||
background: var(--el-fill-color-lighter);
|
background: transparent;
|
||||||
transition: all 0.3s;
|
transition: all 0.25s;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
color: var(--el-color-primary);
|
color: var(--yz-primary);
|
||||||
border-color: var(--el-color-primary-light-7);
|
background: var(--yz-primary-softer);
|
||||||
background: var(--el-color-primary-light-9);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
&.is-active {
|
&.is-active {
|
||||||
color: var(--el-color-primary);
|
border-color: var(--el-color-primary-light-7);
|
||||||
border-color: #4f84ff;
|
background: var(--yz-primary-soft);
|
||||||
background: #4f84ff;
|
color: var(--yz-primary);
|
||||||
color: #fff;
|
font-weight: 600;
|
||||||
|
|
||||||
.el-icon-close {
|
.el-icon-close {
|
||||||
color: rgba(255, 255, 255, 0.8);
|
color: var(--yz-primary);
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
color: #fff;
|
color: var(--yz-primary);
|
||||||
background-color: rgba(255, 255, 255, 0.2);
|
background-color: var(--el-color-primary-light-7);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -625,7 +584,6 @@ const canCloseRight = computed(() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.tabs-extra-actions {
|
.tabs-extra-actions {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -634,20 +592,114 @@ const canCloseRight = computed(() => {
|
|||||||
.extra-btn {
|
.extra-btn {
|
||||||
padding: 8px;
|
padding: 8px;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
color: var(--el-text-color-regular);
|
color: var(--yz-text-regular);
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
color: var(--el-color-primary);
|
color: var(--yz-primary);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.main-body {
|
||||||
|
display: flex;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
background-color: var(--yz-page-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-panel {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
:deep(.el-menu) {
|
:deep(.el-menu) {
|
||||||
border-right: none !important;
|
border-right: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== 手机端侧栏抽屉(仅 ≤768px 生效,桌面端不受影响) ==========
|
||||||
|
.mobile-menu-btn {
|
||||||
|
display: none;
|
||||||
|
position: fixed;
|
||||||
|
top: 12px;
|
||||||
|
left: 12px;
|
||||||
|
z-index: 2200;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: none;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--yz-primary);
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: 0 4px 12px rgba(47, 107, 255, 0.3);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
||||||
|
|
||||||
|
&:active {
|
||||||
|
transform: scale(0.92);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-sidebar-mask {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
z-index: 2000;
|
||||||
|
background: rgba(0, 0, 0, 0.45);
|
||||||
|
backdrop-filter: blur(2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.mask-fade-enter-active,
|
||||||
|
.mask-fade-leave-active {
|
||||||
|
transition: opacity 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mask-fade-enter-from,
|
||||||
|
.mask-fade-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.mobile-menu-btn {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 覆盖 el-aside 的 :width 内联宽度(224px/64px),改为 fixed 抽屉
|
||||||
|
.common-layout .common-aside-wrapper {
|
||||||
|
position: fixed !important;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 260px !important;
|
||||||
|
max-width: 80vw;
|
||||||
|
height: 100vh;
|
||||||
|
z-index: 2100;
|
||||||
|
transform: translateX(-100%);
|
||||||
|
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||||
|
box-shadow: none;
|
||||||
|
|
||||||
|
&.mobile-open {
|
||||||
|
transform: translateX(0);
|
||||||
|
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.25);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-container {
|
||||||
|
:deep(.el-header),
|
||||||
|
:deep(.el-main) {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.right-main {
|
||||||
|
padding: 64px 12px 12px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 回到顶部按钮样式
|
// 回到顶部按钮样式
|
||||||
.backtop-button {
|
.backtop-button {
|
||||||
width: 40px;
|
width: 40px;
|
||||||
@@ -655,16 +707,15 @@ const canCloseRight = computed(() => {
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
background: var(--el-color-primary);
|
background: var(--yz-primary);
|
||||||
color: #fff;
|
color: #fff;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
box-shadow: 0 4px 12px rgba(64, 129, 255, 0.4);
|
box-shadow: 0 4px 12px rgba(47, 107, 255, 0.35);
|
||||||
transition: all 0.3s ease;
|
transition: all 0.3s ease;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
background: var(--el-color-primary-light-3);
|
background: var(--el-color-primary-light-3);
|
||||||
box-shadow: 0 6px 16px rgba(64, 129, 255, 0.5);
|
|
||||||
transform: translateY(-2px);
|
transform: translateY(-2px);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -672,34 +723,6 @@ const canCloseRight = computed(() => {
|
|||||||
transform: translateY(0);
|
transform: translateY(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
.common-layout,
|
|
||||||
.main-container {
|
|
||||||
.main-header {
|
|
||||||
height: 64px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.right-main {
|
|
||||||
padding: 8px;
|
|
||||||
|
|
||||||
.multi-tabs-wrapper {
|
|
||||||
margin-bottom: 10px;
|
|
||||||
padding: 6px 8px;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tabs-extra-actions {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.backtop-button {
|
|
||||||
width: 34px;
|
|
||||||
height: 34px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<style lang="less">
|
<style lang="less">
|
||||||
@@ -709,21 +732,23 @@ const canCloseRight = computed(() => {
|
|||||||
z-index: 9999 !important;
|
z-index: 9999 !important;
|
||||||
background: var(--el-bg-color-overlay) !important;
|
background: var(--el-bg-color-overlay) !important;
|
||||||
border: 1px solid var(--el-border-color-lighter) !important;
|
border: 1px solid var(--el-border-color-lighter) !important;
|
||||||
border-radius: 4px !important;
|
border-radius: 8px !important;
|
||||||
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
|
box-shadow: 0 10px 30px rgba(31, 61, 130, 0.16) !important;
|
||||||
min-width: 120px !important;
|
min-width: 128px !important;
|
||||||
padding: 4px 0 !important;
|
padding: 4px !important;
|
||||||
pointer-events: auto !important; // 确保菜单本身可以接收点击
|
pointer-events: auto !important;
|
||||||
|
|
||||||
.context-menu-item {
|
.context-menu-item {
|
||||||
padding: 8px 16px !important;
|
padding: 8px 12px !important;
|
||||||
|
border-radius: 6px !important;
|
||||||
cursor: pointer !important;
|
cursor: pointer !important;
|
||||||
color: var(--el-text-color-primary) !important;
|
color: var(--el-text-color-primary) !important;
|
||||||
font-size: 14px !important;
|
font-size: 13px !important;
|
||||||
transition: background-color 0.2s !important;
|
transition: background-color 0.2s !important;
|
||||||
|
|
||||||
&:hover:not(.is-disabled) {
|
&:hover:not(.is-disabled) {
|
||||||
background-color: var(--el-fill-color-light) !important;
|
background-color: var(--yz-primary-softer) !important;
|
||||||
|
color: var(--yz-primary) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
&.is-disabled {
|
&.is-disabled {
|
||||||
@@ -735,7 +760,7 @@ const canCloseRight = computed(() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 确保编辑器工具栏的 z-index 高于右键菜单
|
// 确保编辑器工具栏的 z-index 高于右键菜单
|
||||||
:deep(.tiptap-toolbar) {
|
.tiptap-toolbar {
|
||||||
z-index: 10000 !important;
|
z-index: 10000 !important;
|
||||||
pointer-events: auto !important;
|
pointer-events: auto !important;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="statistics-container">
|
<div v-loading="loading" class="statistics-container">
|
||||||
<el-row :gutter="20" class="data-overview">
|
<el-row :gutter="20" class="data-overview">
|
||||||
<el-col :xs="12" :sm="12" :md="6" v-for="item in summaryData" :key="item.title">
|
<el-col :xs="12" :sm="12" :md="6" v-for="item in summaryData" :key="item.title">
|
||||||
<el-card shadow="hover" class="data-card">
|
<el-card shadow="hover" class="data-card">
|
||||||
@@ -9,11 +9,18 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="text-box">
|
<div class="text-box">
|
||||||
<div class="title">{{ item.title }}</div>
|
<div class="title">{{ item.title }}</div>
|
||||||
<div class="value">{{ item.value.toLocaleString() }}</div>
|
<div class="value">{{ (item.value || 0).toLocaleString() }}</div>
|
||||||
<div class="trend" :class="item.isUp ? 'up' : 'down'">
|
<div
|
||||||
{{ item.isUp ? '↑' : '↓' }} {{ item.percentage }}%
|
v-if="item.percentage !== null && item.percentage !== undefined"
|
||||||
|
class="trend"
|
||||||
|
:class="item.isUp ? 'up' : 'down'"
|
||||||
|
>
|
||||||
|
{{ item.isUp ? "↑" : "↓" }} {{ item.percentage }}%
|
||||||
<span>较上月</span>
|
<span>较上月</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-else class="trend">
|
||||||
|
<span class="sub-text">{{ item.sub }}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</el-card>
|
</el-card>
|
||||||
@@ -22,12 +29,12 @@
|
|||||||
|
|
||||||
<el-row :gutter="20" class="charts-row">
|
<el-row :gutter="20" class="charts-row">
|
||||||
<el-col :xs="24" :sm="24" :md="16">
|
<el-col :xs="24" :sm="24" :md="16">
|
||||||
<el-card shadow="hover" header="用户增长趋势">
|
<el-card shadow="hover" header="近 14 天新增用户 / 租户">
|
||||||
<div ref="lineChartRef" class="chart-box"></div>
|
<div ref="lineChartRef" class="chart-box"></div>
|
||||||
</el-card>
|
</el-card>
|
||||||
</el-col>
|
</el-col>
|
||||||
<el-col :xs="24" :sm="24" :md="8">
|
<el-col :xs="24" :sm="24" :md="8">
|
||||||
<el-card shadow="hover" header="用户等级分布">
|
<el-card shadow="hover" header="租户用户数分布">
|
||||||
<div ref="pieChartRef" class="chart-box"></div>
|
<div ref="pieChartRef" class="chart-box"></div>
|
||||||
</el-card>
|
</el-card>
|
||||||
</el-col>
|
</el-col>
|
||||||
@@ -36,111 +43,186 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, onMounted, onUnmounted, shallowRef } from 'vue';
|
import { ref, onMounted, onUnmounted, shallowRef, nextTick } from "vue";
|
||||||
import * as echarts from 'echarts';
|
import * as echarts from "echarts";
|
||||||
import { User, Pointer, Connection, Histogram } from '@element-plus/icons-vue';
|
import { ElMessage } from "element-plus";
|
||||||
|
import { User, OfficeBuilding, Pointer, Connection } from "@element-plus/icons-vue";
|
||||||
|
import { getPlatformUserAnalytics } from "@/api/analytics";
|
||||||
|
|
||||||
// --- 类型定义 ---
|
|
||||||
interface SummaryItem {
|
interface SummaryItem {
|
||||||
title: string;
|
title: string;
|
||||||
value: number;
|
value: number;
|
||||||
icon: any;
|
icon: any;
|
||||||
color: string;
|
color: string;
|
||||||
percentage: number;
|
percentage?: number | null;
|
||||||
isUp: boolean;
|
isUp?: boolean;
|
||||||
|
sub?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 响应式数据 ---
|
const loading = ref(false);
|
||||||
const lineChartRef = ref<HTMLElement | null>(null);
|
const lineChartRef = ref<HTMLElement | null>(null);
|
||||||
const pieChartRef = ref<HTMLElement | null>(null);
|
const pieChartRef = ref<HTMLElement | null>(null);
|
||||||
const lineChartInstance = shallowRef<echarts.ECharts | null>(null);
|
const lineChartInstance = shallowRef<echarts.ECharts | null>(null);
|
||||||
const pieChartInstance = shallowRef<echarts.ECharts | null>(null);
|
const pieChartInstance = shallowRef<echarts.ECharts | null>(null);
|
||||||
|
|
||||||
const summaryData = ref<SummaryItem[]>([
|
const summaryData = ref<SummaryItem[]>([
|
||||||
{ title: '总用户数', value: 12840, icon: User, color: '#3973FF', percentage: 12, isUp: true },
|
{ title: "总用户数", value: 0, icon: User, color: "#3973FF", percentage: 0, isUp: true },
|
||||||
{ title: '今日新增', value: 156, icon: Pointer, color: '#67C23A', percentage: 5, isUp: true },
|
{ title: "租户数", value: 0, icon: OfficeBuilding, color: "#67C23A", sub: "启用 0 / 共 0" },
|
||||||
{ title: '活跃用户', value: 3420, icon: Connection, color: '#E6A23C', percentage: 2, isUp: false },
|
{ title: "今日新增用户", value: 0, icon: Pointer, color: "#E6A23C", sub: "本月新增 0" },
|
||||||
{ title: '留存率', value: 85, icon: Histogram, color: '#F56C6C', percentage: 1, isUp: true },
|
{ title: "近 30 天活跃用户", value: 0, icon: Connection, color: "#F56C6C", sub: "今日登录 0 次" },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// --- 初始化图表 ---
|
const trendOption = (days: string[], users: number[], tenants: number[]) => ({
|
||||||
const initCharts = () => {
|
tooltip: { trigger: "axis" },
|
||||||
// 折线图配置
|
legend: { data: ["新增用户", "新增租户"], top: 4 },
|
||||||
if (lineChartRef.value) {
|
grid: { left: "3%", right: "4%", bottom: "3%", top: 48, containLabel: true },
|
||||||
lineChartInstance.value = echarts.init(lineChartRef.value);
|
|
||||||
lineChartInstance.value.setOption({
|
|
||||||
tooltip: { trigger: 'axis' },
|
|
||||||
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
|
|
||||||
xAxis: {
|
xAxis: {
|
||||||
type: 'category',
|
type: "category",
|
||||||
boundaryGap: false,
|
boundaryGap: false,
|
||||||
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
data: days,
|
||||||
},
|
},
|
||||||
yAxis: { type: 'value' },
|
yAxis: { type: "value", minInterval: 1 },
|
||||||
series: [
|
series: [
|
||||||
{
|
{
|
||||||
name: '新增用户',
|
name: "新增用户",
|
||||||
type: 'line',
|
type: "line",
|
||||||
smooth: true,
|
smooth: true,
|
||||||
data: [120, 132, 101, 134, 90, 230, 210],
|
data: users,
|
||||||
areaStyle: { opacity: 0.3 },
|
areaStyle: { opacity: 0.12 },
|
||||||
itemStyle: { color: '#3973FF' }
|
itemStyle: { color: "#3973FF" },
|
||||||
}
|
},
|
||||||
]
|
{
|
||||||
|
name: "新增租户",
|
||||||
|
type: "line",
|
||||||
|
smooth: true,
|
||||||
|
data: tenants,
|
||||||
|
itemStyle: { color: "#67C23A" },
|
||||||
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// 饼图配置
|
const pieOption = (items: { name: string; value: number }[]) => ({
|
||||||
if (pieChartRef.value) {
|
tooltip: { trigger: "item", formatter: "{b}: {c} 人({d}%)" },
|
||||||
pieChartInstance.value = echarts.init(pieChartRef.value);
|
|
||||||
pieChartInstance.value.setOption({
|
|
||||||
tooltip: { trigger: 'item' },
|
|
||||||
legend: {
|
legend: {
|
||||||
orient: 'vertical',
|
orient: "vertical",
|
||||||
right: '5%',
|
right: "5%",
|
||||||
top: 'center',
|
top: "center",
|
||||||
|
type: "scroll",
|
||||||
},
|
},
|
||||||
series: [
|
series: [
|
||||||
{
|
{
|
||||||
name: '等级分布',
|
name: "租户用户数",
|
||||||
type: 'pie',
|
type: "pie",
|
||||||
radius: ['40%', '70%'],
|
radius: ["40%", "70%"],
|
||||||
center: ['35%', '50%'],
|
center: ["35%", "50%"],
|
||||||
avoidLabelOverlap: false,
|
avoidLabelOverlap: false,
|
||||||
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
|
itemStyle: { borderRadius: 10, borderColor: "#fff", borderWidth: 2 },
|
||||||
label: { show: false },
|
label: { show: false },
|
||||||
data: [
|
data: items.length ? items : [{ name: "暂无数据", value: 0 }],
|
||||||
{ value: 1048, name: '普通用户' },
|
},
|
||||||
{ value: 735, name: 'VIP会员' },
|
],
|
||||||
{ value: 580, name: '超级管理员' },
|
|
||||||
{ value: 484, name: '运营人员' }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const initCharts = () => {
|
||||||
|
if (lineChartRef.value && !lineChartInstance.value) {
|
||||||
|
lineChartInstance.value = echarts.init(lineChartRef.value);
|
||||||
|
lineChartInstance.value.setOption(trendOption([], [], []));
|
||||||
|
}
|
||||||
|
if (pieChartRef.value && !pieChartInstance.value) {
|
||||||
|
pieChartInstance.value = echarts.init(pieChartRef.value);
|
||||||
|
pieChartInstance.value.setOption(pieOption([]));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderCharts = (trend: any, tenantUserTop: any[]) => {
|
||||||
|
lineChartInstance.value?.setOption(
|
||||||
|
trendOption(
|
||||||
|
trend?.days || [],
|
||||||
|
trend?.users || [],
|
||||||
|
trend?.tenants || [],
|
||||||
|
),
|
||||||
|
{ notMerge: true },
|
||||||
|
);
|
||||||
|
pieChartInstance.value?.setOption(pieOption(tenantUserTop || []), {
|
||||||
|
notMerge: true,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchAnalytics = async () => {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
const res = await getPlatformUserAnalytics();
|
||||||
|
if (!res || res.code !== 200) {
|
||||||
|
throw new Error(res?.msg || "获取统计数据失败");
|
||||||
|
}
|
||||||
|
const data = res.data || {};
|
||||||
|
|
||||||
|
summaryData.value = [
|
||||||
|
{
|
||||||
|
title: "总用户数",
|
||||||
|
value: Number(data.totalUsers) || 0,
|
||||||
|
icon: User,
|
||||||
|
color: "#3973FF",
|
||||||
|
percentage: Number(data.userGrowthPct) || 0,
|
||||||
|
isUp: data.userGrowthUp !== false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "租户数",
|
||||||
|
value: Number(data.totalTenants) || 0,
|
||||||
|
icon: OfficeBuilding,
|
||||||
|
color: "#67C23A",
|
||||||
|
sub: `启用 ${Number(data.activeTenants) || 0} / 共 ${Number(data.totalTenants) || 0}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "今日新增用户",
|
||||||
|
value: Number(data.todayNewUsers) || 0,
|
||||||
|
icon: Pointer,
|
||||||
|
color: "#E6A23C",
|
||||||
|
sub: `本月新增 ${Number(data.monthNewUsers) || 0}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "近 30 天活跃用户",
|
||||||
|
value: Number(data.activeUsers30d) || 0,
|
||||||
|
icon: Connection,
|
||||||
|
color: "#F56C6C",
|
||||||
|
sub: `今日登录 ${Number(data.todayLogins) || 0} 次`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
await nextTick();
|
||||||
|
renderCharts(data.trend, data.tenantUserTop);
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error("获取统计数据失败:", error);
|
||||||
|
ElMessage.error(error?.message || error?.response?.data?.msg || "获取统计数据失败");
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- 生命周期与自适应 ---
|
|
||||||
const handleResize = () => {
|
const handleResize = () => {
|
||||||
lineChartInstance.value?.resize();
|
lineChartInstance.value?.resize();
|
||||||
pieChartInstance.value?.resize();
|
pieChartInstance.value?.resize();
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(async () => {
|
||||||
|
await nextTick();
|
||||||
initCharts();
|
initCharts();
|
||||||
window.addEventListener('resize', handleResize);
|
await fetchAnalytics();
|
||||||
|
window.addEventListener("resize", handleResize);
|
||||||
});
|
});
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
window.removeEventListener('resize', handleResize);
|
window.removeEventListener("resize", handleResize);
|
||||||
|
lineChartInstance.value?.dispose();
|
||||||
|
lineChartInstance.value = null;
|
||||||
|
pieChartInstance.value?.dispose();
|
||||||
|
pieChartInstance.value = null;
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
.statistics-container {
|
.statistics-container {
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
min-height: 100vh;
|
|
||||||
|
|
||||||
.data-overview {
|
.data-overview {
|
||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
@@ -167,6 +249,7 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
.text-box {
|
.text-box {
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
|
||||||
.title {
|
.title {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
color: #909399;
|
color: #909399;
|
||||||
@@ -174,17 +257,34 @@ onUnmounted(() => {
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
.value {
|
.value {
|
||||||
font-size: 24px;
|
font-size: 24px;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
margin: 4px 0;
|
margin: 4px 0;
|
||||||
color: var(--el-text-color-primary);
|
color: var(--el-text-color-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend {
|
.trend {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
&.up { color: #67c23a; }
|
|
||||||
&.down { color: #f56c6c; }
|
&.up {
|
||||||
span { color: #909399; margin-left: 4px; }
|
color: #67c23a;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.down {
|
||||||
|
color: #f56c6c;
|
||||||
|
}
|
||||||
|
|
||||||
|
span {
|
||||||
|
color: #909399;
|
||||||
|
margin-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sub-text {
|
||||||
|
color: #909399;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -195,11 +295,19 @@ onUnmounted(() => {
|
|||||||
.el-col {
|
.el-col {
|
||||||
margin-bottom: 16px;
|
margin-bottom: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chart-box {
|
.chart-box {
|
||||||
height: 350px;
|
height: 350px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 暗色主题:卡片数字用纯白
|
||||||
|
html.dark & {
|
||||||
|
.data-overview .data-card .card-content .text-box .value {
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
@@ -213,6 +321,7 @@ onUnmounted(() => {
|
|||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
margin-right: 10px;
|
margin-right: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.text-box .value {
|
.text-box .value {
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
}
|
}
|
||||||
@@ -224,7 +333,6 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 深度修改 Element Plus 卡片头部样式
|
|
||||||
:deep(.el-card__header) {
|
:deep(.el-card__header) {
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
|
|||||||
@@ -0,0 +1,269 @@
|
|||||||
|
<template>
|
||||||
|
<div class="container-box">
|
||||||
|
<div class="header-bar">
|
||||||
|
<h2>存储套餐</h2>
|
||||||
|
<div class="header-actions">
|
||||||
|
<el-button @click="refresh">刷新</el-button>
|
||||||
|
<el-button type="primary" @click="openCreate">新增套餐</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-alert
|
||||||
|
type="info"
|
||||||
|
:closable="false"
|
||||||
|
show-icon
|
||||||
|
class="tips"
|
||||||
|
title="附件空间单独计费:租户默认 500MB,超出后购买这里的套餐扩容。容量按「实际可用 = max(基础额度, 生效套餐容量)」计算。"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<el-table :data="list" v-loading="loading" border stripe>
|
||||||
|
<el-table-column prop="name" label="套餐名称" min-width="140" />
|
||||||
|
<el-table-column prop="code" label="编码" min-width="120" />
|
||||||
|
<el-table-column label="容量" width="120">
|
||||||
|
<template #default="{ row }">{{ formatCapacity(row.capacity_mb) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="价格" width="110">
|
||||||
|
<template #default="{ row }">¥{{ Number(row.price || 0).toFixed(2) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="时长" width="110">
|
||||||
|
<template #default="{ row }">{{ durationText(row.duration_days) }}</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="sort" label="排序" width="80" />
|
||||||
|
<el-table-column label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch
|
||||||
|
:model-value="Number(row.status) === 1"
|
||||||
|
@change="(val) => handleToggle(row, val)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
|
||||||
|
<el-table-column label="操作" width="150" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button link type="primary" @click="openEdit(row)">编辑</el-button>
|
||||||
|
<el-button link type="danger" @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<el-dialog
|
||||||
|
v-model="dialogVisible"
|
||||||
|
:title="editingId ? '编辑套餐' : '新增套餐'"
|
||||||
|
width="520px"
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
>
|
||||||
|
<el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
|
||||||
|
<el-form-item label="套餐名称" prop="name">
|
||||||
|
<el-input v-model="form.name" placeholder="如:5GB" maxlength="64" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="套餐编码" prop="code">
|
||||||
|
<el-input v-model="form.code" placeholder="如:storage_5g(可留空)" maxlength="64" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="容量(MB)" prop="capacity_mb">
|
||||||
|
<el-input-number v-model="form.capacity_mb" :min="1" :step="1024" class="full" />
|
||||||
|
<div class="form-tip">1024MB = 1GB,例如 5GB 填 5120</div>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="价格(元)" prop="price">
|
||||||
|
<el-input-number v-model="form.price" :min="0" :precision="2" :step="10" class="full" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="有效天数" prop="duration_days">
|
||||||
|
<el-input-number v-model="form.duration_days" :min="1" :step="30" class="full" />
|
||||||
|
<div class="form-tip">365 = 一年,90 = 一季度</div>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="排序">
|
||||||
|
<el-input-number v-model="form.sort" :min="0" class="full" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="备注">
|
||||||
|
<el-input v-model="form.remark" type="textarea" :rows="2" maxlength="255" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, reactive, ref } from "vue";
|
||||||
|
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
|
||||||
|
import {
|
||||||
|
createStoragePackage,
|
||||||
|
deleteStoragePackage,
|
||||||
|
getStoragePackages,
|
||||||
|
toggleStoragePackage,
|
||||||
|
updateStoragePackage,
|
||||||
|
} from "@/api/storage";
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const list = ref<any[]>([]);
|
||||||
|
|
||||||
|
const dialogVisible = ref(false);
|
||||||
|
const saving = ref(false);
|
||||||
|
const editingId = ref<number | null>(null);
|
||||||
|
const formRef = ref<FormInstance>();
|
||||||
|
|
||||||
|
const form = reactive({
|
||||||
|
name: "",
|
||||||
|
code: "",
|
||||||
|
capacity_mb: 5120,
|
||||||
|
price: 0,
|
||||||
|
duration_days: 365,
|
||||||
|
sort: 0,
|
||||||
|
remark: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rules: FormRules = {
|
||||||
|
name: [{ required: true, message: "请填写套餐名称", trigger: "blur" }],
|
||||||
|
capacity_mb: [{ required: true, message: "请填写容量", trigger: "blur" }],
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCapacity = (mb: any) => {
|
||||||
|
const n = Number(mb) || 0;
|
||||||
|
return n >= 1024 ? `${(n / 1024).toFixed(n % 1024 === 0 ? 0 : 1)} GB` : `${n} MB`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const durationText = (days: any) => {
|
||||||
|
const n = Number(days) || 0;
|
||||||
|
if (n === 365) return "1 年";
|
||||||
|
if (n === 180) return "半年";
|
||||||
|
if (n === 90) return "1 季";
|
||||||
|
if (n === 30) return "1 月";
|
||||||
|
return `${n} 天`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadList = async () => {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
const res = await getStoragePackages();
|
||||||
|
list.value = res?.code === 200 ? res.data?.list || [] : [];
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || "加载套餐失败");
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const refresh = async () => {
|
||||||
|
await loadList();
|
||||||
|
ElMessage.success("刷新成功");
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
editingId.value = null;
|
||||||
|
form.name = "";
|
||||||
|
form.code = "";
|
||||||
|
form.capacity_mb = 5120;
|
||||||
|
form.price = 0;
|
||||||
|
form.duration_days = 365;
|
||||||
|
form.sort = 0;
|
||||||
|
form.remark = "";
|
||||||
|
};
|
||||||
|
|
||||||
|
const openCreate = () => {
|
||||||
|
resetForm();
|
||||||
|
dialogVisible.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEdit = (row: any) => {
|
||||||
|
editingId.value = row.id;
|
||||||
|
form.name = row.name || "";
|
||||||
|
form.code = row.code || "";
|
||||||
|
form.capacity_mb = Number(row.capacity_mb) || 0;
|
||||||
|
form.price = Number(row.price) || 0;
|
||||||
|
form.duration_days = Number(row.duration_days) || 365;
|
||||||
|
form.sort = Number(row.sort) || 0;
|
||||||
|
form.remark = row.remark || "";
|
||||||
|
dialogVisible.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!formRef.value) return;
|
||||||
|
const valid = await formRef.value.validate().catch(() => false);
|
||||||
|
if (!valid) return;
|
||||||
|
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
const payload = { ...form };
|
||||||
|
const res = editingId.value
|
||||||
|
? await updateStoragePackage(editingId.value, payload)
|
||||||
|
: await createStoragePackage(payload);
|
||||||
|
if (res?.code !== 200) {
|
||||||
|
ElMessage.error(res?.msg || "保存失败");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ElMessage.success("保存成功");
|
||||||
|
dialogVisible.value = false;
|
||||||
|
await loadList();
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || "保存失败");
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggle = async (row: any, val: boolean) => {
|
||||||
|
try {
|
||||||
|
const res = await toggleStoragePackage(row.id, val ? 1 : 0);
|
||||||
|
if (res?.code !== 200) {
|
||||||
|
ElMessage.error(res?.msg || "更新失败");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
row.status = val ? 1 : 0;
|
||||||
|
ElMessage.success("已更新");
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || "更新失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (row: any) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确认删除套餐「${row.name}」?`, "提示", {
|
||||||
|
type: "warning",
|
||||||
|
confirmButtonText: "确定",
|
||||||
|
cancelButtonText: "取消",
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await deleteStoragePackage(row.id);
|
||||||
|
if (res?.code !== 200) {
|
||||||
|
ElMessage.error(res?.msg || "删除失败");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ElMessage.success("删除成功");
|
||||||
|
await loadList();
|
||||||
|
} catch (e: any) {
|
||||||
|
ElMessage.error(e?.message || "删除失败");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(loadList);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped lang="less">
|
||||||
|
.header-bar {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tips {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.full {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-tip {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -53,10 +53,9 @@
|
|||||||
* 租户详情内「添加用户」:提交到 /platform/tenantUser/create,
|
* 租户详情内「添加用户」:提交到 /platform/tenantUser/create,
|
||||||
* 后端写入 yz_tenant_user(租户-用户绑定,含冗余账号/密码等字段)。
|
* 后端写入 yz_tenant_user(租户-用户绑定,含冗余账号/密码等字段)。
|
||||||
*/
|
*/
|
||||||
import { ref, reactive, onMounted } from 'vue';
|
import { ref, reactive } from 'vue';
|
||||||
import { ElMessage } from 'element-plus';
|
import { ElMessage } from 'element-plus';
|
||||||
import { createTenantUser } from '@/api/tenantUser';
|
import { createTenantUser, getTenantOrganizations } from '@/api/tenantUser';
|
||||||
import { getOrganizationList } from '@/api/erp';
|
|
||||||
|
|
||||||
const emit = defineEmits(['success']);
|
const emit = defineEmits(['success']);
|
||||||
const visible = ref(false);
|
const visible = ref(false);
|
||||||
@@ -96,11 +95,14 @@ const buildOrgTree = (list: any[]): any[] => {
|
|||||||
return tree;
|
return tree;
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadOrgs = async () => {
|
// 部门下拉取「当前租户」的组织架构(平台自己的组织与租户无关)
|
||||||
|
const loadOrgs = async (tid: number | null) => {
|
||||||
|
orgTree.value = [];
|
||||||
|
if (!tid) return;
|
||||||
try {
|
try {
|
||||||
const res = await getOrganizationList();
|
const res = await getTenantOrganizations(tid);
|
||||||
if (res?.code === 200) {
|
if (res?.code === 200) {
|
||||||
const list = res?.data?.list || res?.data || [];
|
const list = res?.data?.list || [];
|
||||||
orgTree.value = buildOrgTree(list);
|
orgTree.value = buildOrgTree(list);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -108,8 +110,6 @@ const loadOrgs = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(loadOrgs);
|
|
||||||
|
|
||||||
const rules = {
|
const rules = {
|
||||||
account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||||
password: [{ required: true, message: '请输入密码', trigger: 'blur', min: 5 }],
|
password: [{ required: true, message: '请输入密码', trigger: 'blur', min: 5 }],
|
||||||
@@ -151,6 +151,8 @@ const open = (tenantId: number) => {
|
|||||||
status: 1,
|
status: 1,
|
||||||
org_id: undefined
|
org_id: undefined
|
||||||
});
|
});
|
||||||
|
// 每次打开都按当前租户拉一次部门,避免沿用上一个租户的组织
|
||||||
|
loadOrgs(tenantId);
|
||||||
};
|
};
|
||||||
|
|
||||||
const submitForm = async () => {
|
const submitForm = async () => {
|
||||||
|
|||||||
@@ -39,6 +39,11 @@
|
|||||||
controls-position="right" />
|
controls-position="right" />
|
||||||
<div class="form-tip">默认 20 人;达到上限后需增购用户数才能继续开账号</div>
|
<div class="form-tip">默认 20 人;达到上限后需增购用户数才能继续开账号</div>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
<el-form-item label="附件空间(MB)" prop="storage_quota_mb">
|
||||||
|
<el-input-number v-model="formData.storage_quota_mb" :min="0" :step="512"
|
||||||
|
controls-position="right" />
|
||||||
|
<div class="form-tip">默认 500MB;实际可用空间取「本值」与「租户已购存储套餐」的较大者</div>
|
||||||
|
</el-form-item>
|
||||||
<el-form-item v-if="!formData.id" label="指定管理员" prop="admin_identifier">
|
<el-form-item v-if="!formData.id" label="指定管理员" prop="admin_identifier">
|
||||||
<el-input v-model="formData.admin_identifier" placeholder="选填:已有用户的账号或手机号" clearable />
|
<el-input v-model="formData.admin_identifier" placeholder="选填:已有用户的账号或手机号" clearable />
|
||||||
<div class="form-tip">填已有用户,创建后自动绑定为该租户的管理员(不新建账号、不修改其原密码);留空则租户暂无管理员</div>
|
<div class="form-tip">填已有用户,创建后自动绑定为该租户的管理员(不新建账号、不修改其原密码);留空则租户暂无管理员</div>
|
||||||
@@ -114,6 +119,7 @@ const initialData = {
|
|||||||
status: 1,
|
status: 1,
|
||||||
package_id: undefined as number | undefined,
|
package_id: undefined as number | undefined,
|
||||||
user_quota: 20,
|
user_quota: 20,
|
||||||
|
storage_quota_mb: 500,
|
||||||
admin_identifier: '' as string
|
admin_identifier: '' as string
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -124,14 +124,15 @@
|
|||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column prop="status" label="租户状态" width="80" align="center">
|
<!-- 状态与操作都固定在右侧:避免横向滚动时操作列盖住状态标签 -->
|
||||||
|
<el-table-column prop="status" label="租户状态" width="90" align="center" fixed="right">
|
||||||
<template #default="scope">
|
<template #default="scope">
|
||||||
<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{
|
<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{
|
||||||
scope.row.status === 1 ? "启用" : "禁用"
|
scope.row.status === 1 ? "启用" : "禁用"
|
||||||
}}</el-tag>
|
}}</el-tag>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column label="操作" width="160" align="center" fixed="right">
|
<el-table-column label="操作" width="110" align="center" fixed="right">
|
||||||
<template #default="scope">
|
<template #default="scope">
|
||||||
<div class="action-icons">
|
<div class="action-icons">
|
||||||
<el-tooltip content="编辑" placement="top">
|
<el-tooltip content="编辑" placement="top">
|
||||||
@@ -321,7 +322,20 @@ onMounted(() => {
|
|||||||
.action-icons {
|
.action-icons {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 6px;
|
justify-content: center;
|
||||||
|
gap: 4px;
|
||||||
|
|
||||||
|
// 图标按钮保持正方形热区,避免被单元格压缩变形
|
||||||
|
:deep(.el-button.is-text) {
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
padding: 0;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.el-icon) {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 暗色主题适配 =====
|
// ===== 暗色主题适配 =====
|
||||||
|
|||||||
@@ -342,7 +342,6 @@ onUnmounted(() => {
|
|||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
.statistics-container {
|
.statistics-container {
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
min-height: 100vh;
|
|
||||||
|
|
||||||
.data-overview {
|
.data-overview {
|
||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
|
|||||||
@@ -219,6 +219,25 @@ const cleanCaptchaInstance = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- 登录成功后的统一收尾 ---
|
||||||
|
// 重置动态路由加载状态并强制刷新菜单缓存:
|
||||||
|
// 否则可能沿用上一次会话的「已加载」标记或他人账号的菜单缓存,
|
||||||
|
// 导致业务路由没有按本次登录重建,跳转 /home 时命中 404。
|
||||||
|
const afterLogin = async () => {
|
||||||
|
try {
|
||||||
|
const [{ useMenuStore }, { resetDynamicRoutes }] = await Promise.all([
|
||||||
|
import("@/stores/menu"),
|
||||||
|
import("@/router/index"),
|
||||||
|
]);
|
||||||
|
resetDynamicRoutes();
|
||||||
|
await useMenuStore().refreshMenus();
|
||||||
|
} catch (err) {
|
||||||
|
// 菜单拉取失败不阻断登录,路由守卫会再次尝试加载
|
||||||
|
console.warn("登录后刷新菜单失败:", err);
|
||||||
|
}
|
||||||
|
router.push({ path: "/home" });
|
||||||
|
};
|
||||||
|
|
||||||
// --- 执行登录请求 ---
|
// --- 执行登录请求 ---
|
||||||
const performLoginRequest = async () => {
|
const performLoginRequest = async () => {
|
||||||
const res = await login({
|
const res = await login({
|
||||||
@@ -247,7 +266,7 @@ const performLoginRequest = async () => {
|
|||||||
const tabsStore = useTabsStore();
|
const tabsStore = useTabsStore();
|
||||||
tabsStore.resetTabs();
|
tabsStore.resetTabs();
|
||||||
|
|
||||||
router.push({ path: "/home" });
|
await afterLogin();
|
||||||
ElMessage.success("登录成功!");
|
ElMessage.success("登录成功!");
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
@@ -368,7 +387,7 @@ const startGeetest4 = async () => {
|
|||||||
const { useTabsStore } = await import("@/stores");
|
const { useTabsStore } = await import("@/stores");
|
||||||
const tabsStore = useTabsStore();
|
const tabsStore = useTabsStore();
|
||||||
tabsStore.resetTabs();
|
tabsStore.resetTabs();
|
||||||
router.push({ path: "/home" });
|
await afterLogin();
|
||||||
ElMessage.success("登录成功!");
|
ElMessage.success("登录成功!");
|
||||||
} else {
|
} else {
|
||||||
errorMsg.value = loginRes.msg || "登录失败";
|
errorMsg.value = loginRes.msg || "登录失败";
|
||||||
|
|||||||
@@ -181,7 +181,7 @@
|
|||||||
|
|
||||||
<AppTabbar v-if="!embedded" :group="slug" current="home" />
|
<AppTabbar v-if="!embedded" :group="slug" current="home" />
|
||||||
|
|
||||||
<!-- 常用功能选择器:从当前子系统可用功能中勾选 -->
|
<!-- 常用功能选择器:勾选 + 拖动手柄排序(顺序即首页宫格展示顺序) -->
|
||||||
<view v-if="pickerVisible" class="picker-mask" @tap="pickerVisible = false">
|
<view v-if="pickerVisible" class="picker-mask" @tap="pickerVisible = false">
|
||||||
<view class="picker-sheet" @tap.stop>
|
<view class="picker-sheet" @tap.stop>
|
||||||
<view class="picker-head">
|
<view class="picker-head">
|
||||||
@@ -189,23 +189,41 @@
|
|||||||
<text class="picker-title">选择常用功能</text>
|
<text class="picker-title">选择常用功能</text>
|
||||||
<text class="picker-save" @tap="savePicker">完成</text>
|
<text class="picker-save" @tap="savePicker">完成</text>
|
||||||
</view>
|
</view>
|
||||||
<text class="picker-tip">最多选 {{ QUICK_MAX }} 个,按点选顺序展示</text>
|
<text class="picker-tip">最多选 {{ QUICK_MAX }} 个,排在前 {{ QUICK_MAX }} 个会显示在首页;按住右侧手柄拖动可调整</text>
|
||||||
<scroll-view class="picker-body" scroll-y>
|
<scroll-view class="picker-body" scroll-y>
|
||||||
<view v-if="quickCandidates.length === 0" class="picker-empty">
|
<view v-if="pickerItems.length === 0" class="picker-empty">
|
||||||
当前子系统暂无可添加的功能
|
当前子系统暂无可添加的功能
|
||||||
</view>
|
</view>
|
||||||
|
<!-- 整份列表:前 pickerSelectedCount 个为已选(高亮 + 序号),拖进/拖出前 N 个即加入/移出常用功能 -->
|
||||||
<view
|
<view
|
||||||
v-for="(item, index) in quickCandidates"
|
v-for="(item, index) in pickerItems"
|
||||||
:key="item.id"
|
:key="item.id"
|
||||||
class="picker-item"
|
class="picker-row"
|
||||||
|
:class="{ on: index < pickerSelectedCount, dragging: dragId === item.id }"
|
||||||
|
:style="dragRowStyle(item)"
|
||||||
@tap="togglePick(item.id)"
|
@tap="togglePick(item.id)"
|
||||||
>
|
>
|
||||||
<view class="tint-icon picker-icon" :class="item.locked ? 'tint-off' : 'tint-' + (index % 8)">
|
<view class="tint-icon picker-icon" :class="item.locked ? 'tint-off' : 'tint-' + (index % 8)">
|
||||||
<FaIcon :name="item.icon || fallbackIcon" color="#ffffff" :size="16" />
|
<FaIcon :name="item.icon || fallbackIcon" color="#ffffff" :size="16" />
|
||||||
</view>
|
</view>
|
||||||
<text class="picker-name">{{ item.title }}</text>
|
<text class="picker-name">{{ item.title }}</text>
|
||||||
<view class="picker-check" :class="{ on: pickedSet.has(item.id) }">
|
<view class="picker-state">
|
||||||
<FaIcon v-if="pickedSet.has(item.id)" name="check" color="#ffffff" :size="12" />
|
<text v-if="index < pickerSelectedCount" class="picker-num">{{ index + 1 }}</text>
|
||||||
|
<view v-else class="picker-check" />
|
||||||
|
</view>
|
||||||
|
<view
|
||||||
|
class="picker-handle"
|
||||||
|
@tap.stop="noop"
|
||||||
|
@touchstart.stop="onDragStart($event, item)"
|
||||||
|
@touchmove.stop.prevent="onDragMove"
|
||||||
|
@touchend.stop="onDragEnd"
|
||||||
|
@touchcancel.stop="onDragEnd"
|
||||||
|
>
|
||||||
|
<FaIcon
|
||||||
|
name="grip-vertical"
|
||||||
|
:color="dragId === item.id ? '#2563eb' : '#c3cbd9'"
|
||||||
|
:size="14"
|
||||||
|
/>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</scroll-view>
|
</scroll-view>
|
||||||
@@ -288,25 +306,105 @@ const quickMenus = computed(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// ============ 常用功能选择器(末位「+」) ============
|
// ============ 常用功能选择器(末位「+」) ============
|
||||||
|
// 单一列表模型:pickerIds 为全部可选功能的顺序,前 pickerSelectedCount 个即「已选」,
|
||||||
|
// 也就是首页宫格展示的常用功能——拖动改变顺序时,进出前 N 个即自动加入/移出常用功能。
|
||||||
const pickerVisible = ref(false)
|
const pickerVisible = ref(false)
|
||||||
const pickerSelected = ref([])
|
const pickerIds = ref([])
|
||||||
const pickedSet = computed(() => new Set(pickerSelected.value))
|
const pickerSelectedCount = ref(0)
|
||||||
|
|
||||||
|
/** 选择器列表(按当前顺序渲染全部功能) */
|
||||||
|
const pickerItems = computed(() => {
|
||||||
|
const byId = {}
|
||||||
|
quickCandidates.value.forEach((m) => { byId[m.id] = m })
|
||||||
|
return pickerIds.value.map((id) => byId[id]).filter(Boolean)
|
||||||
|
})
|
||||||
|
|
||||||
function openPicker() {
|
function openPicker() {
|
||||||
pickerSelected.value = quickMenus.value.map((m) => m.id)
|
resetDrag()
|
||||||
|
const picked = quickMenus.value.map((m) => m.id).slice(0, QUICK_MAX)
|
||||||
|
const pickedSet = new Set(picked)
|
||||||
|
const rest = quickCandidates.value.map((m) => m.id).filter((id) => !pickedSet.has(id))
|
||||||
|
pickerIds.value = picked.concat(rest)
|
||||||
|
pickerSelectedCount.value = picked.length
|
||||||
pickerVisible.value = true
|
pickerVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 点整行:已选→移出到已选区之后;未选→插到已选区末尾(最多 QUICK_MAX 个) */
|
||||||
function togglePick(id) {
|
function togglePick(id) {
|
||||||
const i = pickerSelected.value.indexOf(id)
|
const ids = pickerIds.value.slice()
|
||||||
if (i >= 0) pickerSelected.value.splice(i, 1)
|
const i = ids.indexOf(id)
|
||||||
else {
|
if (i < 0) return
|
||||||
if (pickerSelected.value.length >= QUICK_MAX) {
|
if (i < pickerSelectedCount.value) {
|
||||||
|
ids.splice(i, 1)
|
||||||
|
ids.splice(Math.max(0, pickerSelectedCount.value - 1), 0, id)
|
||||||
|
pickerSelectedCount.value = Math.max(0, pickerSelectedCount.value - 1)
|
||||||
|
} else {
|
||||||
|
if (pickerSelectedCount.value >= QUICK_MAX) {
|
||||||
uni.showToast({ title: `最多添加 ${QUICK_MAX} 个常用功能`, icon: 'none' })
|
uni.showToast({ title: `最多添加 ${QUICK_MAX} 个常用功能`, icon: 'none' })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
pickerSelected.value.push(id)
|
ids.splice(i, 1)
|
||||||
|
ids.splice(pickerSelectedCount.value, 0, id)
|
||||||
|
pickerSelectedCount.value += 1
|
||||||
}
|
}
|
||||||
|
pickerIds.value = ids
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 列表拖动排序 ----
|
||||||
|
// 行高与样式 .picker-row 的 height 保持同一数值;拖动只作用于右侧手柄,
|
||||||
|
// 手柄上 catchtouchmove 阻止 scroll-view 跟随滚动,因此不会与列表滚动冲突。
|
||||||
|
const SORT_ROW_RPX = 100
|
||||||
|
const dragId = ref(null)
|
||||||
|
const dragOffset = ref(0)
|
||||||
|
let dragStartY = 0
|
||||||
|
let dragRowH = 1
|
||||||
|
let dragFromIndex = -1
|
||||||
|
|
||||||
|
/** 拖拽行跟随手指的残余位移(其余行由数组重排自然换位) */
|
||||||
|
function dragRowStyle(item) {
|
||||||
|
if (dragId.value !== item.id) return ''
|
||||||
|
return `transform: translateY(${dragOffset.value}px);`
|
||||||
|
}
|
||||||
|
|
||||||
|
function noop() {}
|
||||||
|
|
||||||
|
function onDragStart(e, item) {
|
||||||
|
const touch = (e.touches && e.touches[0]) || {}
|
||||||
|
const from = pickerIds.value.indexOf(item.id)
|
||||||
|
if (from < 0) return
|
||||||
|
dragStartY = Number(touch.clientY || 0)
|
||||||
|
dragRowH = uni.upx2px(SORT_ROW_RPX) || 1
|
||||||
|
dragFromIndex = from
|
||||||
|
dragOffset.value = 0
|
||||||
|
dragId.value = item.id
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDragMove(e) {
|
||||||
|
if (dragId.value === null || dragFromIndex < 0) return
|
||||||
|
const touch = (e.touches && e.touches[0]) || {}
|
||||||
|
const delta = Number(touch.clientY || 0) - dragStartY
|
||||||
|
const last = pickerIds.value.length - 1
|
||||||
|
const target = Math.max(0, Math.min(last, dragFromIndex + Math.round(delta / dragRowH)))
|
||||||
|
const cur = pickerIds.value.indexOf(dragId.value)
|
||||||
|
if (cur >= 0 && target !== cur) {
|
||||||
|
const ids = pickerIds.value.slice()
|
||||||
|
ids.splice(cur, 1)
|
||||||
|
ids.splice(target, 0, dragId.value)
|
||||||
|
pickerIds.value = ids
|
||||||
|
}
|
||||||
|
// 抵消已经跨过的整行位移,剩余部分让行跟着手指走;越界时限制在一行内
|
||||||
|
const residual = delta - (target - dragFromIndex) * dragRowH
|
||||||
|
dragOffset.value = Math.max(-dragRowH, Math.min(dragRowH, residual))
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetDrag() {
|
||||||
|
dragId.value = null
|
||||||
|
dragOffset.value = 0
|
||||||
|
dragFromIndex = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDragEnd() {
|
||||||
|
resetDrag()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function savePicker() {
|
async function savePicker() {
|
||||||
@@ -314,7 +412,7 @@ async function savePicker() {
|
|||||||
await request({
|
await request({
|
||||||
url: '/api/quick-menus',
|
url: '/api/quick-menus',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data: { menu_ids: pickerSelected.value }
|
data: { menu_ids: pickerIds.value.slice(0, pickerSelectedCount.value) }
|
||||||
})
|
})
|
||||||
clearHomeCache()
|
clearHomeCache()
|
||||||
await load(true)
|
await load(true)
|
||||||
@@ -791,6 +889,7 @@ onShow(() => {
|
|||||||
.picker-tip {
|
.picker-tip {
|
||||||
padding: 18rpx $page-padding-x 4rpx;
|
padding: 18rpx $page-padding-x 4rpx;
|
||||||
font-size: 22rpx;
|
font-size: 22rpx;
|
||||||
|
line-height: 1.5;
|
||||||
color: $color-text-muted;
|
color: $color-text-muted;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -808,12 +907,56 @@ onShow(() => {
|
|||||||
color: $color-text-muted;
|
color: $color-text-muted;
|
||||||
}
|
}
|
||||||
|
|
||||||
.picker-item {
|
/* 行高固定,拖动排序按行高换算目标位置;改这里需同步 SORT_ROW_RPX */
|
||||||
|
.picker-row {
|
||||||
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 20rpx;
|
gap: 18rpx;
|
||||||
padding: 22rpx 0;
|
height: 100rpx;
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 0 0 0 16rpx;
|
||||||
border-bottom: 1rpx solid $color-divider;
|
border-bottom: 1rpx solid $color-divider;
|
||||||
|
|
||||||
|
/* 前 N 个(已选)高亮,拖动进出即加入/移出常用功能 */
|
||||||
|
&.on {
|
||||||
|
background: #f2f7ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.dragging {
|
||||||
|
z-index: 3;
|
||||||
|
background: #ffffff;
|
||||||
|
border-radius: 16rpx;
|
||||||
|
border-bottom-color: transparent;
|
||||||
|
box-shadow: 0 10rpx 26rpx rgba(15, 23, 42, 0.14);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker-state {
|
||||||
|
width: 40rpx;
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker-num {
|
||||||
|
font-size: 22rpx;
|
||||||
|
font-weight: 600;
|
||||||
|
color: $color-primary;
|
||||||
|
}
|
||||||
|
|
||||||
|
.picker-handle {
|
||||||
|
width: 64rpx;
|
||||||
|
height: 100rpx;
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
|
||||||
|
&:active {
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.picker-icon {
|
.picker-icon {
|
||||||
@@ -831,20 +974,13 @@ onShow(() => {
|
|||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 未选中行:空心圆(点击整行加入常用功能) */
|
||||||
.picker-check {
|
.picker-check {
|
||||||
width: 40rpx;
|
width: 36rpx;
|
||||||
height: 40rpx;
|
height: 36rpx;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
border: 2rpx solid #c7cede;
|
border: 2rpx solid #c7cede;
|
||||||
display: flex;
|
box-sizing: border-box;
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
flex-shrink: 0;
|
|
||||||
|
|
||||||
&.on {
|
|
||||||
background: $color-primary;
|
|
||||||
border-color: $color-primary;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.err-box {
|
.err-box {
|
||||||
|
|||||||
Reference in new issue
Block a user