fix: decouple mobile market API contracts from page routes.

This commit is contained in:
zlwu committed 2026-10-11 13:34:03 +08:00
1 parent 06255d1e41
commit f761c7021e
5 files changed
+91 -158

No files matched your search

+21 -46
View File
@@ -1,22 +1,8 @@
import { MARKET_MODULES, MARKET_ROLES } from '../market/routes.js'
import { moduleResourceName, normalizeMarketContext } from '../market/context-contract.js'
import { getMarketModule } from '../market/module-registry.js'
const RESOURCE_BY_MODULE = Object.freeze({
presign: 'presign-orders',
protocol: 'protocols',
'payment-chase': 'payment-chase',
payment: 'payments',
sample: 'samples',
freight: 'freights'
})
function assertContext(context) {
if (
!MARKET_ROLES.includes(context?.marketRole) ||
!MARKET_MODULES.includes(context?.module)
) {
throw new Error('市场页面配置无效')
}
return normalizeMarketContext(context)
}
export function normalizeMarketEntityId(id, { rejectPathSeparators = false } = {}) {
@@ -36,32 +22,32 @@ export function normalizeMarketEntityId(id, { rejectPathSeparators = false } = {
}
export function buildMarketResourcePath(context, id) {
assertContext(context)
const base = `/mini/market/${context.marketRole}/${RESOURCE_BY_MODULE[context.module]}`
const normalizedContext = assertContext(context)
const base = `/mini/market/${normalizedContext.marketRole}/${moduleResourceName(normalizedContext.module)}`
if (arguments.length < 2) return base
const normalizedId = normalizeMarketEntityId(id, {
rejectPathSeparators: context.module === 'presign'
rejectPathSeparators: normalizedContext.module === 'presign'
})
return `${base}/${encodeURIComponent(normalizedId)}`
}
export function buildMarketFormOptionsPath(context) {
assertContext(context)
return `/mini/market/${context.marketRole}/${RESOURCE_BY_MODULE[context.module]}/form-options`
const normalizedContext = assertContext(context)
return `/mini/market/${normalizedContext.marketRole}/${moduleResourceName(normalizedContext.module)}/form-options`
}
export function buildMarketAttachmentPath(context) {
assertContext(context)
return `/mini/market/${context.marketRole}/${context.module}/attachments`
const normalizedContext = assertContext(context)
return `/mini/market/${normalizedContext.marketRole}/${normalizedContext.module}/attachments`
}
export function buildMarketActionPath(context, action, id, data = {}) {
assertContext(context)
const roleBase = `/mini/market/${context.marketRole}`
const normalizedContext = assertContext(context)
const roleBase = `/mini/market/${normalizedContext.marketRole}`
const encodeId = () => encodeURIComponent(normalizeMarketEntityId(id, {
rejectPathSeparators: context.module === 'presign'
rejectPathSeparators: normalizedContext.module === 'presign'
}))
if (context.module === 'presign') {
if (normalizedContext.module === 'presign') {
const encodedId = encodeId()
if (action === 'delete') return buildMarketResourcePath(context, id)
if (action === 'convert') return `${buildMarketResourcePath(context, id)}/convert`
@@ -76,7 +62,7 @@ export function buildMarketActionPath(context, action, id, data = {}) {
return `${roleBase}/presign-transfers/${encodedId}/${suffix}`
}
}
if (context.module === 'payment') {
if (normalizedContext.module === 'payment') {
if (action === 'register-transfer') return `${roleBase}/payment-transfers`
if (['edit-transfer', 'submit', 'withdraw'].includes(action)) {
const encodedId = encodeId()
@@ -84,20 +70,11 @@ export function buildMarketActionPath(context, action, id, data = {}) {
return `${roleBase}/payment-transfers/${encodedId}${suffix}`
}
}
if (context.module === 'protocol' && ['audit', 'delete'].includes(action)) {
encodeId()
const source = String(data?.source || '').trim()
if (!['cell_storage', 'research_donation'].includes(source)) {
throw new Error('协议业务来源无效')
}
const suffix = action === 'audit' ? '/audit' : ''
return `${buildMarketResourcePath(context, id)}${suffix}?source=${encodeURIComponent(source)}`
}
if (context.module === 'sample' && ['storage-cert', 'insurance'].includes(action)) {
if (normalizedContext.module === 'sample' && ['storage-cert', 'insurance'].includes(action)) {
encodeId()
return `${buildMarketResourcePath(context, id)}/${action}`
}
if (context.module === 'freight' && ['link', 'unlink'].includes(action)) {
if (normalizedContext.module === 'freight' && ['link', 'unlink'].includes(action)) {
encodeId()
return `${buildMarketResourcePath(context, id)}/${action}`
}
@@ -131,9 +108,10 @@ export async function fetchMarketFormOptions(context, params, { signal } = {}) {
export async function saveMarketRecord(context, { id, data }, { signal } = {}) {
const { request } = await import('../utils/http.js')
const normalizedContext = assertContext(context)
const normalizedId = id == null || id === ''
? ''
: normalizeMarketEntityId(id, { rejectPathSeparators: context?.module === 'presign' })
: normalizeMarketEntityId(id, { rejectPathSeparators: normalizedContext.module === 'presign' })
return request({
url: normalizedId
? buildMarketResourcePath(context, normalizedId)
@@ -153,13 +131,10 @@ export function marketActionMethod(action) {
export async function performMarketAction(context, action, { id, data } = {}, { signal } = {}) {
const { request } = await import('../utils/http.js')
const requestData = context.module === 'protocol' && ['audit', 'delete'].includes(action)
? Object.fromEntries(Object.entries(data || {}).filter(([key]) => key !== 'source'))
: data
return request({
url: buildMarketActionPath(context, action, id, data),
method: marketActionMethod(action),
data: action === 'delete' && context.module === 'protocol' ? undefined : requestData,
data,
signal
})
}
@@ -200,6 +175,6 @@ export async function fetchFreightSampleOptions(context, params, { signal } = {}
}
export function marketModuleContract(context) {
assertContext(context)
return getMarketModule(context.module)
const normalizedContext = assertContext(context)
return getMarketModule(normalizedContext.module)
}
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict'
import { existsSync, readFileSync } from 'node:fs'
import test from 'node:test'
import { buildMarketActionPath } from '../api/market.js'
const contractUrl = new URL('./context-contract.js', import.meta.url)
const marketApiSource = readFileSync(new URL('../api/market.js', import.meta.url), 'utf8')
test('market API imports its context from a pure contract module', async () => {
assert.equal(existsSync(contractUrl), true)
assert.doesNotMatch(
marketApiSource,
/from ['"]\.\.\/market\/routes\.js['"]/
)
const { moduleResourceName, normalizeMarketContext } = await import(contractUrl)
assert.deepEqual(
normalizeMarketContext({ marketRole: ' specialist ', module: ' presign ' }),
{ marketRole: 'specialist', module: 'presign' }
)
assert.equal(moduleResourceName('presign'), 'presign-orders')
})
test('Task3 API contract does not expose unimplemented protocol writes', () => {
const protocol = { marketRole: 'specialist', module: 'protocol' }
assert.throws(
() => buildMarketActionPath(protocol, 'audit', 'protocol-1', { source: 'cell_storage' }),
/不支持/
)
assert.throws(
() => buildMarketActionPath(protocol, 'delete', 'protocol-1', { source: 'cell_storage' }),
/不支持/
)
})
@@ -84,10 +84,6 @@ test('normalizes safe entity ids and rejects dangerous presign path segments', (
assert.equal(normalizeMarketEntityId(` ${uuid} `), uuid)
assert.equal(buildMarketResourcePath(presign, ' o 1 '), '/mini/market/specialist/presign-orders/o%201')
assert.equal(buildMarketActionPath(presign, 'submit-transfer', 't 1'), '/mini/market/specialist/presign-transfers/t%201/submit')
assert.equal(
buildMarketActionPath({ marketRole: 'specialist', module: 'protocol' }, 'delete', 'p/1', { source: 'cell_storage' }),
'/mini/market/specialist/protocols/p%2F1?source=cell_storage'
)
for (const id of [null, undefined, '', ' ', '.', '..', 'a/control\u0000id', 'a/control\u009fid', 'x'.repeat(65)]) {
assert.throws(() => normalizeMarketEntityId(id), /ID/)
@@ -0,0 +1,35 @@
export const MARKET_MODULES = Object.freeze([
'presign',
'protocol',
'payment-chase',
'payment',
'sample',
'freight'
])
export const MARKET_ROLES = Object.freeze(['specialist', 'manager'])
const RESOURCE_BY_MODULE = Object.freeze({
presign: 'presign-orders',
protocol: 'protocols',
'payment-chase': 'payment-chase',
payment: 'payments',
sample: 'samples',
freight: 'freights'
})
export function normalizeMarketContext(context) {
const marketRole = String(context?.marketRole || '').trim()
const module = String(context?.module || '').trim()
if (!MARKET_ROLES.includes(marketRole) || !MARKET_MODULES.includes(module)) {
throw new Error('市场页面配置无效')
}
return { marketRole, module }
}
export function moduleResourceName(module) {
const normalized = String(module || '').trim()
const resource = RESOURCE_BY_MODULE[normalized]
if (!resource) throw new Error('市场页面配置无效')
return resource
}
-108
View File
@@ -1,108 +0,0 @@
export const MARKET_MODULES = [
'presign',
'protocol',
'payment-chase',
'payment',
'sample',
'freight'
]
export const MARKET_ROLES = ['specialist', 'manager']
export const MARKET_MODULE_TITLES = Object.freeze({
presign: '预签约订单',
protocol: '协议单',
'payment-chase': '催缴信息',
payment: '缴费信息',
sample: '样本信息',
freight: '运费信息'
})
export const MARKET_ROLE_TITLES = Object.freeze({
specialist: '市场专员',
manager: '地区经理'
})
function isMarketRole(value) {
return MARKET_ROLES.includes(value)
}
function isMarketModule(value) {
return MARKET_MODULES.includes(value)
}
export function getMarketRouteContext(route) {
const marketRole = route?.meta?.marketRole
const module = route?.meta?.module
if (!isMarketRole(marketRole) || !isMarketModule(module)) {
throw new Error('市场页面配置无效')
}
return { marketRole, module }
}
export function shouldLoadMarketListAfterDetail({ previousDetailId, detailId }) {
return Boolean(String(previousDetailId || '').trim()) && !String(detailId || '').trim()
}
export function pickMarketNavigationQuery(query) {
const returnPath = String(query?.returnPath || '').trim()
return returnPath.startsWith('/pages/') && !returnPath.startsWith('//')
? { returnPath }
: {}
}
export function marketRecordNavigationQuery(module, item, query) {
const result = pickMarketNavigationQuery(query)
const source = String(item?.source || '').trim()
if (module === 'protocol' && ['cell_storage', 'research_donation'].includes(source)) {
result.source = source
}
return result
}
export function resolveMarketSavedDetailId(module, currentId, result, action) {
const current = String(currentId || '').trim()
if (module === 'freight' && action === 'unlink' && result?.disappeared === true) return ''
if (module === 'payment' && current) return current
return String(result?.id || current).trim()
}
const listComponent = () => import('../views/market/MarketModuleList.vue')
const detailComponent = () => import('../views/market/MarketModuleDetail.vue')
const formComponent = () => import('../views/market/MarketModuleForm.vue')
export const marketRoutes = MARKET_ROLES.flatMap((marketRole) =>
MARKET_MODULES.map((module) => {
const meta = {
marketRole,
module,
title: MARKET_MODULE_TITLES[module]
}
return {
path: `/market/${marketRole}/${module}`,
name: `market-${marketRole}-${module}`,
component: listComponent,
meta,
children: [
{
path: 'new',
name: `market-${marketRole}-${module}-new`,
component: formComponent,
meta: { ...meta, formMode: 'create' }
},
{
path: ':id/edit',
name: `market-${marketRole}-${module}-edit`,
component: formComponent,
meta: { ...meta, formMode: 'edit' }
},
{
path: ':id',
name: `market-${marketRole}-${module}-detail`,
component: detailComponent,
meta: { ...meta, detail: true }
}
]
}
})
)