feat(mobile-oa-h5): rename freight unlink action to 取消运费
Also include the two-button freight config/cancel design spec and plan. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
f659ec602e
commit
97bf67c962
6 files changed
+1946
No files matched your search
@@ -0,0 +1,783 @@
|
||||
# 运费「配置 / 取消」双按钮规则 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 协议单、运费信息页与市场小程序对齐:已配运费样本不可再进「配置运费」;混合勾选跳过并提示;「取消运费」统一弹窗勾选后再 unlink。
|
||||
|
||||
**Architecture:** 抽取纯函数分区「未配 / 已配」样本;Web 抽公共 `FreightUnlinkDialog`;协议单配置只带未配样本;运费页文案与批量取消改为弹窗路径;小程序仅改文案与断言(create/link 已过滤 `freightId`)。
|
||||
|
||||
**Tech Stack:** Vue 3 + Element Plus(web-admin)、Vue 3 + Vant(mobile-oa-h5)、`node:test` 单测、现有 `/web/admin/sample-freights` API(无后端契约变更)。
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-12-freight-config-cancel-two-button-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File map
|
||||
|
||||
| 文件 | 职责 |
|
||||
|------|------|
|
||||
| Create: `web-admin/src/utils/sample-freight-config-guard.ts` | 分区样本、生成跳过/全已配提示文案 |
|
||||
| Create: `web-admin/src/utils/sample-freight-config-guard.test.ts` | 上述纯函数单测 |
|
||||
| Create: `web-admin/src/components/business/freight-unlink-dialog/index.vue` | 公共「取消运费」勾选弹窗 |
|
||||
| Modify: `web-admin/src/components/business/sample-transport-form-section/index.vue` | 配置过滤 + 取消弹窗接入 + 文案 |
|
||||
| Modify: `web-admin/src/views/cell-storage/sample-freight/index.vue` | 文案、改用公共弹窗、批量取消改弹窗选样 |
|
||||
| Modify: `mobile-oa-h5/src/market/list-presenter.js` | `unlink` →「取消运费」 |
|
||||
| Modify: `mobile-oa-h5/src/market/components/MarketBottomBar.vue` | `unlink` →「取消运费」 |
|
||||
| Modify: `mobile-oa-h5/src/market/list-presenter.test.js` | 断言文案更新 |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 配置运费选样守卫(纯函数 + TDD)
|
||||
|
||||
**Files:**
|
||||
- Create: `web-admin/src/utils/sample-freight-config-guard.ts`
|
||||
- Create: `web-admin/src/utils/sample-freight-config-guard.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```ts
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
partitionFreightConfigSamples,
|
||||
freightConfigSkipMessage,
|
||||
freightConfigAllConfiguredMessage
|
||||
} from './sample-freight-config-guard'
|
||||
|
||||
function row(partial: Record<string, unknown>) {
|
||||
return partial
|
||||
}
|
||||
|
||||
describe('partitionFreightConfigSamples', () => {
|
||||
it('splits configured vs unconfigured (id / draft / freightId)', () => {
|
||||
const selected = [
|
||||
row({ id: 'a', freight: { id: 'f1' } }),
|
||||
row({ id: 'b', freightDraft: { clientKey: 'k1' } }),
|
||||
row({ id: 'c', freightId: 'f2' }),
|
||||
row({ id: 'd' }),
|
||||
row({ id: 'e', freight: null, freightId: '' })
|
||||
]
|
||||
const { configurable, skipped } = partitionFreightConfigSamples(selected)
|
||||
assert.deepEqual(
|
||||
configurable.map((r) => r.id),
|
||||
['d', 'e']
|
||||
)
|
||||
assert.deepEqual(
|
||||
skipped.map((r) => r.id),
|
||||
['a', 'b', 'c']
|
||||
)
|
||||
})
|
||||
|
||||
it('treats empty selection as no configurable', () => {
|
||||
const { configurable, skipped } = partitionFreightConfigSamples([])
|
||||
assert.equal(configurable.length, 0)
|
||||
assert.equal(skipped.length, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('freight config messages', () => {
|
||||
it('builds skip and all-configured copy', () => {
|
||||
assert.equal(
|
||||
freightConfigSkipMessage(2),
|
||||
'已跳过 2 个已配置运费的样本,将仅为其余样本配置运费'
|
||||
)
|
||||
assert.equal(
|
||||
freightConfigAllConfiguredMessage(),
|
||||
'所选样本均已配置运费,请先取消运费后再配置'
|
||||
)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
cd web-admin && node --import tsx --test src/utils/sample-freight-config-guard.test.ts
|
||||
```
|
||||
|
||||
Expected: FAIL(模块不存在)
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```ts
|
||||
/** 协议单/运费配置:区分可配置与已配样本 */
|
||||
|
||||
export function sampleHasFreight(row: Record<string, any> | null | undefined): boolean {
|
||||
if (!row) return false
|
||||
if (row.freight && typeof row.freight === 'object' && row.freight.id) return true
|
||||
if (row.freightDraft && typeof row.freightDraft === 'object') return true
|
||||
const fid = String(row.freightId || '').trim()
|
||||
return !!fid
|
||||
}
|
||||
|
||||
export function partitionFreightConfigSamples<T extends Record<string, any>>(selected: T[]): {
|
||||
configurable: T[]
|
||||
skipped: T[]
|
||||
} {
|
||||
const configurable: T[] = []
|
||||
const skipped: T[] = []
|
||||
for (const row of selected || []) {
|
||||
if (sampleHasFreight(row)) skipped.push(row)
|
||||
else configurable.push(row)
|
||||
}
|
||||
return { configurable, skipped }
|
||||
}
|
||||
|
||||
export function freightConfigSkipMessage(skippedCount: number): string {
|
||||
return `已跳过 ${skippedCount} 个已配置运费的样本,将仅为其余样本配置运费`
|
||||
}
|
||||
|
||||
export function freightConfigAllConfiguredMessage(): string {
|
||||
return '所选样本均已配置运费,请先取消运费后再配置'
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
cd web-admin && node --import tsx --test src/utils/sample-freight-config-guard.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add web-admin/src/utils/sample-freight-config-guard.ts web-admin/src/utils/sample-freight-config-guard.test.ts
|
||||
git commit -m "$(cat <<'EOF'
|
||||
feat(web-admin): add freight config sample partition helper
|
||||
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 公共「取消运费」弹窗组件
|
||||
|
||||
**Files:**
|
||||
- Create: `web-admin/src/components/business/freight-unlink-dialog/index.vue`
|
||||
|
||||
- [ ] **Step 1: Create the dialog component**
|
||||
|
||||
实现要点(对齐运费页现有取消弹窗 UI,标题改为「取消运费」):
|
||||
|
||||
```vue
|
||||
<!-- web-admin/src/components/business/freight-unlink-dialog/index.vue -->
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
title="取消运费"
|
||||
width="720px"
|
||||
class="dialog-form-layout"
|
||||
align-center
|
||||
append-to-body
|
||||
modal-class="protocol-dialog-mask"
|
||||
destroy-on-close
|
||||
:close-on-click-modal="false"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<p class="unlink-hint">勾选要取消运费的样本:</p>
|
||||
<el-table
|
||||
ref="tableRef"
|
||||
:data="items"
|
||||
stripe
|
||||
class="list-table"
|
||||
max-height="360"
|
||||
row-key="rowKey"
|
||||
@selection-change="onSelectionChange"
|
||||
>
|
||||
<el-table-column type="selection" min-width="48" align="center" header-align="center" />
|
||||
<el-table-column label="来源" min-width="100" align="center" header-align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.sampleSource === 'cell_storage' ? 'success' : 'warning'" size="small">
|
||||
{{ row.sampleSource === 'cell_storage' ? '细胞存储' : '科研捐赠' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="protocolNo" label="协议单号" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column prop="sampleCode" label="样本编码" min-width="120" show-overflow-tooltip />
|
||||
<el-table-column prop="sampleTypeName" label="样本类型" min-width="110" show-overflow-tooltip />
|
||||
</el-table>
|
||||
<template #footer>
|
||||
<el-button class="btn-ghost" @click="emit('update:modelValue', false)">
|
||||
<el-icon><Close /></el-icon>
|
||||
取消
|
||||
</el-button>
|
||||
<el-button class="btn-main" type="primary" :loading="submitting" @click="onConfirm">
|
||||
<el-icon><Check /></el-icon>
|
||||
确定
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { Check, Close } from '@element-plus/icons-vue'
|
||||
import type { SampleFreightItem } from '@/api/sample-freight'
|
||||
import { nextTick, ref, watch } from 'vue'
|
||||
|
||||
export type FreightUnlinkRow = SampleFreightItem & {
|
||||
rowKey: string
|
||||
freightId: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
items: FreightUnlinkRow[]
|
||||
/** 默认勾选的 rowKey 列表 */
|
||||
defaultSelectedKeys?: string[]
|
||||
submitting?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [boolean]
|
||||
confirm: [FreightUnlinkRow[]]
|
||||
}>()
|
||||
|
||||
const tableRef = ref()
|
||||
const selected = ref<FreightUnlinkRow[]>([])
|
||||
|
||||
function onSelectionChange(rows: FreightUnlinkRow[]) {
|
||||
selected.value = rows
|
||||
}
|
||||
|
||||
async function applyDefaultSelection() {
|
||||
await nextTick()
|
||||
const table = tableRef.value
|
||||
if (!table) return
|
||||
table.clearSelection?.()
|
||||
const keys = new Set(props.defaultSelectedKeys || [])
|
||||
for (const row of props.items) {
|
||||
if (keys.has(row.rowKey)) table.toggleRowSelection(row, true)
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.modelValue, props.items, props.defaultSelectedKeys] as const,
|
||||
([visible]) => {
|
||||
if (visible) applyDefaultSelection()
|
||||
}
|
||||
)
|
||||
|
||||
function onConfirm() {
|
||||
if (!selected.value.length) {
|
||||
ElMessage.warning('请勾选要取消运费的样本')
|
||||
return
|
||||
}
|
||||
emit('confirm', selected.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.unlink-hint {
|
||||
margin: 0 0 12px;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Smoke-check import path**
|
||||
|
||||
确认 `@/components/business/freight-unlink-dialog/index.vue` 可被其它 Vue 文件 import(无语法错误即可;完整联调在 Task 3/4)。
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add web-admin/src/components/business/freight-unlink-dialog/index.vue
|
||||
git commit -m "$(cat <<'EOF'
|
||||
feat(web-admin): add shared freight unlink dialog
|
||||
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 协议单 SampleTransportFormSection 接入
|
||||
|
||||
**Files:**
|
||||
- Modify: `web-admin/src/components/business/sample-transport-form-section/index.vue`
|
||||
|
||||
- [ ] **Step 1: Import guard + dialog; rename toolbar button**
|
||||
|
||||
将工具栏「取消运费关联」改为「取消运费」,并引入:
|
||||
|
||||
```ts
|
||||
import FreightUnlinkDialog, {
|
||||
type FreightUnlinkRow
|
||||
} from '@/components/business/freight-unlink-dialog/index.vue'
|
||||
import {
|
||||
partitionFreightConfigSamples,
|
||||
freightConfigSkipMessage,
|
||||
freightConfigAllConfiguredMessage,
|
||||
sampleHasFreight
|
||||
} from '@/utils/sample-freight-config-guard'
|
||||
import { fetchSampleFreightDetail, fetchUnlinkSampleFreight } from '@/api/sample-freight'
|
||||
```
|
||||
|
||||
`canUnlinkFreight` 保持:勾选中存在 `sampleHasFreight(row)` 才可点。
|
||||
|
||||
- [ ] **Step 2: Rewrite `openFreightDialog`**
|
||||
|
||||
替换清空后直接打开的逻辑:
|
||||
|
||||
```ts
|
||||
async function openFreightDialog() {
|
||||
if (!selectedSamples.value.length) {
|
||||
ElMessage.warning('请先勾选需要配置运费的样本')
|
||||
return
|
||||
}
|
||||
const { configurable, skipped } = partitionFreightConfigSamples(selectedSamples.value)
|
||||
if (!configurable.length) {
|
||||
ElMessage.warning(freightConfigAllConfiguredMessage())
|
||||
return
|
||||
}
|
||||
if (skipped.length) {
|
||||
ElMessage.info(freightConfigSkipMessage(skipped.length))
|
||||
}
|
||||
// 后续弹窗内 confirmFreight 必须只用 configurable,不要再用全部 selectedSamples
|
||||
freightConfigTargets.value = configurable
|
||||
freightMode.value = 'create'
|
||||
freightForm.transportMode = ''
|
||||
freightForm.freightAmount = null
|
||||
selectedExistingFreight.value = null
|
||||
selectedFreightId.value = ''
|
||||
existingFreightKeyword.value = ''
|
||||
await loadTransportModeOptions()
|
||||
await reloadExistingFreights()
|
||||
freightDialogVisible.value = true
|
||||
}
|
||||
```
|
||||
|
||||
新增 `freightConfigTargets = ref<Array<Record<string, any>>>([])`。在 `confirmFreight` 开头:
|
||||
|
||||
```ts
|
||||
const selected = freightConfigTargets.value.length
|
||||
? freightConfigTargets.value
|
||||
: selectedSamples.value
|
||||
```
|
||||
|
||||
(其余 create/link 逻辑不变,但对象改为 `selected`。)
|
||||
|
||||
- [ ] **Step 3: Replace `unlinkSelectedFreight` with dialog flow**
|
||||
|
||||
删除「直接对勾选行 unlink」的主路径,改为:
|
||||
|
||||
```ts
|
||||
const unlinkDialogVisible = ref(false)
|
||||
const unlinkDialogItems = ref<FreightUnlinkRow[]>([])
|
||||
const unlinkDefaultKeys = ref<string[]>([])
|
||||
const unlinkSubmitting = ref(false)
|
||||
|
||||
function unlinkRowKey(it: { sampleSource: string; sampleId: string }) {
|
||||
return `${it.sampleSource}:${it.sampleId}`
|
||||
}
|
||||
|
||||
async function openUnlinkFreightDialog() {
|
||||
const seeds = selectedSamples.value.filter((r) => sampleHasFreight(r))
|
||||
if (!seeds.length) {
|
||||
ElMessage.warning('请先选择已配置运费的样本')
|
||||
return
|
||||
}
|
||||
const freightIds = [
|
||||
...new Set(
|
||||
seeds
|
||||
.map((r) => String(r.freight?.id || r.freightId || '').trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
]
|
||||
const byKey = new Map<string, FreightUnlinkRow>()
|
||||
for (const fid of freightIds) {
|
||||
try {
|
||||
const res = await fetchSampleFreightDetail(fid)
|
||||
const data = ((res as any)?.data || res) as { items?: any[]; id?: string }
|
||||
for (const it of data.items || []) {
|
||||
const row: FreightUnlinkRow = {
|
||||
...it,
|
||||
freightId: fid,
|
||||
rowKey: unlinkRowKey(it)
|
||||
}
|
||||
byKey.set(row.rowKey, row)
|
||||
}
|
||||
} catch {
|
||||
/* 单批失败时下面用种子兜底 */
|
||||
}
|
||||
}
|
||||
for (const s of seeds) {
|
||||
const source = String(props.sampleSource || 'cell_storage')
|
||||
const sampleId = String(s.id || '')
|
||||
if (!sampleId) {
|
||||
// 仅草稿:本地清除,不进服务端 items
|
||||
continue
|
||||
}
|
||||
const key = unlinkRowKey({ sampleSource: source as any, sampleId })
|
||||
if (!byKey.has(key)) {
|
||||
byKey.set(key, {
|
||||
sampleSource: source as any,
|
||||
sampleId,
|
||||
protocolId: s.protocolId,
|
||||
sampleCode: s.sampleCode,
|
||||
sampleTypeName: sampleTypeName(s.sampleTypeId),
|
||||
freightId: String(s.freight?.id || s.freightId || ''),
|
||||
rowKey: key
|
||||
})
|
||||
}
|
||||
}
|
||||
// 纯 freightDraft 无 id:确认时本地清 draft(见 Step 3b)
|
||||
unlinkDialogItems.value = [...byKey.values()]
|
||||
unlinkDefaultKeys.value = seeds
|
||||
.filter((s) => s.id)
|
||||
.map((s) =>
|
||||
unlinkRowKey({
|
||||
sampleSource: String(props.sampleSource || 'cell_storage') as any,
|
||||
sampleId: String(s.id)
|
||||
})
|
||||
)
|
||||
if (!unlinkDialogItems.value.length && seeds.every((s) => !s.id && s.freightDraft)) {
|
||||
// 仅草稿:确认框后本地清除
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
'确定取消所选样本的运费吗?取消后可再次配置运费。',
|
||||
'取消运费',
|
||||
{ type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
clearLocalFreight(seeds)
|
||||
ElMessage.success('已取消运费')
|
||||
return
|
||||
}
|
||||
if (!unlinkDialogItems.value.length) {
|
||||
ElMessage.warning('没有可取消的运费样本')
|
||||
return
|
||||
}
|
||||
unlinkDialogVisible.value = true
|
||||
}
|
||||
|
||||
function clearLocalFreight(rows: Array<Record<string, any>>) {
|
||||
updateSamples(
|
||||
props.samples.map((row) => {
|
||||
const hit = rows.some(
|
||||
(r) =>
|
||||
(r.id && row.id && r.id === row.id) ||
|
||||
(r._rowKey && row._rowKey && r._rowKey === row._rowKey)
|
||||
)
|
||||
if (!hit) return row
|
||||
return { ...row, freight: null, freightId: '', freightDraft: undefined }
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
async function onUnlinkDialogConfirm(rows: FreightUnlinkRow[]) {
|
||||
unlinkSubmitting.value = true
|
||||
try {
|
||||
const byFreight = new Map<string, FreightUnlinkRow[]>()
|
||||
for (const row of rows) {
|
||||
const fid = String(row.freightId || '').trim()
|
||||
if (!fid) continue
|
||||
if (!byFreight.has(fid)) byFreight.set(fid, [])
|
||||
byFreight.get(fid)!.push(row)
|
||||
}
|
||||
for (const [fid, list] of byFreight) {
|
||||
await fetchUnlinkSampleFreight(
|
||||
fid,
|
||||
list.map((x) => ({
|
||||
sampleSource: x.sampleSource,
|
||||
sampleId: x.sampleId,
|
||||
protocolId: x.protocolId,
|
||||
sampleCode: x.sampleCode
|
||||
}))
|
||||
)
|
||||
}
|
||||
const idSet = new Set(rows.map((r) => r.sampleId))
|
||||
updateSamples(
|
||||
props.samples.map((row) => {
|
||||
if (!row.id || !idSet.has(String(row.id))) return row
|
||||
return { ...row, freight: null, freightId: '', freightDraft: undefined }
|
||||
})
|
||||
)
|
||||
// 同时清勾选中的纯 draft
|
||||
const draftSeeds = selectedSamples.value.filter((r) => !r.id && r.freightDraft)
|
||||
if (draftSeeds.length) clearLocalFreight(draftSeeds)
|
||||
unlinkDialogVisible.value = false
|
||||
ElMessage.success('已取消运费')
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || '取消运费失败')
|
||||
} finally {
|
||||
unlinkSubmitting.value = false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
模板中按钮 `@click="openUnlinkFreightDialog"`,并挂上:
|
||||
|
||||
```vue
|
||||
<FreightUnlinkDialog
|
||||
v-model="unlinkDialogVisible"
|
||||
:items="unlinkDialogItems"
|
||||
:default-selected-keys="unlinkDefaultKeys"
|
||||
:submitting="unlinkSubmitting"
|
||||
@confirm="onUnlinkDialogConfirm"
|
||||
/>
|
||||
```
|
||||
|
||||
实现时将 `clearLocalFreight` 写成单一清晰版本(按 `id` / `_rowKey` 匹配即可),避免上面草稿里的重复分支。
|
||||
|
||||
- [ ] **Step 4: Manual check list (protocol)**
|
||||
|
||||
1. 未配样本 → 配置运费正常。
|
||||
2. 已配样本 → 提示先取消。
|
||||
3. 混合勾选 → info 跳过 N,弹窗只配未配。
|
||||
4. 取消运费 → 弹窗列出同批样本,可只取消部分。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add web-admin/src/components/business/sample-transport-form-section/index.vue
|
||||
git commit -m "$(cat <<'EOF'
|
||||
feat(web-admin): gate protocol freight config and unify cancel dialog
|
||||
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 运费信息页对齐
|
||||
|
||||
**Files:**
|
||||
- Modify: `web-admin/src/views/cell-storage/sample-freight/index.vue`
|
||||
|
||||
- [ ] **Step 1: Rename labels**
|
||||
|
||||
- 工具栏「取消关联」→「取消运费」
|
||||
- 行内「取消关联」→「取消运费」
|
||||
- 内联 `el-dialog` title「取消关联」删除,改用 `FreightUnlinkDialog`
|
||||
- 确定按钮文案「确定解除」→「确定」(与公共组件一致)
|
||||
- 批量确认框标题/文案中的「取消关联」改为「取消运费」
|
||||
|
||||
- [ ] **Step 2: Replace inline unlink dialog with FreightUnlinkDialog**
|
||||
|
||||
删除模板内联取消 `el-dialog`(约 title=`取消关联` 那段)。改为:
|
||||
|
||||
```vue
|
||||
<FreightUnlinkDialog
|
||||
v-model="unlinkVisible"
|
||||
:items="unlinkDialogItems"
|
||||
:default-selected-keys="unlinkDefaultKeys"
|
||||
:submitting="unlinkSubmitting"
|
||||
@confirm="confirmUnlinkFromDialog"
|
||||
/>
|
||||
```
|
||||
|
||||
`openUnlinkDialog(freightId)`:
|
||||
|
||||
```ts
|
||||
async function openUnlinkDialog(freightId: string) {
|
||||
try {
|
||||
const res = await fetchSampleFreightDetail(freightId)
|
||||
const data = ((res as any)?.data || res) as SampleFreight
|
||||
unlinkDialogItems.value = (data.items || []).map((it) => ({
|
||||
...it,
|
||||
freightId,
|
||||
rowKey: `${it.sampleSource}:${it.sampleId}`
|
||||
}))
|
||||
unlinkDefaultKeys.value = [] // 行内进入:不预勾选,或预勾选全部——推荐预勾选全部以便「取消整批」
|
||||
unlinkDefaultKeys.value = unlinkDialogItems.value.map((r) => r.rowKey)
|
||||
unlinkVisible.value = true
|
||||
} catch {
|
||||
ElMessage.error('加载关联样本失败')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`confirmUnlinkFromDialog(rows)`:按 `freightId` 分组调用 `fetchUnlinkSampleFreight`(支持多批),成功后 `loadData()`。
|
||||
|
||||
- [ ] **Step 3: Change batch toolbar cancel to dialog(禁止整批无勾选直清)**
|
||||
|
||||
`handleBatchUnlink` 不再 `MessageBox` 后直接 unlink 全部 items。改为:
|
||||
|
||||
```ts
|
||||
async function handleBatchUnlink() {
|
||||
if (!selectedFreightIds.value.length) return
|
||||
const byKey = new Map<string, FreightUnlinkRow>()
|
||||
for (const id of selectedFreightIds.value) {
|
||||
const res = await fetchSampleFreightDetail(id)
|
||||
const data = ((res as any)?.data || res) as SampleFreight
|
||||
for (const it of data.items || []) {
|
||||
const row = {
|
||||
...it,
|
||||
freightId: id,
|
||||
rowKey: `${it.sampleSource}:${it.sampleId}`
|
||||
}
|
||||
byKey.set(row.rowKey, row)
|
||||
}
|
||||
}
|
||||
unlinkDialogItems.value = [...byKey.values()]
|
||||
unlinkDefaultKeys.value = unlinkDialogItems.value.map((r) => r.rowKey)
|
||||
if (!unlinkDialogItems.value.length) {
|
||||
ElMessage.warning('所选运费下没有关联样本')
|
||||
return
|
||||
}
|
||||
unlinkVisible.value = true
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: FreightConfigDialog already filters `freightId`**
|
||||
|
||||
`FreightConfigDialog.vue` 的 `isSampleSelectable` / `onSampleSelectionChange` 已排除已配样本,本 Task **不必改**。若打开时无提示,可保持现状(配置从全局选样,用户看不到已配行)。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add web-admin/src/views/cell-storage/sample-freight/index.vue
|
||||
git commit -m "$(cat <<'EOF'
|
||||
feat(web-admin): align sample-freight page cancel UX with two-button rules
|
||||
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: 市场小程序文案对齐
|
||||
|
||||
**Files:**
|
||||
- Modify: `mobile-oa-h5/src/market/list-presenter.js`
|
||||
- Modify: `mobile-oa-h5/src/market/components/MarketBottomBar.vue`
|
||||
- Modify: `mobile-oa-h5/src/market/list-presenter.test.js`
|
||||
|
||||
- [ ] **Step 1: Update failing assertion first**
|
||||
|
||||
在 `list-presenter.test.js` 中把:
|
||||
|
||||
```js
|
||||
assert.equal(actionLabel('unlink'), '取消关联')
|
||||
```
|
||||
|
||||
改为:
|
||||
|
||||
```js
|
||||
assert.equal(actionLabel('unlink'), '取消运费')
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
cd mobile-oa-h5 && node --test src/market/list-presenter.test.js
|
||||
```
|
||||
|
||||
Expected: FAIL on unlink label
|
||||
|
||||
- [ ] **Step 3: Update labels**
|
||||
|
||||
`list-presenter.js`:
|
||||
|
||||
```js
|
||||
unlink: '取消运费'
|
||||
```
|
||||
|
||||
`MarketBottomBar.vue`:
|
||||
|
||||
```js
|
||||
unlink: '取消运费'
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
```bash
|
||||
cd mobile-oa-h5 && node --test src/market/list-presenter.test.js src/market/module-contracts.test.js
|
||||
```
|
||||
|
||||
Expected: PASS(create/link 仍只返回无 `freightId` 样本;unlink 仍用 detail items,满足部分取消)
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add mobile-oa-h5/src/market/list-presenter.js \
|
||||
mobile-oa-h5/src/market/components/MarketBottomBar.vue \
|
||||
mobile-oa-h5/src/market/list-presenter.test.js
|
||||
git commit -m "$(cat <<'EOF'
|
||||
feat(mobile-oa-h5): rename freight unlink action to 取消运费
|
||||
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: 验收与图谱(若改了 web-admin / backend 结构)
|
||||
|
||||
**Files:** 无强制代码;按需跑脚本
|
||||
|
||||
- [ ] **Step 1: Run web-admin unit test**
|
||||
|
||||
```bash
|
||||
cd web-admin && node --import tsx --test src/utils/sample-freight-config-guard.test.ts
|
||||
```
|
||||
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 2: Run mobile tests**
|
||||
|
||||
```bash
|
||||
cd mobile-oa-h5 && node --test src/market/list-presenter.test.js src/market/module-contracts.test.js
|
||||
```
|
||||
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 3: Manual QA checklist(对照 spec §7)**
|
||||
|
||||
1. 协议单:已配不可配置;混合跳过 N;取消弹窗可部分解除。
|
||||
2. 运费信息页:文案「取消运费」;弹窗勾选;编辑仍可用。
|
||||
3. 小程序:列表/底栏「取消运费」;create/link 选不到已关联样本。
|
||||
|
||||
- [ ] **Step 4: Update graphify if web-admin files created**
|
||||
|
||||
```bash
|
||||
./scripts/update-graph.sh frontend
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Final commit if graph or leftover docs**
|
||||
|
||||
```bash
|
||||
git add web-admin/graphify-out docs/superpowers/specs/2026-10-12-freight-config-cancel-two-button-design.md \
|
||||
docs/superpowers/plans/2026-10-12-freight-config-cancel-two-button.md
|
||||
git commit -m "$(cat <<'EOF'
|
||||
docs: add freight two-button config/cancel spec and plan
|
||||
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
(若用户要求不自动 commit 文档,可跳过本步,仅保留工作区文件。)
|
||||
|
||||
---
|
||||
|
||||
## Spec coverage checklist
|
||||
|
||||
| Spec 要求 | Task |
|
||||
|-----------|------|
|
||||
| 双按钮文案「配置运费」「取消运费」 | 3, 4, 5 |
|
||||
| 已配不可进配置;混合跳过 N | 1, 3 |
|
||||
| 取消统一弹窗勾选、可部分解除 | 2, 3, 4 |
|
||||
| 编辑运费保留 | 4(不改编辑入口) |
|
||||
| Web 协议单 + 运费页 | 3, 4 |
|
||||
| mobile-oa-h5 对齐 | 5 |
|
||||
| 无新 API | 全任务 |
|
||||
| 废除单按钮串联 | 未实现该路径 |
|
||||
|
||||
## Self-review notes
|
||||
|
||||
- `clearLocalFreight` 在 Task 3 步骤中写了冗余分支,实现时收敛为按 `id`/`_rowKey` 一次 map。
|
||||
- 运费页批量取消改为弹窗,满足「不一定整批全消」。
|
||||
- 小程序 create/link 已 filter `!freightId`,本计划以文案对齐为主,避免无必要大改表单。
|
||||
@@ -0,0 +1,174 @@
|
||||
# 运费「配置 / 取消」双按钮规则 — 设计
|
||||
|
||||
> 日期:2026-10-12
|
||||
> 状态:待审阅
|
||||
> 关联:
|
||||
>
|
||||
> - `docs/superpowers/specs/2026-10-07-sample-freight-batch-design.md`(运费批次基线)
|
||||
> - `docs/superpowers/specs/2026-10-08-sample-freight-menu-design.md`(运费信息页)
|
||||
> - 实现入口:`SampleTransportFormSection`、`sample-freight/*`、`mobile-oa-h5` 运费模块
|
||||
|
||||
## 1. 背景与结论
|
||||
|
||||
### 1.1 问题
|
||||
|
||||
采集协议单「样本及运输信息」中,样本已配置或关联运费后,再次点击「配置运费」会打开空白「新建」弹窗,既不回填历史,也不阻止重复配置。相对基线设计中的「修改方式与金额」能力,现状易造成误建批次或静默换绑。
|
||||
|
||||
### 1.2 产品决策(本需求)
|
||||
|
||||
采用**双按钮、先取消再配置**模型,放弃「单按钮:确认取消后直接进配置」方案:
|
||||
|
||||
| 决策 | 说明 |
|
||||
|------|------|
|
||||
| 两个按钮 | **配置运费**、**取消运费**(原「取消运费关联 / 取消关联」统一改名) |
|
||||
| 已配不可再配 | 已有运费的样本不得进入配置弹窗作为配置对象 |
|
||||
| 混合勾选 | 「配置运费」可点;仅未配样本进入弹窗;提示已跳过 N 个已配样本 |
|
||||
| 取消可部分解除 | 点「取消运费」先开弹窗,列出相关已关联样本,勾选后再确认;同批多个样本不必全部取消 |
|
||||
| 覆盖范围 | Web:协议单 + 运费信息页;市场小程序:`mobile-oa-h5` 行为对齐 |
|
||||
| 编辑批次头 | 「编辑运费」(改运输方式/金额)保留,与取消/重配分离 |
|
||||
|
||||
**心智模型:** 配置 = 给「还没有运费」的样本挂批次;改挂靠关系 = 先取消再配置;改金额/方式 = 编辑。
|
||||
|
||||
## 2. 非目标
|
||||
|
||||
- 不新增「重新配置」原子 API。
|
||||
- 不在配置弹窗内直接编辑已关联批次的方式/金额(改价走「编辑运费」)。
|
||||
- 不改合同/缴费与运费的无联动约定。
|
||||
- 不强制物理删除运费批次(仍按现有:无剩余关联则软删批次)。
|
||||
- 不改造经典 `miniprogram` 工程(本需求仅 `web-admin` + `mobile-oa-h5`)。
|
||||
|
||||
## 3. 交互规则
|
||||
|
||||
### 3.1 配置运费
|
||||
|
||||
前置:用户已勾选至少一个样本(协议单表格)或已在配置弹窗内选样(运费信息页 / 小程序)。
|
||||
|
||||
| 勾选/选样情况 | 行为 |
|
||||
|---------------|------|
|
||||
| 无有效未配运费样本(全部已有运费,或未选) | **不打开**配置弹窗;提示先取消运费(或先勾选未配置样本) |
|
||||
| 全部未配运费 | 打开配置弹窗(新建 / 关联已有),对象 = 全部选中样本 |
|
||||
| 混合(部分已配、部分未配) | 打开配置弹窗,对象 = **仅未配**样本;**必须**提示:已跳过 N 个已配置运费的样本 |
|
||||
|
||||
配置弹窗打开后表单为空(新建默认),不回填已跳过样本的历史运费。关联已有时,目标批次可选;提交后仅挂到「本次弹窗内的未配样本」。
|
||||
|
||||
**提示文案(建议):**
|
||||
|
||||
- 全部已配:`所选样本均已配置运费,请先取消运费后再配置`
|
||||
- 混合跳过:`已跳过 N 个已配置运费的样本,将仅为其余样本配置运费`
|
||||
|
||||
### 3.2 取消运费
|
||||
|
||||
两端(协议单、运费信息页)与小程序统一流程:
|
||||
|
||||
1. 用户触发「取消运费」(工具栏或行内)。
|
||||
2. 打开弹窗,标题为 **取消运费**。
|
||||
3. 列出**相关已关联样本**,支持多选;默认勾选与触发上下文相关的样本(见 §4)。
|
||||
4. 用户确认 → 仅对勾选样本调用现有 unlink API;未勾选的同批样本保持关联。
|
||||
5. 批次下若无剩余有效关联 → 沿用现有软删批次逻辑。
|
||||
|
||||
**确认文案(建议):** `确定取消所选样本的运费吗?取消后可再次配置运费。`
|
||||
|
||||
无任何可取消样本时:按钮禁用,或点击后提示「请先选择已配置运费的样本」。
|
||||
|
||||
### 3.3 与「编辑运费」的边界
|
||||
|
||||
| 诉求 | 入口 |
|
||||
|------|------|
|
||||
| 给未配样本挂新建/已有批次 | 配置运费 |
|
||||
| 解除部分或全部样本与批次的关联 | 取消运费 |
|
||||
| 改同一批次的运输方式/金额(关联样本不变) | 编辑运费 |
|
||||
|
||||
## 4. Web 管理端
|
||||
|
||||
### 4.1 协议单(细胞存储 / 科研捐赠)
|
||||
|
||||
组件:`web-admin/src/components/business/sample-transport-form-section/index.vue`(两协议共用)。
|
||||
|
||||
| 控件 | 改动 |
|
||||
|------|------|
|
||||
| 配置运费 | 按 §3.1 过滤;`openFreightDialog` 仅传入未配样本;混合时 `ElMessage` 提示跳过 N |
|
||||
| 取消运费 | 文案替换「取消运费关联」;**不再**对表格勾选直接 unlink;改为打开共用取消弹窗 |
|
||||
| 取消弹窗样本来源 | 以当前表格勾选中「已有运费」的样本为种子;按其所涉 `freightId` 拉取批次详情,**列出这些批次下的全部关联样本**(可含其他协议单上的共用样本,与运费信息页一致)。拉取失败时至少列出种子样本。默认勾选 = 种子样本 |
|
||||
|
||||
### 4.2 运费信息页
|
||||
|
||||
路径:`/#/market/cell-storage/sample-freight`
|
||||
组件:`sample-freight/index.vue`、`FreightConfigDialog.vue` 等。
|
||||
|
||||
| 控件 | 改动 |
|
||||
|------|------|
|
||||
| 工具栏 / 行内「取消关联」 | 文案改为 **取消运费** |
|
||||
| 取消弹窗 | 保持「按批次列出 items 勾选」能力;标题改为「取消运费」;可抽为公共组件供协议单复用 |
|
||||
| 配置运费 | 选样列表中已有 `freightId` 的样本不可作为本次配置对象(过滤或禁用勾选);若用户从外部带入混合集,适用 §3.1 跳过提示 |
|
||||
| 编辑 | 保留 |
|
||||
|
||||
### 4.3 公共组件(建议)
|
||||
|
||||
新建或抽离:`web-admin/src/components/business/freight-unlink-dialog/index.vue`(名称可微调)
|
||||
|
||||
- Props:可见性、候选样本列表、默认勾选、提交中状态
|
||||
- Emits:确认(勾选 items)、取消
|
||||
- 展示列:来源、协议单号、样本编码、样本类型(与现运费页取消弹窗对齐)
|
||||
|
||||
协议单与运费信息页共用,避免两套文案与列定义。
|
||||
|
||||
### 4.4 API
|
||||
|
||||
不新增接口。沿用:
|
||||
|
||||
- `POST /web/admin/sample-freights`(新建)
|
||||
- `POST /web/admin/sample-freights/{id}/link`
|
||||
- `POST /web/admin/sample-freights/{id}/unlink`
|
||||
- `PUT /web/admin/sample-freights/{id}`(编辑)
|
||||
- `GET /web/admin/sample-freights/{id}`(取消弹窗补全同批样本时按需)
|
||||
|
||||
## 5. 市场小程序(mobile-oa-h5)
|
||||
|
||||
模块:`mobile-oa-h5/src/market/modules/freight.js` 及列表/详情/表单视图。
|
||||
|
||||
| 动作 | 行为 |
|
||||
|------|------|
|
||||
| create / link | 选样仅未关联样本可提交;若出现已关联样本则跳过并提示 N;候选全为已关联则阻断并提示先取消运费 |
|
||||
| unlink | 对外文案 **取消运费**;表单内多选要解除的样本(沿用 detail items),允许只取消一部分 |
|
||||
| edit | 保留批次头编辑 |
|
||||
|
||||
权限:后端 `unlink` 能力保留;前端主按钮文案与禁用/提示规则与 Web 对齐。列表 presenter 中 `unlink` 展示名由「取消关联」改为「取消运费」。
|
||||
|
||||
## 6. 错误与边界
|
||||
|
||||
| 场景 | 处理 |
|
||||
|------|------|
|
||||
| unlink 失败 | 提示错误;不假装已取消;列表按服务端刷新 |
|
||||
| 配置提交失败 | 已跳过的已配样本不受影响;未配样本保持未配 |
|
||||
| 取消弹窗未勾选任何行点确定 | 前端拦截,提示至少选择一条 |
|
||||
| 用户取消确认框 | 不调用 API |
|
||||
| 草稿样本(仅 `freightDraft`) | 视为「已配」:配置时跳过;取消时从本地清除 draft / 若有 `freightId` 再调 unlink |
|
||||
|
||||
## 7. 验收标准
|
||||
|
||||
1. 协议单:已配样本不会出现在「配置运费」提交对象中;混合勾选有跳过 N 提示;全部已配时无法进入配置。
|
||||
2. 协议单与运费信息页:「取消运费」均先弹窗勾选样本再确认;可只取消同批中的部分样本。
|
||||
3. 所有相关按钮/标题文案为「取消运费」,不再使用「取消运费关联」「取消关联」(编辑除外)。
|
||||
4. 运费信息页「编辑」仍可改方式与金额。
|
||||
5. mobile-oa-h5 运费 create/link/unlink 与 §3、§5 一致。
|
||||
6. 回归:未配样本配置新建/关联已有、共用批金额展示、协议保存与 enrichment 正常。
|
||||
|
||||
## 8. 影响面(实现时核对)
|
||||
|
||||
| 区域 | 路径(预期) |
|
||||
|------|----------------|
|
||||
| Web 协议运输区 | `web-admin/src/components/business/sample-transport-form-section/index.vue` |
|
||||
| Web 运费页 | `web-admin/src/views/cell-storage/sample-freight/*` |
|
||||
| Web 公共取消弹窗 | `web-admin/src/components/business/freight-unlink-dialog/`(新建) |
|
||||
| 小程序运费模块 | `mobile-oa-h5/src/market/modules/freight.js`、`list-presenter.js`、表单/详情视图 |
|
||||
| 测试 | 按需补前端单测或手工验收清单;后端无契约变更则可不改 pytest |
|
||||
|
||||
## 9. 修订相对基线设计
|
||||
|
||||
相对 `2026-10-07-sample-freight-batch-design.md` §4.3–§4.4:
|
||||
|
||||
- **不再**要求「配置运费」弹窗内直接修改已关联批次的方式与金额。
|
||||
- **明确**已关联样本必须先「取消运费」再配置;混合勾选跳过已配并提示。
|
||||
- 取消交互升级为统一弹窗勾选(与运费信息页能力对齐并反哺协议单)。
|
||||
|
||||
本文档为本需求的权威交互说明;实现与评审以本文为准。
|
||||
@@ -0,0 +1,74 @@
|
||||
<template>
|
||||
<footer v-if="normalizedActions.length" class="market-bottom-bar">
|
||||
<van-button
|
||||
v-for="action in normalizedActions"
|
||||
:key="action.actionKey || action.code"
|
||||
class="market-bottom-bar__button"
|
||||
:type="action.primary ? 'primary' : 'default'"
|
||||
:disabled="action.disabled || loading"
|
||||
:loading="loading && (action.actionKey || action.code) === loadingAction"
|
||||
round
|
||||
@click="$emit('action', action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</van-button>
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const ACTION_LABELS = {
|
||||
edit: '编辑',
|
||||
audit: '审核',
|
||||
delete: '删除',
|
||||
create: '新增',
|
||||
convert: '转正式协议',
|
||||
submit: '提交',
|
||||
withdraw: '撤回',
|
||||
'register-transfer': '登记转账',
|
||||
'edit-transfer': '编辑转账',
|
||||
'create-transfer': '添加意向金',
|
||||
'edit-presign-transfer': '编辑意向金',
|
||||
'delete-transfer': '删除意向金',
|
||||
'submit-transfer': '提交财务确认',
|
||||
'withdraw-transfer': '撤回意向金',
|
||||
'storage-cert': '办理储存证',
|
||||
insurance: '办理保险',
|
||||
link: '关联样本',
|
||||
unlink: '取消运费'
|
||||
}
|
||||
|
||||
const props = defineProps({
|
||||
allowedActions: { type: Array, default: () => [] },
|
||||
loading: { type: Boolean, default: false },
|
||||
loadingAction: { type: String, default: '' }
|
||||
})
|
||||
|
||||
defineEmits(['action'])
|
||||
|
||||
const normalizedActions = computed(() =>
|
||||
props.allowedActions
|
||||
.map((action, index) => {
|
||||
if (typeof action === 'string') {
|
||||
return {
|
||||
code: action,
|
||||
label: ACTION_LABELS[action] || action,
|
||||
primary: index === 0,
|
||||
disabled: false
|
||||
}
|
||||
}
|
||||
const code = String(action?.code || action?.action || '').trim()
|
||||
if (!code) return null
|
||||
return {
|
||||
...action,
|
||||
code,
|
||||
label: action.label || ACTION_LABELS[code] || code,
|
||||
primary: action.primary ?? index === 0,
|
||||
disabled: Boolean(action.disabled)
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
)
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
const SEARCH_PLACEHOLDERS = Object.freeze({
|
||||
protocol: '搜索母亲姓名 / 样本编码',
|
||||
'payment-chase': '搜索协议号 / 客户 / 样本编码',
|
||||
payment: '搜索协议号 / 客户 / 样本编码',
|
||||
sample: '搜索母亲姓名 / 样本编码',
|
||||
freight: '搜索批次号 / 母亲姓名 / 样本编码'
|
||||
})
|
||||
|
||||
const PROTOCOL_SEARCH_PLACEHOLDERS = Object.freeze({
|
||||
cell_storage: '搜索母亲姓名 / 样本编码',
|
||||
research_donation: '搜索母亲姓名 / 捐赠编号 / 样本编码'
|
||||
})
|
||||
|
||||
const ACTION_LABELS = Object.freeze({
|
||||
view: '查看',
|
||||
edit: '编辑',
|
||||
audit: '审核',
|
||||
delete: '删除',
|
||||
'view-payment': '查看缴费',
|
||||
'view-payment-detail': '缴费明细',
|
||||
'view-protocol': '协议单',
|
||||
'view-storage-qc': '储存证质检信息',
|
||||
'register-transfer': '登记转账',
|
||||
'edit-transfer': '编辑转账',
|
||||
submit: '提交财务确认',
|
||||
withdraw: '撤回转账',
|
||||
'storage-cert': '登记储存证',
|
||||
insurance: '登记保险',
|
||||
link: '关联样本',
|
||||
unlink: '取消运费'
|
||||
})
|
||||
|
||||
const PAY_MODE_LABELS = Object.freeze({ dj: '趸交', fq: '分期', fgd: '分改趸', djfq: '趸交+分期' })
|
||||
const SOURCE_LABELS = Object.freeze({ cell_storage: '细胞存储', research_donation: '科研捐赠' })
|
||||
const PROTOCOL_STATUS_LABELS = Object.freeze({
|
||||
dsx: '待生效', dqr: '待确认', sxz: '生效中', ygq: '已过期', yzf: '已作废',
|
||||
sdfq: '属地废弃', zckc: '转细胞存储', zky: '转科研'
|
||||
})
|
||||
const NEWBORN_SEX_LABELS = Object.freeze({ '1': '男', '0': '女' })
|
||||
const DELIVERY_MODE_LABELS = Object.freeze({ sc: '顺产', pgc: '剖宫产' })
|
||||
|
||||
const text = (value, fallback = '—') => String(value ?? '').trim() || fallback
|
||||
const label = (map, value) => {
|
||||
const key = String(value ?? '').trim()
|
||||
if (!key) return '—'
|
||||
return map[key] || (/[㐀-鿿]/u.test(key) ? key : '未知')
|
||||
}
|
||||
const referenceName = (name, id) => {
|
||||
const displayName = String(name ?? '').trim()
|
||||
const referenceId = String(id ?? '').trim()
|
||||
return displayName && displayName !== referenceId
|
||||
? displayName
|
||||
: referenceId ? '未知' : '—'
|
||||
}
|
||||
const personName = (name, id) => {
|
||||
const displayName = String(name ?? '').trim()
|
||||
const referenceId = String(id ?? '').trim()
|
||||
return displayName && displayName !== referenceId
|
||||
? displayName
|
||||
: referenceId ? '未知人员' : '—'
|
||||
}
|
||||
const field = (labelText, value, options = {}) => ({ label: labelText, value: text(value), ...options })
|
||||
export function money(value) {
|
||||
const amount = Number(value)
|
||||
if (!Number.isFinite(amount)) return '—'
|
||||
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
|
||||
}
|
||||
|
||||
export function marketSearchPlaceholder(module, source) {
|
||||
if (module === 'protocol' || module === 'sample') {
|
||||
return PROTOCOL_SEARCH_PLACEHOLDERS[source] || SEARCH_PLACEHOLDERS[module]
|
||||
}
|
||||
return SEARCH_PLACEHOLDERS[module] || '搜索编号、姓名或关键词'
|
||||
}
|
||||
|
||||
export function actionLabel(action) {
|
||||
return ACTION_LABELS[action] || '操作'
|
||||
}
|
||||
|
||||
function allowed(item, ownActions = []) {
|
||||
const backend = new Set(Array.isArray(item.allowedActions) ? item.allowedActions.map((action) => typeof action === 'string' ? action : action.code) : [])
|
||||
return ownActions.filter((action) => backend.has(action))
|
||||
}
|
||||
|
||||
function protocolCard(item) {
|
||||
const actions = allowed(item, ['edit', 'delete'])
|
||||
const status = label(PROTOCOL_STATUS_LABELS, item.protocolStatus || item.donationStatus || item.status)
|
||||
return {
|
||||
title: text(item.motherName || item.customerName),
|
||||
subtitle: `${label(SOURCE_LABELS, item.source)} · ${text(item.sampleCode)}`,
|
||||
status,
|
||||
fields: [
|
||||
field('状态', status, { tag: true }),
|
||||
field(item.source === 'research_donation' ? '捐赠日期' : '登记日期', item.registerDate || item.donationDate),
|
||||
field('母亲姓名', item.motherName || item.customerName),
|
||||
field('母亲电话', item.motherPhone),
|
||||
field('母亲身份证号', item.motherIdCard, { wide: true }),
|
||||
field('父亲姓名', item.fatherName),
|
||||
field('新生儿性别', label(NEWBORN_SEX_LABELS, item.newbornSex)),
|
||||
field('分娩方式', label(DELIVERY_MODE_LABELS, item.deliveryMode)),
|
||||
field('新生儿体重(克)', item.newbornWeightGram),
|
||||
field('采集地区', referenceName(item.regionName, item.regionId)),
|
||||
field('采集医院', referenceName(item.hospitalName, item.hospitalId), { wide: true }),
|
||||
field('采集专员', personName(item.collectorUserName, item.collectorUserId)),
|
||||
field('市场专员', personName(item.salesUserName, item.salesUserId)),
|
||||
field('样本采集时间', item.sampleCollectTime, { wide: true }),
|
||||
field('创建时间', item.createTime, { wide: true })
|
||||
],
|
||||
actions: ['view', ...actions]
|
||||
}
|
||||
}
|
||||
|
||||
function chaseCard(item) {
|
||||
const timing = item.chaseStatus === 'overdue'
|
||||
? `已逾期 ${Number(item.daysOverdue || 0)} 天`
|
||||
: `${Number(item.daysUntilDue || 0)} 天内到期`
|
||||
return {
|
||||
title: `${text(item.motherName)} · 第 ${text(item.scheduleNo, '1')} 期`,
|
||||
subtitle: text(item.sampleCode),
|
||||
status: timing,
|
||||
fields: [
|
||||
field('协议号', item.protocolNo, { wide: true }), field('客户', item.motherName),
|
||||
field('联系电话', item.motherPhone), field('样本编码', item.sampleCode, { wide: true }),
|
||||
field('市场专员', personName(item.salesUserName, item.salesUserId)), field('缴费方式', label(PAY_MODE_LABELS, item.payMode), { tag: true }),
|
||||
field('期次', `第 ${text(item.scheduleNo, '1')} 期`), field('应缴日', item.dueDate),
|
||||
field('应缴金额', money(item.dueAmount), { money: true }), field('已缴金额', money(item.paidAmount), { money: true }),
|
||||
field('欠缴金额', money(item.arrearsAmount), { money: true }),
|
||||
field('协议状态', label(PROTOCOL_STATUS_LABELS, item.protocolStatus), { tag: true })
|
||||
],
|
||||
actions: ['view-protocol']
|
||||
}
|
||||
}
|
||||
|
||||
function paymentCard(item) {
|
||||
const progress = label({}, item.paymentProgress || item.progress || (Number(item.remainAmount || 0) <= 0 ? '已缴清' : Number(item.paidAmount || 0) > 0 ? '部分缴费' : '待缴费'))
|
||||
const periods = Array.from({ length: 6 }, (_, index) => item.periods?.[index] || {})
|
||||
const periodFields = periods.flatMap((period, index) => {
|
||||
const prefix = `第${index + 1}期·`
|
||||
return [
|
||||
field(`${prefix}应缴费金额(元)`, money(period.dueAmount), { money: true }),
|
||||
field(`${prefix}应缴费时间`, period.dueDate),
|
||||
field(`${prefix}已缴费金额`, money(period.displayPaidAmount ?? period.paidAmount), { money: true }),
|
||||
field(`${prefix}已缴费时间`, period.payDate),
|
||||
field(`${prefix}欠缴费金额`, money(period.arrearsAmount), { money: true })
|
||||
]
|
||||
})
|
||||
return {
|
||||
title: text(item.motherName), subtitle: text(item.protocolNo), status: progress,
|
||||
fields: [
|
||||
field('姓名', item.motherName), field('手机号', item.motherPhone),
|
||||
field('合同编号', item.protocolNo, { wide: true }), field('签署日期', item.signDate),
|
||||
field('存储年限', item.storageYears), field('存储项目', item.sampleTypeName, { wide: true }),
|
||||
field('合同总额', money(item.contractAmount), { money: true }),
|
||||
field('缴费方式', label(PAY_MODE_LABELS, item.payMode), { tag: true }),
|
||||
field('优惠金额', money(item.discountAmount), { money: true }),
|
||||
field('应收总额', money(item.receivableAmount), { money: true }),
|
||||
...periodFields,
|
||||
field('累计实缴', money(item.paidAmount), { money: true }),
|
||||
field('待缴金额', money(item.dueRemainAmount ?? item.remainAmount), { money: true }),
|
||||
field('备注', item.remark, { wide: true })
|
||||
],
|
||||
actions: ['view-protocol', 'view-payment-detail']
|
||||
}
|
||||
}
|
||||
|
||||
function progressLabel(item, key, fallback) {
|
||||
const value = item.progress?.[key]?.label
|
||||
return value ? label({}, value) : fallback
|
||||
}
|
||||
|
||||
function sampleCard(item) {
|
||||
const status = label(PROTOCOL_STATUS_LABELS, item.protocolStatus || item.donationStatus || item.statusLabel)
|
||||
return {
|
||||
title: text(item.motherName || item.customerName), subtitle: text(item.sampleCode), status,
|
||||
fields: [
|
||||
field('协议状态', status, { tag: true }), field('预产期', item.expectedDeliveryDate),
|
||||
field('母亲姓名', item.motherName || item.customerName), field('新生儿姓名', item.newbornName),
|
||||
field('样本编码', item.sampleCode, { wide: true }), field('实验室入库编码', item.labStorageCode, { wide: true }),
|
||||
field('样本类型', referenceName(item.sampleTypeName, item.sampleTypeId), { wide: true })
|
||||
],
|
||||
progressTags: [
|
||||
`采集 · ${progressLabel(item, 'collection', '未采集')}`,
|
||||
`接收 · ${progressLabel(item, 'reception', '未接收')}`,
|
||||
`质检 · ${progressLabel(item, 'qc', '未完成')}`,
|
||||
`入库 · ${progressLabel(item, 'storage', '未入库')}`,
|
||||
...(item.source === 'cell_storage' ? [
|
||||
`储存证 · ${item.storageCert?.label ? label({}, item.storageCert.label) : '未办理'}`,
|
||||
`保险 · ${item.insurance?.label ? label({}, item.insurance.label) : '未办理'}`
|
||||
] : [])
|
||||
],
|
||||
actions: [
|
||||
'view',
|
||||
...(item.source === 'cell_storage' ? ['view-storage-qc'] : []),
|
||||
...allowed(item, ['storage-cert', 'insurance'])
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function freightCard(role, item) {
|
||||
const first = item.items?.[0] || {}
|
||||
const transportMode = label({}, item.transportModeLabel || item.transportMode)
|
||||
const source = label(SOURCE_LABELS, first.sampleSource || item.sourceLabel)
|
||||
return {
|
||||
title: text(item.freightNo),
|
||||
subtitle: `${transportMode} · ${money(item.freightAmount)}`,
|
||||
status: source,
|
||||
fields: [
|
||||
field('批次号', item.freightNo, { wide: true }), field('运输方式', transportMode, { tag: true }),
|
||||
field('运费金额', money(item.freightAmount), { money: true }),
|
||||
field('关联数', role === 'manager' ? String(item.visibleItemCount || item.items?.length || 0) : '仅本人相关'),
|
||||
field('来源', source, { tag: true }),
|
||||
field('母亲姓名', first.motherName), field('子女姓名', first.newbornName),
|
||||
field('样本编码', first.sampleCode, { wide: true }), field('样本类型', first.sampleTypeName, { wide: true }),
|
||||
field('创建人', personName(item.creatorName || item.createByName, item.createBy)), field('创建时间', item.createTime)
|
||||
],
|
||||
detailTags: role === 'manager' ? (item.items || []).map((row) => `${text(row.motherName)} · ${text(row.sampleCode)}`) : [],
|
||||
privacyNote: role === 'specialist' ? '同批次其他专员明细已脱敏' : '',
|
||||
actions: allowed(item, ['edit', 'link', 'unlink'])
|
||||
}
|
||||
}
|
||||
|
||||
export function buildMarketCard(module, role, item = {}) {
|
||||
if (module === 'protocol') return protocolCard(item)
|
||||
if (module === 'payment-chase') return chaseCard(item)
|
||||
if (module === 'payment') return paymentCard(item)
|
||||
if (module === 'sample') return sampleCard(item)
|
||||
if (module === 'freight') return freightCard(role, item)
|
||||
return { title: text(item.title || item.name || item.code), subtitle: '', status: '', fields: [], actions: ['view'] }
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
actionLabel,
|
||||
buildMarketCard,
|
||||
marketSearchPlaceholder
|
||||
} from './list-presenter.js'
|
||||
|
||||
test('remaining modules use the approved search placeholders', () => {
|
||||
assert.equal(marketSearchPlaceholder('protocol'), '搜索母亲姓名 / 样本编码')
|
||||
assert.equal(
|
||||
marketSearchPlaceholder('protocol', 'cell_storage'),
|
||||
'搜索母亲姓名 / 样本编码'
|
||||
)
|
||||
assert.equal(
|
||||
marketSearchPlaceholder('protocol', 'research_donation'),
|
||||
'搜索母亲姓名 / 捐赠编号 / 样本编码'
|
||||
)
|
||||
assert.equal(marketSearchPlaceholder('payment-chase'), '搜索协议号 / 客户 / 样本编码')
|
||||
assert.equal(marketSearchPlaceholder('payment'), '搜索协议号 / 客户 / 样本编码')
|
||||
assert.equal(marketSearchPlaceholder('sample'), '搜索母亲姓名 / 样本编码')
|
||||
assert.equal(
|
||||
marketSearchPlaceholder('sample', 'cell_storage'),
|
||||
'搜索母亲姓名 / 样本编码'
|
||||
)
|
||||
assert.equal(
|
||||
marketSearchPlaceholder('sample', 'research_donation'),
|
||||
'搜索母亲姓名 / 捐赠编号 / 样本编码'
|
||||
)
|
||||
assert.equal(marketSearchPlaceholder('freight'), '搜索批次号 / 母亲姓名 / 样本编码')
|
||||
})
|
||||
|
||||
test('protocol card exposes web parity fields without truncating to three rows', () => {
|
||||
const card = buildMarketCard('protocol', 'specialist', {
|
||||
motherName: '李安然', protocolNo: 'XBC-001', sampleCode: 'S-001', source: 'cell_storage',
|
||||
protocolStatus: 'sxz', collectDate: '2026-10-11', labStorageCode: 'LAB-1',
|
||||
sampleTypeName: '脐带血', coStored: true, regionName: '合肥区域', hospitalName: '省妇幼',
|
||||
sampleCollectTime: '2026-10-11 09:20', payMode: 'dj', firstPayTime: '2026-10-11',
|
||||
salesUserName: '王敏', managerName: '赵经理', transportMode: '冷链',
|
||||
allowedActions: ['audit', 'edit', 'delete']
|
||||
})
|
||||
assert.equal(card.title, '李安然')
|
||||
assert.equal(card.subtitle, '细胞存储 · S-001')
|
||||
assert.ok(card.fields.length >= 12)
|
||||
assert.deepEqual(card.actions, ['view', 'edit', 'delete'])
|
||||
assert.equal(buildMarketCard('protocol', 'specialist', {
|
||||
motherName: '捐赠客户', protocolNo: 'JZ-001', donationNo: 'JZ-001',
|
||||
sampleCode: 'S-DONATE', source: 'research_donation', donationStatus: 'sxz'
|
||||
}).subtitle, '科研捐赠 · S-DONATE')
|
||||
assert.equal(buildMarketCard('protocol', 'specialist', {
|
||||
protocolStatus: 'sdfq'
|
||||
}).status, '属地废弃')
|
||||
assert.equal(buildMarketCard('protocol', 'specialist', {
|
||||
protocolStatus: 'zckc'
|
||||
}).status, '转细胞存储')
|
||||
})
|
||||
|
||||
test('payment card formats summary totals and progress', () => {
|
||||
const card = buildMarketCard('payment', 'manager', {
|
||||
protocolNo: 'P-1', motherName: '周雨桐', sampleCode: 'S-1', payMode: 'fq',
|
||||
contractAmount: '10000.00', paidAmount: '3000.00', remainAmount: '7000.00',
|
||||
signDate: '2026-10-01', storageYears: 20, sampleTypeName: '脐带血',
|
||||
discountAmount: '1000.00', receivableAmount: '9000.00', remark: '首期已缴',
|
||||
periods: [{ scheduleNo: 1, dueAmount: 3000, dueDate: '2026-10-10', displayPaidAmount: 3000, payDate: '2026-10-11', arrearsAmount: 0 }],
|
||||
clearedScheduleCount: 1, activeScheduleCount: 4, paymentProgress: '部分缴费',
|
||||
allowedActions: ['register-transfer']
|
||||
})
|
||||
assert.equal(card.status, '部分缴费')
|
||||
assert.ok(card.fields.some((field) => field.label === '签署日期' && field.value === '2026-10-01'))
|
||||
assert.ok(card.fields.some((field) => field.label === '存储项目' && field.value === '脐带血'))
|
||||
assert.ok(card.fields.some((field) => field.label === '第1期·应缴费金额(元)' && field.value === '¥3,000.00'))
|
||||
assert.ok(card.fields.some((field) => field.label === '待缴金额' && field.value === '¥7,000.00'))
|
||||
assert.deepEqual(card.actions, ['view-protocol', 'view-payment-detail'])
|
||||
})
|
||||
|
||||
test('payment chase keeps the Web action column while paid totals remain card data', () => {
|
||||
const card = buildMarketCard('payment-chase', 'specialist', {
|
||||
protocolNo: 'P-1', protocolId: 'protocol-1', motherName: '周雨桐',
|
||||
sampleCode: 'S-1', paidAmount: '100.00', dueAmount: '200.00', arrearsAmount: '100.00',
|
||||
salesUserId: 'sales-raw'
|
||||
})
|
||||
assert.deepEqual(card.actions, ['view-protocol'])
|
||||
assert.equal(card.fields.find((field) => field.label === '市场专员').value, '未知人员')
|
||||
})
|
||||
|
||||
test('specialist freight card masks batch-wide counts while manager sees visible details', () => {
|
||||
const item = {
|
||||
freightNo: 'YF-1', transportModeLabel: '冷链配送', freightAmount: '120.00',
|
||||
visibleItemCount: 2, items: [{ motherName: '李安然', sampleCode: 'S-1', sampleTypeName: '脐带血' }],
|
||||
allowedActions: ['edit', 'link', 'unlink']
|
||||
}
|
||||
const specialist = buildMarketCard('freight', 'specialist', item)
|
||||
const manager = buildMarketCard('freight', 'manager', item)
|
||||
assert.equal(specialist.privacyNote, '同批次其他专员明细已脱敏')
|
||||
assert.ok(specialist.fields.some((field) => field.label === '关联数' && field.value === '仅本人相关'))
|
||||
assert.equal(manager.privacyNote, '')
|
||||
assert.ok(manager.fields.some((field) => field.label === '关联数' && field.value === '2'))
|
||||
assert.deepEqual(manager.detailTags, ['李安然 · S-1'])
|
||||
})
|
||||
|
||||
test('action labels cover module-specific operations', () => {
|
||||
assert.equal(actionLabel('audit'), '审核')
|
||||
assert.equal(actionLabel('storage-cert'), '登记储存证')
|
||||
assert.equal(actionLabel('insurance'), '登记保险')
|
||||
assert.equal(actionLabel('link'), '关联样本')
|
||||
assert.equal(actionLabel('unlink'), '取消运费')
|
||||
assert.equal(actionLabel('internal-action-code'), '操作')
|
||||
})
|
||||
|
||||
test('list cards hide unresolved reference and dictionary codes while retaining business identifiers', () => {
|
||||
const protocol = buildMarketCard('protocol', 'specialist', {
|
||||
protocolNo: 'P-KEEP-1', sampleCode: 'S-KEEP-1', source: 'raw-source',
|
||||
protocolStatus: 'raw-status', newbornSex: 'raw-sex', deliveryMode: 'raw-delivery',
|
||||
regionId: 'region-raw', hospitalId: 'hospital-raw',
|
||||
collectorUserId: 'collector-raw', collectorUserName: 'collector-raw',
|
||||
salesUserId: 'sales-raw', salesUserName: 'sales-raw'
|
||||
})
|
||||
assert.ok(protocol.subtitle.includes('S-KEEP-1'))
|
||||
assert.ok(protocol.subtitle.startsWith('未知 ·'))
|
||||
assert.equal(protocol.status, '未知')
|
||||
assert.equal(protocol.fields.find((field) => field.label === '采集专员').value, '未知人员')
|
||||
assert.equal(protocol.fields.find((field) => field.label === '采集地区').value, '未知')
|
||||
|
||||
const freight = buildMarketCard('freight', 'manager', {
|
||||
freightNo: 'F-KEEP-1', transportMode: 'raw-transport', createBy: 'creator-raw', creatorName: 'creator-raw',
|
||||
items: [{ sampleSource: 'raw-source', sampleCode: 'S-KEEP-2' }]
|
||||
})
|
||||
assert.equal(freight.title, 'F-KEEP-1')
|
||||
assert.ok(freight.subtitle.startsWith('未知 ·'))
|
||||
assert.equal(freight.fields.find((field) => field.label === '创建人').value, '未知人员')
|
||||
assert.equal(freight.fields.find((field) => field.label === '样本编码').value, 'S-KEEP-2')
|
||||
|
||||
const payment = buildMarketCard('payment', 'manager', {
|
||||
protocolNo: 'P-KEEP-2', payMode: 'raw-pay-mode'
|
||||
})
|
||||
assert.equal(payment.subtitle, 'P-KEEP-2')
|
||||
assert.equal(payment.fields.find((field) => field.label === '缴费方式').value, '未知')
|
||||
|
||||
const sample = buildMarketCard('sample', 'specialist', {
|
||||
sampleCode: 'S-KEEP-3', protocolStatus: 'raw-status', sampleTypeId: 'type-raw',
|
||||
progress: { collection: { label: 'raw-progress' } },
|
||||
source: 'cell_storage', storageCert: { label: 'raw-cert-status' }
|
||||
})
|
||||
assert.equal(sample.subtitle, 'S-KEEP-3')
|
||||
assert.equal(sample.status, '未知')
|
||||
assert.equal(sample.fields.find((field) => field.label === '样本类型').value, '未知')
|
||||
assert.ok(sample.progressTags.includes('采集 · 未知'))
|
||||
assert.ok(sample.progressTags.includes('储存证 · 未知'))
|
||||
})
|
||||
@@ -0,0 +1,536 @@
|
||||
<template>
|
||||
<MarketPageShell
|
||||
:title="formTitle"
|
||||
:eyebrow="roleTitle"
|
||||
:show-header="false"
|
||||
:has-bottom-bar="true"
|
||||
>
|
||||
<div v-if="loading" class="market-state"><van-loading color="#0a9f6d">加载表单…</van-loading></div>
|
||||
<van-empty v-else-if="errorMessage" image="error" :description="errorMessage">
|
||||
<van-button type="primary" size="small" round @click="load">重新加载</van-button>
|
||||
</van-empty>
|
||||
<template v-else>
|
||||
<MarketFormSection
|
||||
v-for="section in visibleSections"
|
||||
:key="section.key"
|
||||
:section="section"
|
||||
:model-value="sectionValue(section)"
|
||||
:options="formOptions"
|
||||
:source="formData.source"
|
||||
:mode="mode"
|
||||
:uploading="uploadPending > 0"
|
||||
:disabled="formBusy"
|
||||
@update:model-value="setSectionValue(section, $event)"
|
||||
@upload="uploadField"
|
||||
@field-change="handleFieldChange"
|
||||
/>
|
||||
|
||||
<section v-if="context.module === 'freight' && action !== 'edit'" class="market-form-section">
|
||||
<h2>关联样本</h2>
|
||||
<van-search
|
||||
v-if="contract.usesPagedSampleOptions?.(action)"
|
||||
v-model="sampleKeyword"
|
||||
:disabled="formBusy"
|
||||
placeholder="搜索样本或协议编号"
|
||||
@search="loadSampleOptions"
|
||||
/>
|
||||
<van-checkbox-group
|
||||
v-model="selectedSampleKeys"
|
||||
:disabled="formBusy"
|
||||
class="market-sample-options"
|
||||
@change="handleSampleSelection"
|
||||
>
|
||||
<van-checkbox v-for="item in sampleOptions" :key="sampleKey(item)" :name="sampleKey(item)">
|
||||
{{ item.sampleCode || '-' }} · {{ item.customerName || item.protocolNo || '-' }}
|
||||
</van-checkbox>
|
||||
</van-checkbox-group>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template #bottom>
|
||||
<footer class="market-bottom-bar market-form-bottom">
|
||||
<van-button class="market-bottom-bar__button" round :disabled="formBusy" @click="back">取消</van-button>
|
||||
<van-button
|
||||
class="market-bottom-bar__button"
|
||||
type="primary"
|
||||
round
|
||||
:loading="submitting"
|
||||
:disabled="loading || Boolean(errorMessage) || !action || submitting || uploadPending > 0"
|
||||
@click="submit"
|
||||
>保存</van-button>
|
||||
</footer>
|
||||
</template>
|
||||
</MarketPageShell>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { showConfirmDialog, showSuccessToast, showToast } from 'vant'
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
fetchFreightSampleOptions,
|
||||
fetchMarketDetail,
|
||||
fetchMarketFormOptions,
|
||||
performMarketAction,
|
||||
saveMarketRecord,
|
||||
uploadMarketAttachment
|
||||
} from '../../api/market.js'
|
||||
import {
|
||||
collectAllowedActions,
|
||||
resolveAllowedActionTarget,
|
||||
resolveMarketFormAction
|
||||
} from '../../market/action-policy.js'
|
||||
import {
|
||||
buildMarketActionPayload,
|
||||
pickConfiguredPayload,
|
||||
sanitizeMarketPayload,
|
||||
validateRequiredFields
|
||||
} from '../../market/form-payload.js'
|
||||
import { appendMarketAttachment } from '../../market/attachment-presenter.js'
|
||||
import { marketErrorMessage } from '../../market/market-error.js'
|
||||
import { canLeaveMarketForm, createAsyncGenerationGuard } from '../../market/form-state.js'
|
||||
import { getMarketModule } from '../../market/module-registry.js'
|
||||
import {
|
||||
hydrateProtocolReferenceOptions,
|
||||
hydrateSampleHandleOptions
|
||||
} from '../../market/reference-options.js'
|
||||
import {
|
||||
getMarketRouteContext,
|
||||
MARKET_MODULE_TITLES,
|
||||
MARKET_ROLE_TITLES,
|
||||
marketRecordNavigationQuery,
|
||||
resolveMarketSavedDetailId
|
||||
} from '../../market/routes.js'
|
||||
import MarketFormSection from '../../market/components/MarketFormSection.vue'
|
||||
import MarketPageShell from '../../market/components/MarketPageShell.vue'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const context = computed(() => getMarketRouteContext(route))
|
||||
const contract = computed(() => getMarketModule(context.value.module))
|
||||
const id = computed(() => String(route.params.id || '').trim())
|
||||
const mode = computed(() => route.meta.formMode || (id.value ? 'edit' : 'create'))
|
||||
const action = computed(() => resolveMarketFormAction(
|
||||
context.value.module,
|
||||
context.value.marketRole,
|
||||
mode.value,
|
||||
route.query.action
|
||||
))
|
||||
const roleTitle = computed(() => MARKET_ROLE_TITLES[context.value.marketRole])
|
||||
const formTitle = computed(() => {
|
||||
if (mode.value === 'create') return `新增${MARKET_MODULE_TITLES[context.value.module]}`
|
||||
const actionTitle = {
|
||||
edit: '编辑',
|
||||
'register-transfer': '登记转账',
|
||||
'edit-transfer': '编辑转账',
|
||||
'storage-cert': '登记储存证',
|
||||
insurance: '登记保险',
|
||||
link: '关联样本',
|
||||
unlink: '取消运费'
|
||||
}[action.value]
|
||||
return actionTitle || `办理${MARKET_MODULE_TITLES[context.value.module]}`
|
||||
})
|
||||
const loading = ref(true)
|
||||
const submitting = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const dirty = ref(false)
|
||||
const formData = ref({})
|
||||
const formOptions = ref({})
|
||||
const uploadPending = ref(0)
|
||||
const sampleOptions = ref([])
|
||||
const selectedSampleKeys = ref([])
|
||||
const selectedSampleMap = new Map()
|
||||
const sampleKeyword = ref('')
|
||||
const authorizedAction = ref(null)
|
||||
const formBusy = computed(() => submitting.value || uploadPending.value > 0)
|
||||
const mountGuard = createAsyncGenerationGuard()
|
||||
const mountToken = mountGuard.begin()
|
||||
const loadGuard = createAsyncGenerationGuard()
|
||||
const sampleOptionsGuard = createAsyncGenerationGuard()
|
||||
let loadController = null
|
||||
let sampleOptionsController = null
|
||||
let cascadeOptionsController = null
|
||||
let submitController = null
|
||||
const uploadControllers = new Set()
|
||||
let allowLeave = false
|
||||
|
||||
const visibleSections = computed(() => {
|
||||
let sections = contract.value.formSections || []
|
||||
if (context.value.module === 'payment') sections = [{ key: 'transfer', title: '转账登记', nested: true, fields: contract.value.transferFields }]
|
||||
if (context.value.module === 'sample') sections = [{ key: 'handle', title: action.value === 'insurance' ? '办理保险' : '办理储存证', nested: true, fields: contract.value.handleFields }]
|
||||
return sections.filter((section) =>
|
||||
!(section.createOnly && mode.value !== 'create') &&
|
||||
!(section.editOnly && mode.value !== 'edit') &&
|
||||
(!section.source || section.source === formData.value.source)
|
||||
)
|
||||
})
|
||||
|
||||
function sectionValue(section) {
|
||||
if (section.nested || section.repeat || ['transfer', 'handle'].includes(section.key)) {
|
||||
return formData.value[section.key] || (section.repeat ? [] : {})
|
||||
}
|
||||
return formData.value
|
||||
}
|
||||
function setSectionValue(section, value) {
|
||||
formData.value = section.nested || section.repeat || ['transfer', 'handle'].includes(section.key)
|
||||
? { ...formData.value, [section.key]: value }
|
||||
: { ...formData.value, ...value }
|
||||
dirty.value = true
|
||||
}
|
||||
|
||||
async function handleFieldChange({ section, field, value, index }) {
|
||||
if (context.value.module !== 'protocol') return
|
||||
if (section.key === 'samples' && field.key === 'sampleCodeId') {
|
||||
const option = (formOptions.value.sampleCodes || []).find(
|
||||
(item) => String(item.value) === String(value)
|
||||
)
|
||||
const samples = [...(formData.value.samples || [])]
|
||||
samples[index] = {
|
||||
...(samples[index] || {}),
|
||||
sampleCodeId: value,
|
||||
sampleCode: option?.sampleCode || ''
|
||||
}
|
||||
formData.value = { ...formData.value, samples }
|
||||
dirty.value = true
|
||||
return
|
||||
}
|
||||
if (section.key !== 'collection' || field.key !== 'regionId') return
|
||||
const selectedRegion = (formOptions.value.regions || []).find(
|
||||
(item) => String(item?.value) === String(value)
|
||||
)
|
||||
formData.value = {
|
||||
...formData.value,
|
||||
collection: {
|
||||
...(formData.value.collection || {}),
|
||||
regionId: value,
|
||||
regionName: selectedRegion?.label || '',
|
||||
hospitalId: '',
|
||||
hospitalName: ''
|
||||
}
|
||||
}
|
||||
cascadeOptionsController?.abort()
|
||||
cascadeOptionsController = new AbortController()
|
||||
try {
|
||||
const options = await fetchMarketFormOptions(
|
||||
context.value,
|
||||
{ regionId: value, ...(id.value ? { businessId: id.value } : {}) },
|
||||
{ signal: cascadeOptionsController.signal }
|
||||
)
|
||||
if (!mountGuard.isCurrent(mountToken)) return
|
||||
formOptions.value = hydrateProtocolReferenceOptions(
|
||||
{ ...formOptions.value, ...options },
|
||||
formData.value
|
||||
)
|
||||
} catch (error) {
|
||||
if (error?.name !== 'AbortError' && mountGuard.isCurrent(mountToken)) {
|
||||
showToast(marketErrorMessage(error, '医院选项加载失败'))
|
||||
}
|
||||
}
|
||||
}
|
||||
function sampleKey(item) {
|
||||
return `${item.sampleSource}:${item.sampleId}`
|
||||
}
|
||||
function selectedItems() {
|
||||
return selectedSampleKeys.value
|
||||
.map((key) => selectedSampleMap.get(key))
|
||||
.filter(Boolean)
|
||||
.map((item) => ({ sampleSource: item.sampleSource, sampleId: item.sampleId }))
|
||||
}
|
||||
|
||||
function handleSampleSelection(keys) {
|
||||
for (const item of sampleOptions.value) selectedSampleMap.set(sampleKey(item), item)
|
||||
const selected = new Set(keys)
|
||||
for (const key of [...selectedSampleMap.keys()]) {
|
||||
if (!selected.has(key)) selectedSampleMap.delete(key)
|
||||
}
|
||||
dirty.value = true
|
||||
}
|
||||
|
||||
async function loadSampleOptions() {
|
||||
if (context.value.module !== 'freight' || !contract.value.usesPagedSampleOptions?.(action.value)) return
|
||||
const requestToken = sampleOptionsGuard.begin()
|
||||
sampleOptionsController?.abort()
|
||||
sampleOptionsController = new AbortController()
|
||||
try {
|
||||
const result = await fetchFreightSampleOptions(
|
||||
context.value,
|
||||
{ keyword: sampleKeyword.value, page: 1, pageSize: 100 },
|
||||
{ signal: sampleOptionsController.signal }
|
||||
)
|
||||
if (!mountGuard.isCurrent(mountToken) || !sampleOptionsGuard.isCurrent(requestToken)) return
|
||||
const rows = result?.list || []
|
||||
sampleOptions.value = contract.value.sampleOptions?.(action.value, [], rows) || []
|
||||
for (const item of sampleOptions.value) selectedSampleMap.set(sampleKey(item), item)
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError' || !mountGuard.isCurrent(mountToken) || !sampleOptionsGuard.isCurrent(requestToken)) return
|
||||
showToast(marketErrorMessage(error, '样本选项加载失败'))
|
||||
}
|
||||
}
|
||||
|
||||
function loadUnlinkOptions(detail) {
|
||||
sampleOptions.value = contract.value.sampleOptions?.(action.value, detail?.items, []) || []
|
||||
for (const item of sampleOptions.value) selectedSampleMap.set(sampleKey(item), item)
|
||||
}
|
||||
|
||||
function resolveCreateProtocolSource() {
|
||||
const raw = String(route.query.source || route.query.tab || '').trim()
|
||||
return ['cell_storage', 'research_donation'].includes(raw) ? raw : 'cell_storage'
|
||||
}
|
||||
|
||||
function initialForm(detail) {
|
||||
if (!detail) {
|
||||
if (context.value.module === 'protocol') {
|
||||
return {
|
||||
source: resolveCreateProtocolSource(),
|
||||
customer: {},
|
||||
collection: {},
|
||||
samples: [],
|
||||
payment: {},
|
||||
attachments: {},
|
||||
confirm: { confirmed: false }
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
if (context.value.module === 'protocol') {
|
||||
return {
|
||||
...(detail.protocol || detail.basic || detail),
|
||||
source: detail.source,
|
||||
customer: detail.customer || {},
|
||||
collection: detail.collection || {},
|
||||
samples: detail.samples || [],
|
||||
payment: detail.payment || {},
|
||||
attachments: detail.attachments || {},
|
||||
confirm: { confirmed: false }
|
||||
}
|
||||
}
|
||||
if (context.value.module === 'payment') {
|
||||
return contract.value.initialForm?.(detail, authorizedAction.value) || { transfer: {} }
|
||||
}
|
||||
if (context.value.module === 'sample') {
|
||||
return contract.value.initialForm?.(detail, action.value) || { handle: {} }
|
||||
}
|
||||
return detail
|
||||
}
|
||||
|
||||
function hydrateCurrentOptions(options, detail) {
|
||||
if (context.value.module === 'protocol') {
|
||||
return hydrateProtocolReferenceOptions(options, detail)
|
||||
}
|
||||
if (context.value.module === 'sample') {
|
||||
return hydrateSampleHandleOptions(options, detail, action.value)
|
||||
}
|
||||
return options || {}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const requestToken = loadGuard.begin()
|
||||
loadController?.abort()
|
||||
sampleOptionsController?.abort()
|
||||
sampleOptionsGuard.begin()
|
||||
loadController = new AbortController()
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
authorizedAction.value = null
|
||||
if (!action.value) {
|
||||
errorMessage.value = '当前模块不支持该表单操作'
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
try {
|
||||
const hasFormOptions = ['presign', 'protocol', 'payment', 'sample', 'freight'].includes(context.value.module)
|
||||
const optionParams = contract.value.formOptionsParams?.(id.value, action.value) ??
|
||||
(id.value ? { businessId: id.value } : undefined)
|
||||
const [options, detail] = await Promise.all([
|
||||
hasFormOptions
|
||||
? fetchMarketFormOptions(context.value, optionParams, { signal: loadController.signal })
|
||||
: Promise.resolve({}),
|
||||
id.value ? fetchMarketDetail(context.value, id.value, {
|
||||
signal: loadController.signal,
|
||||
params: context.value.module === 'protocol' ? { source: route.query.source } : undefined
|
||||
}) : Promise.resolve(null)
|
||||
])
|
||||
if (!mountGuard.isCurrent(mountToken) || !loadGuard.isCurrent(requestToken)) return
|
||||
if (mode.value === 'edit') {
|
||||
const allowed = collectAllowedActions(
|
||||
context.value.module,
|
||||
context.value.marketRole,
|
||||
detail
|
||||
)
|
||||
authorizedAction.value = resolveAllowedActionTarget(allowed, action.value, {
|
||||
scheduleId: route.query.scheduleId,
|
||||
transferId: route.query.transferId
|
||||
})
|
||||
if (!authorizedAction.value) {
|
||||
throw new Error('当前状态不可执行该操作')
|
||||
}
|
||||
}
|
||||
formData.value = initialForm(detail)
|
||||
formOptions.value = hydrateCurrentOptions(options, detail)
|
||||
if (context.value.module === 'freight') {
|
||||
if (action.value === 'unlink') loadUnlinkOptions(detail)
|
||||
else if (contract.value.usesPagedSampleOptions?.(action.value)) await loadSampleOptions()
|
||||
}
|
||||
dirty.value = false
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError' || !mountGuard.isCurrent(mountToken) || !loadGuard.isCurrent(requestToken)) return
|
||||
errorMessage.value = marketErrorMessage(error, '表单加载失败')
|
||||
} finally {
|
||||
if (mountGuard.isCurrent(mountToken) && loadGuard.isCurrent(requestToken)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadField({ section, field, index, file }) {
|
||||
if (submitting.value) return
|
||||
const controller = new AbortController()
|
||||
uploadControllers.add(controller)
|
||||
uploadPending.value += 1
|
||||
try {
|
||||
const uploaded = await uploadMarketAttachment(context.value, file, { signal: controller.signal })
|
||||
if (!mountGuard.isCurrent(mountToken)) return
|
||||
const url = uploaded?.fileUrl || uploaded?.url
|
||||
if (!url) throw new Error('上传结果缺少文件地址')
|
||||
const attachment = {
|
||||
...uploaded,
|
||||
fileUrl: url,
|
||||
fileName: uploaded?.fileName || file.name
|
||||
}
|
||||
const current = sectionValue(section)
|
||||
if (section.repeat) {
|
||||
const rows = current.map((row, rowIndex) => rowIndex === index
|
||||
? { ...row, [field.key]: appendMarketAttachment(row[field.key], attachment) }
|
||||
: row)
|
||||
setSectionValue(section, rows)
|
||||
} else {
|
||||
setSectionValue(section, {
|
||||
...current,
|
||||
[field.key]: appendMarketAttachment(current[field.key], attachment)
|
||||
})
|
||||
}
|
||||
showSuccessToast('上传成功')
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError' || !mountGuard.isCurrent(mountToken)) return
|
||||
showToast(marketErrorMessage(error, '附件上传失败'))
|
||||
} finally {
|
||||
uploadControllers.delete(controller)
|
||||
if (mountGuard.isCurrent(mountToken)) uploadPending.value -= 1
|
||||
}
|
||||
}
|
||||
|
||||
function buildPayload() {
|
||||
if (context.value.module === 'payment') {
|
||||
return {
|
||||
...formData.value.transfer,
|
||||
scheduleId: String(authorizedAction.value?.scheduleId || '')
|
||||
}
|
||||
}
|
||||
if (context.value.module === 'sample') return formData.value.handle
|
||||
if (context.value.module === 'freight') {
|
||||
const fields = pickConfiguredPayload(contract.value.formSections, formData.value)
|
||||
return ['create', 'link', 'unlink'].includes(action.value)
|
||||
? { ...fields, items: selectedItems() }
|
||||
: fields
|
||||
}
|
||||
return pickConfiguredPayload(visibleSections.value, formData.value)
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (submitting.value || uploadPending.value > 0) return
|
||||
const validationMessage = validateRequiredFields(visibleSections.value, formData.value)
|
||||
if (validationMessage) {
|
||||
showToast(validationMessage)
|
||||
return
|
||||
}
|
||||
const payload = buildMarketActionPayload(
|
||||
context.value.module,
|
||||
action.value,
|
||||
sanitizeMarketPayload(buildPayload())
|
||||
)
|
||||
if (context.value.module === 'freight' && ['create', 'link', 'unlink'].includes(action.value) && !payload.items?.length) {
|
||||
showToast('请至少选择一个样本')
|
||||
return
|
||||
}
|
||||
if (context.value.module === 'payment' && action.value === 'register-transfer' && !payload.scheduleId) {
|
||||
showToast('缺少应缴期标识')
|
||||
return
|
||||
}
|
||||
submitting.value = true
|
||||
submitController = new AbortController()
|
||||
try {
|
||||
let result
|
||||
if (['register-transfer', 'edit-transfer', 'storage-cert', 'insurance', 'link', 'unlink'].includes(action.value)) {
|
||||
const targetId = action.value === 'edit-transfer'
|
||||
? authorizedAction.value?.transferId
|
||||
: id.value
|
||||
result = await performMarketAction(
|
||||
context.value,
|
||||
action.value,
|
||||
{ id: targetId, data: payload },
|
||||
{ signal: submitController.signal }
|
||||
)
|
||||
} else {
|
||||
result = await saveMarketRecord(
|
||||
context.value,
|
||||
{ id: mode.value === 'edit' ? id.value : '', data: payload },
|
||||
{ signal: submitController.signal }
|
||||
)
|
||||
}
|
||||
if (!mountGuard.isCurrent(mountToken)) return
|
||||
dirty.value = false
|
||||
allowLeave = true
|
||||
showSuccessToast('保存成功')
|
||||
const detailId = resolveMarketSavedDetailId(context.value.module, id.value, result, action.value)
|
||||
await router.replace({
|
||||
name: detailId
|
||||
? `market-${context.value.marketRole}-${context.value.module}-detail`
|
||||
: `market-${context.value.marketRole}-${context.value.module}`,
|
||||
params: detailId ? { id: detailId } : {},
|
||||
query: marketRecordNavigationQuery(context.value.module, result || formData.value, route.query)
|
||||
})
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError' || !mountGuard.isCurrent(mountToken)) return
|
||||
showToast(marketErrorMessage(error))
|
||||
} finally {
|
||||
if (mountGuard.isCurrent(mountToken)) submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmLeave() {
|
||||
if (canLeaveMarketForm({ allowLeave, pending: formBusy.value, dirty: dirty.value })) return true
|
||||
if (formBusy.value) return false
|
||||
try {
|
||||
await showConfirmDialog({ title: '放弃修改?', message: '当前内容尚未保存,确认离开吗?' })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
async function back() {
|
||||
if (formBusy.value) return
|
||||
if (!(await confirmLeave())) return
|
||||
allowLeave = true
|
||||
router.back()
|
||||
}
|
||||
function beforeUnload(event) {
|
||||
if (!dirty.value && !formBusy.value) return
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
onBeforeRouteLeave(() => confirmLeave())
|
||||
onMounted(() => {
|
||||
window.addEventListener('beforeunload', beforeUnload)
|
||||
load()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
mountGuard.dispose()
|
||||
loadGuard.dispose()
|
||||
sampleOptionsGuard.dispose()
|
||||
loadController?.abort()
|
||||
sampleOptionsController?.abort()
|
||||
cascadeOptionsController?.abort()
|
||||
submitController?.abort()
|
||||
for (const controller of uploadControllers) controller.abort()
|
||||
uploadControllers.clear()
|
||||
window.removeEventListener('beforeunload', beforeUnload)
|
||||
})
|
||||
</script>
|
||||
Reference in new issue
Block a user