Files
zkxw/mobile-oa-h5/src/views/market/MarketModuleForm.vue
T
zlwu f343f12645 fix(mobile): 修复协议单项目校验引用导致保存中断
循环模板内字符串 ref 被 Vue 收集为数组,调用 validate 时在请求前抛错。改用函数 ref 保持单组件实例,并覆盖两角色新增、编辑及项目校验提示。关联工单 #78。
2026-11-10 09:21:29 +08:00

1323 lines
47 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<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>
<div v-else-if="errorMessage" class="market-state">
<van-empty image="error" :description="errorMessage">
<van-button type="primary" round @click="load">重新加载</van-button>
</van-empty>
</div>
<template v-else>
<template v-for="section in leadingSections" :key="section.key">
<MarketFormSection
v-if="!(context.module === 'protocol' && section.key === 'protocol')"
:section="section"
:model-value="sectionValue(section)"
:options="formOptions"
:source="formData.source"
:mode="mode"
:uploading="false"
:disabled="fieldsLocked"
:search-customers="searchProtocolCustomers"
@update:model-value="setSectionValue(section, $event)"
@upload="uploadField"
@field-change="handleFieldChange"
@customer-select="handleCustomerSelect"
/>
<MarketFormSection
v-else
:section="section"
:model-value="sectionValue(section)"
:options="formOptions"
:source="formData.source"
:mode="mode"
:uploading="false"
:disabled="fieldsLocked"
:search-customers="searchProtocolCustomers"
:insert-before-keys="['protocolStatus', 'donationStatus']"
@update:model-value="setSectionValue(section, $event)"
@upload="uploadField"
@field-change="handleFieldChange"
@customer-select="handleCustomerSelect"
>
<template #insert>
<ProjectAssignmentField
:ref="(instance) => (projectAssignment = instance)"
embedded
v-model="formData.projectId"
:biz-type="formData.source"
:editing="mode === 'edit'"
:record="formData"
:disabled="fieldsLocked"
@update:model-value="dirty = true"
/>
</template>
</MarketFormSection>
</template>
<section
v-if="context.module === 'protocol' && formData.source === 'cell_storage' && showDepositSection"
class="market-form-section"
>
<h2>意向金(关联预签约)</h2>
<p v-if="depositHintText" class="market-protocol-total-sync">{{ depositHintText }}</p>
<div class="market-deposit-transfer-list">
<PresignTransferCard
v-for="(tr, index) in formData.depositTransfers || []"
:key="tr.id || `deposit-${index}`"
:model-value="tr"
:index="index"
:transfer-types="formOptions.transferTypes || []"
disabled
/>
<van-empty
v-if="!(formData.depositTransfers || []).length"
description="暂无意向金转账"
/>
</div>
</section>
<ProtocolSampleTransportPanel
v-if="context.module === 'protocol'"
v-model="formData.samples"
:source="formData.source || 'cell_storage'"
:protocol-id="id"
:market-role="context.marketRole"
:sample-types="formOptions.sampleTypes || []"
:sample-codes="formOptions.sampleCodes || []"
:sample-code-loading="sampleCodeLoading"
:transport-modes="formOptions.transportModes || []"
:disabled="fieldsLocked"
@update:model-value="onSamplesChange"
@refresh-sample-codes="refreshSampleCodes"
/>
<ProtocolSamplePaymentPanel
v-if="context.module === 'protocol' && formData.source === 'cell_storage' && isProtocolV2"
v-model="formData.samplePayments"
:protocol-total-amount="formData.protocolTotalAmount"
:samples="formData.samples || []"
:disabled="fieldsLocked"
:protocol-id="id"
:market-role="context.marketRole"
:transfer-types="formOptions.transferTypes || []"
:sample-contract-sum="sampleContractSumDisplay"
:protocol-total-hint="protocolTotalHintText"
@update:model-value="onSamplePaymentsChange"
@update:protocol-total-amount="onProtocolTotalAmountChange"
@transfer-dirty-change="handleTransferDirtyChange"
/>
<ProtocolV1PaymentPanel
v-if="context.module === 'protocol' && formData.source === 'cell_storage' && isProtocolV1"
v-model:payment="formData.payment"
v-model:payment-details="formData.paymentDetails"
:protocol-total-amount="formData.protocolTotalAmount"
:disabled="fieldsLocked"
:uploading="false"
:transfer-types="formOptions.transferTypes || []"
@upload="uploadV1PaymentAttachment"
@update:protocol-total-amount="onProtocolTotalAmountChange"
@change="dirty = true"
/>
<MarketFormSection
v-for="section in trailingSections"
:key="section.key"
:section="section"
:model-value="sectionValue(section)"
:options="formOptions"
:source="formData.source"
:mode="mode"
:uploading="false"
:disabled="fieldsLocked"
:search-customers="searchProtocolCustomers"
@update:model-value="setSectionValue(section, $event)"
@upload="uploadField"
@field-change="handleFieldChange"
@customer-select="handleCustomerSelect"
/>
<section v-if="context.module === 'freight' && action !== 'edit'" class="market-form-section">
<h2>关联样本</h2>
<div
v-if="contract.usesPagedSampleOptions?.(action)"
class="market-sample-toolbar"
>
<van-search
v-model="sampleKeyword"
shape="round"
clearable
:disabled="fieldsLocked"
placeholder="搜索样本编码 / 母亲姓名"
@search="loadSampleOptions"
@clear="loadSampleOptions"
/>
<div class="market-sample-toolbar__filter-row">
<van-dropdown-menu active-color="#0a9f6d">
<van-dropdown-item
v-model="sampleSource"
:options="sampleSourceOptions"
:disabled="fieldsLocked"
@change="loadSampleOptions"
/>
</van-dropdown-menu>
</div>
</div>
<van-list
v-model:loading="sampleOptionsLoading"
:finished="sampleOptionsFinished"
finished-text="没有更多样本了"
@load="loadMoreSampleOptions"
>
<van-checkbox-group
v-model="selectedSampleKeys"
:disabled="fieldsLocked"
class="market-sample-options"
@change="handleSampleSelection"
>
<van-checkbox
v-for="item in sampleOptions"
:key="sampleKey(item)"
:name="sampleKey(item)"
:disabled="sampleOptionDisabled(item)"
class="market-sample-option"
>
<strong>{{ item.sampleCode || '—' }}</strong>
<span>{{ sampleSourceLabel(item.sampleSource) }}</span>
<span>母亲 {{ item.customerName || '—' }} · 新生儿 {{ item.newbornName || '—' }}</span>
<span>样本类型 {{ item.sampleTypeName || '—' }}</span>
<span v-if="item.freightId" class="market-sample-option__linked">
当前运费 {{ item.freightNo || item.freightId }}
</span>
</van-checkbox>
</van-checkbox-group>
</van-list>
</section>
</template>
<template #bottom>
<footer class="market-bottom-bar market-form-bottom">
<van-button class="market-bottom-bar__button" :disabled="formBusy" @click="back">取消</van-button>
<van-button
class="market-bottom-bar__button"
type="primary"
:loading="submitting"
:disabled="loading || Boolean(errorMessage) || !action || submitting || uploadPending > 0"
@click="submit"
>保存</van-button>
</footer>
</template>
</MarketPageShell>
</template>
<script setup>
import ProjectAssignmentField from '../../market/components/ProjectAssignmentField.vue'
const projectAssignment = ref(null)
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { showConfirmDialog, showSuccessToast, showToast } from 'vant'
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
import {
fetchFreightSampleOptions,
fetchMarketDetail,
fetchMarketFormOptions,
fetchMarketProtocolCustomers,
performMarketAction,
saveMarketRecord,
uploadMarketAttachment
} from '../../api/market.js'
import {
applyCustomerSelect,
calcBirthYmFromIdCard,
clearCustomerLinkIfNameChanged,
initLinkedCustomerNames
} from '../../market/protocol-customer-link.js'
import {
collectAllowedActions,
resolveAllowedActionTarget,
resolveMarketFormAction
} from '../../market/action-policy.js'
import {
buildMarketActionPayload,
mergeProtocolCustomerLinks,
mergeProtocolSamplePayments,
pickConfiguredPayload,
sanitizeMarketPayload,
validateRequiredFields
} from '../../market/form-payload.js'
import {
freightSampleKey,
freightSamplePageFinished,
mergeFreightSamplePage,
reconcileFreightSampleSelection,
rememberFreightSampleRows,
selectedFreightSamples
} from '../../market/freight-sample-options.js'
import {
nextProtocolTotalFromSamples,
protocolTotalMismatchHint,
sampleScheduleDuesMismatchHint,
sampleScheduleRequiredFieldsHint,
shouldFollowProtocolTotal,
sumSampleContractAmounts
} from '../../market/protocol-sample-payment.js'
import PresignTransferCard from '../../market/components/PresignTransferCard.vue'
import ProtocolSamplePaymentPanel from '../../market/components/ProtocolSamplePaymentPanel.vue'
import ProtocolV1PaymentPanel from '../../market/components/ProtocolV1PaymentPanel.vue'
import ProtocolSampleTransportPanel from '../../market/components/ProtocolSampleTransportPanel.vue'
import { applyProtocolCreateDefaults, todayYmd } from '../../market/protocol-form-defaults.js'
import {
buildProtocolSamplesPayload,
buildSampleCodeSearchParams
} from '../../market/protocol-sample-transport.js'
import {
createPendingMarketAttachment,
dropPendingMarketAttachment,
resolvePendingMarketAttachment,
withPendingMarketAttachment
} from '../../market/attachment-upload-state.js'
import { marketErrorMessage } from '../../market/market-error.js'
import {
collectTransfersSavedWithProtocol,
findScheduleIdAfterProtocolSave,
protocolSaveTransferBlockMessage
} from '../../market/protocol-transfer-dirty.js'
import {
flattenSamplePaymentTransfers,
formatAutoSubmitFinanceFailureMessage,
submitDfjTransfersOnSave
} from '../../market/presign/presign-form-state.js'
import {
createLegacyPaymentState,
serializeLegacyPaymentState,
validateLegacyPaymentState
} from '../../market/protocol-v1-payment.js'
import { compareMoney, formatMoney, normalizeMoney } from '../../market/money.js'
import { canLeaveMarketForm, createAsyncGenerationGuard } from '../../market/form-state.js'
import { getMarketModule } from '../../market/module-registry.js'
import { hydrateProtocolReferenceOptions } 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': '编辑转账',
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 transferDirty = 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 sampleSource = ref('')
const sampleSourceOptions = [
{ text: '全部来源', value: '' },
{ text: '细胞存储', value: 'cell_storage' },
{ text: '科研捐赠', value: 'research_donation' }
]
const SAMPLE_OPTION_PAGE_SIZE = 20
const sampleOptionsPage = ref(0)
const sampleOptionsTotal = ref(0)
const sampleOptionsLoading = ref(false)
const sampleOptionsRequestPending = ref(false)
const sampleOptionsFinished = computed(() =>
action.value === 'unlink' || (
sampleOptionsPage.value > 0 &&
freightSamplePageFinished(sampleOptions.value, sampleOptionsTotal.value)
)
)
const authorizedAction = ref(null)
const formBusy = computed(() => submitting.value || uploadPending.value > 0)
/** 附件上传中仍可编辑;仅保存中锁定字段 */
const fieldsLocked = computed(() => submitting.value)
const mountGuard = createAsyncGenerationGuard()
const mountToken = mountGuard.begin()
const loadGuard = createAsyncGenerationGuard()
const sampleOptionsGuard = createAsyncGenerationGuard()
let loadController = null
let sampleOptionsController = null
let cascadeOptionsController = null
let sampleCodeOptionsController = null
const sampleCodeLoading = ref(false)
let submitController = null
const uploadControllers = new Set()
let allowLeave = false
function protocolPaymentModelVersion() {
const value = formData.value.paymentModelVersion
if (value == null || value === '') return mode.value === 'create' ? 2 : 1
const parsed = Number(value)
return Number.isFinite(parsed) ? parsed : 1
}
const isProtocolV1 = computed(() => protocolPaymentModelVersion() < 2)
const isProtocolV2 = computed(() => protocolPaymentModelVersion() >= 2)
const visibleSections = computed(() => {
let sections = contract.value.formSections || []
if (context.value.module === 'payment') sections = [{ key: 'transfer', title: '转账登记', nested: true, fields: contract.value.transferFields }]
return sections.filter((section) =>
!(section.createOnly && mode.value !== 'create') &&
!(section.editOnly && mode.value !== 'edit') &&
(!section.source || section.source === formData.value.source)
)
})
/** 普通分区(不含须垫底的提交确认等) */
const leadingSections = computed(() =>
visibleSections.value.filter((section) => !section.renderLast)
)
/** 提交确认等须排在样本运输 / 缴费面板之后 */
const trailingSections = computed(() =>
visibleSections.value.filter((section) => section.renderLast)
)
function sectionValue(section) {
if (section.nested || section.repeat || section.key === 'transfer') {
return formData.value[section.key] || (section.repeat ? [] : {})
}
return formData.value
}
function setSectionValue(section, value) {
formData.value = section.nested || section.repeat || section.key === 'transfer'
? { ...formData.value, [section.key]: value }
: { ...formData.value, ...value }
dirty.value = true
}
const protocolTotalFollowSamples = ref(true)
const sampleContractSum = computed(() =>
sumSampleContractAmounts(formData.value.samplePayments || [])
)
const sampleContractSumDisplay = computed(() => sampleContractSum.value)
const protocolTotalHintText = computed(() =>
context.value.module === 'protocol' && formData.value.source === 'cell_storage'
? protocolTotalMismatchHint(formData.value.protocolTotalAmount, sampleContractSum.value)
: null
)
const depositHintText = computed(() => {
const h = formData.value.presignDepositHint
if (!h) return ''
const cnt = Number(h.confirmedTransferCount || 0)
return `来源预签约已确认意向金合计 ${formatMoney(h.confirmedDepositAmount || 0)}(${cnt} 笔)`
})
const showDepositSection = computed(() =>
Boolean(depositHintText.value || (formData.value.depositTransfers || []).length)
)
function syncProtocolTotalFromSamples() {
if (context.value.module !== 'protocol' || formData.value.source !== 'cell_storage') return
if (!isProtocolV2.value) return
if (!protocolTotalFollowSamples.value) return
const next = nextProtocolTotalFromSamples(
true,
sampleContractSum.value,
formData.value.protocolTotalAmount
)
if (next === formData.value.protocolTotalAmount) return
if (
next != null &&
formData.value.protocolTotalAmount != null &&
compareMoney(next, formData.value.protocolTotalAmount) === 0
) {
return
}
formData.value = { ...formData.value, protocolTotalAmount: next }
}
function onSamplePaymentsChange(value) {
formData.value = { ...formData.value, samplePayments: value }
dirty.value = true
syncProtocolTotalFromSamples()
}
function onProtocolTotalAmountChange(value) {
formData.value = { ...formData.value, protocolTotalAmount: value }
dirty.value = true
if (!isProtocolV2.value) return
const total = normalizeMoney(value)
protocolTotalFollowSamples.value = shouldFollowProtocolTotal(total, sampleContractSum.value)
}
function handleTransferDirtyChange(value) {
transferDirty.value = Boolean(value)
}
function onSamplesChange(value) {
formData.value = { ...formData.value, samples: value }
dirty.value = true
}
/** 按样本类型前缀和弹窗输入重拉可选编码(后台 keyword 检索) */
async function refreshSampleCodes({ codeFilter, keyword } = {}) {
if (context.value.module !== 'protocol') return
sampleCodeOptionsController?.abort()
const controller = new AbortController()
sampleCodeOptionsController = controller
sampleCodeLoading.value = true
try {
const options = await fetchMarketFormOptions(
context.value,
{
...(id.value ? { businessId: id.value } : {}),
...buildSampleCodeSearchParams({ codeFilter, keyword })
},
{ signal: controller.signal }
)
if (!mountGuard.isCurrent(mountToken) || sampleCodeOptionsController !== controller) return
formOptions.value = hydrateProtocolReferenceOptions(
{
...formOptions.value,
sampleCodes: options?.sampleCodes || []
},
formData.value
)
} catch (error) {
if (
error?.name !== 'AbortError' &&
mountGuard.isCurrent(mountToken) &&
sampleCodeOptionsController === controller
) {
showToast(marketErrorMessage(error, '样本编码加载失败'))
}
} finally {
if (sampleCodeOptionsController === controller) sampleCodeLoading.value = false
}
}
watch(sampleContractSum, () => {
syncProtocolTotalFromSamples()
})
async function searchProtocolCustomers(keyword) {
if (context.value.module !== 'protocol') return []
const data = await fetchMarketProtocolCustomers(context.value, {
keyword,
page: 1,
pageSize: 20
})
return data?.list || []
}
function handleCustomerSelect({ section, field, customer }) {
if (context.value.module !== 'protocol' || section?.key !== 'customer') return
const role = field?.role === 'father' ? 'father' : 'mother'
const current = formData.value.customer || {}
const patch = applyCustomerSelect(current, customer, role)
formData.value = {
...formData.value,
customer: { ...current, ...patch }
}
dirty.value = true
}
async function handleFieldChange({ section, field, value, index }) {
if (context.value.module === 'freight' && field?.key === 'transportMode') {
formData.value = value === 'sfkd'
? { ...formData.value, freightAmount: '' }
: { ...formData.value, waybillNo: '' }
dirty.value = true
return
}
if (context.value.module !== 'protocol') return
if (section.key === 'protocol' && field.key === 'source' && mode.value === 'create') {
const today = todayYmd()
if (value === 'research_donation' && !formData.value.donationDate) {
formData.value = { ...formData.value, donationDate: today }
} else if (value === 'cell_storage' && !formData.value.registerDate) {
formData.value = { ...formData.value, registerDate: today }
}
return
}
if (section.key === 'customer' && (field.key === 'motherName' || field.key === 'fatherName')) {
const role = field.key === 'fatherName' ? 'father' : 'mother'
const current = formData.value.customer || {}
const clearPatch = clearCustomerLinkIfNameChanged(current, role, value)
const next = { ...current, [field.key]: value, ...(clearPatch || {}) }
if (field.key === 'motherName' || clearPatch) {
formData.value = { ...formData.value, customer: next }
dirty.value = true
}
return
}
if (section.key === 'customer' && field.key === 'motherIdCard') {
const current = formData.value.customer || {}
formData.value = {
...formData.value,
customer: {
...current,
motherIdCard: value,
motherBirthYm: calcBirthYmFromIdCard(value)
}
}
dirty.value = true
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
await applyCollectionRegion(value, { resetHospital: true, defaultManager: true })
}
/** 切换采集地区:刷新医院/人员选项,可选默认地区经理 */
async function applyCollectionRegion(regionId, { resetHospital = true, defaultManager = false } = {}) {
const value = String(regionId || '').trim()
cascadeOptionsController?.abort()
const controller = new AbortController()
cascadeOptionsController = controller
const selectedRegion = (formOptions.value.regions || []).find(
(item) => String(item?.value) === value
) || (formOptions.value.currentUserRegions || []).find(
(item) => String(item?.value) === value
)
const collection = {
...(formData.value.collection || {}),
regionId: value,
regionName: selectedRegion?.label || ''
}
if (resetHospital) {
collection.hospitalId = ''
collection.hospitalName = ''
}
if (defaultManager || !value) {
collection.regionManagerUserId = ''
collection.regionManagerUserName = ''
}
formData.value = { ...formData.value, collection }
formOptions.value = hydrateProtocolReferenceOptions({
...formOptions.value,
...(resetHospital ? { hospitals: [] } : {}),
staff: []
}, formData.value)
if (!value) return
try {
const options = await fetchMarketFormOptions(
context.value,
{ regionId: value, ...(id.value ? { businessId: id.value } : {}) },
{ signal: controller.signal }
)
if (!mountGuard.isCurrent(mountToken) || cascadeOptionsController !== controller) return
formOptions.value = hydrateProtocolReferenceOptions(
{ ...formOptions.value, ...options },
formData.value
)
if (defaultManager && !formData.value.collection?.regionManagerUserId) {
const leader = (options?.staff || []).find((item) =>
item.isLeader && (options?.regionManagers || []).some(
(manager) => String(manager.value) === String(item.value)
)
)
if (leader?.value) {
formData.value = {
...formData.value,
collection: {
...(formData.value.collection || {}),
regionManagerUserId: String(leader.value),
regionManagerUserName: String(leader.label || '')
}
}
formOptions.value = hydrateProtocolReferenceOptions(formOptions.value, formData.value)
}
}
} catch (error) {
if (error?.name !== 'AbortError' && mountGuard.isCurrent(mountToken) && cascadeOptionsController === controller) {
showToast(marketErrorMessage(error, '医院选项加载失败'))
}
}
}
function sampleKey(item) {
return freightSampleKey(item)
}
function selectedItems() {
return selectedFreightSamples(selectedSampleMap, selectedSampleKeys.value)
}
function handleSampleSelection(keys) {
selectedSampleKeys.value = reconcileFreightSampleSelection(
selectedSampleMap,
keys,
sampleOptions.value
)
dirty.value = true
}
async function loadSampleOptions() {
sampleOptionsController?.abort()
sampleOptionsGuard.begin()
sampleOptions.value = []
sampleOptionsPage.value = 0
sampleOptionsTotal.value = 0
sampleOptionsLoading.value = false
sampleOptionsRequestPending.value = false
return loadMoreSampleOptions()
}
async function loadMoreSampleOptions() {
if (context.value.module !== 'freight' || !contract.value.usesPagedSampleOptions?.(action.value)) return
if (sampleOptionsRequestPending.value) return
if (sampleOptionsFinished.value && sampleOptionsPage.value > 0) {
sampleOptionsLoading.value = false
return
}
const requestToken = sampleOptionsGuard.begin()
sampleOptionsController?.abort()
sampleOptionsController = new AbortController()
const nextPage = sampleOptionsPage.value + 1
sampleOptionsRequestPending.value = true
sampleOptionsLoading.value = true
try {
const result = await fetchFreightSampleOptions(
context.value,
{
keyword: sampleKeyword.value.trim(),
sampleSource: sampleSource.value,
page: nextPage,
pageSize: SAMPLE_OPTION_PAGE_SIZE
},
{ signal: sampleOptionsController.signal }
)
if (!mountGuard.isCurrent(mountToken) || !sampleOptionsGuard.isCurrent(requestToken)) return
const rows = result?.list || []
const normalized = contract.value.sampleOptions?.(action.value, [], rows) || []
sampleOptions.value = mergeFreightSamplePage(sampleOptions.value, normalized)
sampleOptionsPage.value = nextPage
sampleOptionsTotal.value = Math.max(0, Number(result?.total) || 0)
rememberFreightSampleRows(selectedSampleMap, sampleOptions.value)
} catch (error) {
if (error?.name === 'AbortError' || !mountGuard.isCurrent(mountToken) || !sampleOptionsGuard.isCurrent(requestToken)) return
showToast(marketErrorMessage(error, '样本选项加载失败'))
} finally {
if (mountGuard.isCurrent(mountToken) && sampleOptionsGuard.isCurrent(requestToken)) {
sampleOptionsRequestPending.value = false
sampleOptionsLoading.value = false
}
}
}
function loadUnlinkOptions(detail) {
sampleOptions.value = contract.value.sampleOptions?.(action.value, detail?.items, []) || []
sampleOptionsPage.value = 1
sampleOptionsTotal.value = sampleOptions.value.length
rememberFreightSampleRows(selectedSampleMap, sampleOptions.value)
}
function sampleSourceLabel(source) {
return source === 'research_donation' ? '科研捐赠' : '细胞存储'
}
function sampleOptionDisabled(item) {
return action.value !== 'unlink' && Boolean(item?.freightId)
}
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: [],
samplePayments: [],
payment: {},
paymentDetails: [],
attachments: {},
confirm: { confirmed: false }
}
}
return {}
}
if (context.value.module === 'protocol') {
const paymentModelVersion = detail.paymentModelVersion ?? detail.basic?.paymentModelVersion
const legacyPayment = detail.source === 'cell_storage' && Number(paymentModelVersion || 1) < 2
? createLegacyPaymentState({
payment: detail.payment,
paymentDetails: detail.paymentDetails
})
: null
return {
...(detail.protocol || detail.basic || detail),
source: detail.source,
paymentModelVersion,
customer: initLinkedCustomerNames(detail.customer || {}),
collection: detail.collection || {},
samples: detail.samples || [],
samplePayments: detail.samplePayments || [],
depositTransfers: detail.depositTransfers || [],
presignDepositHint: detail.presignDepositHint || null,
payment: legacyPayment?.payment || detail.payment || {},
paymentDetails: legacyPayment?.details || detail.paymentDetails || [],
attachments: detail.attachments || {},
confirm: { confirmed: false }
}
}
if (context.value.module === 'payment') {
return contract.value.initialForm?.(detail, authorizedAction.value) || { transfer: {} }
}
return detail
}
function hydrateCurrentOptions(options, detail) {
if (context.value.module === 'protocol') {
return hydrateProtocolReferenceOptions(options, detail)
}
return options || {}
}
async function load() {
const requestToken = loadGuard.begin()
loadController?.abort()
sampleOptionsController?.abort()
sampleCodeOptionsController?.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', '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)
transferDirty.value = false
formOptions.value = hydrateCurrentOptions(options, detail)
if (context.value.module === 'protocol' && mode.value === 'create') {
formData.value = applyProtocolCreateDefaults(formData.value, formOptions.value)
const defaultRegionId = String(formData.value.collection?.regionId || '').trim()
if (defaultRegionId) {
await applyCollectionRegion(defaultRegionId, {
resetHospital: true,
defaultManager: true
})
if (!mountGuard.isCurrent(mountToken) || !loadGuard.isCurrent(requestToken)) return
}
}
if (
context.value.module === 'protocol' &&
formData.value.source === 'cell_storage' &&
isProtocolV2.value
) {
protocolTotalFollowSamples.value = shouldFollowProtocolTotal(
formData.value.protocolTotalAmount,
sumSampleContractAmounts(formData.value.samplePayments || [])
)
syncProtocolTotalFromSamples()
} else {
protocolTotalFollowSamples.value = true
}
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
}
}
function patchUploadFieldValue(section, field, index, nextValue) {
const current = sectionValue(section)
if (section.repeat) {
const rows = current.map((row, rowIndex) =>
rowIndex === index ? { ...row, [field.key]: nextValue } : row
)
setSectionValue(section, rows)
return
}
setSectionValue(section, {
...current,
[field.key]: nextValue
})
}
function readUploadFieldValue(section, field, index) {
const current = sectionValue(section)
if (section.repeat) return current?.[index]?.[field.key]
return current?.[field.key]
}
async function uploadField({ section, field, index, file }) {
if (submitting.value || !file) return
const pending = createPendingMarketAttachment(file)
patchUploadFieldValue(
section,
field,
index,
withPendingMarketAttachment(readUploadFieldValue(section, field, index), pending)
)
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('上传结果缺少文件地址')
patchUploadFieldValue(
section,
field,
index,
resolvePendingMarketAttachment(
readUploadFieldValue(section, field, index),
pending._pendingId,
{
...uploaded,
fileUrl: url,
fileName: uploaded?.fileName || file.name
}
)
)
showSuccessToast('上传成功')
} catch (error) {
if (mountGuard.isCurrent(mountToken)) {
patchUploadFieldValue(
section,
field,
index,
dropPendingMarketAttachment(
readUploadFieldValue(section, field, index),
pending._pendingId
)
)
}
if (error?.name === 'AbortError' || !mountGuard.isCurrent(mountToken)) return
showToast(marketErrorMessage(error, '附件上传失败'))
} finally {
uploadControllers.delete(controller)
if (mountGuard.isCurrent(mountToken)) uploadPending.value -= 1
}
}
async function uploadV1PaymentAttachment({ index, file }) {
if (submitting.value || !file) return
const pending = createPendingMarketAttachment(file)
const begin = [...(formData.value.paymentDetails || [])]
if (!begin[index]) return
begin[index] = {
...begin[index],
transferAttachments: withPendingMarketAttachment(begin[index].transferAttachments, pending)
}
formData.value = { ...formData.value, paymentDetails: begin }
dirty.value = true
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 details = [...(formData.value.paymentDetails || [])]
if (!details[index]) return
details[index] = {
...details[index],
transferAttachments: resolvePendingMarketAttachment(
details[index].transferAttachments,
pending._pendingId,
{
...uploaded,
fileUrl: url,
fileName: uploaded?.fileName || file.name
}
)
}
formData.value = { ...formData.value, paymentDetails: details }
dirty.value = true
showSuccessToast('上传成功')
} catch (error) {
if (mountGuard.isCurrent(mountToken)) {
const details = [...(formData.value.paymentDetails || [])]
if (details[index]) {
details[index] = {
...details[index],
transferAttachments: dropPendingMarketAttachment(
details[index].transferAttachments,
pending._pendingId
)
}
formData.value = { ...formData.value, paymentDetails: details }
}
}
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 === 'freight') {
const fields = pickConfiguredPayload(contract.value.formSections, formData.value)
if (String(fields.transportMode || '') === 'sfkd') {
fields.freightAmount = null
fields.waybillNo = String(fields.waybillNo ?? '').trim()
}
return ['create', 'link', 'unlink'].includes(action.value)
? { ...fields, items: selectedItems() }
: fields
}
if (context.value.module === 'protocol') {
const fields = pickConfiguredPayload(visibleSections.value, formData.value)
if (mode.value === 'create' && formData.value.projectId) fields.projectId = formData.value.projectId
const withLinks = mergeProtocolCustomerLinks(fields, formData.value.customer)
const withSamples = buildProtocolSamplesPayload(
withLinks,
formData.value.samples || []
)
if (formData.value.source !== 'cell_storage') return withSamples
if (isProtocolV1.value) {
const legacy = serializeLegacyPaymentState(createLegacyPaymentState({
payment: formData.value.payment,
paymentDetails: formData.value.paymentDetails
}))
const payload = { ...withSamples, ...legacy }
delete payload.samplePayments
return payload
}
const payload = mergeProtocolSamplePayments(withSamples, formData.value.samplePayments)
delete payload.payment
delete payload.paymentDetails
return payload
}
return pickConfiguredPayload(visibleSections.value, formData.value)
}
async function submit() {
const projectError = projectAssignment.value?.validate()
if (projectError) { showToast(projectError); return }
if (submitting.value || uploadPending.value > 0) return
const transferMessage = context.value.module === 'protocol'
&& isProtocolV2.value
? protocolSaveTransferBlockMessage(id.value, formData.value.samplePayments)
: ''
if (transferMessage) {
showToast(transferMessage)
return
}
const validationMessage = validateRequiredFields(visibleSections.value, formData.value)
if (validationMessage) {
showToast(validationMessage)
return
}
if (
context.value.module === 'protocol' &&
formData.value.source === 'cell_storage' &&
isProtocolV1.value
) {
const legacyHint = validateLegacyPaymentState(createLegacyPaymentState({
payment: formData.value.payment,
paymentDetails: formData.value.paymentDetails
}))
if (legacyHint) {
showToast(legacyHint)
return
}
}
if (
context.value.module === 'protocol' &&
formData.value.source === 'cell_storage' &&
isProtocolV2.value
) {
for (const pay of formData.value.samplePayments || []) {
const requiredHint = sampleScheduleRequiredFieldsHint(pay)
if (requiredHint) {
showToast(requiredHint)
return
}
const mismatchHint = sampleScheduleDuesMismatchHint(pay)
if (mismatchHint) {
showToast(mismatchHint)
return
}
}
const totalHint = protocolTotalMismatchHint(
formData.value.protocolTotalAmount,
sumSampleContractAmounts(formData.value.samplePayments || [])
)
if (totalHint) {
try {
await showConfirmDialog({ title: '提示', message: totalHint })
} catch {
return
}
}
}
let payload
try {
payload = buildMarketActionPayload(
context.value.module,
action.value,
sanitizeMarketPayload(buildPayload())
)
} catch (error) {
showToast(marketErrorMessage(error, '组装保存数据失败'))
return
}
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
}
if (context.value.module === 'freight' && ['link', 'unlink'].includes(action.value)) {
try {
await showConfirmDialog({
title: action.value === 'link' ? '确认关联样本' : '确认取消样本关联',
message: action.value === 'link'
? `确认将已选的 ${payload.items.length} 个样本关联到当前运费批次吗?`
: `确认取消已选 ${payload.items.length} 个样本的运费关联吗?`
})
} catch {
return
}
}
const pendingTransfers = context.value.module === 'protocol' && isProtocolV2.value
? collectTransfersSavedWithProtocol(formData.value.samplePayments)
: { ready: [], incomplete: [] }
submitting.value = true
submitController = new AbortController()
try {
let result
if (['register-transfer', 'edit-transfer', '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
const detailId = resolveMarketSavedDetailId(context.value.module, id.value, result, action.value)
let saveToast = '保存成功'
if (
context.value.module === 'protocol' &&
String(formData.value.source || '') === 'cell_storage' &&
detailId &&
!['register-transfer', 'edit-transfer', 'link', 'unlink'].includes(action.value)
) {
try {
const detail = await fetchMarketDetail(context.value, detailId, {
signal: submitController.signal
})
if (!mountGuard.isCurrent(mountToken)) return
const version = Number(
detail?.paymentModelVersion ?? detail?.basic?.paymentModelVersion ?? formData.value.paymentModelVersion ?? 2
)
if (version >= 2) {
const paymentCtx = {
module: 'payment',
marketRole: context.value.marketRole
}
const registered = []
const registerFailures = []
for (const draft of pendingTransfers.ready) {
const scheduleId = findScheduleIdAfterProtocolSave(detail?.samplePayments, draft)
if (!scheduleId) {
registerFailures.push({ message: '未找到应缴批次' })
continue
}
try {
const remote = await performMarketAction(paymentCtx, 'register-transfer', {
data: { scheduleId, ...draft.payload }
}, { signal: submitController.signal })
const data = remote?.data || remote || {}
if (data.id) {
registered.push({ id: data.id, payStatus: data.payStatus || 'dfj' })
}
} catch (error) {
registerFailures.push({
message: marketErrorMessage(error, '转账保存失败')
})
}
}
const rows = [
...flattenSamplePaymentTransfers(detail?.samplePayments || []),
...registered
]
const failures = await submitDfjTransfersOnSave(rows, (transferId) =>
performMarketAction(paymentCtx, 'submit', { id: transferId }, {
signal: submitController.signal
})
)
const notes = []
if (pendingTransfers.incomplete.length) {
notes.push(`有 ${pendingTransfers.incomplete.length} 笔转账信息不完整,未写入`)
}
if (registerFailures.length) {
notes.push(`有 ${registerFailures.length} 笔转账保存失败:${registerFailures.map((item) => item.message).join(';')}`)
}
if (failures.length) {
saveToast = [formatAutoSubmitFinanceFailureMessage(failures, '协议'), ...notes].filter(Boolean).join('。')
} else if (notes.length) {
saveToast = `协议已保存。${notes.join('。')}`
}
}
} catch (autoSubmitError) {
if (autoSubmitError?.name === 'AbortError' || !mountGuard.isCurrent(mountToken)) return
saveToast = '协议已保存,但自动提交财务确认失败,请在缴费信息中手动提交'
}
}
if (saveToast === '保存成功') showSuccessToast(saveToast)
else showToast(saveToast)
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()
sampleCodeOptionsController?.abort()
submitController?.abort()
for (const controller of uploadControllers) controller.abort()
uploadControllers.clear()
window.removeEventListener('beforeunload', beforeUnload)
})
</script>