From 68a2b4d8921235495916c26009da08812346a942 Mon Sep 17 00:00:00 2001 From: xiewenjun <88080888@163.com> Date: Thu, 15 Oct 2026 09:39:26 +0800 Subject: [PATCH] fix: export payment client types for production build Co-Authored-By: Craft Agent --- frontend/src/api.ts | 18 ++++++++++-- frontend/src/orders-api.ts | 5 +++- frontend/src/router.test.ts | 6 +++- frontend/src/router.ts | 4 ++- frontend/src/views/OrdersPanel.test.ts | 30 ++++++++++++++++++-- frontend/src/views/OrdersPanel.vue | 38 ++++++++++++++++++++++++-- frontend/src/views/Overview.vue | 10 ++++--- 7 files changed, 97 insertions(+), 14 deletions(-) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 16d064c..d97cf61 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -1,9 +1,23 @@ import axios from 'axios' +export class ApiError extends Error { + readonly code?:string + readonly status?:number + + constructor(message:string, code?:unknown, status?:unknown) { + super(message) + this.name = 'ApiError' + // Retain bounded machine-readable metadata, never the response/config/request. + if (typeof code === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(code)) this.code = code + if (typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599) this.status = status + } +} + export const api = axios.create({ baseURL: '/api/v1', timeout: 8000, withCredentials: true }) api.interceptors.response.use((response) => response, (error) => { - const message = error.response?.data?.error?.message || '请求失败,请稍后重试' - return Promise.reject(new Error(message)) + const detail = error.response?.data?.error + const message = typeof detail?.message === 'string' && detail.message ? detail.message : '请求失败,请稍后重试' + return Promise.reject(new ApiError(message, detail?.code, error.response?.status)) }) export type Customer = { id:number; name:string; contact_email:string; status:string; created_at:string; updated_at:string } diff --git a/frontend/src/orders-api.ts b/frontend/src/orders-api.ts index 349e5f4..37b26aa 100644 --- a/frontend/src/orders-api.ts +++ b/frontend/src/orders-api.ts @@ -1,6 +1,9 @@ import { api, type License } from './api' -export type Order = { id:number; order_no:string; customer_id:number; customer_name:string; product_id:number; product_name:string; amount_cents:number; currency:string; status:string; payment_reference:string|null; paid_at:string|null; license_id:number|null; created_at:string; updated_at:string } +export type Order = { id:number; order_no:string; customer_id:number; customer_name:string; product_id:number; product_name:string; amount_cents:number; currency:string; payment_channel?:string|null; payment_status?:string; status:string; payment_reference:string|null; paid_at:string|null; license_id:number|null; created_at:string; updated_at:string } +export type PaymentChannel = 'alipay' | 'wechat' +export type OrderPayment = { merchant_order_no:string; checkout_token:string; checkout_url:string; code_url:string; status:string } +export const createOrderPayment = (id:number,body:{channel:PaymentChannel;license_days:number},key:string) => api.post<{data:OrderPayment}>(`/orders/${id}/payment`,body,{headers:{'Idempotency-Key':key}}) export type NewOrder = { customer_id:number; product_id:number; amount_cents:number; currency:string } export const listOrders = (page:number) => api.get<{data:Order[];meta:{total:number}}>('/orders',{params:{page,page_size:20}}) export const getOrder = (id:number) => api.get<{data:Order}>(`/orders/${id}`) diff --git a/frontend/src/router.test.ts b/frontend/src/router.test.ts index 3555c35..a87e65d 100644 --- a/frontend/src/router.test.ts +++ b/frontend/src/router.test.ts @@ -1,3 +1,7 @@ import { describe, expect, it } from 'vitest' import router from './router' -describe('administration routes',()=>{it('provides a destination for all management navigation items while preserving the customer portal',()=>{const paths=router.getRoutes().map(route=>route.path);for(const path of ['/','/licenses','/customers','/products','/orders','/releases','/integration','/audit','/settings','/customer'])expect(paths).toContain(path)})}) +describe('administration routes',()=>{it('provides a destination for all management navigation items while preserving the customer portal',()=>{const paths=router.getRoutes().map(route=>route.path);for(const path of ['/','/licenses','/customers','/products','/orders','/payments','/releases','/integration','/audit','/settings','/customer'])expect(paths).toContain(path)})}) + +it('routes payment management through the administrator view',()=>{const resolved=router.resolve('/payments');expect(resolved.meta.view).toBe('payments');expect(resolved.meta.public).not.toBe(true);expect(resolved.matched[0]!.components!.default).toBe(router.resolve('/orders').matched[0]!.components!.default)}) + +it('routes checkout outside the administrator session view',()=>{const resolved=router.resolve('/checkout#token=test');expect(resolved.matched).toHaveLength(1);expect(resolved.meta.public).toBe(true);expect(resolved.matched[0]!.components!.default).not.toBe(router.resolve('/orders').matched[0]!.components!.default)}) diff --git a/frontend/src/router.ts b/frontend/src/router.ts index 5643028..6d719be 100644 --- a/frontend/src/router.ts +++ b/frontend/src/router.ts @@ -1,10 +1,12 @@ import { createRouter, createWebHistory } from 'vue-router' import Overview from './views/Overview.vue' import CustomerPortal from './views/CustomerPortal.vue' +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:'/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:'/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:'/'} ] diff --git a/frontend/src/views/OrdersPanel.test.ts b/frontend/src/views/OrdersPanel.test.ts index f420c1f..2ee7daa 100644 --- a/frontend/src/views/OrdersPanel.test.ts +++ b/frontend/src/views/OrdersPanel.test.ts @@ -4,7 +4,7 @@ import type { Customer, Product } from '../api' import ElementPlus from 'element-plus' import { defineComponent } from 'vue' const SelectStub = defineComponent({ name:'ElSelect', props:['modelValue'], emits:['update:modelValue'], template:'' }) -const calls = vi.hoisted(() => ({ listOrders:vi.fn(),getOrder:vi.fn(),createOrder:vi.fn(),confirmPayment:vi.fn(),issueOrder:vi.fn() })) +const calls = vi.hoisted(() => ({ createOrderPayment:vi.fn(),listOrders:vi.fn(),getOrder:vi.fn(),createOrder:vi.fn(),confirmPayment:vi.fn(),issueOrder:vi.fn() })) vi.mock('../orders-api', () => calls) import OrdersPanel from './OrdersPanel.vue' const order = {id:42,order_no:'test-order',customer_id:1,customer_name:'测试客户',product_id:2,product_name:'测试产品',amount_cents:100,currency:'CNY',status:'paid',payment_reference:'BANK-001',license_id:null} @@ -31,7 +31,33 @@ describe('OrdersPanel',()=>{ expect(calls.createOrder.mock.calls[0]![0]).toEqual({customer_id:1,product_id:2,amount_cents:100,currency:'CNY'}) wrapper.unmount() }) - it('displays loading failures',async()=>{ + it('retries payment creation with the same key and shows a safe checkout link',async()=>{ + calls.listOrders.mockResolvedValue({data:{data:[{...order,status:'pending_payment'}],meta:{total:1}}}) + calls.createOrderPayment.mockRejectedValueOnce(new Error('network')).mockResolvedValueOnce({data:{data:{checkout_url:'/checkout#token=test-token'}}}) + const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus],stubs:{teleport:true,ElSelect:SelectStub}}});await flushPromises() + await button(wrapper,'创建付款链接').trigger('click');await flushPromises() + await button(wrapper,'生成付款链接').trigger('click');await flushPromises() + expect(wrapper.text()).toContain('创建付款链接失败') + await button(wrapper,'重试创建').trigger('click');await flushPromises() + expect(calls.createOrderPayment.mock.calls[0]!.slice(0,2)).toEqual([42,{channel:'alipay',license_days:365}]) + expect(calls.createOrderPayment.mock.calls[0]![2]).toBe(calls.createOrderPayment.mock.calls[1]![2]) + expect(wrapper.get('a').attributes('href')).toBe(`${window.location.origin}/checkout#token=test-token`) + wrapper.unmount() + }) + it('changes the idempotency key when the channel changes and rejects script checkout URLs',async()=>{ + calls.listOrders.mockResolvedValue({data:{data:[{...order,status:'pending_payment'}],meta:{total:1}}}) + calls.createOrderPayment.mockResolvedValue({data:{data:{checkout_url:'javascript:alert(1)'}}}) + const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus],stubs:{teleport:true,ElSelect:SelectStub}}});await flushPromises() + await button(wrapper,'创建付款链接').trigger('click');await flushPromises() + await button(wrapper,'生成付款链接').trigger('click');await flushPromises() + expect(wrapper.find('a').exists()).toBe(false) + wrapper.findComponent({name:'ElSelect'}).vm.$emit('update:modelValue','wechat');await flushPromises() + await button(wrapper,'重试创建').trigger('click');await flushPromises() + expect(calls.createOrderPayment.mock.calls[1]![1]).toEqual({channel:'wechat',license_days:365}) + expect(calls.createOrderPayment.mock.calls[1]![2]).not.toBe(calls.createOrderPayment.mock.calls[0]![2]) + wrapper.unmount() + }) + it('displays loading failures' ,async()=>{ calls.listOrders.mockRejectedValue(new Error('订单接口失败')) const wrapper=mount(OrdersPanel,{props,global:{plugins:[ElementPlus]}});await flushPromises() expect(wrapper.get('[role="alert"]').text()).toBe('订单接口失败');wrapper.unmount() diff --git a/frontend/src/views/OrdersPanel.vue b/frontend/src/views/OrdersPanel.vue index 5bf3004..62045df 100644 --- a/frontend/src/views/OrdersPanel.vue +++ b/frontend/src/views/OrdersPanel.vue @@ -3,12 +3,15 @@ import { formatDateTime } from '../date-format' import { onMounted, ref } from 'vue' import { ElMessage } from 'element-plus' import { type Customer, type Product } from '../api' -import { createOrder, confirmPayment, getOrder, issueOrder, listOrders, type Order } from '../orders-api' +import { createOrderPayment, type PaymentChannel, createOrder, confirmPayment, getOrder, issueOrder, listOrders, type Order } from '../orders-api' + +import { checkoutLink } from '../payments-api' const props = defineProps<{customers:Customer[];products:Product[]}>() const emit = defineEmits<{issued:[]}>() const orders = ref([]), total = ref(0), page = ref(1), loading = ref(false), busy = ref(false), error = ref('') const createOpen = ref(false), paymentOpen = ref(false), issueOpen = ref(false), detailOpen = ref(false) +const onlineOpen = ref(false), channel = ref('alipay'), paymentLink = ref(''), onlineError = ref('') const selected = ref(null) const form = ref({customer_id:null as number|null,product_id:null as number|null,amount_cents:100,currency:'CNY'}) const payment = ref({amount_cents:0,payment_reference:''}) @@ -32,6 +35,26 @@ async function detail(order:Order) { } function openPayment(order:Order) { selected.value = order; payment.value = {amount_cents:order.amount_cents,payment_reference:''}; paymentOpen.value = true } function openIssue(order:Order) { selected.value = order; period.value = {starts_at:new Date().toISOString(),expires_at:new Date(Date.now()+365*86400000).toISOString()}; issueOpen.value = true } +function openOnlinePayment(order:Order) { + selected.value = order; channel.value = 'alipay'; paymentLink.value = ''; onlineError.value = ''; onlineOpen.value = true +} +async function submitOnlinePayment() { + if (busy.value || !selected.value) return + busy.value = true; onlineError.value = ''; paymentLink.value = '' + const id = selected.value.id, operation = `online-payment:${id}` + const body = {channel:channel.value,license_days:365} + try { + const result = (await createOrderPayment(id,body,retryKey(operation,body))).data.data + paymentLink.value = checkoutLink(result.checkout_url) + pending.delete(operation) + await refresh() + } catch { onlineError.value = '创建付款链接失败,请重试' } + finally { busy.value = false } +} +async function copyPaymentLink() { + try { await navigator.clipboard.writeText(paymentLink.value); ElMessage.success('付款链接已复制') } + catch { onlineError.value = '复制失败,请手动复制付款链接' } +} async function submit(operation:'create'|'payment'|'issue') { if (busy.value) return busy.value = true @@ -64,19 +87,28 @@ onMounted(refresh)