feat: add client self-service purchases and integration kit
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled

Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
2026-10-15 17:33:52 +08:00
parent 68a2b4d892
commit cfcc9b386b
33 changed files with 2598 additions and 44 deletions

View File

@@ -0,0 +1,20 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from './api'
import { createPaymentPlan, createPurchaseCredential, listPaymentPlans, listPurchaseCredentials, purchaseConfigError, setPurchaseCredentialEnabled, updatePaymentPlan } from './purchase-config-api'
vi.mock('./api',()=>({api:{get:vi.fn(),post:vi.fn(),put:vi.fn()},ApiError:class ApiError extends Error{code?:string;status?:number;constructor(message:string,code?:string,status?:number){super(message);this.code=code;this.status=status}}}))
import { api } from './api'
describe('purchase config API',()=>{
afterEach(()=>vi.clearAllMocks())
it('uses admin API endpoints and exact write payloads',async()=>{
vi.mocked(api.get).mockResolvedValue({data:{data:[]}} as never);vi.mocked(api.post).mockResolvedValue({data:{data:{}}} as never);vi.mocked(api.put).mockResolvedValue({data:{data:{}}} as never)
const input={product_id:3,code:'p30',name:'30天',amount_cents:5000,currency:'CNY' as const,license_days:30,enabled:false}
const update={...input,version:2}
await listPaymentPlans();await createPaymentPlan(input);await updatePaymentPlan(8,update);await listPurchaseCredentials();await createPurchaseCredential({customer_id:4,product_id:3,label:'桌面端'});await setPurchaseCredentialEnabled(9,false)
expect(api.get).toHaveBeenNthCalledWith(1,'/payment-plans');expect(api.post).toHaveBeenCalledWith('/payment-plans',input);expect(api.put).toHaveBeenNthCalledWith(1,'/payment-plans/8',update);expect(api.get).toHaveBeenNthCalledWith(2,'/purchase-credentials');expect(api.post).toHaveBeenCalledWith('/purchase-credentials',{customer_id:4,product_id:3,label:'桌面端'});expect(api.put).toHaveBeenNthCalledWith(2,'/purchase-credentials/9',{enabled:false})
})
it('returns fixed allowlisted errors and never returns raw server messages',()=>{
expect(purchaseConfigError(new ApiError('secret backend detail','invalid_request',400),'fallback')).toBe('填写内容无效,请检查金额、固定天数与客户产品范围')
expect(purchaseConfigError(new ApiError('secret backend detail','unknown_error',500),'安全的默认提示')).toBe('安全的默认提示')
expect(purchaseConfigError(new ApiError('x','x',401),'fallback')).toBe('登录已失效,请重新登录')
})
})

View File

@@ -0,0 +1,29 @@
import { api, ApiError } from './api'
export type PaymentPlan = { id:number; product_id:number; code:string; name:string; amount_cents:number; currency:'CNY'|string; license_days:number; enabled:boolean; version:number }
export type PurchaseCredential = { id:number; customer_id:number; product_id:number; label:string; enabled:boolean; created_at?:string }
export type PlanInput = Omit<PaymentPlan,'id'|'version'>
export type PlanUpdate = PlanInput & {version:number}
export function purchaseConfigError(error:unknown, fallback:string) {
if (!(error instanceof ApiError)) return fallback
if (error.status === 401) return '登录已失效,请重新登录'
if (error.status === 403) return '无权限管理套餐与购买凭据,请联系管理员'
if (error.status === 404) return '服务版本不支持该接口,请更新并重启服务'
const messages:Record<string,string> = {
plan_conflict:'套餐编码已存在,请使用其他编码',
plan_version_conflict:'套餐已被其他管理员修改,请刷新后重新编辑',
plan_identity_conflict:'套餐产品与编码不可修改,请创建新套餐',
product_unavailable:'产品不可用,请选择有效产品',
scope_unavailable:'客户或产品范围不可用,请重新选择',
invalid_request:'填写内容无效,请检查金额、固定天数与客户产品范围',
purchase_unavailable:'购买服务暂不可用,请稍后重试',
}
return error.code && messages[error.code] || fallback
}
export async function listPaymentPlans() { return api.get<{data:PaymentPlan[]}>('/payment-plans') }
export async function createPaymentPlan(value:PlanInput) { return api.post<{data:PaymentPlan}>('/payment-plans',value) }
export async function updatePaymentPlan(id:number,value:PlanUpdate) { return api.put<{data:PaymentPlan}>(`/payment-plans/${id}`,value) }
export async function listPurchaseCredentials() { return api.get<{data:PurchaseCredential[]}>('/purchase-credentials') }
export async function createPurchaseCredential(value:Pick<PurchaseCredential,'customer_id'|'product_id'|'label'>) { return api.post<{data:PurchaseCredential & {token:string}}>('/purchase-credentials',value) }
export async function setPurchaseCredentialEnabled(id:number,enabled:boolean) { return api.put<{data:PurchaseCredential}>(`/purchase-credentials/${id}`,{enabled}) }

View File

@@ -5,7 +5,7 @@ import Checkout from './views/Checkout.vue'
export default createRouter({
history: createWebHistory(),
routes: [
...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})),
...[{path:'/',view:'dashboard'},{path:'/licenses',view:'licenses'},{path:'/customers',view:'customers'},{path:'/products',view:'products'},{path:'/orders',view:'orders'},{path:'/payments',view:'payments'},{path:'/payment-plans',view:'payment-plans'},{path:'/releases',view:'releases'},{path:'/integration',view:'integration'},{path:'/audit',view:'audit'},{path:'/settings',view:'settings'},{path:'/admins',view:'admins'}].map(({path,view})=>({path,component:Overview,meta:{view}})),
{path:'/checkout',component:Checkout,meta:{public:true}},
{path:'/customer',component:CustomerPortal},
{path:'/:pathMatch(.*)*',redirect:'/'}

View File

@@ -14,6 +14,13 @@ describe('IntegrationPanel',()=>{
expect(wrapper.text()).toContain('https://license.yihuiyong.cn');expect(wrapper.text()).toContain('LICENSE_API_BASE_URL')
expect(wrapper.find('a[href*="archive"]').attributes('href')).toContain('language=python&mode=service')
expect(wrapper.find('a[href*="download"]').exists()).toBe(true)
expect(wrapper.text()).toContain('管理员交付实例')
const purchaseMode = wrapper.find('input[type="radio"][value="purchase"]')
expect(purchaseMode.exists()).toBe(true)
await purchaseMode.setValue(); await flushPromises()
expect(wrapper.text()).toContain('先原子保存购买参数与幂等键')
expect(wrapper.text()).toContain('购买前没有实例')
expect(wrapper.text()).toContain('purchase.md')
await wrapper.find('select[aria-label="目标语言"]').setValue('dotnet');await flushPromises()
expect(calls.getIntegrationKit).toHaveBeenLastCalledWith('dotnet','service')
expect(wrapper.find('a[href*="archive"]').attributes('href')).toContain('language=dotnet')
@@ -22,6 +29,6 @@ describe('IntegrationPanel',()=>{
it('shows API failures without retaining old content',async()=>{
calls.getIntegrationKit.mockRejectedValueOnce(new Error('资料不可用'))
const wrapper=mount(IntegrationPanel,{global:{plugins:[ElementPlus]}});await flushPromises()
expect(wrapper.text()).toContain('资料不可用');expect(wrapper.find('.prompt-box').exists()).toBe(false);wrapper.unmount()
expect(wrapper.text()).toContain('接入资料加载失败,请稍后重试');expect(wrapper.text()).not.toContain('资料不可用');expect(wrapper.find('.prompt-box').exists()).toBe(false);wrapper.unmount()
})
})

View File

@@ -5,6 +5,7 @@ import { ElMessage } from 'element-plus'
import { getIntegrationKit, type IntegrationKit, type IntegrationLanguage, type IntegrationMode } from '../admin-api'
const language = ref<IntegrationLanguage>('python')
const acquisition = ref<'manual'|'purchase'>('manual')
const mode = ref<IntegrationMode>('service')
const kit = ref<IntegrationKit|null>(null)
const loading = ref(false)
@@ -23,7 +24,7 @@ async function load() {
const sequence = ++requestSequence
loading.value = true; error.value = ''; kit.value = null
try { const result = await getIntegrationKit(language.value, mode.value); if (sequence === requestSequence) kit.value = result.data.data }
catch (e) { if (sequence === requestSequence) error.value = e instanceof Error ? e.message : '接入资料加载失败' }
catch { if (sequence === requestSequence) error.value = '接入资料加载失败,请稍后重试' }
finally { if (sequence === requestSequence) loading.value = false }
}
async function copyPrompt() {
@@ -37,14 +38,21 @@ onMounted(load)
<template>
<section class="admin-module integration-panel">
<div class="module-toolbar"><div class="module-section-heading"><div><h2>客户端接入包</h2><p>选择目标语言和运行方式,交付给外部工程团队实现客户端 SDK 与升级能力。</p></div></div><el-button :loading="loading" @click="load">刷新资料</el-button></div>
<section class="module-create onboarding-section" aria-label="接入流程"><h3>快速接入:开发联调 → 生产上线</h3>
<ol>
<li>开发:准备本机签名私钥及匹配的 v2 公钥环,创建测试客户、产品、授权和实例。</li>
<li>交付:下载语言接入包;从实例页下载激活凭据与信任配置 JSON,通过受控渠道交付开发团队。</li>
<li>联调:实现两个 JSON 的导入,先通过 ZIP 内测试向量,再验证激活、心跳、断网、到期及冻结行为。</li>
<li>生产:在生产管理台重新创建实例并交付生产地址、公钥及绑定信息;使用生产凭据,核对公钥指纹,完成首次激活和心跳。</li>
<section class="module-create onboarding-section" aria-label="接入流程"><h3>授权获取方式</h3>
<el-radio-group v-model="acquisition" aria-label="授权获取方式"><el-radio-button value="manual">管理员交付实例</el-radio-button><el-radio-button value="purchase">客户端扫码新购</el-radio-button></el-radio-group>
<ol v-if="acquisition==='manual'">
<li>开发:配置签名私钥与匹配的 v2 公钥环,创建测试客户、产品、授权和实例。</li>
<li>交付:下载接入包,从实例页导出激活凭据与绑定实例的信任配置 JSON,经受控渠道交付。</li>
<li>联调:验证导入、激活、心跳、断网、到期及冻结行为。</li>
<li>生产:在生产管理台重新创建实例,核对公钥指纹后交付生产凭据并完成激活。</li>
</ol>
<p class="subheading">接入包提供协议和验签向量;各语言客户端 SDK、信任配置导入器仍由客户端工程实现。测试公钥、开发凭据不能带入生产。</p>
<ol v-else>
<li>后台:创建既有客户、产品与启用套餐,发放限定客户和产品的购买凭据;此时不要预创建该笔授权实例。</li>
<li>交付:经受控渠道分别预置 HTTPS 根地址、产品范围、可信生产公钥及购买凭据。购买前没有实例,不能导入绑定实例的信任文件。</li>
<li>客户端:先原子保存购买参数与幂等键,查询套餐、扫码付款并用原订单恢复;服务端确认并签发后 claim 同一实例和 secret。</li>
<li>启用:先安全保存实例凭据,再用 claim 返回的实例 UUID 激活和心跳;验签且租约落盘后才能启用。二维码过期不代表渠道关单。</li>
</ol>
<p class="subheading">ZIP 包含 Node.js 购买参考 SDK 和 Python/Node 升级参考 SDK;其他语言的购买实现、信任导入器、OS 保护存储及终端界面仍由客户端工程完成。开发凭据和测试公钥不得用于生产。</p>
</section>
<TrustDeliveryPanel />
<section class="module-list" aria-label="接入资料">
@@ -66,8 +74,9 @@ onMounted(load)
<ul class="integration-rules"><li v-for="rule in kit.security_rules" :key="rule">{{ rule }}</li></ul>
<h3>完整协议</h3>
<details><summary>查看协议与验收要求</summary><pre class="vector-box">{{ kit.protocol }}</pre></details>
<h3>首次激活凭据从哪里获取?</h3>
<p>进入“License 授权”,签发授权后点击该行“实例”,选择“创建实例并获取激活凭据”。授权码是后台授权密钥(license_key);实例 ID(instance_id)和激活密钥(secret)由平台生成。每条授权仅绑定一个实例,配置加密留存后可重复查看和下载,旧实例仅存哈希时无法恢复。secret 持续用于心跳和下载;验签公钥及实例绑定从管理台交付并由开发团队预置。</p>
<h3 v-if="acquisition==='manual'">首次激活凭据从哪里获取?</h3>
<p v-if="acquisition==='manual'">进入“License 授权”,签发授权后点击该行“实例”,选择“创建实例并获取激活凭据”。授权码是后台授权密钥(license_key);实例 ID(instance_id)和激活密钥(secret)由平台生成。每条授权仅绑定一个实例,配置加密留存后可重复查看和下载,旧实例仅存哈希时无法恢复。secret 持续用于心跳和下载;验签公钥及实例绑定从管理台交付并由开发团队预置。</p>
<template v-else><h3>扫码新购接入</h3><p>在“套餐管理”配置套餐与购买凭据。Node.js 20+ 的购买 SDK、验签依赖与离线测试包含在 ZIP 中;购买凭据仅单独安全交付,不随 ZIP 或共享安装包分发。客户端按同一幂等键恢复订单,claim 后使用返回的实例 UUID,按协议验签并落盘才能启用。详见 ZIP 内 purchase.md 和 client/purchase-sdk.md。</p><p class="subheading">Python、Go、Java、.NET 暂无购买参考 SDK,须按 OpenAPI 与协议自行实现;静态二维码或客户端报告付款不构成授权依据。</p></template>
<h3>客户端升级方案</h3>
<p class="subheading">当前支持实例门户版本查询和授权下载;ZIP、Markdown 及工程提示词包含 UpdateClient 查询、下载、校验和安装适配要求。已提供 update-v1 签名升级检查;参考 SDK 仅完整下载。应用须实现平台兼容性、强制升级评估、安装与回滚;灰度和升级回报尚未提供。</p>
<details><summary>查看升级流程、安全边界与三种部署方案</summary><pre class="vector-box">{{ kit.upgrade }}</pre></details>

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
import { mount,flushPromises } from '@vue/test-utils'
import { afterEach,describe,expect,it,vi } from 'vitest'
import type { Customer,Product } from '../api'
import PurchasePlansPanel from './PurchasePlansPanel.vue'
import { createPaymentPlan,createPurchaseCredential,listPaymentPlans,listPurchaseCredentials,purchaseConfigError,setPurchaseCredentialEnabled,updatePaymentPlan } from '../purchase-config-api'
vi.mock('../purchase-config-api',()=>({createPaymentPlan:vi.fn(),createPurchaseCredential:vi.fn(),listPaymentPlans:vi.fn(),listPurchaseCredentials:vi.fn(),purchaseConfigError:(_e:unknown,f:string)=>f,setPurchaseCredentialEnabled:vi.fn(),updatePaymentPlan:vi.fn()}))
const stubs={ElButton:{template:'<button :disabled="disabled" @click="$emit(\'click\')"><slot/></button>',props:['disabled']},ElSelect:{name:'ElSelect',template:'<div><slot/></div>',props:['modelValue']},ElOption:true,ElInput:{template:'<input :value="modelValue" @input="$emit(\'update:modelValue\',$event.target.value)"/>',props:['modelValue']},ElSwitch:{template:'<input type="checkbox" :checked="modelValue"/>',props:['modelValue']},ElTable:{name:'ElTable',template:'<div><slot/></div>',props:['data']},ElTableColumn:true}
const products=[{id:3,name:'产品甲',code:'a',active:true}] as Product[],customers=[{id:4,name:'客户甲',status:'active'}] as Customer[]
const ok=(data:unknown)=>({data:{data}})
function setup(){vi.mocked(listPaymentPlans).mockResolvedValue(ok([]) as never);vi.mocked(listPurchaseCredentials).mockResolvedValue(ok([]) as never);const wrapper=mount(PurchasePlansPanel,{props:{products,customers},global:{stubs,directives:{loading:()=>{}}}});return{wrapper}}
describe('PurchasePlansPanel',()=>{afterEach(()=>{vi.clearAllMocks();vi.restoreAllMocks()})
it('defaults plans to disabled, keeps quick prices as form-only values, and creates fixed-day plan only on explicit action',async()=>{const{wrapper}=setup();await flushPromises();expect(wrapper.text()).toContain('固定天数');expect(wrapper.text()).toContain('不等同于自然月');await wrapper.findAll('button').find(b=>b.text()==='50 元')!.trigger('click');expect(createPaymentPlan).not.toHaveBeenCalled();wrapper.findAllComponents(stubs.ElSelect)[0]!.vm.$emit('update:modelValue',3);const fields=wrapper.findAll('input');await fields[0]!.setValue('p30');await fields[1]!.setValue('30天');await fields[2]!.setValue('5000');await fields[4]!.setValue('30');vi.mocked(createPaymentPlan).mockResolvedValue(ok({id:1,product_id:3,code:'p30',name:'30天',amount_cents:5000,currency:'CNY',license_days:30,enabled:false,version:1}) as never);await wrapper.findAll('button').find(b=>b.text()==='创建套餐')!.trigger('click');await flushPromises();expect(createPaymentPlan).toHaveBeenCalledWith(expect.objectContaining({product_id:3,amount_cents:5000,license_days:30,enabled:false,currency:'CNY'}));expect(wrapper.findAllComponents(stubs.ElTable)[0]!.props('data')).toEqual([expect.objectContaining({license_days:30,enabled:false})])})
it('shows returned credential token once and does not keep it in list metadata',async()=>{const{wrapper}=setup();vi.mocked(createPurchaseCredential).mockResolvedValue(ok({id:2,customer_id:4,product_id:3,label:'桌面端',enabled:true,token:'once-secret'}) as never);await flushPromises();const selects=wrapper.findAllComponents(stubs.ElSelect);selects[1]!.vm.$emit('update:modelValue',4);selects[2]!.vm.$emit('update:modelValue',3);const fields=wrapper.findAll('input');await fields[6]!.setValue('桌面端');await wrapper.findAll('button').find(b=>b.text()==='创建购买凭据')!.trigger('click');await flushPromises();expect(wrapper.text()).toContain('once-secret');expect(wrapper.text()).toContain('只显示一次');const rows=wrapper.findAllComponents(stubs.ElTable).flatMap(table=>table.props('data') as unknown[]);expect(rows.some(row=>row&&typeof row==='object'&&'token' in row)).toBe(false);await wrapper.findAll('button').find(b=>b.text().includes('已安全保存'))!.trigger('click');expect(wrapper.text()).not.toContain('once-secret')})
it('does not render raw server response errors',async()=>{const{wrapper}=setup();await flushPromises();vi.mocked(listPaymentPlans).mockRejectedValueOnce(new Error('sensitive raw detail'));await wrapper.findAll('button').find(b=>b.text()==='刷新')!.trigger('click');await flushPromises();expect(wrapper.text()).not.toContain('sensitive raw detail');expect(wrapper.text()).toContain('加载失败,请刷新重试')})})

View File

@@ -0,0 +1,37 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { Customer, Product } from '../api'
import { createPaymentPlan, createPurchaseCredential, listPaymentPlans, listPurchaseCredentials, purchaseConfigError, setPurchaseCredentialEnabled, updatePaymentPlan, type PaymentPlan, type PlanInput, type PurchaseCredential } from '../purchase-config-api'
const props=defineProps<{customers:Customer[];products:Product[]}>()
const plans=ref<PaymentPlan[]>([]),credentials=ref<PurchaseCredential[]>([]),loading=ref(false),saving=ref(false),error=ref(''),notice=ref(''),tokenOnce=ref('')
const blankPlan=():PlanInput=>({product_id:0,code:'',name:'',amount_cents:0,currency:'CNY',license_days:30,enabled:false})
const plan=ref<PlanInput>(blankPlan()),editing=ref<number|null>(null),editingVersion=ref<number|null>(null)
const credential=ref({customer_id:0,product_id:0,label:''})
const quickAmounts=[5000,50000,80000,100000]
async function load(){loading.value=true;error.value='';try{const [p,c]=await Promise.all([listPaymentPlans(),listPurchaseCredentials()]);plans.value=p.data.data;credentials.value=c.data.data.map(({...row})=>row)}catch(e){error.value=purchaseConfigError(e,'加载失败,请刷新重试')}finally{loading.value=false}}
function edit(row:PaymentPlan){editing.value=row.id;editingVersion.value=row.version;plan.value={product_id:row.product_id,code:row.code,name:row.name,amount_cents:row.amount_cents,currency:row.currency,license_days:row.license_days,enabled:row.enabled};notice.value='';tokenOnce.value=''}
function reset(){editing.value=null;editingVersion.value=null;plan.value=blankPlan()}
async function savePlan(){error.value='';notice.value='';if(saving.value)return;if(!plan.value.product_id||!plan.value.code.trim()||!plan.value.name.trim()||!Number.isInteger(plan.value.amount_cents)||plan.value.amount_cents<1||!Number.isInteger(plan.value.license_days)||plan.value.license_days<1){error.value='请填写产品、套餐编码、名称、正整数金额和固定天数';return}saving.value=true;try{const result=editing.value?await updatePaymentPlan(editing.value,{...plan.value,version:editingVersion.value!}):await createPaymentPlan(plan.value);const row=result.data.data,index=plans.value.findIndex(x=>x.id===row.id);if(index<0)plans.value.unshift(row);else plans.value[index]=row;notice.value=editing.value?'套餐已更新':'套餐已创建';reset()}catch(e){error.value=purchaseConfigError(e,'套餐保存失败,请核对填写内容后重试')}finally{saving.value=false}}
async function togglePlan(row:PaymentPlan,enabled:boolean){error.value='';try{const result=await updatePaymentPlan(row.id,{product_id:row.product_id,code:row.code,name:row.name,amount_cents:row.amount_cents,currency:row.currency,license_days:row.license_days,enabled,version:row.version});Object.assign(row,result.data.data)}catch(e){error.value=purchaseConfigError(e,'套餐状态更新失败,请重试')}}
async function addCredential(){error.value='';notice.value='';tokenOnce.value='';if(!credential.value.customer_id||!credential.value.product_id||!credential.value.label.trim()){error.value='请选择客户、产品并填写凭据标签';return}saving.value=true;try{const result=await createPurchaseCredential(credential.value);const data=result.data.data;tokenOnce.value=data.token;const {token,...metadata}=data;credentials.value.unshift(metadata);credential.value={customer_id:0,product_id:0,label:''};notice.value='凭据已创建。Token 仅显示本次,请立即安全保存;关闭或离开此页后无法再次查看。'}catch(e){error.value=purchaseConfigError(e,'购买凭据创建失败,请核对客户与产品后重试')}finally{saving.value=false}}
async function toggleCredential(row:PurchaseCredential,enabled:boolean){error.value='';try{const result=await setPurchaseCredentialEnabled(row.id,enabled);Object.assign(row,result.data.data)}catch(e){error.value=purchaseConfigError(e,'凭据状态更新失败,请重试')}}
onMounted(load)
</script>
<template>
<section class="plans-workspace" aria-labelledby="plans-title">
<header class="heading"><div><p class="eyebrow">支付配置</p><h2 id="plans-title">套餐与购买凭据</h2><p class="muted">套餐期限按固定天数计算;本版本支持首次购买,不提供在线续费或用户自注册。</p></div><el-button :loading="loading" @click="load">刷新</el-button></header>
<section class="editor" aria-labelledby="plan-editor-title"><div class="subhead"><div><h3 id="plan-editor-title">{{editing?'编辑套餐':'创建套餐'}}</h3><p>仅启用后的套餐可供客户端购买。固定天数不等同于自然月。</p></div></div><div class="form-grid">
<label><span>产品</span><el-select v-model="plan.product_id" :disabled="editing!==null" placeholder="选择产品"><el-option v-for="p in props.products" :key="p.id" :value="p.id" :label="`${p.name}(${p.code})`" :disabled="!p.active"/></el-select></label>
<label><span>套餐编码</span><el-input v-model="plan.code" :disabled="editing!==null" placeholder="例如 starter-30d"/></label><label><span>套餐名称</span><el-input v-model="plan.name" placeholder="输入名称"/></label>
<label><span>金额(分)</span><el-input v-model.number="plan.amount_cents" type="number" min="1"/><small>快捷填写:<button v-for="amount in quickAmounts" :key="amount" type="button" @click="plan.amount_cents=amount">{{amount/100}} 元</button></small></label>
<label><span>币种</span><el-input :model-value="plan.currency" disabled/></label><label><span>有效期(固定天数)</span><el-input v-model.number="plan.license_days" type="number" min="1"/></label>
</div><div class="actions"><el-switch v-model="plan.enabled" active-text="启用套餐" aria-label="启用套餐"/><span class="grow"/><el-button v-if="editing" @click="reset">取消编辑</el-button><el-button type="primary" :loading="saving" @click="savePlan">{{editing?'保存修改':'创建套餐'}}</el-button></div><p v-if="error" class="error" role="alert">{{error}}</p><p v-if="notice" class="success" role="status">{{notice}}</p></section>
<section class="list" aria-label="套餐列表"><div class="subhead"><h3>套餐列表</h3><span>{{plans.length}} 个</span></div><div class="table-wrap"><el-table :data="plans" v-loading="loading" empty-text="暂无套餐"><el-table-column prop="code" label="编码" min-width="150"/><el-table-column prop="name" label="名称" min-width="150"/><el-table-column label="产品" min-width="130"><template #default="{row}">{{props.products.find(p=>p.id===row.product_id)?.name||row.product_id}}</template></el-table-column><el-table-column label="价格" width="120"><template #default="{row}">{{row.currency}} {{(row.amount_cents/100).toFixed(2)}}</template></el-table-column><el-table-column label="期限" width="125"><template #default="{row}">{{row.license_days}} 天(固定)</template></el-table-column><el-table-column label="状态" width="100"><template #default="{row}">{{row.enabled?'已启用':'已停用'}}</template></el-table-column><el-table-column label="操作" width="150"><template #default="{row}"><el-button link @click="edit(row)">编辑</el-button><el-button link :type="row.enabled?'danger':'primary'" @click="togglePlan(row,!row.enabled)">{{row.enabled?'停用':'启用'}}</el-button></template></el-table-column></el-table></div></section>
<section class="editor credential-editor" aria-labelledby="credential-title"><div class="subhead"><div><h3 id="credential-title">客户购买凭据</h3><p>为已入驻客户创建限定产品范围的客户端购买凭据。</p></div></div><div class="form-grid"><label><span>客户</span><el-select v-model="credential.customer_id" placeholder="选择客户"><el-option v-for="c in props.customers" :key="c.id" :value="c.id" :label="c.name" :disabled="c.status!=='active'"/></el-select></label><label><span>产品范围</span><el-select v-model="credential.product_id" placeholder="选择产品"><el-option v-for="p in props.products" :key="p.id" :value="p.id" :label="p.name" :disabled="!p.active"/></el-select></label><label><span>凭据标签</span><el-input v-model="credential.label" placeholder="便于识别的名称"/></label><div class="submit"><el-button type="primary" :loading="saving" @click="addCredential">创建购买凭据</el-button></div></div>
<div v-if="tokenOnce" class="token-once" role="alert"><strong>请立即安全保存,此 Token 只显示一次</strong><code>{{tokenOnce}}</code><el-button @click="tokenOnce=''">已安全保存并关闭</el-button></div><p v-if="error" class="error" role="alert">{{error}}</p>
<div class="table-wrap credential-table"><el-table :data="credentials" v-loading="loading" empty-text="暂无购买凭据"><el-table-column prop="label" label="标签" min-width="180"/><el-table-column prop="customer_id" label="客户 ID" width="110"/><el-table-column prop="product_id" label="产品 ID" width="110"/><el-table-column prop="created_at" label="创建时间" min-width="190"/><el-table-column label="状态" width="100"><template #default="{row}">{{row.enabled?'已启用':'已停用'}}</template></el-table-column><el-table-column label="操作" width="110"><template #default="{row}"><el-button link :type="row.enabled?'danger':'primary'" @click="toggleCredential(row,!row.enabled)">{{row.enabled?'禁用':'启用'}}</el-button></template></el-table-column></el-table></div></section>
</section>
</template>
<style scoped>
.plans-workspace{--line:#e5eaf0;--muted:#687586;--ink:#17202b;color:var(--ink)}.heading{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;padding-bottom:18px;border-bottom:1px solid var(--line)}.heading h2{margin:0;font-size:20px}.eyebrow{margin:0 0 5px;color:#1769e0;font-size:11px;font-weight:700}.muted,.subhead p{margin:5px 0 0;color:var(--muted);font-size:13px}.editor{margin-top:20px;padding:18px 20px;border:1px solid var(--line);border-radius:6px;background:#f7f9fc}.subhead{display:flex;align-items:center;justify-content:space-between;gap:12px}.subhead h3{margin:0;font-size:14px}.form-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-top:17px}.form-grid label{display:grid;gap:7px;min-width:0}.form-grid label>span{font-size:12px;font-weight:600;color:#526173}.form-grid :deep(.el-select),.form-grid :deep(.el-input){width:100%}.form-grid small{display:flex;gap:9px;flex-wrap:wrap;color:var(--muted);font-size:11px}.form-grid small button{padding:0;border:0;background:none;color:#1769e0;cursor:pointer}.actions{display:flex;align-items:center;gap:10px;margin-top:17px}.grow{flex:1}.error{color:#b44830;font-size:13px}.success{color:#16845b;font-size:13px}.list{margin-top:23px}.table-wrap{overflow-x:auto;border:1px solid var(--line);border-radius:6px;margin-top:12px}.table-wrap :deep(.el-table){min-width:760px}.table-wrap :deep(th.el-table__cell){background:#f7f9fc;color:#657387;font-size:12px}.credential-editor{margin-top:26px}.submit{display:flex;align-items:end}.credential-table{margin-top:18px}.token-once{display:grid;gap:10px;margin-top:16px;padding:14px;border:1px solid #efcf83;border-radius:5px;background:#fff9e9}.token-once code{padding:10px;overflow-wrap:anywhere;background:#fff;font-size:13px}.token-once :deep(.el-button){justify-self:start}@media(max-width:800px){.form-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:560px){.form-grid{grid-template-columns:1fr}.heading{align-items:flex-start}}
</style>