2026-08-13 18:16:38 +08:00

768 lines
23 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="order-sub-container" :style="{ height: containerHeight }">
<scan-box
ref="scanBox"
width="220px"
:tree-props="{ children: 'children', label: 'label' }"
:auto-submit="false"
:preset-tree="presetTree"
:available-fields="availableFieldsRef"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
@submit="handleSubmit"
/>
<div class="main-content">
<div class="toolbar">
<div class="toolbar-left">
<order-toolbar-button-group
:buttons="toolbarButtons"
:resolve-disabled="resolveButtonDisabled"
:resolve-loading="resolveButtonLoading"
:resolve-label="resolveButtonLabel"
:layout-key="toolbarLayoutKey"
@action="handleToolbarButtonClick"
/>
</div>
</div>
<div class="upper-wrapper">
<upper-table
ref="upperTable"
title="店铺列表"
default-align="center"
table-id="setting-shops"
:data="tableData"
:columns="columns"
:table-size="tableSize"
:pagination="pagination"
:show-index="true"
:show-actions="true"
:loading="loading"
:query-time="queryTime"
row-key="id"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadList"
>
<template #column-auth_expire_at="{ row }">
<el-tag :type="isAuthExpired(row.auth_expire_at) ? 'danger' : 'info'" size="small">
{{ formatAuthExpireAt(row.auth_expire_at) }}
</el-tag>
</template>
<template #column-access_token="{ row }">
<div v-if="row.access_token" class="token-cell">
<span class="token-text">{{ tokenVisibleMap[row.id] ? row.access_token : '●●●●●●●●●●●●●●●●●●●●●●●●' }}</span>
<el-button
link
type="primary"
size="small"
@click.stop="toggleTokenVisible(row)"
>
{{ tokenVisibleMap[row.id] ? '隐藏' : '查看' }}
</el-button>
<el-button
link
type="success"
size="small"
@click.stop="copyToken(row.access_token)"
>
复制
</el-button>
</div>
<span v-else class="token-empty">--</span>
</template>
<template #column-status="{ row }">
<el-tag :type="formatShopStatus(row.status).type" size="small">
{{ formatShopStatus(row.status).text }}
</el-tag>
</template>
<template #column-actions="{ row }">
<div class="wave-operation-actions">
<el-button link type="primary" size="small" @click.stop="openEdit(row)">编辑</el-button>
<el-button link type="success" size="small" @click.stop="openAuthorize(row)">授权</el-button>
<el-button link type="danger" size="small" @click.stop="handleDelete(row)">删除</el-button>
</div>
</template>
<template #empty>
<div class="empty-tip">暂无店铺数据,可调整左侧筛选条件</div>
</template>
</upper-table>
</div>
</div>
<el-dialog
v-model="dialogVisible"
:title="dialogMode === 'create' ? '新增店铺' : '编辑店铺'"
width="560px"
align-center
@close="resetForm"
>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
<el-form-item label="平台" prop="platform_code">
<el-select
v-model="formData.platform_code"
placeholder="请选择平台"
filterable
style="width: 100%"
>
<el-option
v-for="item in platformOptions"
:key="item.code"
:label="item.label || item.name"
:value="item.code"
/>
</el-select>
</el-form-item>
<el-form-item label="自定义名称" prop="custom_name">
<el-input v-model="formData.custom_name" placeholder="最大 100 字符" maxlength="100" show-word-limit />
</el-form-item>
<el-form-item label="店铺名称" prop="shop_name">
<el-input v-model="formData.shop_name" placeholder="最大 100 字符" maxlength="100" show-word-limit />
</el-form-item>
<el-form-item v-if="dialogMode === 'create'">
<el-text type="info" size="small">
店铺名称由服务端生成待授权占位名,完成平台授权后将自动同步真实店铺名。
</el-text>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
</template>
</el-dialog>
<el-dialog
v-model="authDialogVisible"
title="店铺授权"
width="560px"
align-center
@close="resetAuthForm"
>
<el-form ref="authFormRef" :model="authForm" :rules="authRules" label-width="110px">
<el-form-item label="店铺">
<el-input :model-value="authForm.shopLabel" disabled />
</el-form-item>
<el-form-item label="平台">
<el-input :model-value="authForm.platform_name || authForm.platformCode || '--'" disabled />
</el-form-item>
<el-form-item label="授权">
<el-button type="primary" plain :loading="authLinkLoading" @click="handleOpenAuthorizeLink">
去授权
</el-button>
</el-form-item>
<template v-if="isWechatChannel">
<el-form-item label="appId" prop="appId">
<el-input v-model="authForm.appId" placeholder="请输入视频号 appId" clearable />
</el-form-item>
<el-form-item label="toUserName" prop="toUserName">
<el-input v-model="authForm.toUserName" placeholder="请输入视频号 toUserName" clearable />
</el-form-item>
</template>
<el-form-item v-else-if="authNeedCallbackUrl" label="回调地址" prop="callbackurl">
<el-input
v-model="authForm.callbackurl"
placeholder="请输入授权完成后的回调 URL"
clearable
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="authDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="authConfirmLoading" @click="submitConfirmAuthorize">
确认授权
</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
import type { ToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
import { safeInvoke } from '@/utils/safe-invoke'
import { getPrintPlatformList } from '@/api/setting.expressinterface/expressInterface'
import { getPlatformOauthLink } from '@/api/index/index'
import {
shopGetAuthorizeSessionKey,
shopsAdd,
shopsDel,
shopsEdit,
shopsList
} from '@/api/shops/shops'
import { useSettingsStore } from '@/stores/modules/settings'
import {
buildShopListPayload,
formatShopStatus,
normalizeShopScanConditionToWhere,
shopColumns,
shopScanFields,
type ShopRecord
} from './shops-config'
type PlatformOption = {
code: string
name: string
label?: string
need_callback_url?: number | boolean
}
const settingsStore = useSettingsStore()
const scanBox = ref<any>(null)
const upperTable = ref<any>(null)
const presetTree = ref<any[]>([])
const availableFieldsRef = reactive(JSON.parse(JSON.stringify(shopScanFields)))
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
const containerHeight = computed(() =>
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
)
const columns = shopColumns
const loading = ref(false)
const saving = ref(false)
const authDialogVisible = ref(false)
const authLinkLoading = ref(false)
const authConfirmLoading = ref(false)
const authFormRef = ref<FormInstance>()
const tableData = ref<ShopRecord[]>([])
const platformOptions = ref<PlatformOption[]>([])
const tokenVisibleMap = reactive<Record<number, boolean>>({})
const queryTime = ref(0)
const tableSize = ref<'small' | 'default' | 'large'>('small')
const currentConditionRaw = ref<any>(null)
const toolbarButtons: ToolbarButtonConfig[] = [
{ key: 'refresh', label: '刷新', category: 'refresh', size: 'small', loadingKey: 'loading', action: 'loadList' },
{ key: 'create', label: '新增店铺', category: 'action', size: 'small', action: 'openCreate' },
]
const buttonLoadingMap = computed(() => ({
loading: loading.value
}))
const buttonDisabledMap = computed(() => ({}))
const buttonLabelMap = computed(() => ({}))
const toolbarLayoutKey = computed(() =>
JSON.stringify({ loading: buttonLoadingMap.value, disabled: buttonDisabledMap.value, labels: buttonLabelMap.value })
)
function resolveButtonLoading(loadingKey?: string) {
if (!loadingKey) return false
return Boolean((buttonLoadingMap.value as Record<string, boolean>)[loadingKey])
}
function resolveButtonDisabled(disabledKey?: string) {
if (!disabledKey) return false
return Boolean((buttonDisabledMap.value as Record<string, boolean>)[disabledKey])
}
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
if (!dynamicLabelKey) return defaultLabel
return (buttonLabelMap.value as Record<string, string>)[dynamicLabelKey] || defaultLabel
}
const toolbarActionMap: Record<string, () => void> = {
loadList: () => { void loadList() },
openCreate: () => openCreate()
}
function handleToolbarButtonClick(action: ToolbarButtonConfig['action']) {
const handler = toolbarActionMap[action]
if (!handler) return
safeInvoke(() => handler())
}
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const formRef = ref<FormInstance>()
const formData = reactive({
id: undefined as number | undefined,
platform_code: '',
custom_name: '',
shop_name: ''
})
const rules: FormRules = {
platform_code: [{ required: true, message: '请选择平台', trigger: 'change' }],
custom_name: [
{ required: true, message: '请输入自定义名称', trigger: 'blur' },
{ max: 100, message: '最多 100 个字符', trigger: 'blur' }
],
shop_name: [
{ max: 100, message: '最多 100 个字符', trigger: 'blur' }
]
}
const authForm = reactive({
shopId: undefined as number | undefined,
shopLabel: '',
platform_name: '',
platformCode: '',
callbackurl: '',
appId: '',
toUserName: ''
})
/** 视频号平台需要 appId + toUserName,callbackUrl 固定为 "-" */
const isWechatChannel = computed(() => {
const code = String(authForm.platformCode || '').trim().toLowerCase()
const name = String(authForm.platform_name || '').trim().toLowerCase()
return (
code.includes('shipinhao') ||
code.includes('视频号') ||
name.includes('视频号')
)
})
const authNeedCallbackUrl = computed(() => {
const code = String(authForm.platformCode || '').trim()
if (!code) return false
// 视频号不需要显示 callbackurl
if (isWechatChannel.value) return false
const platform = platformOptions.value.find((item) => item.code === code)
return isNeedCallbackUrl(platform?.need_callback_url)
})
const authRules = computed<FormRules>(() => {
if (isWechatChannel.value) {
return {
appId: [{ required: true, message: '请输入 appId', trigger: 'blur' }],
toUserName: [{ required: true, message: '请输入 toUserName', trigger: 'blur' }]
}
}
if (!authNeedCallbackUrl.value) return {}
return {
callbackurl: [{ required: true, message: '请输入回调地址', trigger: 'blur' }]
}
})
const isSuccess = (res: any) => res && [0, 1, 200].includes(res.code)
function isNeedCallbackUrl(value: unknown): boolean {
return value === 1 || value === '1' || value === true
}
function extractOauthUrl(res: any): string {
const data = res?.data
if (typeof data === 'string') return data
if (!data || typeof data !== 'object') return ''
const candidates = [
data.url,
data.link,
data.oauth_link,
data.authorize_url,
data.authLink,
data.oauth_url,
data.oauthUrl,
data.redirect_url,
data.redirectUrl
]
const hit = candidates.find((item) => typeof item === 'string' && item.trim())
return hit ? String(hit).trim() : ''
}
function syncSelectOptions() {
const platformField = availableFieldsRef.find((f: any) => f.value === 'platform_code')
if (platformField) {
platformField.options = platformOptions.value.map((item) => ({
label: item.label || item.name,
value: item.code
}))
}
}
function parseAuthExpireAt(value: unknown): number | null {
if (value === null || value === undefined || value === '') return null
if (typeof value === 'number' && Number.isFinite(value)) {
return value > 1e12 ? value : value * 1000
}
const raw = String(value).trim()
if (!raw) return null
if (/^\d+$/.test(raw)) {
const num = Number(raw)
if (!Number.isFinite(num)) return null
return num > 1e12 ? num : num * 1000
}
const ts = new Date(raw).getTime()
return Number.isFinite(ts) ? ts : null
}
function formatAuthExpireAt(value: unknown): string {
const ts = parseAuthExpireAt(value)
if (ts === null) {
const text = String(value ?? '').trim()
return text || '--'
}
const d = new Date(ts)
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
function isAuthExpired(value: unknown): boolean {
const ts = parseAuthExpireAt(value)
if (ts === null) return false
return ts < Date.now()
}
function toggleTokenVisible(row: ShopRecord) {
if (!row.id) return
tokenVisibleMap[row.id] = !tokenVisibleMap[row.id]
}
async function copyToken(token: string) {
if (!token) return
try {
await navigator.clipboard.writeText(token)
ElMessage.success('密钥已复制到剪贴板')
} catch {
ElMessage.error('复制失败,请手动复制')
}
}
async function loadList() {
if (loading.value) return
loading.value = true
const start = Date.now()
try {
const where = normalizeShopScanConditionToWhere(currentConditionRaw.value)
const res: any = await shopsList(
buildShopListPayload({
page: pagination.currentPage,
pageSize: pagination.pageSize,
where
})
)
if (!isSuccess(res)) {
ElMessage.error(res?.message || '获取店铺列表失败')
tableData.value = []
pagination.total = 0
return
}
const data = res?.data || {}
tableData.value = data.list || []
pagination.total = Number(data.pagination?.total ?? data.total ?? 0)
} catch {
tableData.value = []
pagination.total = 0
ElMessage.error('获取店铺列表失败')
} finally {
queryTime.value = Date.now() - start
loading.value = false
}
}
async function loadPlatformOptions() {
try {
const res: any = await getPrintPlatformList({})
if (!isSuccess(res)) {
platformOptions.value = []
return
}
platformOptions.value = (res?.data || []).map((item: any) => ({
code: item.platform_code || item.code,
name: item.platform_name || item.name,
label: item.label || item.platform_name || item.name,
need_callback_url: item.need_callback_url
}))
} catch {
platformOptions.value = []
}
}
function handleConditionChange(condition: any) {
currentConditionRaw.value = condition
pagination.currentPage = 1
loadList()
}
function handleSubmit() {
pagination.currentPage = 1
loadList()
}
function handleConditionClear() {
currentConditionRaw.value = null
pagination.currentPage = 1
loadList()
}
function handleConditionReset() {
currentConditionRaw.value = null
pagination.currentPage = 1
if (scanBox.value?.reset) {
scanBox.value.reset()
} else if (scanBox.value?.clear) {
scanBox.value.clear()
}
loadList()
}
function handlePageChange(page: number) {
pagination.currentPage = page
loadList()
}
function handlePageSizeChange(size: number) {
pagination.pageSize = size
pagination.currentPage = 1
loadList()
}
function resetForm() {
formData.id = undefined
formData.platform_code = ''
formData.custom_name = ''
formData.shop_name = ''
formRef.value?.clearValidate()
}
function openCreate() {
dialogMode.value = 'create'
dialogVisible.value = true
resetForm()
}
function openEdit(row: ShopRecord) {
if (!row.id) return
dialogMode.value = 'edit'
dialogVisible.value = true
formData.id = row.id
formData.platform_code = row.platform_code || ''
formData.custom_name = row.custom_name || ''
formData.shop_name = row.shop_name || ''
formRef.value?.clearValidate()
}
async function submitForm() {
if (!formRef.value || saving.value) return
const valid = await formRef.value.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
if (dialogMode.value === 'create') {
const payload: {
platform_code: string
custom_name: string
} = {
platform_code: formData.platform_code,
custom_name: formData.custom_name.trim()
}
const res: any = await shopsAdd(payload)
if (!isSuccess(res)) {
ElMessage.error(res?.message || '新增失败')
return
}
ElMessage.success('新增成功')
} else {
if (!formData.id) return
const platformCode = formData.platform_code.trim()
const customName = formData.custom_name.trim()
const shopName = formData.shop_name.trim()
if (!platformCode && !customName && !shopName) {
ElMessage.warning('请至少修改平台、自定义名称或店铺名称')
return
}
const payload: {
id: number
platform_code?: string
custom_name?: string
shop_name?: string
} = { id: formData.id }
if (platformCode) payload.platform_code = platformCode
if (customName) payload.custom_name = customName
if (shopName) payload.shop_name = shopName
const res: any = await shopsEdit(payload)
if (!isSuccess(res)) {
ElMessage.error(res?.message || '更新失败')
return
}
ElMessage.success('更新成功')
}
dialogVisible.value = false
loadList()
} catch {
ElMessage.error('保存失败')
} finally {
saving.value = false
}
}
function handleDelete(row: ShopRecord) {
if (!row.id) return
const name = row.custom_name || row.shop_name || String(row.id)
ElMessageBox.confirm(`确认删除店铺「${name}」吗?删除后相关快递接口将不可用`, '提示', { type: 'warning' })
.then(async () => {
const res: any = await shopsDel({ id: row.id as number })
if (!isSuccess(res)) {
ElMessage.error(res?.message || '删除失败')
return
}
ElMessage.success('删除成功')
if (tableData.value.length === 1 && pagination.currentPage > 1) {
pagination.currentPage -= 1
}
loadList()
})
.catch(() => undefined)
}
function resetAuthForm() {
authForm.shopId = undefined
authForm.shopLabel = ''
authForm.platform_name = ''
authForm.platformCode = ''
authForm.callbackurl = ''
authForm.appId = ''
authForm.toUserName = ''
authFormRef.value?.clearValidate()
}
function openAuthorize(row: ShopRecord) {
if (!row.id) return
authForm.shopId = row.id
authForm.shopLabel = row.custom_name || row.shop_name || String(row.id)
authForm.platform_name = String(row.platform_name || '').trim()
authForm.platformCode = String(row.platform_code || '').trim()
authForm.callbackurl = ''
authDialogVisible.value = true
authFormRef.value?.clearValidate()
}
async function handleOpenAuthorizeLink() {
if (authLinkLoading.value || !authForm.shopId) return
const platformCode = String(authForm.platformCode || '').trim()
if (!platformCode) {
ElMessage.warning('未获取到平台编码')
return
}
authLinkLoading.value = true
try {
const res: any = await getPlatformOauthLink({
code: platformCode,
platform_code: platformCode,
platformCode
})
if (!isSuccess(res)) {
ElMessage.error(res?.message || '获取授权链接失败')
return
}
const oauthUrl = extractOauthUrl(res)
if (!oauthUrl) {
ElMessage.error('未获取到有效的授权链接')
return
}
const win = window.open(oauthUrl, '_blank')
if (!win) {
window.location.href = oauthUrl
}
} catch {
ElMessage.error('获取授权链接失败')
} finally {
authLinkLoading.value = false
}
}
async function submitConfirmAuthorize() {
if (authConfirmLoading.value || !authForm.shopId || !authFormRef.value) return
const valid = await authFormRef.value.validate().catch(() => false)
if (!valid) return
authConfirmLoading.value = true
try {
const payload: { id: number; callbackurl: string; appId?: string; toUserName?: string } = {
id: authForm.shopId,
callbackurl: ''
}
if (isWechatChannel.value) {
payload.appId = authForm.appId.trim()
payload.toUserName = authForm.toUserName.trim()
payload.callbackurl = '-'
} else {
payload.callbackurl = String(authForm.callbackurl || '').trim()
}
const res: any = await shopGetAuthorizeSessionKey(payload)
if (!isSuccess(res)) {
ElMessage.error(res?.message || '确认授权失败')
return
}
ElMessage.success(res?.data?.message || res?.message || '授权成功')
authDialogVisible.value = false
loadList()
} catch {
ElMessage.error('确认授权失败')
} finally {
authConfirmLoading.value = false
}
}
onMounted(async () => {
await loadPlatformOptions()
syncSelectOptions()
await loadList()
})
</script>
<style scoped lang="scss">
@use "../../../order/orderManagement/styles/order-sub.scss";
.empty-tip {
text-align: center;
font-size: 13px;
color: #909399;
padding: 16px;
}
.wave-operation-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
}
.auth-tip {
display: block;
margin-top: 8px;
line-height: 1.5;
}
.token-cell {
display: inline-flex;
align-items: center;
gap: 4px;
max-width: 100%;
}
.token-text {
font-family: 'Courier New', monospace;
font-size: 12px;
color: #303133;
word-break: break-all;
}
.token-empty {
color: #c0c4cc;
}
</style>