WEB/src/views/system/setting/basicManagement/newview/pages/MiniProgramConfigForm.vue
2026-09-23 18:10:36 +08:00

3410 lines
122 KiB
Vue
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

<!--
MiniProgramConfigForm — 微信小程序配置页
对接接口:
- setting.warehouse.getweChatApp(settingWarehouseGetWeChatApp):拉取当前仓库已授权的微信小程序配置
- wechat.getAuthUrl(wechatGetAuthUrl):未配置时点击「去授权」获取授权链接,并在新小窗口中打开
- wechat.queryauth(wechatQueryAuth):查询当前仓库小程序的微信认证进度(左菜单「认证状态」)
(返回 `{is_verified, appid, verify_type_id/verify_type_text, principal_name, signature, taskid,
task_status/task_status_text, apply_status/apply_status_text}`)
- wechat.wxaauth(wechatWxaauth):发起小程序认证(「认证状态」未认证时的「发起微信认证」弹窗):
新版入参 = customer_type / account_name / account_name_type / pay_type / third_party_phone / contact_info{name,email,mobile}
+ auth_data 白名单(qualification / qualification_other / account_supplemental / auth_ident_material 等,
图片传 COS URL,后端换 mediaid 后以 `{ auth_data }` 包裹调微信 wxa/sec/wxaauth);
返回 taskid / auth_url;已认证时后端拒绝重复发起
- wechat.getAuthorizerInfo(wechatGetAuthorizerInfo):同步微信侧小程序基础信息
(昵称/主体/认证类型/账号状态/权限集 → 落库后刷新本页;头部「同步微信信息」按钮)
- wechat.registerMiniprogram(wechatRegisterMiniprogram):提交企业信息创建企业小程序注册任务
(「代注册小程序」弹窗;后端调微信 fastregisterweapp,法人微信收模板消息做人脸核身,
接口返回 errcode/errmsg、**不返回链接**,故不再开小窗)
- wechat.getTemplateList(wechatGetTemplateList):拉普通代码模板库列表(左菜单「发布」,后端缓存 24h)
- wechat.commit(wechatCommit):选定模板上传代码、生成体验版(需授权权限集 18)
(**入参只有 template_id**:版本号/代码描述由后端从模板库的模板取用,ext_json 由后端固定生成
`{extEnable:true, extAppid:小程序appid}`;故页面不再展示这三项)
- wechat.getTrialQRCode(wechatGetTrialQRCode):获取体验版二维码(后端转存 COS 后返回 URL)
- wechat.submitAudit(wechatSubmitAudit):提交代码审核(后端仅在 audit_status!=1 时允许;回写 audit_id)
⚠️ 无审核状态查询接口,页面只能回显「已提交 + 审核单 ID」
- wechat.userList(wechatUserList):小程序用户列表(左菜单「微信用户」;where/pagination/sort,
app_id 可指定单个小程序,is_bound 标识是否已绑定真实账号,
agreement_version_id 为该用户登录时同意的协议版本记录 id)
- wechat.getAgreementVersion(wechatGetAgreementVersion):按协议版本记录 id 取协议内容(需登录、免权限)
两个入口:①「用户协议」页常显的「按版本记录 id 查看协议原文」(查询 / 调试);
②「微信用户」行操作「查看协议」回看该用户同意时的协议原文
- wechat.bindByEmployee(wechatBindByEmployee):按工号绑定微信(「微信用户」行操作「绑定工号」;
传工号 id + 微信记录 id,后端写 wms_user_oauth.user_id;已绑同一账号幂等;需同名接口权限)
- wechat.getUserAgreement(wechatGetUserAgreement):读当前仓库小程序「用户须知」富文本(左菜单「用户协议」);
返回**最新版本**:appid / nickname / version_id(记录 id,自增即最新)/ text
- wechat.setUserAgreement(wechatSetUserAgreement):保存用户须知 —— **每次提交自动新增一个版本**
(直接插入副表 wms_wechat_agreement_version,id 自增即最新),并清除小程序端读取的 24h 缓存;
响应回带新增的 version_id;text 可传空字符串清空
- wechat.getUserAgreementText(wechatGetUserAgreementText):**免登录**、小程序端按 appid 读取用户须知
(Redis 缓存 24h,响应带 version_id / from_cache);网页端仅用于预览小程序实际拿到的内容
交互约定:
1) 页面挂载即拉取配置;无配置(未授权)时提示「需要授权」并高亮「去授权」入口
2) 授权链接**不自动打开**:必须用户点击按钮后才请求接口并弹小窗
3) 小窗口打开后:轮询配置,流程完成自动刷新;小窗关闭后做最后一次刷新
4) 域名限制:微信小程序**授权页**只能从主域名进入(主域名 = 品牌豁免域名
VITE_FRONT_CONFIG_EXEMPT_HOSTS,与 frontBrand 同源);非主域名下禁用授权按钮并提示。
代注册 / 发布走纯后端接口、无微信页面跳转,故不做域名限制。
5) 认证状态:切到「认证状态」菜单时按需查询一次,可手动刷新
6) 发布:切到「发布」菜单时按需拉模板列表;上传代码成功后自动刷新配置并重取体验版二维码;
提交审核后可回显审核单 ID
7) 失败响应识别:本套接口失败时返回 `{flag:'failure', code:0, success:false, message, data:null}`,
而 axios 拦截器把 code=0 也当作成功码 → 必须用 `okCode(res)` 显式判 flag/success,
授权类失败(如「小程序未授权相关权限(权限集 18/86),请重新授权」)即使是静默刷新也要提示
8) 微信用户:切到「微信用户」菜单时按需拉列表(分页 + 昵称模糊 + 绑定状态 + 小程序筛选);
绑定状态用 `user_id` 的 gt/eq 0 表达(is_bound 不在后端 where 白名单内)
使用方:
1) basicManagement/newview 的 viewType='form' 标签页「微信小程序」
2) 独立页面 views/system/setting/miniprogram/index.vue(备用入口,共用本组件)
-->
<template>
<div v-loading="pageLoading" class="mp-config-page">
<div class="settings-header">
<div class="header-text">
<span class="title">微信小程序</span>
<span class="sub">
当前仓库已授权的微信小程序配置(数据来自微信授权,只读)
<template v-if="lastLoadedAt">|更新于 {{ lastLoadedAt }}</template>
|当前域名:{{ currentHost }}{{ isMainDomain ? '' : '(非主域名,不可授权)' }}
</span>
</div>
<div class="header-actions">
<el-button :disabled="pageLoading" @click="loadConfig">刷新</el-button>
<!-- 同步微信侧基础信息(主体/认证类型/账号状态/权限集)→ 后端落库后刷新本页 -->
<el-tooltip :disabled="authorized" content="需先完成小程序授权" placement="bottom-end">
<span class="mp-auth-trigger">
<el-button
:disabled="!authorized"
:loading="authorizerInfoLoading"
@click="handleSyncAuthorizerInfo"
>
同步微信信息
</el-button>
</span>
</el-tooltip>
<!-- 代注册走纯后端接口(无微信页面跳转),不受主域名限制 -->
<el-button @click="handleRegister">代注册小程序</el-button>
<el-tooltip :disabled="isMainDomain" :content="mainDomainTip" placement="bottom-end">
<span class="mp-auth-trigger">
<el-button
type="primary"
:disabled="!isMainDomain"
:loading="authUrlLoading"
@click="handleAuthorize"
>
{{ authorized ? '重新授权' : '去授权' }}
</el-button>
</span>
</el-tooltip>
</div>
</div>
<!-- ===== 未授权:提示需要授权 ===== -->
<template v-if="!pageLoading && !authorized">
<el-alert
:type="isMainDomain ? 'warning' : 'error'"
show-icon
:closable="false"
class="mp-config-alert"
:title="
isMainDomain
? '当前仓库尚未授权微信小程序,需要先完成授权'
: '当前访问域名不支持微信授权,请从主域名进入'
"
:description="
isMainDomain
? '点击右上角「去授权」后,会在新小窗口中打开微信授权页;完成授权后本页会自动刷新。'
: `微信小程序授权页只能从主域名进入(当前域名:${currentHost})。请改用主域名访问本页后再授权;配置查看不受影响。`
"
/>
<div class="mp-empty">
<el-empty :description="isMainDomain ? '暂无微信小程序配置' : '当前域名不可授权,暂无配置'">
<el-tooltip :disabled="isMainDomain" :content="mainDomainTip" placement="top">
<span class="mp-auth-trigger">
<el-button
type="primary"
:disabled="!isMainDomain"
:loading="authUrlLoading"
@click="handleAuthorize"
>去授权</el-button>
</span>
</el-tooltip>
</el-empty>
</div>
</template>
<!-- ===== 已授权:左菜单 + 右明细 ===== -->
<div v-else-if="authorized" class="mp-layout">
<!-- 左侧菜单 -->
<aside class="mp-nav">
<ul class="mp-nav__list">
<li
v-for="menu in MENU_LIST"
:key="menu.key"
class="mp-nav__item"
:class="{ 'is-active': activeMenu === menu.key }"
@click="activeMenu = menu.key"
>
<el-icon class="mp-nav__icon"><component :is="menu.icon" /></el-icon>
<span class="mp-nav__label">{{ menu.label }}</span>
<el-tag
v-if="menu.pending"
class="mp-nav__tag"
size="small"
type="info"
effect="plain"
>待接入</el-tag>
</li>
</ul>
</aside>
<!-- 右侧明细 -->
<section class="mp-detail">
<!-- ① 基础信息(接口已有:setting.warehouse.getweChatApp) -->
<template v-if="activeMenu === 'basic'">
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">小程序基础信息</h3>
<p class="mp-panel__desc">来源:setting.warehouse.getweChatApp(如需变更请重新授权)</p>
</header>
<el-form
label-width="150px"
label-position="right"
class="mp-info-form"
>
<el-form-item
v-for="item in infoItems"
:key="`mp-info-${item.key}`"
:label="item.label"
>
<div class="mp-field-row">
<el-input
v-if="!item.isImage"
:model-value="item.value"
disabled
class="mp-field"
:title="item.value"
/>
<el-image
v-if="item.isImage"
:src="item.imageSrc"
:preview-src-list="[item.imageSrc]"
preview-teleported
fit="cover"
class="mp-thumb"
>
<template #error><span class="mp-thumb__tip">图片无法加载</span></template>
</el-image>
<el-button
v-if="item.isSecret"
link
type="primary"
size="small"
@click="copyText(config[item.key])"
>复制</el-button>
</div>
<!-- 授权功能集(func_info 为 JSON 字符串):解析后逐项展示 -->
<div v-if="item.isFuncInfo && funcInfoItems.length" class="mp-func-list">
<el-tag
v-for="fn in funcInfoItems"
:key="`mp-func-${fn.id}`"
class="mp-func-tag"
size="small"
effect="plain"
:title="fn.raw"
>{{ fn.label }}</el-tag>
</div>
</el-form-item>
</el-form>
</section>
<!-- 未纳管字段(后端新增字段自动展示,便于核对) -->
<section v-if="otherItems.length" class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">其他信息</h3>
<p class="mp-panel__desc">接口返回的其余字段</p>
</header>
<el-form
label-width="150px"
label-position="right"
class="mp-info-form"
>
<el-form-item
v-for="item in otherItems"
:key="`mp-other-${item.key}`"
:label="item.label"
>
<div class="mp-field-row">
<el-input
v-if="!item.isImage"
:model-value="item.value"
disabled
class="mp-field"
:title="item.value"
/>
<el-image
v-if="item.isImage"
:src="item.imageSrc"
:preview-src-list="[item.imageSrc]"
preview-teleported
fit="cover"
class="mp-thumb"
>
<template #error><span class="mp-thumb__tip">图片无法加载</span></template>
</el-image>
<el-button
v-if="item.isSecret"
link
type="primary"
size="small"
@click="copyText(config[item.key])"
>复制</el-button>
</div>
</el-form-item>
</el-form>
</section>
</template>
<!-- ② 认证状态(接口:wechat.queryauth) -->
<template v-else-if="activeMenu === 'cert'">
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">认证状态</h3>
<p class="mp-panel__desc">
来源:wechat.queryauth(按当前仓库已启用的小程序查询微信认证进度)
</p>
</header>
<div v-loading="certLoading" class="mp-cert">
<el-empty
v-if="!certLoading && !certInfo"
description="暂无认证状态数据"
:image-size="72"
>
<el-button @click="loadAuthStatus">重新查询</el-button>
</el-empty>
<template v-else-if="certInfo">
<el-descriptions :column="1" border size="small" class="mp-cert__desc">
<el-descriptions-item label="认证状态">
<el-tag :type="certStateMeta.type" size="small" effect="light">
{{ certStateMeta.text }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item v-for="row in certRows" :key="row.label" :label="row.label">
{{ row.value }}
</el-descriptions-item>
</el-descriptions>
<el-alert
v-if="!certInfo.is_verified && !certHasTask"
type="info"
show-icon
:closable="false"
class="mp-config-alert"
title="尚未认证:需先发起微信认证任务"
description="微信认证不会自动开始:点下方「发起微信认证」提交联系人/主体/法人/材料,后端换 media_id 后创建认证任务,再由法人微信完成核身与支付,本页才能看到进度。"
/>
<ol v-if="!certInfo.is_verified" class="mp-cert__flow">
<li>
发起认证:点「发起微信认证」填写材料,后端调
<code>wxa/sec/wxaauth</code> 创建认证任务(返回 taskid / auth_url)
</li>
<li>法人核身:法人微信号完成人脸核身 / 手机验证(任务状态 3 → 4 → 6 → 9)</li>
<li>支付审核费:待支付 → 审核中(审核单状态 1 → 2)</li>
<li>认证通过:审核单状态 4 时后端回写 verify_type_id=0,本页转为「已认证」</li>
</ol>
<div class="mp-cert__actions">
<el-tooltip
v-if="!certInfo.is_verified"
:content="
certHasTask
? `已存在认证任务 ${certInfo.taskid || ''},重新发起会创建新任务`
: '填写认证材料并创建微信认证任务'
"
placement="top"
>
<span>
<el-button size="small" type="primary" @click="openAuthApplyDialog">
发起微信认证
</el-button>
</span>
</el-tooltip>
<el-button size="small" :loading="certLoading" @click="loadAuthStatus">
刷新认证状态
</el-button>
</div>
</template>
</div>
<el-alert
type="info"
show-icon
:closable="false"
class="mp-config-alert"
title="认证材料 / 有效期 / 订单等待后端补充"
description="wechat.queryauth 已返回:是否已认证、认证类型与主体名称、帐号简介(已认证时)、认证任务 ID、任务状态、审核单状态;主体证件、认证有效期、认证订单与支付记录等待后端补充。"
/>
<div class="mp-placeholder">
<div
v-for="block in currentMenu?.blocks ?? []"
:key="block.title"
class="mp-placeholder__block"
>
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
<p class="mp-placeholder__desc">{{ block.desc }}</p>
</div>
</div>
</section>
</template>
<!-- ③ 发布(接口:wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode / wechat.submitAudit) -->
<template v-else-if="activeMenu === 'publish'">
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">代码包上传</h3>
<p class="mp-panel__desc">
来源:wechat.getTemplateList / wechat.commit(取当前仓库启用小程序,需授权权限集 18
代码管理)。commit 入参只有 template_id:版本号与代码描述取自所选模板,
ext_json 由后端生成;上传成功后后端回写 wms_wechat_app.template_id / user_version。
</p>
</header>
<el-form label-width="110px" label-position="right" class="mp-publish-form">
<el-form-item label="代码模板">
<div class="mp-publish-row">
<el-select
v-model="commitForm.template_id"
:loading="templateLoading"
placeholder="请选择代码模板"
class="mp-publish-select"
>
<el-option
v-for="tpl in templateList"
:key="String(tpl.template_id)"
:value="tpl.template_id"
:label="templateOptionLabel(tpl)"
/>
</el-select>
<el-button :loading="templateLoading" @click="loadTemplateList(true)">
刷新模板
</el-button>
<el-tag v-if="templateFromCache" size="small" type="info" effect="plain">
后端缓存
</el-tag>
</div>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="commitSubmitting" @click="submitCommit">
上传代码并生成体验版
</el-button>
</el-form-item>
</el-form>
</section>
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">体验版二维码</h3>
<p class="mp-panel__desc">
来源:wechat.getTrialQRCode(微信生成 jpeg,后端转存 COS 后返回 URL;需权限集 18 / 86)
</p>
</header>
<el-form label-width="110px" label-position="right" class="mp-publish-form">
<el-form-item label="页面路径">
<div class="mp-publish-row">
<el-input
v-model="trialQRCodePath"
placeholder="选填,如 page/index?action=1"
class="mp-publish-input"
/>
<el-button :loading="trialQRCodeLoading" @click="loadTrialQRCode()">
获取二维码
</el-button>
</div>
</el-form-item>
</el-form>
<div class="mp-qrcode">
<el-image
v-if="trialQRCodeUrl"
:src="trialQRCodeUrl"
:preview-src-list="[trialQRCodeUrl]"
preview-teleported
fit="contain"
class="mp-qrcode__img"
>
<template #error><span class="mp-thumb__tip">二维码无法加载</span></template>
</el-image>
<p v-else class="mp-publish-hint">
上传代码生成体验版后,点「获取二维码」即可扫码体验
</p>
</div>
</section>
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">提交审核</h3>
<p class="mp-panel__desc">
来源:wechat.submitAudit(需权限集 18;后端仅在没有审核中的版本,即 audit_status != 1 时
允许提交,成功后记录 audit_status=1 与 audit_id)
</p>
</header>
<el-form label-width="130px" label-position="right" class="mp-publish-form">
<el-form-item label="版本描述">
<el-input
v-model="auditForm.version_desc"
maxlength="64"
placeholder="选填,便于审核人员理解本次改动"
class="mp-publish-input"
/>
</el-form-item>
<el-form-item label="地理位置接口">
<el-switch v-model="auditForm.privacy_api_not_use" />
<span class="mp-publish-inline-hint">
{{ auditForm.privacy_api_not_use ? '声明不使用地理位置接口' : '未声明(默认)' }}
</span>
</el-form-item>
<el-form-item label="审核类目">
<el-input
v-model="auditForm.item_list_text"
type="textarea"
:rows="3"
placeholder='选填,JSON 数组;留空则不传。例:[{"address":"教育/在线教育","tag":"","first_class":"教育"}]'
/>
<p class="mp-publish-hint">
后端未提供「可选类目」查询接口,故需按微信格式手填;不需要时可留空
</p>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="auditSubmitting" @click="submitAudit">
提交审核
</el-button>
<span class="mp-publish-inline-hint">提交前请先「上传代码并生成体验版」</span>
</el-form-item>
</el-form>
<el-alert
v-if="auditResult"
type="success"
show-icon
:closable="false"
class="mp-audit-result"
:title="`已提交审核:审核单 ID ${auditResult.auditid ?? '-'}`"
:description="`提交时间:${auditResult.submittedAt}|AppID:${auditResult.appid || '-'}|审核结果由微信事件回写后端,页面暂无查询接口`"
/>
</section>
<el-alert
type="info"
show-icon
:closable="false"
class="mp-config-alert"
title="「发布记录」等待后端补充"
description="微信的正式发布 / 回滚等接口尚未收录;审核状态(审核中 / 驳回原因)也没有查询接口,提交后需等后端补充查询能力。"
/>
<div class="mp-placeholder">
<div
v-for="block in currentMenu?.blocks ?? []"
:key="block.title"
class="mp-placeholder__block"
>
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
<p class="mp-placeholder__desc">{{ block.desc }}</p>
</div>
</div>
</template>
<!-- ④ 微信用户(接口:wechat.userList) -->
<template v-else-if="activeMenu === 'wxuser'">
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">小程序用户</h3>
<p class="mp-panel__desc">
来源:wechat.userList(表 wms_user_oauth;按当前仓库启用小程序查询,响应已排除
session_key / access_token / refresh_token 等敏感字段);
`agreement_version_id` 为用户登录时同意的协议版本记录 id,可用行操作「查看协议」回看原文
</p>
</header>
<div class="mp-user-filters">
<el-select
v-model="userQuery.app_id"
placeholder="全部小程序"
clearable
class="mp-user-filter__select"
@change="handleUserQueryChange"
>
<el-option
v-for="app in userAppOptions"
:key="String(app.id)"
:value="app.id"
:label="app.nickname || app.appid || `小程序 #${app.id}`"
/>
</el-select>
<el-input
v-model="userQuery.nickname"
placeholder="昵称(模糊)"
clearable
class="mp-user-filter__input"
@keyup.enter="handleUserQueryChange"
/>
<el-select
v-model="userQuery.bound"
placeholder="绑定状态"
clearable
class="mp-user-filter__select"
@change="handleUserQueryChange"
>
<el-option value="bound" label="已绑定账号" />
<el-option value="unbound" label="未绑定" />
</el-select>
<el-button type="primary" :loading="userLoading" @click="handleUserQueryChange">
查询
</el-button>
<el-button :disabled="userLoading" @click="resetUserQuery">重置</el-button>
</div>
<el-table
v-loading="userLoading"
:data="userList"
size="small"
border
class="mp-user-table"
>
<el-table-column label="头像" width="64">
<template #default="{ row }">
<el-image
v-if="row.headimgurl"
:src="normalizeImageUrl(String(row.headimgurl))"
:preview-src-list="[normalizeImageUrl(String(row.headimgurl))]"
preview-teleported
fit="cover"
class="mp-user-avatar"
>
<template #error><span class="mp-thumb__tip">-</span></template>
</el-image>
<span v-else class="mp-user-empty">-</span>
</template>
</el-table-column>
<el-table-column label="昵称" min-width="120" show-overflow-tooltip>
<template #default="{ row }">{{ row.nickname || '-' }}</template>
</el-table-column>
<el-table-column label="openid" min-width="200" show-overflow-tooltip>
<template #default="{ row }">{{ row.openid || '-' }}</template>
</el-table-column>
<el-table-column label="unionid" min-width="200" show-overflow-tooltip>
<template #default="{ row }">{{ row.unionid || '-' }}</template>
</el-table-column>
<el-table-column label="性别" width="70">
<template #default="{ row }">{{ WECHAT_SEX_TEXT[Number(row.sex)] ?? '-' }}</template>
</el-table-column>
<el-table-column label="登录次数" width="90">
<template #default="{ row }">{{ row.login_count ?? 0 }}</template>
</el-table-column>
<el-table-column label="最近登录" width="160">
<template #default="{ row }">
{{ formatDateTimeValue('login_time', toDisplayText(row.login_time)) || '-' }}
</template>
</el-table-column>
<el-table-column label="绑定账号" width="110">
<template #default="{ row }">
<el-tag :type="row.is_bound ? 'success' : 'info'" size="small" effect="plain">
{{ row.is_bound ? `已绑定 #${row.user_id}` : '未绑定' }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="协议版本" width="100">
<template #default="{ row }">
<el-tag
v-if="Number(row.agreement_version_id) > 0"
type="success"
size="small"
effect="plain"
>
#{{ row.agreement_version_id }}
</el-tag>
<el-tag v-else type="info" size="small" effect="plain">未记录</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="170" fixed="right">
<template #default="{ row }">
<el-button
v-if="!row.is_bound"
link
type="primary"
size="small"
@click="openBindEmployeeDialog(row)"
>
绑定工号
</el-button>
<el-button
v-if="Number(row.agreement_version_id) > 0"
link
type="primary"
size="small"
@click="openAgreementVersionDialog(row)"
>
查看协议
</el-button>
<span
v-if="row.is_bound && !(Number(row.agreement_version_id) > 0)"
class="mp-user-empty"
>
已绑定
</span>
</template>
</el-table-column>
</el-table>
<div class="mp-user-pager">
<el-pagination
v-model:current-page="userQuery.page"
v-model:page-size="userQuery.pageSize"
:total="userTotal"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next"
size="small"
background
@current-change="handleUserPageChange"
@size-change="handleUserPageSizeChange"
/>
</div>
</section>
<el-alert
type="info"
show-icon
:closable="false"
class="mp-config-alert"
title="「解绑 / 用户状态」等待后端补充"
description="绑定已接入(wechat.bindByEmployee,按工号绑定,需同名接口权限);解绑、拉黑与备注等操作接口尚未收录。"
/>
<div class="mp-placeholder">
<div
v-for="block in currentMenu?.blocks ?? []"
:key="block.title"
class="mp-placeholder__block"
>
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
<p class="mp-placeholder__desc">{{ block.desc }}</p>
</div>
</div>
</template>
<!-- ⑤ 用户协议(接口:wechat.getUserAgreement / wechat.setUserAgreement;getUserAgreementText 为小程序端免登录读取) -->
<template v-else-if="activeMenu === 'wxagreement'">
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">小程序用户须知</h3>
<p class="mp-panel__desc">
来源:wechat.getUserAgreement / wechat.setUserAgreement(按当前仓库启用小程序;
每次保存会新增一条协议版本记录,并清除小程序端 wechat.getUserAgreementText 的 24h 缓存);
正文以富文本 HTML 保存,建议只用基础标签(p / h2 / h3 / ul / ol / b / a / img),
以便小程序 rich-text 渲染;仓库未绑定小程序时会提示先绑定
</p>
</header>
<div v-loading="agreementLoading" class="mp-agreement">
<div class="mp-agreement__meta">
<el-tag v-if="agreementMeta.appid" size="small" type="info" effect="plain">
小程序:{{ agreementMeta.nickname || '未命名' }}
</el-tag>
<span class="mp-agreement__appid">AppID:{{ agreementMeta.appid || '-' }}</span>
<el-tag v-if="agreementMeta.version_id" size="small" type="success" effect="plain">
当前版本 #{{ agreementMeta.version_id }}
</el-tag>
<el-tag v-else-if="agreementLoaded" size="small" type="warning" effect="plain">
暂无版本
</el-tag>
<el-tag v-if="agreementDirty" size="small" type="warning" effect="plain">
有未保存修改
</el-tag>
<el-button size="small" :disabled="agreementLoading" @click="loadAgreement()">
重新加载
</el-button>
</div>
<RichTextEditor
v-model="agreementText"
min-height="300px"
placeholder="请输入用户须知正文;用上方工具栏设置标题 / 列表 / 链接 / 图片(粘贴默认转纯文本)"
/>
<p class="mp-publish-hint">
当前 {{ agreementText.length }} 字符(含 HTML 标签);保存会新增一条协议版本记录
(副表 id 自增即最新)并清除小程序端 24h 缓存;留空保存会清空该仓库小程序的用户须知
</p>
<div class="mp-agreement__actions">
<el-button type="primary" :loading="agreementSaving" @click="saveAgreement">
保存
</el-button>
<el-button
:loading="agreementPreviewLoading"
@click="previewAgreementForMiniProgram"
>
预览小程序侧读取结果
</el-button>
</div>
<el-alert
v-if="agreementPreview"
:type="agreementPreview.from_cache ? 'info' : 'success'"
show-icon
:closable="false"
class="mp-config-alert"
:title="
agreementPreview.from_cache
? '小程序端读取:命中 24h 缓存'
: '小程序端读取:实时读取(缓存已失效)'
"
:description="`小程序端实际拿到:协议版本 id ${agreementPreview.version_id ?? '-'},内容长度 ${agreementPreview.text?.length ?? 0} 字符`"
/>
<!-- 常显入口:按协议版本记录 id 查看原文(核对指定/历史版本、调试用;wechat.getAgreementVersion) -->
<div class="mp-agreement__lookup">
<span class="mp-agreement__lookup-label">按版本记录 id 查看协议原文</span>
<el-input
v-model="agreementVersionQueryId"
placeholder="版本记录 id(正整数)"
clearable
class="mp-agreement__lookup-input"
@keyup.enter="queryAgreementVersionById()"
/>
<el-button
:loading="agreementVersionLoading"
@click="queryAgreementVersionById()"
>
查看协议
</el-button>
<el-button
v-if="agreementMeta.version_id"
link
type="primary"
@click="queryAgreementVersionById(agreementMeta.version_id)"
>
查看当前版本 #{{ agreementMeta.version_id }}
</el-button>
</div>
</div>
</section>
<div class="mp-placeholder">
<div
v-for="block in currentMenu?.blocks ?? []"
:key="block.title"
class="mp-placeholder__block"
>
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
<p class="mp-placeholder__desc">{{ block.desc }}</p>
</div>
</div>
</template>
<!-- ⑥ 其余菜单:页面结构已预留,接口待定 -->
<template v-else>
<section class="mp-panel">
<header class="mp-panel__head">
<h3 class="mp-panel__title">{{ currentMenu?.label }}</h3>
<p class="mp-panel__desc">{{ currentMenu?.desc }}</p>
</header>
<el-alert
type="info"
show-icon
:closable="false"
class="mp-config-alert"
title="接口待定:本菜单页面结构已预留"
description="后端接口确定后在此接入;下方为规划中的内容分区,仅占位。"
/>
<div class="mp-placeholder">
<div
v-for="block in currentMenu?.blocks ?? []"
:key="block.title"
class="mp-placeholder__block"
>
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
<p class="mp-placeholder__desc">{{ block.desc }}</p>
</div>
</div>
</section>
</template>
</section>
</div>
<!-- ===== 代注册企业小程序:提交企业信息(wechat.registerMiniprogram) ===== -->
<el-dialog
v-model="registerDialogVisible"
title="代注册企业小程序"
width="580px"
align-center
append-to-body
:close-on-click-modal="false"
>
<el-alert
type="warning"
show-icon
:closable="false"
style="margin-bottom: 16px"
title="提交后微信会给法人微信推送模板消息,需法人本人完成人脸核身"
description="企业信息须与工商登记一致;审核结果由微信事件回调后端,可在「认证状态」菜单查看进度。"
/>
<el-form
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
label-width="110px"
label-position="right"
>
<el-form-item label="企业名称" prop="name">
<el-input
v-model="registerForm.name"
maxlength="64"
placeholder="与工商登记一致(无主体名称的个体工商户填「个体户+法人姓名」)"
/>
</el-form-item>
<el-form-item label="企业代码" prop="code">
<el-input
v-model="registerForm.code"
maxlength="32"
placeholder="统一社会信用代码 / 组织机构代码 / 营业执照注册号"
/>
</el-form-item>
<el-form-item label="代码类型" prop="code_type">
<el-select
v-model="registerForm.code_type"
placeholder="请选择企业代码类型"
style="width: 100%"
>
<el-option :value="1" label="统一社会信用代码(18 位)" />
<el-option :value="2" label="组织机构代码(9 位)" />
<el-option :value="3" label="营业执照注册号(15 位)" />
</el-select>
</el-form-item>
<el-form-item label="法人微信号" prop="legal_persona_wechat">
<el-input
v-model="registerForm.legal_persona_wechat"
maxlength="64"
placeholder="仅支持微信号,不支持手机号 / 微信名"
/>
</el-form-item>
<el-form-item label="法人姓名" prop="legal_persona_name">
<el-input
v-model="registerForm.legal_persona_name"
maxlength="64"
placeholder="须与法人绑定银行卡的姓名一致"
/>
</el-form-item>
<el-form-item label="联系电话" prop="component_phone">
<el-input
v-model="registerForm.component_phone"
maxlength="20"
placeholder="选填,第三方联系电话"
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="registerDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="registerSubmitting" @click="submitRegister">
提交注册
</el-button>
</template>
</el-dialog>
<!-- ===== 发起微信认证:提交认证材料(wechat.wxaauth) ===== -->
<el-dialog
v-model="authApplyDialogVisible"
title="发起微信认证"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
>
<el-alert
type="warning"
show-icon
:closable="false"
style="margin-bottom: 16px"
title="提交后由微信侧继续:主体核身 → 支付审核费 → 审核中"
description="新版 wxaauth:带 * 为必填;材料图片可上传(后端调 wxa/sec/uploadauthmaterial 换 mediaid,再以 auth_data 包裹提交)或直接填 COS URL / mediaid。进度在本页「认证状态」查看。"
/>
<el-form
ref="authApplyFormRef"
:model="authApplyForm"
:rules="authApplyRules"
label-width="140px"
label-position="right"
>
<el-divider content-position="left">账号与联系人(必填)</el-divider>
<el-form-item label="账号主体类型" prop="customer_type">
<el-select v-model="authApplyForm.customer_type" style="width: 100%">
<el-option :value="1" label="企业" />
<el-option :value="12" label="个体工商户" />
<el-option :value="15" label="个人" />
</el-select>
</el-form-item>
<el-form-item label="小程序账号名称" prop="account_name">
<el-input
v-model="authApplyForm.account_name"
maxlength="64"
placeholder="必填,待认证的小程序名称"
/>
</el-form-item>
<el-form-item label="命名类型" prop="account_name_type">
<el-select v-model="authApplyForm.account_name_type" style="width: 100%">
<el-option :value="1" label="基于自选词汇" />
<el-option :value="2" label="基于商标" />
</el-select>
</el-form-item>
<el-form-item label="支付方式" prop="pay_type">
<el-select v-model="authApplyForm.pay_type" style="width: 100%">
<el-option :value="1" label="消耗服务商预购包(服务商代缴)" />
<el-option :value="2" label="小程序开发者自行支付" />
</el-select>
</el-form-item>
<el-form-item label="第三方联系电话" prop="third_party_phone">
<el-input v-model="authApplyForm.third_party_phone" maxlength="20" placeholder="必填" />
</el-form-item>
<el-form-item label="联系人姓名" prop="contact_name">
<el-input v-model="authApplyForm.contact_name" maxlength="64" placeholder="必填" />
</el-form-item>
<el-form-item label="联系人邮箱" prop="contact_email">
<el-input v-model="authApplyForm.contact_email" maxlength="64" placeholder="必填" />
</el-form-item>
<el-form-item label="联系人手机">
<el-input v-model="authApplyForm.contact_mobile" maxlength="20" placeholder="选填" />
</el-form-item>
<el-divider content-position="left">材料(选填,可上传或填 COS URL / mediaid)</el-divider>
<el-form-item label="主体资质材料">
<div class="mp-media-row">
<el-input
v-model="authApplyForm.qualification"
placeholder="非个人主体必填(单张):上传图片或填 COS URL / mediaid"
/>
<el-upload
:show-file-list="false"
accept="image/*"
:http-request="handleQualificationUpload"
>
<el-button :loading="authQualificationUploading">上传</el-button>
</el-upload>
<el-image
v-if="authApplyForm.qualification"
:src="authApplyForm.qualification"
:preview-src-list="[authApplyForm.qualification]"
preview-teleported
fit="cover"
class="mp-media-preview"
/>
<el-button
v-if="authApplyForm.qualification"
link
type="primary"
@click="authApplyForm.qualification = ''"
>
清除
</el-button>
</div>
</el-form-item>
<el-form-item label="资质其他材料">
<el-input
v-model="authApplyForm.qualification_other_text"
type="textarea"
:rows="3"
placeholder="一行一个 COS URL / mediaid,最多 10 个;没有则留空"
/>
</el-form-item>
<el-form-item label="名称关键词补充材料">
<el-input
v-model="authApplyForm.account_supplemental_text"
type="textarea"
:rows="3"
placeholder="一行一个 COS URL / mediaid,最多 10 个;命名类型选「基于商标」时可补充"
/>
</el-form-item>
<el-form-item v-if="authApplyForm.customer_type === 15" label="个人认证材料">
<el-input
v-model="authApplyForm.auth_ident_material_text"
type="textarea"
:rows="3"
placeholder="一行一个 COS URL / mediaid,最多 10 个"
/>
</el-form-item>
<el-divider content-position="left">高级字段(选填)</el-divider>
<el-form-item label="服务商 AppID">
<el-input
v-model="authApplyForm.service_appid"
maxlength="64"
placeholder="支付方式选「消耗服务商预购包」时必填"
/>
</el-form-item>
<el-form-item label="重填任务 ID">
<el-input
v-model="authApplyForm.taskid"
maxlength="64"
placeholder="仅「打回重填」时需要(已自动带出库中 taskid)"
/>
</el-form-item>
<el-form-item label="JSON">
<el-input
v-model="authApplyExtraJson"
type="textarea"
:rows="4"
placeholder='用于未覆盖的白名单字段,如 {"invoice_info":{...},"auth_identification":{...}}'
/>
<p class="mp-publish-hint">
按微信新版 auth_data 原样透传;与上方字段同名时以此处为准
</p>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="authApplyDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="authApplySubmitting" @click="submitAuthApply">
发起认证
</el-button>
</template>
</el-dialog>
<!-- ===== 绑定工号:微信用户 → 工号(wechat.bindByEmployee) ===== -->
<el-dialog
v-model="bindEmployeeDialogVisible"
title="绑定工号"
width="520px"
align-center
append-to-body
:close-on-click-modal="false"
>
<el-alert
type="info"
show-icon
:closable="false"
style="margin-bottom: 16px"
title="把该微信用户绑定到系统工号"
description="后端按工号查账号并写入绑定关系;该微信已绑定其他账号 / 工号不属于当前仓库时会被拒绝。"
/>
<el-form label-width="90px" label-position="right">
<el-form-item label="微信用户">
<span class="mp-bind-target">
{{ bindTargetUser?.nickname || '(无昵称)' }}
<span class="mp-bind-openid">openid:{{ bindTargetUser?.openid || '-' }}</span>
</span>
</el-form-item>
<el-form-item label="工号">
<el-select
v-model="bindEmployeeId"
filterable
clearable
:loading="employeeLoading"
placeholder="请选择工号(可按姓名 / 账号搜索)"
style="width: 100%"
>
<el-option
v-for="emp in employeeOptions"
:key="String(emp.employee_id)"
:value="emp.employee_id"
:label="employeeOptionLabel(emp)"
:disabled="Number(emp.status) !== 1"
/>
</el-select>
<p class="mp-publish-hint">
工号来自「账号管理」(setting.account.list);已停用的工号不可绑定
</p>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="bindEmployeeDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="bindEmployeeSubmitting" @click="submitBindEmployee">
绑定
</el-button>
</template>
</el-dialog>
<!-- ===== 查看用户同意过的协议版本(wechat.getAgreementVersion) ===== -->
<el-dialog
v-model="agreementVersionDialogVisible"
title="用户已同意的协议版本"
width="720px"
align-center
append-to-body
>
<el-alert
type="info"
show-icon
:closable="false"
style="margin-bottom: 12px"
title="按协议版本记录 id 读取内容(wechat.getAgreementVersion)"
:description="agreementVersionDesc"
/>
<div v-loading="agreementVersionLoading" class="mp-agreement-version">
<p class="mp-agreement__appid">
小程序:{{ agreementVersionMeta.nickname || '未命名' }}|AppID:{{ agreementVersionMeta.appid || '-' }}
</p>
<!-- 协议内容来自本系统后端(与小程序 rich-text 同源),故直接渲染 HTML -->
<div v-if="agreementVersionText" class="mp-agreement-version__body" v-html="agreementVersionText" />
<el-empty
v-else-if="!agreementVersionLoading"
description="暂无协议内容"
:image-size="72"
/>
</div>
<template #footer>
<el-button @click="agreementVersionDialogVisible = false">关闭</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch, type Component } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Document, InfoFilled, Medal, Promotion, Reading, User, Wallet } from '@element-plus/icons-vue'
import {
settingWarehouseGetWeChatApp
} from '@/api/setting.warehouse/settingwarehouse'
import {
wechatBindByEmployee,
wechatCommit,
wechatGetAuthorizerInfo,
wechatGetAgreementVersion,
wechatGetAuthUrl,
wechatGetTemplateList,
wechatGetTrialQRCode,
wechatGetUserAgreement,
wechatGetUserAgreementText,
wechatQueryAuth,
wechatRegisterMiniprogram,
wechatSetUserAgreement,
wechatSubmitAudit,
wechatUserList,
wechatWxaauth,
type WeChatAgreementVersionData,
type WeChatAuditItem,
type WeChatBindByEmployeeData,
type WeChatCommitData,
type WeChatQueryAuthData,
type WeChatRegisterMiniprogramParams,
type WeChatSubmitAuditData,
type WeChatTemplateItem,
type WeChatTemplateListData,
type WeChatUserAgreementData,
type WeChatUserAgreementTextData,
type WeChatUserItem,
type WeChatUserListData,
type WeChatUserListParams,
type WeChatUserWhereValue,
type WeChatWxaauthData,
type WeChatWxaauthParams
} from '@/api/wechat/wechat'
import { accountList } from '@/api/setting.account/account'
import { isMainDomainHost, normalizeFrontHost } from '@/stores/modules/frontBrand'
import { uploadImageToCos } from '@/utils/cosImageUpload'
// 自研轻量富文本编辑器(无三方依赖,输出基础标签,便于小程序 rich-text 渲染)
import RichTextEditor from '@/components/RichTextEditor/index.vue'
defineOptions({ name: 'MiniProgramConfigForm' })
/** 本套接口响应中与成功/失败判定相关的字段 */
type ApiFlagFields = { code?: unknown; flag?: unknown; success?: unknown; message?: unknown }
/**
* 判定接口是否成功。
* ⚠️ 本套接口失败时返回 `{ flag:'failure', code:0, success:false, message, data:null }`,
* 而 `code=0` 也被 axios 拦截器(SUCCESS_CODES)视为成功,因此**必须显式识别 flag/success**;
* 否则「小程序未授权相关权限(权限集 18/86),请重新授权」这类失败会被当成成功(data 为 null 只显示空值)。
*/
const okCode = (res: unknown) => {
if (!res || typeof res !== 'object') return false
const raw = res as ApiFlagFields
if (raw.flag === 'failure' || raw.flag === 'fail' || raw.success === false) return false
return raw.code === 1 || raw.code === 200 || raw.code === 0
}
/** 网关信封字段(不属于业务数据) */
const WECHAT_ENVELOPE_KEYS = ['flag', 'code', 'success', 'message', 'msg', 'timestamp', 'data']
/**
* 取 wechat.* 接口的业务数据。
* 这类接口实际有**两种**返回形态,踩过的坑:
* 1) 平铺(如 wechat.userList):`{flag, code, message, list, apps, pagination, timestamp}`
* —— 业务字段与信封同级,**根本没有 data 字段**,读 `res.data` 永远拿不到列表;
* 2) 包一层:`{flag, code, message, data:{...}}`。
* 因此这里优先取 `data`,否则去掉信封字段后返回其余字段(列表类接口靠这一步拿到 list/pagination/apps)。
*/
function pickWechatPayload<T extends object = Record<string, unknown>>(res: unknown): T | null {
if (!res || typeof res !== 'object') return null
const raw = res as Record<string, unknown>
const nested = raw.data
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
return nested as T
}
const out: Record<string, unknown> = {}
for (const [key, value] of Object.entries(raw)) {
if (WECHAT_ENVELOPE_KEYS.includes(key)) continue
out[key] = value
}
return Object.keys(out).length ? (out as T) : null
}
/** 授权类失败(缺少授权权限集)→ 在提示里补上「重新授权」指引 */
const AUTH_FAILURE_RE = /权限集|重新授权|未授权/
/**
* 统一错误提示。
* silent 仅抑制「非授权类」失败提示:授权类失败(权限集缺失)即使静默刷新也要提示,否则问题会被完全吞掉。
*/
function showApiError(res: unknown, fallback: string, silent = false) {
const message = String((res as ApiFlagFields | null | undefined)?.message ?? '').trim() || fallback
const authIssue = AUTH_FAILURE_RE.test(message)
if (silent && !authIssue) return
ElMessage.error(
authIssue ? `${message}(请在「基础信息」中点击「重新授权」,确认授予全部权限后重试)` : message
)
}
// ============================================================
// 常量
// ============================================================
/** 与「已授权」判定无关的字段(未授权时后端只回这些,不应视为已配置) */
const NEUTRAL_KEYS = new Set([
'id',
'warehouse_id',
'code',
'message',
'msg',
'data',
'created_at',
'updated_at'
])
/** 已知字段展示映射(按顺序取第一个命中且非空的字段;后端字段名以后端为准,多形态兼容) */
type FieldDefinition = {
label: string
keys: string[]
/** 值翻译(如 1=启用 / 0=停用) */
valueMap?: Record<string, string>
/** 不展示:仅用于消耗字段(不让其落到「其他信息」兜底区),如 id / warehouse_id */
hidden?: boolean
}
const FIELD_DEFINITIONS: FieldDefinition[] = [
{ label: '小程序名称', keys: ['nickname', 'nick_name', 'mini_name', 'app_name', 'authorizer_nick_name', 'name'] },
{ label: 'AppID', keys: ['appid', 'app_id', 'authorizer_appid', 'mini_appid'] },
{ label: 'AppSecret', keys: ['app_secret', 'appsecret', 'secret', 'authorizer_secret'] },
{ label: '原始ID', keys: ['user_name', 'original_id', 'gh_id', 'username'] },
{ label: '主体名称', keys: ['principal_name', 'principal'] },
{ label: '微信号/别名', keys: ['alias', 'wechat_id'] },
{ label: '授权状态', keys: ['auth_status', 'status', 'is_authorized', 'authorized'] },
{ label: '授权时间', keys: ['auth_time', 'authorized_at', 'authorize_time', 'auth_at'] },
{ label: '到期时间', keys: ['expires_at', 'expire_time', 'authorization_expires_at', 'expired_at'] },
{ label: '授权功能集', keys: ['func_info'] },
{ label: '头像', keys: ['head_img', 'headimgurl', 'head_img_url', 'avatar'] },
{ label: '二维码', keys: ['qrcode_url'] },
{ label: '授权码', keys: ['authorization_code', 'auth_code'] },
{ label: '创建时间', keys: ['created_at'] },
{ label: '更新时间', keys: ['updated_at'] },
// 以下字段按需求不展示(hidden 仅用于占位消耗,避免落入「其他信息」)
{ label: '启用状态', keys: ['is_enabled', 'enabled'], hidden: true },
{ label: '所属仓库', keys: ['warehouse_id'], hidden: true },
{ label: '记录ID', keys: ['id'], hidden: true }
]
/** 授权链接可能的字段名(按优先级取值) */
const AUTH_URL_KEYS = [
'url',
'auth_url',
'authUrl',
'authorize_url',
'authorizeUrl',
'authorization_url',
'redirect_url',
'link'
]
/** 授权小窗打开后的轮询间隔 / 最长时长 */
const AUTH_WATCH_INTERVAL = 3000
const AUTH_WATCH_MAX_DURATION = 5 * 60 * 1000
/** 需要打码 + 支持复制的字段 */
const SECRET_KEY_PATTERN = /secret|token|key|password/i
/** 视为图片地址的字段 */
const IMAGE_KEY_PATTERN = /img|image|avatar|logo|qrcode|qr_code/i
// ============================================================
// 左侧菜单(已授权时:左菜单 + 右明细)
// ============================================================
/** 菜单下规划中的内容分区(接口未接入时占位展示) */
type MenuBlock = { title: string; desc: string }
type MiniProgramMenuItem = {
key: string
label: string
icon: Component
desc: string
/** 接口待定:仅预留页面结构 */
pending?: boolean
/** 规划中的内容分区(占位) */
blocks?: MenuBlock[]
}
const MENU_LIST: MiniProgramMenuItem[] = [
{
key: 'basic',
label: '基础信息',
icon: InfoFilled,
desc: '小程序授权基础信息(接口已接入:setting.warehouse.getweChatApp)'
},
{
key: 'cert',
label: '认证状态',
icon: Medal,
desc: '小程序微信认证状态与进度(已接入:wechat.queryauth 查询 / wechat.wxaauth 发起)',
blocks: [
{ title: '认证材料(待后端补充)', desc: '认证主体证件号 / 认证有效期 / 认证订单与支付记录' },
{ title: '认证结果通知(待后端补充)', desc: '认证结果回调记录 / 失败原因与重试' },
{ title: '认证历史(待后端补充)', desc: '认证历史记录 / 年审提醒' }
]
},
{
key: 'beian',
label: '备案配置',
icon: Document,
desc: '小程序 ICP 备案主体、备案信息与核验材料(接口待定)',
pending: true,
blocks: [
{ title: '备案主体', desc: '主体名称 / 主体证件类型 / 主体证件号 / 负责人信息' },
{ title: '小程序备案信息', desc: '备案号 / 服务内容类型 / 备案状态 / 审核意见' },
{ title: '材料与核验', desc: '证件照片 / 人脸核验记录 / 承诺书上传(预预留上传入口)' }
]
},
{
key: 'publish',
label: '发布',
icon: Promotion,
desc: '上传代码生成体验版、提交微信审核(接口已接入:wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode / wechat.submitAudit)',
blocks: [
{ title: '发布记录(待后端补充)', desc: '版本号 / 发布时间 / 发布人 / 回滚操作' }
]
},
{
key: 'pay',
label: '支付配置',
icon: Wallet,
desc: '微信支付商户信息、密钥证书与回调地址(接口待定)',
pending: true,
blocks: [
{ title: '商户信息', desc: '商户号 / 商户主体 / 结算账户 / 与小程序绑定关系' },
{ title: '密钥与证书', desc: 'API 密钥 / APIv3 密钥 / 证书序列号 / 证书文件上传' },
{ title: '回调与通知', desc: '支付回调地址 / 退款回调地址 / 通知模板' }
]
},
{
key: 'wxuser',
label: '微信用户',
icon: User,
desc: '小程序侧用户(openid)列表、工号绑定与协议版本回看(已接入:wechat.userList / wechat.bindByEmployee / wechat.getAgreementVersion)',
blocks: [
{
title: '解绑与更多操作(待后端补充)',
desc: '与系统账号的解绑、拉黑 / 备注 / 操作日志(协议同意记录已可按用户回看)'
}
]
},
{
key: 'wxagreement',
label: '用户协议',
icon: Reading,
desc: '小程序用户须知(已接入:wechat.getUserAgreement / wechat.setUserAgreement,富文本编辑 + 版本记录 id)',
blocks: [
{
title: '历史版本列表(待后端补充)',
desc: '页面已提供「按版本记录 id 查看协议原文」入口(也可从「微信用户」行查看该用户同意过的版本);历史版本列表 / 生效时间待后端提供'
}
]
}
]
/** 当前选中的左侧菜单(默认基础信息) */
const activeMenu = ref(MENU_LIST[0]?.key ?? 'basic')
/** 当前菜单项(兼容未知 key) */
const currentMenu = computed<MiniProgramMenuItem | undefined>(() =>
MENU_LIST.find((menu) => menu.key === activeMenu.value) ?? MENU_LIST[0]
)
/** 基础信息/其他信息的一行展示项(值为不可编辑输入框;图片类只展示图片) */
type DisplayItem = {
key: string
label: string
/** 展示值(已翻译、已格式化;密钥类已打码) */
value: string
/** 图片地址(仅图片类字段有值,已做 https 归一化) */
imageSrc: string
isImage: boolean
isSecret: boolean
/** 授权功能集:下方额外渲染解析后的功能项 */
isFuncInfo: boolean
}
/** 授权功能集单项(func_info 为 JSON 字符串:[{funcscope_category:{id}}…]) */
type FuncInfoItem = { id: string; label: string; raw: string }
// ============================================================
// 状态
// ============================================================
const pageLoading = ref(false)
const authUrlLoading = ref(false)
const config = ref<Record<string, unknown>>({})
const lastLoadedAt = ref('')
/** 认证状态(wechat.queryauth) */
const certLoading = ref(false)
const certInfo = ref<WeChatQueryAuthData | null>(null)
const certLoaded = ref(false)
/** 代注册弹窗(wechat.registerMiniprogram) */
const registerDialogVisible = ref(false)
const registerSubmitting = ref(false)
const registerFormRef = ref<FormInstance>()
const registerForm = reactive<WeChatRegisterMiniprogramParams>({
name: '',
code: '',
code_type: 1,
legal_persona_wechat: '',
legal_persona_name: '',
component_phone: ''
})
const registerRules: FormRules = {
name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
code: [{ required: true, message: '请输入企业代码', trigger: 'blur' }],
code_type: [{ required: true, message: '请选择企业代码类型', trigger: 'change' }],
legal_persona_wechat: [{ required: true, message: '请输入法人微信号', trigger: 'blur' }],
legal_persona_name: [{ required: true, message: '请输入法人姓名', trigger: 'blur' }]
}
/** 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode) */
const templateLoading = ref(false)
const templateLoaded = ref(false)
const templateList = ref<WeChatTemplateItem[]>([])
const templateFromCache = ref(false)
const commitSubmitting = ref(false)
/** 入参只有 template_id:版本号/代码描述取自模板,ext_json 由后端生成 */
const commitForm = reactive<{ template_id?: number }>({ template_id: undefined })
/** 当前选中的模板(其 user_version / user_desc 会被后端直接当上传参数用,仅用于提交前校验) */
const selectedTemplate = computed<WeChatTemplateItem | undefined>(() =>
templateList.value.find((tpl) => Number(tpl.template_id) === Number(commitForm.template_id))
)
const trialQRCodeLoading = ref(false)
const trialQRCodePath = ref('')
const trialQRCodeUrl = ref('')
/** 微信用户列表(wechat.userList) */
const userLoading = ref(false)
const userLoaded = ref(false)
const userList = ref<WeChatUserItem[]>([])
const userTotal = ref(0)
/** 接口返回的「本次查询命中的小程序」列表,作为小程序筛选项 */
const userApps = ref<{ id?: number; appid?: string; nickname?: string }[]>([])
const userQuery = reactive<{
app_id?: number
nickname: string
bound: '' | 'bound' | 'unbound'
page: number
pageSize: number
}>({
app_id: undefined,
nickname: '',
bound: '',
page: 1,
pageSize: 20
})
const userAppOptions = computed(() => userApps.value)
/** 提交审核(wechat.submitAudit) */
const auditSubmitting = ref(false)
const auditForm = reactive<{
version_desc: string
privacy_api_not_use: boolean
item_list_text: string
}>({
version_desc: '',
privacy_api_not_use: false,
item_list_text: ''
})
/** 最近一次提交审核的返回(无审核状态查询接口,仅回显本次提交信息) */
const auditResult = ref<{ appid?: string; auditid?: number; submittedAt: string } | null>(null)
/** 授权小窗句柄与轮询计时器 */
let authWindow: Window | null = null
let authWatchTimer: number | null = null
let authWatchStartedAt = 0
let authWatchBusy = false
// ============================================================
// 域名限制:微信小程序授权页只能从主域名进入
// ============================================================
/** 当前访问域名(去协议/端口/路径,小写) */
const currentHost = normalizeFrontHost(window.location.hostname)
/** 是否主域名(= 品牌豁免域名 VITE_FRONT_CONFIG_EXEMPT_HOSTS,与 frontBrand 同源) */
const isMainDomain = isMainDomainHost(currentHost)
/** 非主域名时的提示文案 */
const mainDomainTip = `微信小程序授权只能从主域名进入(当前域名:${currentHost || '未知'})`
// ============================================================
// 取值 / 归一化
// ============================================================
/** 非空判定:null/undefined/空串/空数组/空对象均视为空 */
function isEmptyValue(value: unknown): boolean {
if (value === null || value === undefined) return true
if (typeof value === 'string') return value.trim() === ''
if (Array.isArray(value)) return value.length === 0
if (typeof value === 'object') return Object.keys(value as Record<string, unknown>).length === 0
return false
}
/** 展示文本归一化(对象/数组转 JSON 字符串) */
function toDisplayText(value: unknown): string {
if (value === null || value === undefined) return ''
if (typeof value === 'object') {
try {
return JSON.stringify(value)
} catch {
return String(value)
}
}
return String(value)
}
/** 敏感值打码:保留前 4 / 后 4 位 */
function maskSecret(text: string): string {
if (text.length <= 8) return '******'
return `${text.slice(0, 4)}******${text.slice(-4)}`
}
/** 配置中的有效字段(剔除 meta / neutral 字段,且值非空) */
const entries = computed<[string, unknown][]>(() =>
Object.entries(config.value).filter(([key, value]) => {
const lower = key.toLowerCase()
if (NEUTRAL_KEYS.has(lower) && isEmptyValue(value)) return false
return !isEmptyValue(value)
})
)
/** 是否已授权:存在任一「非中性」且有值的字段即视为已配置 */
const authorized = computed(() =>
entries.value.some(([key]) => !NEUTRAL_KEYS.has(key.toLowerCase()))
)
/** 已命中展示映射的字段 key(避免在「其他信息」重复展示) */
const mappedKeys = computed(() => {
const used = new Set<string>()
const keys = new Set(entries.value.map(([key]) => key))
for (const def of FIELD_DEFINITIONS) {
const hit = def.keys.find((key) => keys.has(key))
if (hit) used.add(hit)
}
return used
})
function buildItem(def: FieldDefinition, key: string, rawValue: unknown): DisplayItem {
const rawText = toDisplayText(rawValue)
const mappedText = def.valueMap ? (def.valueMap[rawText] ?? rawText) : rawText
const displayText = formatDateTimeValue(key, mappedText)
const isSecret = SECRET_KEY_PATTERN.test(key)
const isImage = IMAGE_KEY_PATTERN.test(key) && /^https?:\/\//i.test(rawText)
return {
key,
label: def.label,
value: isSecret ? maskSecret(displayText) : displayText,
imageSrc: isImage ? normalizeImageUrl(rawText) : '',
isImage,
isSecret,
isFuncInfo: key === 'func_info'
}
}
/** 图片地址归一化:页面为 https 时把 http 图片改走 https,避免混合内容被浏览器拦截(如微信头像 CDN) */
function normalizeImageUrl(raw: string): string {
if (window.location.protocol === 'https:' && /^http:\/\//i.test(raw)) {
return raw.replace(/^http:\/\//i, 'https://')
}
return raw
}
/** 本地时间格式化为 YYYY-MM-DD HH:mm:ss */
function toLocalDateTime(date: Date): string {
const pad = (num: number) => String(num).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
/**
* 时间展示:ISO 字符串(2026-09-21T11:14:03.000Z)始终转换;
* Unix 时间戳(10 位=秒、13 位=毫秒,如 auth_time: 1789989241)仅在时间类字段上转换,避免 ID 被误判
*/
function formatDateTimeValue(key: string, text: string): string {
if (!text) return text
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(text)) {
const date = new Date(text)
return Number.isNaN(date.getTime()) ? text : toLocalDateTime(date)
}
if (/(time|_at$|date)/i.test(key)) {
if (/^\d{10}$/.test(text)) return toLocalDateTime(new Date(Number(text) * 1000))
if (/^\d{13}$/.test(text)) return toLocalDateTime(new Date(Number(text)))
}
return text
}
/**
* 授权功能集:func_info 为 JSON 字符串,形如
* [{"funcscope_category":{"id":17}},{"funcscope_category":{"id":25},"confirm_info":{...}}]
* 解析后逐项展示(功能名称由后端注册表提供时再补充,此处仅展示功能 ID 与需确认标记)
*/
const funcInfoItems = computed<FuncInfoItem[]>(() => {
const raw = config.value.func_info
const text = typeof raw === 'string' ? raw.trim() : raw ? JSON.stringify(raw) : ''
if (!text) return []
try {
const parsed: unknown = JSON.parse(text)
if (!Array.isArray(parsed)) return []
return parsed.map((entry: any) => {
const id = entry?.funcscope_category?.id ?? entry?.id ?? '-'
const needConfirm = Number(entry?.confirm_info?.need_confirm) === 1
return {
id: String(id),
label: needConfirm ? `功能 ${id}(需确认)` : `功能 ${id}`,
raw: JSON.stringify(entry)
}
})
} catch {
return []
}
})
/** 已知字段展示项(hidden 字段不展示,但仍消耗掉对应 key) */
const infoItems = computed<DisplayItem[]>(() => {
const items: DisplayItem[] = []
for (const def of FIELD_DEFINITIONS) {
if (def.hidden) continue
const hit = def.keys.find((key) => !isEmptyValue(config.value[key]))
if (!hit) continue
items.push(buildItem(def, hit, config.value[hit]))
}
// 授权功能集:可解析时用摘要替换原始 JSON,明细由下方功能项标签展示
const funcItem = items.find((item) => item.isFuncInfo)
if (funcItem && funcInfoItems.value.length) {
funcItem.value = `共 ${funcInfoItems.value.length} 项:${funcInfoItems.value
.map((fn) => fn.id)
.join('、')}`
}
return items
})
/** 其余字段展示项(后端新增字段兜底展示) */
const otherItems = computed<DisplayItem[]>(() =>
entries.value
.filter(([key]) => !mappedKeys.value.has(key))
.map(([key, value]) => buildItem({ label: key, keys: [key] }, key, value))
)
// ============================================================
// 拉取配置
// ============================================================
async function loadConfig(options: { silent?: boolean } = {}) {
if (!options.silent) pageLoading.value = true
try {
const res: any = await settingWarehouseGetWeChatApp()
if (!okCode(res)) {
showApiError(res, '获取微信小程序配置失败', options.silent)
return
}
// 未授权时后端返回 data:null(不能用整包 res 兜底,否则 flag/timestamp 会被误判为已配置)
const payload = res.data
config.value =
payload && typeof payload === 'object' && !Array.isArray(payload)
? (payload as Record<string, unknown>)
: {}
lastLoadedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
return config.value
} catch (e: unknown) {
if (!options.silent) {
ElMessage.error(e instanceof Error ? e.message : '获取微信小程序配置失败')
}
} finally {
if (!options.silent) pageLoading.value = false
}
}
// ============================================================
// 认证状态(wechat.queryauth)
// ============================================================
/** 已认证时的认证类型(后端返回 verify_type_text,缺省按 verify_type_id 兜底) */
const VERIFY_TYPE_TEXT: Record<number, string> = {
0: '微信认证',
1: '新浪微博认证',
3: '资质通过未名称认证',
4: '资质通过+微博认证'
}
/** 审核单状态(apply_status)→ 文案与颜色 */
const APPLY_STATUS_META: Record<
number,
{ text: string; type: 'info' | 'warning' | 'success' | 'danger' }
> = {
0: { text: '审核单不存在', type: 'info' },
1: { text: '待支付', type: 'warning' },
2: { text: '审核中', type: 'warning' },
3: { text: '打回重填', type: 'warning' },
4: { text: '认证通过', type: 'success' },
5: { text: '认证最终失败', type: 'danger' }
}
/** 认证任务状态(task_status)→ 标签颜色(文案优先用后端 task_status_text) */
const TASK_STATUS_TYPE: Record<number, 'info' | 'warning' | 'success' | 'danger'> = {
0: 'info',
1: 'danger',
2: 'danger',
3: 'warning',
4: 'warning',
5: 'danger',
6: 'warning',
7: 'warning',
8: 'danger',
9: 'warning',
11: 'danger',
12: 'warning',
14: 'danger',
15: 'warning'
}
/** 认证主状态:已认证 → 审核单状态 → 认证任务状态 → 尚未认证 */
const certStateMeta = computed<{ text: string; type: 'info' | 'warning' | 'success' | 'danger' }>(() => {
const info = certInfo.value
if (!info) return { text: '未知状态', type: 'info' }
if (info.is_verified) {
const typeId = info.verify_type_id === null || info.verify_type_id === undefined ? null : Number(info.verify_type_id)
return {
text: info.verify_type_text || (typeId !== null ? VERIFY_TYPE_TEXT[typeId] : '') || '已认证',
type: 'success'
}
}
if (info.apply_status !== null && info.apply_status !== undefined) {
const status = Number(info.apply_status)
const meta = APPLY_STATUS_META[status]
return {
text: info.apply_status_text || meta?.text || `未知状态(${status})`,
type: meta?.type ?? 'info'
}
}
if (info.task_status !== null && info.task_status !== undefined) {
const status = Number(info.task_status)
return {
text: info.task_status_text || `认证任务进行中(${status})`,
type: TASK_STATUS_TYPE[status] ?? 'warning'
}
}
return { text: '尚未认证', type: 'info' }
})
/** 是否存在认证任务(taskid / task_status);无任务即后端还没发起过认证 */
const certHasTask = computed(() => {
const info = certInfo.value
if (!info) return false
const hasTaskId = info.taskid !== null && info.taskid !== undefined && String(info.taskid).trim() !== ''
const hasTaskStatus = info.task_status !== null && info.task_status !== undefined
return hasTaskId || hasTaskStatus
})
/** 认证明细(只展示能明确命名的字段,空值不占位) */
const certRows = computed<{ label: string; value: string }[]>(() => {
const info = certInfo.value
if (!info) return []
const rows: { label: string; value: string }[] = []
const push = (label: string, value: unknown) => {
if (value === null || value === undefined) return
const text = String(value).trim()
if (!text) return
rows.push({ label, value: text })
}
push('小程序 AppID', info.appid)
if (info.is_verified) {
const typeId =
info.verify_type_id === null || info.verify_type_id === undefined ? null : Number(info.verify_type_id)
push(
'认证类型',
info.verify_type_text || (typeId !== null ? VERIFY_TYPE_TEXT[typeId] : '') || (typeId !== null ? `认证类型 ${typeId}` : '')
)
push('主体名称', info.principal_name)
push('帐号简介', info.signature)
}
push('认证任务 ID', info.taskid)
push('任务状态', info.task_status_text)
push('审核单状态', info.apply_status_text)
return rows
})
/** 查询认证状态(切到「认证状态」菜单时按需拉取,也可手动刷新) */
async function loadAuthStatus(options: { silent?: boolean; taskid?: string } = {}) {
if (!options.silent) certLoading.value = true
try {
// 入参 taskid 优先(发起认证后立即带新 taskid 查),缺省时用库中 auth_task_id
const res: any = await wechatQueryAuth(options.taskid ? { taskid: options.taskid } : {})
if (!okCode(res)) {
showApiError(res, '查询小程序认证状态失败', options.silent)
return null
}
const payload = pickWechatPayload<WeChatQueryAuthData>(res)
certInfo.value = payload
certLoaded.value = true
return certInfo.value
} catch (e: unknown) {
if (!options.silent) {
ElMessage.error(e instanceof Error ? e.message : '查询小程序认证状态失败')
}
return null
} finally {
if (!options.silent) certLoading.value = false
}
}
/** 切菜单时按需拉取(已查过不重复请求,可手动刷新) */
watch(activeMenu, (key) => {
if (key === 'cert' && !certLoaded.value && !certLoading.value) void loadAuthStatus()
if (key === 'publish' && !templateLoaded.value && !templateLoading.value) void loadTemplateList()
if (key === 'wxuser' && !userLoaded.value && !userLoading.value) void loadUserList()
if (key === 'wxagreement' && !agreementLoaded.value && !agreementLoading.value) {
void loadAgreement()
}
})
// ============================================================
// 微信用户列表(wechat.userList)
// ============================================================
/** 微信性别文案(0 未知、1 男、2 女) */
const WECHAT_SEX_TEXT: Record<number, string> = { 0: '未知', 1: '男', 2: '女' }
/**
* 组装 where(字段白名单:id/user_id/app_id/openid/unionid/nickname/sex/login_time/login_count/created_at/updated_at)。
* 「绑定状态」在后端没有对应字段,用 user_id 的 gt/eq 0 表达(is_bound = user_id > 0)。
*/
function buildUserWhere(): NonNullable<WeChatUserListParams['where']> {
const where: NonNullable<WeChatUserListParams['where']> = {}
const nickname = userQuery.nickname.trim()
if (nickname) where.nickname = { operator: 'contains', value: nickname }
if (userQuery.bound === 'bound') where.user_id = { operator: 'gt', value: 0 }
if (userQuery.bound === 'unbound') where.user_id = { operator: 'eq', value: 0 }
return where
}
/** 拉取用户列表(切到「微信用户」菜单时按需拉,筛选 / 分页变化时重拉) */
async function loadUserList(options: { silent?: boolean } = {}) {
if (!options.silent) userLoading.value = true
try {
const where = buildUserWhere()
const params: WeChatUserListParams = {
pagination: { page: userQuery.page, pageSize: userQuery.pageSize },
sort: { sortField: 'updated_at', sortOrder: 'desc' }
}
if (userQuery.app_id !== undefined && userQuery.app_id !== null) {
params.app_id = userQuery.app_id
}
if (Object.keys(where).length) params.where = where
const res: any = await wechatUserList(params)
if (!okCode(res)) {
showApiError(res, '获取微信用户列表失败', options.silent)
return null
}
// 实测该接口为「平铺」结构:list / pagination / apps 与 flag/code/message 同级(不在 data 里)
const payload = pickWechatPayload<Partial<WeChatUserListData>>(res) ?? {}
userList.value = Array.isArray(payload.list) ? payload.list : []
userTotal.value = Number(payload.pagination?.total ?? userList.value.length) || 0
if (Array.isArray(payload.apps) && payload.apps.length) userApps.value = payload.apps
userLoaded.value = true
return userList.value
} catch (e: unknown) {
if (!options.silent) {
ElMessage.error(e instanceof Error ? e.message : '获取微信用户列表失败')
}
return null
} finally {
if (!options.silent) userLoading.value = false
}
}
/** 筛选条件变化:回到第 1 页重查 */
function handleUserQueryChange() {
userQuery.page = 1
void loadUserList()
}
function handleUserPageChange() {
void loadUserList()
}
function handleUserPageSizeChange() {
userQuery.page = 1
void loadUserList()
}
function resetUserQuery() {
userQuery.app_id = undefined
userQuery.nickname = ''
userQuery.bound = ''
userQuery.page = 1
void loadUserList()
}
// ============================================================
// 绑定工号(wechat.bindByEmployee)
// ============================================================
/** 工号候选(来自「账号管理」setting.account.list) */
type EmployeeOption = {
employee_id?: number
account_id?: number
store_id?: number
real_name?: string
username?: string
phone?: string
status?: number
}
const bindEmployeeDialogVisible = ref(false)
const bindEmployeeSubmitting = ref(false)
/** 待绑定的微信用户(来自 wechat.userList 的行) */
const bindTargetUser = ref<WeChatUserItem | null>(null)
const bindEmployeeId = ref<number | undefined>(undefined)
const employeeLoading = ref(false)
const employeeOptions = ref<EmployeeOption[]>([])
/** 工号下拉选项文案:姓名(账号 #工号id)+停用标识 */
function employeeOptionLabel(emp: EmployeeOption): string {
const name = emp.real_name || emp.username || '未命名工号'
const account = emp.username ? `(${emp.username})` : ''
const id = emp.employee_id != null ? ` #${emp.employee_id}` : ''
const disabled = Number(emp.status) !== 1 ? '(已停用)' : ''
return `${name}${account}${id}${disabled}`
}
/** 拉取工号候选(setting.account.list;响应为 data 数组,兼容 data.list) */
async function loadEmployeeOptions() {
if (employeeLoading.value) return
employeeLoading.value = true
try {
const res: any = await accountList({})
if (!okCode(res)) {
showApiError(res, '获取工号列表失败')
return
}
const payload = res?.data
const list = Array.isArray(payload)
? payload
: Array.isArray(payload?.list)
? payload.list
: []
employeeOptions.value = list as EmployeeOption[]
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '获取工号列表失败')
} finally {
employeeLoading.value = false
}
}
/** 打开「绑定工号」弹窗 */
function openBindEmployeeDialog(row: WeChatUserItem) {
bindTargetUser.value = row
bindEmployeeId.value = undefined
bindEmployeeDialogVisible.value = true
void loadEmployeeOptions()
}
/** 提交绑定:wechat.bindByEmployee(工号 id + 微信记录 id) */
async function submitBindEmployee() {
const row = bindTargetUser.value
const oauthId = Number(row?.id)
if (!row || !Number.isFinite(oauthId) || oauthId <= 0) {
ElMessage.error('缺少微信用户记录 ID,请刷新列表后重试')
return
}
const employeeId = Number(bindEmployeeId.value)
if (!Number.isFinite(employeeId) || employeeId <= 0) {
ElMessage.warning('请选择要绑定的工号')
return
}
bindEmployeeSubmitting.value = true
try {
const res: any = await wechatBindByEmployee({ id: employeeId, oauth_id: oauthId })
if (!okCode(res)) {
showApiError(res, '绑定工号失败')
return
}
const payload = pickWechatPayload<Partial<WeChatBindByEmployeeData>>(res) ?? {}
if (payload.already_bound) {
ElMessage.info('该微信此前已绑定同一工号(幂等)')
} else {
const name = payload.account?.real_name || payload.account?.username || ''
ElMessage.success(name ? `绑定成功:${name}` : '绑定成功')
}
bindEmployeeDialogVisible.value = false
// 重新拉列表,让「绑定账号」列刷成已绑定
userLoaded.value = false
await loadUserList()
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '绑定工号失败')
} finally {
bindEmployeeSubmitting.value = false
}
}
// ============================================================
// 查看某条协议版本内容(wechat.getAgreementVersion)
// ============================================================
const agreementVersionDialogVisible = ref(false)
const agreementVersionLoading = ref(false)
/** 正在查看的协议版本记录 id(来自 userList 行的 agreement_version_id,或「用户协议」页手输) */
const agreementVersionId = ref<number | null>(null)
/** 从「微信用户」入口进入时携带的用户(仅用于弹窗提示文案) */
const agreementVersionUser = ref<WeChatUserItem | null>(null)
const agreementVersionMeta = ref<{ appid?: string; nickname?: string }>({})
const agreementVersionText = ref('')
/** 「用户协议」页常显入口的输入值(协议版本记录 id) */
const agreementVersionQueryId = ref('')
/** 弹窗顶部说明文案(区分「用户入口」与「直接按 id 查询」) */
const agreementVersionDesc = computed(() => {
const parts = [`协议版本记录 id:${agreementVersionId.value ?? '-'}`]
if (agreementVersionUser.value) {
parts.push(`用户:${agreementVersionUser.value.nickname || '(无昵称)'}`)
}
return parts.join('|')
})
/**
* 打开「协议版本内容」弹窗并拉取内容(按版本记录 id 查,需登录但免接口权限)。
* `user` 仅在从「微信用户」行进入时传入,只用于弹窗提示。
*/
async function viewAgreementVersion(id: number, user: WeChatUserItem | null = null) {
agreementVersionId.value = id
agreementVersionUser.value = user
agreementVersionMeta.value = {}
agreementVersionText.value = ''
agreementVersionDialogVisible.value = true
agreementVersionLoading.value = true
try {
const res: any = await wechatGetAgreementVersion({ id })
if (!okCode(res)) {
showApiError(res, '获取协议版本内容失败')
return
}
// 与其他 wechat.* 一致:优先扁平响应,兼容 data 包裹
const payload = pickWechatPayload<Partial<WeChatAgreementVersionData>>(res) ?? {}
agreementVersionMeta.value = { appid: payload.appid, nickname: payload.nickname }
agreementVersionText.value = String(payload.text ?? '')
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '获取协议版本内容失败')
} finally {
agreementVersionLoading.value = false
}
}
/** 「微信用户」行操作入口:取该用户记录里同意的协议版本 id */
function openAgreementVersionDialog(row: WeChatUserItem) {
const id = Number(row?.agreement_version_id)
if (!Number.isFinite(id) || id <= 0) {
ElMessage.warning('该用户未记录协议版本(agreement_version_id 为空)')
return
}
void viewAgreementVersion(id, row)
}
/** 「用户协议」页常显入口:按指定 / 输入框里的版本记录 id 查询 */
function queryAgreementVersionById(presetId?: number) {
const id = Number(presetId ?? agreementVersionQueryId.value)
if (!Number.isFinite(id) || id <= 0) {
ElMessage.warning('请输入正确的版本记录 id(正整数)')
return
}
agreementVersionQueryId.value = String(id)
void viewAgreementVersion(id)
}
// ============================================================
// 用户协议 / 用户须知(wechat.getUserAgreement / setUserAgreement)
// ============================================================
const agreementLoading = ref(false)
const agreementSaving = ref(false)
/** 是否已拉过(切菜单按需拉) */
const agreementLoaded = ref(false)
/** 用户须知富文本(编辑中,HTML) */
const agreementText = ref('')
/** 已加载/已保存内容的快照,用于「有未保存修改」提示 */
const agreementSavedText = ref('')
/** 当前编辑区内容与已保存内容是否有差异 */
const agreementDirty = computed(() => agreementText.value !== agreementSavedText.value)
/** 当前仓库小程序的 appid / 昵称 / 最新协议版本记录 id(来自 getUserAgreement) */
const agreementMeta = ref<{ appid?: string; nickname?: string; version_id?: number }>({})
const agreementPreviewLoading = ref(false)
/** 「预览小程序侧读取结果」:小程序端实际拿到的文本、协议版本与缓存命中情况 */
const agreementPreview = ref<{
text?: string
from_cache?: boolean
version_id?: number
} | null>(null)
/** 拉取当前仓库小程序的用户须知(回显到编辑器,仅取最新版本) */
async function loadAgreement(options: { silent?: boolean } = {}) {
if (!options.silent) agreementLoading.value = true
try {
const res: any = await wechatGetUserAgreement()
if (!okCode(res)) {
showApiError(res, '获取小程序用户须知失败', options.silent)
return null
}
const payload = pickWechatPayload<Partial<WeChatUserAgreementData>>(res) ?? {}
agreementMeta.value = {
appid: payload.appid,
nickname: payload.nickname,
version_id: payload.version_id
}
agreementText.value = String(payload.text ?? '')
agreementSavedText.value = agreementText.value
agreementPreview.value = null
agreementLoaded.value = true
return payload
} catch (e: unknown) {
if (!options.silent) {
ElMessage.error(e instanceof Error ? e.message : '获取小程序用户须知失败')
}
return null
} finally {
if (!options.silent) agreementLoading.value = false
}
}
/** 保存用户须知(每次提交自动新增版本;空内容需二次确认) */
async function saveAgreement() {
const text = agreementText.value
if (!text.trim()) {
const confirmed = await ElMessageBox.confirm(
'当前内容为空,保存后会清空该仓库小程序的用户须知,确定继续?',
'清空用户须知',
{ type: 'warning', confirmButtonText: '确定清空', cancelButtonText: '取消' }
)
.then(() => true)
.catch(() => false)
if (!confirmed) return
}
agreementSaving.value = true
try {
const res: any = await wechatSetUserAgreement({ text })
if (!okCode(res)) {
showApiError(res, '保存小程序用户须知失败')
return
}
const payload = pickWechatPayload<Partial<WeChatUserAgreementData>>(res) ?? {}
agreementText.value = String(payload.text ?? text)
agreementSavedText.value = agreementText.value
agreementMeta.value = {
...agreementMeta.value,
appid: payload.appid ?? agreementMeta.value.appid,
version_id: payload.version_id ?? agreementMeta.value.version_id
}
// 保存后缓存已清,旧预览作废
agreementPreview.value = null
ElMessage.success(
payload.version_id != null
? `已保存为版本 #${payload.version_id}(小程序端读取缓存已清除)`
: '已保存(小程序端读取缓存已清除)'
)
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '保存小程序用户须知失败')
} finally {
agreementSaving.value = false
}
}
/** 预览小程序端(免登录 getUserAgreementText)实际拿到的内容与缓存命中情况 */
async function previewAgreementForMiniProgram() {
const appid = String(agreementMeta.value.appid ?? '').trim()
if (!appid) {
ElMessage.warning('未获取到小程序 AppID,请先点「重新加载」')
return
}
agreementPreviewLoading.value = true
try {
const res: any = await wechatGetUserAgreementText({ appId: appid })
if (!okCode(res)) {
showApiError(res, '获取小程序侧用户须知失败')
return
}
const payload = pickWechatPayload<Partial<WeChatUserAgreementTextData>>(res) ?? {}
agreementPreview.value = {
text: String(payload.text ?? ''),
from_cache: Boolean(payload.from_cache),
version_id: payload.version_id
}
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '获取小程序侧用户须知失败')
} finally {
agreementPreviewLoading.value = false
}
}
// ============================================================
// 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode)
// ============================================================
/** 模板下拉选项文案:版本号 + 模板 ID + 描述 + 创建时间 */
function templateOptionLabel(tpl: WeChatTemplateItem): string {
const version = tpl.user_version || '未命名版本'
const id = tpl.template_id != null ? `#${tpl.template_id}` : '#-'
const desc = tpl.user_desc ? `|${tpl.user_desc}` : ''
const time = tpl.create_time ? `|${toLocalDateTime(new Date(tpl.create_time * 1000))}` : ''
return `${version} ${id}${desc}${time}`
}
/** 拉取普通模板库列表(后端缓存 24h,from_cache 标识是否命中缓存;force=true 时重新请求) */
async function loadTemplateList(force = false) {
if (templateLoading.value) return null
if (templateLoaded.value && !force) return templateList.value
templateLoading.value = true
try {
const res: any = await wechatGetTemplateList()
if (!okCode(res)) {
showApiError(res, '获取代码模板列表失败')
return null
}
const payload = pickWechatPayload<Partial<WeChatTemplateListData>>(res) ?? {}
templateList.value = Array.isArray(payload.list) ? payload.list : []
templateFromCache.value = Boolean(payload.from_cache)
templateLoaded.value = true
return templateList.value
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '获取代码模板列表失败')
return null
} finally {
templateLoading.value = false
}
}
/** 上传代码并生成体验版(wechat.commit;入参只有 template_id,版本号/描述由后端从模板取) */
async function submitCommit() {
const templateId = commitForm.template_id
if (templateId === undefined || templateId === null) {
ElMessage.warning('请先选择代码模板')
return
}
const tpl = selectedTemplate.value
if (!tpl) {
ElMessage.warning('所选模板不在当前模板列表中,请先刷新模板')
return
}
// 后端直接取模板的 user_version / user_desc 上传,模板缺这两项必然失败 → 前端提前拦
if (!String(tpl.user_version ?? '').trim() || !String(tpl.user_desc ?? '').trim()) {
ElMessage.warning('所选模板缺少版本号或代码描述,请先在微信模板库补充后再上传')
return
}
commitSubmitting.value = true
try {
const res: any = await wechatCommit({ template_id: Number(templateId) })
if (!okCode(res)) {
showApiError(res, '上传代码失败')
return
}
const payload = pickWechatPayload<Partial<WeChatCommitData>>(res) ?? {}
ElMessage.success(
payload.user_version
? `代码已上传,体验版已生成(版本 ${payload.user_version})`
: '代码已上传,体验版已生成'
)
// 后端会回写 wms_wechat_app.template_id,刷新基础信息保持一致
await loadConfig({ silent: true })
// 体验版内容已变化,旧二维码作废并自动重取
trialQRCodeUrl.value = ''
await loadTrialQRCode({ silent: true })
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '上传代码失败')
} finally {
commitSubmitting.value = false
}
}
/** 获取体验版二维码(wechat.getTrialQRCode;path 选填,不传则由后端处理) */
async function loadTrialQRCode(options: { silent?: boolean } = {}) {
if (!options.silent) trialQRCodeLoading.value = true
try {
const path = trialQRCodePath.value.trim()
const res: any = await wechatGetTrialQRCode(path ? { path } : {})
if (!okCode(res)) {
showApiError(res, '获取体验版二维码失败', options.silent)
return null
}
const payload = pickWechatPayload<{ url?: string }>(res) ?? {}
trialQRCodeUrl.value = payload.url || ''
if (!trialQRCodeUrl.value && !options.silent) ElMessage.error('未获取到二维码地址')
return trialQRCodeUrl.value
} catch (e: unknown) {
if (!options.silent) {
ElMessage.error(e instanceof Error ? e.message : '获取体验版二维码失败')
}
return null
} finally {
if (!options.silent) trialQRCodeLoading.value = false
}
}
/**
* 提交代码审核(wechat.submitAudit)。
* item_list 后端未提供可选类目接口,按微信格式手填(JSON 数组,留空则不传)。
*/
async function submitAudit() {
let itemList: WeChatAuditItem[] | undefined
const rawItemList = auditForm.item_list_text.trim()
if (rawItemList) {
try {
const parsed: unknown = JSON.parse(rawItemList)
if (!Array.isArray(parsed)) {
ElMessage.error('审核类目必须是 JSON 数组')
return
}
itemList = parsed as WeChatAuditItem[]
} catch {
ElMessage.error('审核类目不是合法的 JSON')
return
}
}
auditSubmitting.value = true
try {
const res: any = await wechatSubmitAudit({
version_desc: auditForm.version_desc.trim() || undefined,
privacy_api_not_use: auditForm.privacy_api_not_use || undefined,
...(itemList ? { item_list: itemList } : {})
})
if (!okCode(res)) {
showApiError(res, '提交审核失败')
return
}
const payload = pickWechatPayload<Partial<WeChatSubmitAuditData>>(res) ?? {}
auditResult.value = {
appid: payload.appid,
auditid: payload.auditid,
submittedAt: toLocalDateTime(new Date())
}
ElMessage.success(
payload.auditid != null ? `已提交审核(审核单 ${payload.auditid})` : '已提交审核'
)
// 后端已回写 audit_status / audit_id,刷新一次让基础信息同步
await loadConfig({ silent: true })
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '提交审核失败')
} finally {
auditSubmitting.value = false
}
}
// ============================================================
// 授权(点击按钮后才获取链接并弹小窗)
// ============================================================
/** 从响应中取链接(字段名多形态兼容,兜底扫描 http 开头的字符串) */
function pickUrl(raw: Record<string, unknown>): string {
for (const key of AUTH_URL_KEYS) {
const value = raw[key]
if (typeof value === 'string' && /^https?:\/\//i.test(value.trim())) return value.trim()
}
for (const value of Object.values(raw)) {
if (typeof value === 'string' && /^https?:\/\//i.test(value.trim())) return value.trim()
}
return ''
}
/**
* 在新小窗口中打开链接(授权 / 代注册共用)。
* @param url 目标地址。
* @param windowName 窗口名(同名窗口会被复用)。
* @param tipText 打开后的提示文案。
* @param shouldWatch 是否启动「授权小窗」配置轮询(发起认证改为手动刷新认证状态,传 false)。
*/
function openSmallWindow(url: string, windowName: string, tipText: string, shouldWatch = true) {
const width = 760
const height = 780
const left = Math.max(0, Math.round((window.screen.width - width) / 2))
const top = Math.max(0, Math.round((window.screen.height - height) / 2))
const features = `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
const opened = window.open(url, windowName, features)
if (!opened) {
ElMessage.warning('窗口被浏览器拦截:请允许本站弹出窗口后重试')
return
}
ElMessage.info(tipText)
if (shouldWatch) {
authWindow = opened
startWatch()
}
}
/** 点击「去授权」:获取授权链接 → 打开小窗(仅主域名可用) */
async function handleAuthorize() {
if (!isMainDomain) {
ElMessage.warning(mainDomainTip)
return
}
authUrlLoading.value = true
try {
const res: any = await wechatGetAuthUrl()
if (!okCode(res)) {
showApiError(res, '获取微信授权链接失败')
return
}
// 链接字段可能平铺在信封上(无 data),也可能在 data 里 → 两层都并进去再扫
const url = pickUrl({ ...(res ?? {}), ...(pickWechatPayload(res) ?? {}) })
if (!url) {
ElMessage.error('未获取到授权链接,请稍后重试')
return
}
openSmallWindow(url, 'wx-miniprogram-authorize', '请在新打开的小窗口中完成微信授权,完成后本页会自动刷新')
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '获取微信授权链接失败')
} finally {
authUrlLoading.value = false
}
}
/** 点击「代注册小程序」:打开企业信息弹窗(wechat.registerMiniprogram,不走小窗 / 不受主域名限制) */
function handleRegister() {
registerDialogVisible.value = true
}
/** 重置代注册表单 */
function resetRegisterForm() {
registerFormRef.value?.clearValidate()
Object.assign(registerForm, {
name: '',
code: '',
code_type: 1,
legal_persona_wechat: '',
legal_persona_name: '',
component_phone: ''
})
}
/**
* 提交代注册:后端调微信 fastregisterweapp?action=create 创建注册任务。
* 响应为 { errcode, errmsg }(无链接),errcode=0 视为提交成功;
* 之后由法人微信完成人脸核身,审核结果经微信事件回调后端,认证进度用 wechat.queryauth 查看。
*/
async function submitRegister() {
const form = registerFormRef.value
if (!form) return
const valid = await form.validate().catch(() => false)
if (!valid) return
registerSubmitting.value = true
try {
const res: any = await wechatRegisterMiniprogram({ ...registerForm })
const raw = (res ?? {}) as Record<string, any>
const nested = (raw.data && typeof raw.data === 'object' ? raw.data : {}) as Record<string, any>
const errcode = Number(nested.errcode ?? raw.errcode)
const errmsg = String(nested.errmsg ?? raw.errmsg ?? raw.message ?? '')
// flag/success 显式失败时,不能被 errcode===0 的兜底救回来
const flagFailure = raw.flag === 'failure' || raw.flag === 'fail' || raw.success === false
if (flagFailure || !(okCode(raw) || errcode === 0)) {
ElMessage.error(errmsg || '提交代注册失败')
return
}
ElMessage.success('注册任务已提交:请法人本人留意微信模板消息并完成人脸核身')
registerDialogVisible.value = false
resetRegisterForm()
// 注册结果由微信事件回调后端,这里刷新一次配置与认证进度
await Promise.all([loadConfig({ silent: true }), loadAuthStatus({ silent: true })])
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '提交代注册失败')
} finally {
registerSubmitting.value = false
}
}
// ============================================================
// 同步微信基础信息(wechat.getAuthorizerInfo)
// ============================================================
const authorizerInfoLoading = ref(false)
/** 调微信 api_get_authorizer_info 同步主体/认证类型/账号状态/权限集,落库后刷新本页 */
async function handleSyncAuthorizerInfo() {
if (!authorized.value) {
ElMessage.warning('请先完成小程序授权')
return
}
authorizerInfoLoading.value = true
try {
const res = await wechatGetAuthorizerInfo()
if (!okCode(res)) {
showApiError(res, '同步微信信息失败')
return
}
ElMessage.success('已同步微信侧小程序基础信息')
await loadConfig({ silent: true })
// 认证类型 / 账号状态可能变化 → 认证状态重新查询
certLoaded.value = false
if (activeMenu.value === 'cert') await loadAuthStatus()
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '同步微信信息失败')
} finally {
authorizerInfoLoading.value = false
}
}
// ============================================================
// 发起微信认证(wechat.wxaauth)
// ============================================================
const authApplyDialogVisible = ref(false)
const authApplySubmitting = ref(false)
const authApplyFormRef = ref<FormInstance>()
/** 主体资质材料正在上传(用于按钮 loading) */
const authQualificationUploading = ref(false)
/** 高级字段 JSON:auth_data 白名单字段原样透传,与上方表单同名时以此为准 */
const authApplyExtraJson = ref('')
/** 发起认证表单(对齐新版 wxaauth:6 个必填 + auth_data 白名单可选) */
const authApplyForm = reactive({
customer_type: 1,
account_name: '',
account_name_type: 1,
pay_type: 1,
third_party_phone: '',
contact_name: '',
contact_email: '',
contact_mobile: '',
qualification: '',
qualification_other_text: '',
account_supplemental_text: '',
auth_ident_material_text: '',
service_appid: '',
taskid: ''
})
const authApplyRules: FormRules = {
customer_type: [{ required: true, message: '请选择账号主体类型', trigger: 'change' }],
account_name: [{ required: true, message: '请输入小程序账号名称', trigger: 'blur' }],
account_name_type: [{ required: true, message: '请选择命名类型', trigger: 'change' }],
pay_type: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
third_party_phone: [{ required: true, message: '请输入第三方联系电话', trigger: 'blur' }],
contact_name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
contact_email: [
{ required: true, message: '请输入联系人邮箱', trigger: 'blur' },
{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
]
}
/** 打开「发起微信认证」弹窗(保留已填内容,仅清校验态;打回重填时自动带出库中 taskid) */
function openAuthApplyDialog() {
const info = certInfo.value
if (info?.apply_status === 3 && info.taskid && !authApplyForm.taskid) {
authApplyForm.taskid = String(info.taskid)
}
authApplyFormRef.value?.clearValidate()
authApplyDialogVisible.value = true
}
/** 主体资质材料上传:复用 COS 直传(后端提交前会自动换 mediaid) */
async function handleQualificationUpload(options: { file: File }) {
const file = options?.file
if (!file) return
authQualificationUploading.value = true
try {
const uploaded = await uploadImageToCos(file)
authApplyForm.qualification = uploaded.fileUrl
ElMessage.success('图片已上传')
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '图片上传失败')
} finally {
authQualificationUploading.value = false
}
}
/** 多图字段:一行一个 COS URL / mediaid(上限 10);超限时提示并返回 null */
function parseAuthMediaLines(text: string, label: string): string[] | null {
const list = text
.split(/\r?\n/)
.map((item) => item.trim())
.filter(Boolean)
if (list.length > 10) {
ElMessage.error(`${label}最多 10 项(当前 ${list.length} 项)`)
return null
}
return list
}
/** 提交发起认证:成功刷新认证状态,必要时打开微信认证链接 */
async function submitAuthApply() {
const form = authApplyFormRef.value
if (!form) return
const valid = await form.validate().catch(() => false)
if (!valid) return
// 高级字段:必须是 JSON 对象
let extra: Record<string, unknown> = {}
const rawExtra = authApplyExtraJson.value.trim()
if (rawExtra) {
try {
const parsed: unknown = JSON.parse(rawExtra)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
ElMessage.error('高级字段必须是 JSON 对象')
return
}
extra = parsed as Record<string, unknown>
} catch {
ElMessage.error('高级字段不是合法的 JSON')
return
}
}
// 多图字段:一行一个 COS URL / mediaid(上限 10)
const qualificationOther = parseAuthMediaLines(
authApplyForm.qualification_other_text,
'资质其他材料'
)
if (!qualificationOther) return
const accountSupplemental = parseAuthMediaLines(
authApplyForm.account_supplemental_text,
'名称关键词补充材料'
)
if (!accountSupplemental) return
const authIdentMaterial = parseAuthMediaLines(
authApplyForm.auth_ident_material_text,
'个人认证材料'
)
if (!authIdentMaterial) return
const customerType = Number(authApplyForm.customer_type) || 1
const qualification = authApplyForm.qualification.trim()
// 非个人主体:主体资质材料必填(文档:qualification 非个人必填)
if (customerType !== 15 && !qualification) {
ElMessage.error('非个人主体必须提供「主体资质材料」(上传图片或填 COS URL / mediaid)')
return
}
const payload: WeChatWxaauthParams = {
customer_type: customerType,
account_name: authApplyForm.account_name.trim(),
account_name_type: Number(authApplyForm.account_name_type) || 1,
pay_type: Number(authApplyForm.pay_type) || 1,
third_party_phone: authApplyForm.third_party_phone.trim(),
contact_info: {
name: authApplyForm.contact_name.trim(),
email: authApplyForm.contact_email.trim()
}
}
const mobile = authApplyForm.contact_mobile.trim()
if (mobile) payload.contact_info.mobile = mobile
if (qualification) payload.qualification = qualification
if (qualificationOther.length) payload.qualification_other = qualificationOther
if (accountSupplemental.length) payload.account_supplemental = accountSupplemental
if (authIdentMaterial.length) payload.auth_ident_material = authIdentMaterial
const serviceAppid = authApplyForm.service_appid.trim()
if (serviceAppid) payload.service_appid = serviceAppid
const reauthTaskId = authApplyForm.taskid.trim()
if (reauthTaskId) payload.taskid = reauthTaskId
Object.assign(payload, extra)
authApplySubmitting.value = true
try {
const res = await wechatWxaauth(payload)
if (!okCode(res)) {
showApiError(res, '发起认证失败')
return
}
const data = pickWechatPayload<WeChatWxaauthData>(res) ?? {}
authApplyDialogVisible.value = false
ElMessage.success(
data.taskid
? `认证已发起(任务 ${data.taskid}),请前往微信完成认证`
: '认证已发起,请前往微信完成认证'
)
const url = data.auth_url ? String(data.auth_url) : ''
if (url) {
openSmallWindow(
url,
'wx-miniprogram-auth-apply',
'请在新窗口中完成微信认证(法人核身 / 支付审核费),完成后点「刷新认证状态」',
false
)
}
await loadAuthStatus(data.taskid ? { taskid: String(data.taskid) } : {})
} catch (e: unknown) {
ElMessage.error(e instanceof Error ? e.message : '发起认证失败')
} finally {
authApplySubmitting.value = false
}
}
/** 小窗打开期间轮询配置:流程完成即自动刷新 */
function startWatch() {
stopAuthWatch()
authWatchStartedAt = Date.now()
authWatchTimer = window.setInterval(async () => {
if (authWatchBusy) return
if (Date.now() - authWatchStartedAt > AUTH_WATCH_MAX_DURATION) {
stopAuthWatch()
return
}
// 小窗已关闭:做最后一次刷新后停止
if (authWindow && authWindow.closed) {
stopAuthWatch()
authWindow = null
await loadConfig({ silent: true })
return
}
authWatchBusy = true
try {
const payload = await loadConfig({ silent: true })
if (payload && Object.entries(payload).some(([key, value]) => !NEUTRAL_KEYS.has(key.toLowerCase()) && !isEmptyValue(value))) {
stopAuthWatch()
ElMessage.success('微信小程序授权成功,配置已刷新')
// 授权可能换绑小程序(appid 变化),认证状态需重新查询
certLoaded.value = false
certInfo.value = null
if (activeMenu.value === 'cert') void loadAuthStatus()
}
} finally {
authWatchBusy = false
}
}, AUTH_WATCH_INTERVAL)
}
function stopAuthWatch() {
if (authWatchTimer !== null) {
window.clearInterval(authWatchTimer)
authWatchTimer = null
}
}
/** 复制文本 */
async function copyText(value: unknown) {
const text = toDisplayText(value).trim()
if (!text) {
ElMessage.warning('无内容可复制')
return
}
try {
await navigator.clipboard.writeText(text)
ElMessage.success('已复制到剪贴板')
} catch {
ElMessage.warning('复制失败,请手动选中复制')
}
}
onMounted(() => {
void loadConfig()
})
onBeforeUnmount(() => {
stopAuthWatch()
})
</script>
<style lang="scss" scoped>
.mp-config-page {
display: flex;
flex-direction: column;
flex: 1;
height: 100%;
min-height: 0;
padding: 12px 16px 16px;
box-sizing: border-box;
background: #fff;
}
.settings-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.header-text {
display: flex;
flex-direction: column;
gap: 4px;
}
.title {
font-size: 16px;
font-weight: 600;
color: #303133;
}
.sub {
font-size: 13px;
color: #909399;
}
.header-actions {
display: flex;
gap: 8px;
}
/* 禁用按钮外包一层,保证 tooltip 在 disabled 状态下仍可触发 */
.mp-auth-trigger {
display: inline-flex;
}
.mp-config-alert {
flex-shrink: 0;
margin-bottom: 16px;
}
.mp-empty {
flex-shrink: 0;
border: 1px solid #ebeef5;
border-radius: 6px;
padding: 24px 16px;
background: #fff;
}
.mp-panel {
border: 1px solid #ebeef5;
border-radius: 6px;
padding: 12px 16px;
margin-bottom: 16px;
background: #fff;
}
.mp-panel__head {
margin-bottom: 12px;
}
.mp-panel__title {
margin: 0;
font-size: 14px;
font-weight: 600;
color: #303133;
}
.mp-panel__desc {
margin: 4px 0 0;
font-size: 12px;
color: #909399;
line-height: 18px;
}
/* ===== 基础信息 / 其他信息:名称 + 不可编辑输入框 ===== */
.mp-info-form {
max-width: 900px;
}
.mp-info-form :deep(.el-form-item) {
margin-bottom: 12px;
}
.mp-field-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.mp-field {
max-width: 560px;
}
/* 禁用态下保持可读文字颜色(只读展示) */
.mp-field :deep(.el-input__inner) {
color: #303133;
-webkit-text-fill-color: #303133;
}
.mp-thumb {
flex: 0 0 auto;
width: 56px;
height: 56px;
border-radius: 6px;
background: #f5f7fa;
cursor: pointer;
}
.mp-thumb__tip {
font-size: 12px;
color: #c0c4cc;
}
/* ===== 微信用户列表(wechat.userList) ===== */
.mp-user-filters {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.mp-user-filter__select {
width: 180px;
}
.mp-user-filter__input {
width: 200px;
}
.mp-user-table {
width: 100%;
}
.mp-user-avatar {
width: 32px;
height: 32px;
border-radius: 4px;
background: #f5f7fa;
}
.mp-user-empty {
font-size: 12px;
color: #c0c4cc;
}
.mp-user-pager {
display: flex;
justify-content: flex-end;
margin-top: 12px;
}
/* ===== 绑定工号弹窗 ===== */
.mp-bind-target {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13px;
color: #303133;
}
.mp-bind-openid {
font-size: 12px;
color: #909399;
word-break: break-all;
}
/* ===== 用户协议(用户须知) ===== */
.mp-agreement {
max-width: 900px;
}
.mp-agreement__meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 8px;
}
.mp-agreement__appid {
font-size: 12px;
color: #909399;
word-break: break-all;
}
.mp-agreement__actions {
display: flex;
gap: 8px;
margin-top: 12px;
}
/* 常显入口:按版本记录 id 查看协议原文(wechat.getAgreementVersion) */
.mp-agreement__lookup {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-top: 14px;
padding-top: 12px;
border-top: 1px dashed #e4e7ed;
}
.mp-agreement__lookup-label {
font-size: 13px;
color: #606266;
}
.mp-agreement__lookup-input {
width: 220px;
}
/* 查看某条协议版本(wechat.getAgreementVersion 弹窗内容) */
.mp-agreement-version {
max-height: 56vh;
overflow-y: auto;
.mp-agreement__appid {
margin: 0 0 8px;
}
}
.mp-agreement-version__body {
border: 1px solid #ebeef5;
border-radius: 6px;
padding: 12px 14px;
background: #fff;
color: #303133;
font-size: 14px;
line-height: 1.7;
:deep(h2) {
margin: 12px 0 8px;
font-size: 18px;
font-weight: 600;
}
:deep(h3) {
margin: 10px 0 6px;
font-size: 16px;
font-weight: 600;
}
:deep(p) {
margin: 6px 0;
}
:deep(ul),
:deep(ol) {
margin: 6px 0;
padding-left: 24px;
list-style: revert;
}
:deep(blockquote) {
margin: 8px 0;
padding: 4px 10px;
border-left: 3px solid #dcdfe6;
color: #606266;
background: #fafafa;
}
:deep(a) {
color: var(--el-color-primary);
word-break: break-all;
}
:deep(img) {
max-width: 100%;
height: auto;
}
}
/* 授权功能集:解析后的功能项标签 */
.mp-func-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 6px;
}
.mp-func-tag {
cursor: default;
}
/* ===== 认证状态(wechat.queryauth) ===== */
.mp-cert {
min-height: 80px;
}
.mp-cert__desc {
max-width: 560px;
}
.mp-cert__actions {
margin-top: 12px;
}
/* 未认证时的认证流程说明(发起认证接口待后端提供) */
.mp-cert__flow {
margin: 12px 0 0;
padding-left: 20px;
color: #606266;
font-size: 13px;
line-height: 1.9;
}
.mp-cert__flow code {
padding: 0 4px;
border-radius: 3px;
background: #f4f6f9;
font-size: 12px;
}
/* 发起微信认证弹窗:材料图片行 */
.mp-media-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.mp-media-preview {
flex: none;
width: 40px;
height: 40px;
border: 1px solid #e8eef7;
border-radius: 4px;
}
/* ===== 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode) ===== */
.mp-publish-form {
max-width: 640px;
}
.mp-publish-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
}
.mp-publish-select {
flex: 1 1 auto;
min-width: 0;
max-width: 400px;
}
.mp-publish-input {
max-width: 320px;
}
.mp-publish-hint {
margin: 4px 0 0;
font-size: 12px;
color: #909399;
line-height: 18px;
}
.mp-publish-inline-hint {
margin-left: 8px;
font-size: 12px;
color: #909399;
line-height: 18px;
}
.mp-audit-result {
margin-top: 4px;
}
.mp-qrcode {
display: flex;
flex-direction: column;
gap: 8px;
}
.mp-qrcode__img {
width: 220px;
height: 220px;
border: 1px solid #ebeef5;
border-radius: 6px;
background: #fff;
}
/* ===== 已授权:左菜单 + 右明细(均铺满高度) ===== */
.mp-layout {
flex: 1;
min-height: 0;
display: flex;
align-items: stretch;
gap: 16px;
}
/* 左侧菜单:竖向铺满到底,菜单过长时自身上下滚动 */
.mp-nav {
flex: 0 0 200px;
min-height: 0;
padding: 8px;
border: 1px solid #e8eef7;
border-radius: 6px;
background: #f8fbff;
box-sizing: border-box;
overflow-y: auto;
overscroll-behavior: contain;
}
.mp-nav__list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.mp-nav__item {
display: flex;
align-items: center;
gap: 8px;
height: 38px;
padding: 0 10px;
border-radius: 6px;
font-size: 14px;
color: #606266;
cursor: pointer;
transition: all 0.2s;
&:hover {
color: #409eff;
background: rgba(64, 158, 255, 0.06);
}
&.is-active {
color: #409eff;
font-weight: 600;
background: #fff;
box-shadow: inset 0 0 0 1px #e8eef7;
}
}
.mp-nav__icon {
flex: 0 0 auto;
font-size: 16px;
}
.mp-nav__label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mp-nav__tag {
flex: 0 0 auto;
}
/* 右侧明细:边框铺满到底,内容过长时自身上下滚动 */
.mp-detail {
flex: 1;
min-width: 0;
min-height: 0;
padding: 12px 16px;
border: 1px solid #e8eef7;
border-radius: 6px;
background: #fff;
box-sizing: border-box;
overflow-y: auto;
overscroll-behavior: contain;
> :last-child {
margin-bottom: 0;
}
/* 右侧本身就是带边框的容器,内部面板不再重复描边(避免“多一个框”) */
.mp-panel {
padding: 0;
border: none;
border-radius: 0;
background: transparent;
margin-bottom: 16px;
}
}
.mp-placeholder {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.mp-placeholder__block {
flex: 1 1 240px;
min-width: 220px;
padding: 12px;
border: 1px dashed #d9e4f2;
border-radius: 6px;
background: #fbfdff;
box-sizing: border-box;
}
.mp-placeholder__title {
margin: 0;
font-size: 13px;
font-weight: 600;
color: #303133;
}
.mp-placeholder__desc {
margin: 6px 0 0;
font-size: 12px;
color: #909399;
line-height: 18px;
}
@media (max-width: 900px) {
.mp-layout {
flex-direction: column;
overflow-y: auto;
}
.mp-nav {
flex: 0 0 auto;
width: 100%;
overflow-y: visible;
}
.mp-nav__list {
flex-direction: row;
flex-wrap: wrap;
}
.mp-detail {
flex: 0 0 auto;
overflow-y: visible;
}
}
</style>