feat(pl): 实现合同产品用证与额度结转以支持购买证和运输证全流程管理。

This commit is contained in:
wuzilong committed 2026-11-01 18:56:05 +08:00
1 parent cb0344498a
commit fb866c7fa7
104 files changed
+10187 -3833

No files matched your search

@@ -1,5 +1,6 @@
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<PlQuotaSettlementDialog ref="quotaSettlementDialog" />
<el-dialog
v-model="innerVisible"
:title="dialogTitle"
@@ -9,6 +10,8 @@
class="dialog-form-layout pl-plan-archive-dialog"
modal-class="order-module-dialog-mask"
:close-on-click-modal="false"
:close-on-press-escape="!submitLoading"
:show-close="!submitLoading"
style="backdrop-filter: none"
@close="handleClose"
@closed="handleClosed"
@@ -221,7 +224,7 @@
<template #footer>
<div class="dialog-footer pl-arrange-footer">
<el-button @click="innerVisible = false">
<el-button :disabled="submitLoading" @click="innerVisible = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button
@@ -243,6 +246,9 @@
</template>
<script setup lang="ts">
import PlQuotaSettlementDialog from '@/components/business/pl-quota-settlement-dialog/index.vue'
const quotaSettlementDialog = ref<InstanceType<typeof PlQuotaSettlementDialog>>()
let quotaArchiveAttempt = { signature: '', id: '' }
import { Check, Close, Document, Edit } from '@element-plus/icons-vue'
import { fetchProductDetail, type ProductDetail } from '@/api/crm/product'
import {
@@ -271,7 +277,6 @@
import PlVehicleSummaryStrip from '@/components/business/pl-vehicle-summary-strip/index.vue'
import PlVehicleViewDialog from '@/components/business/pl-vehicle-view-dialog/index.vue'
import { type PlanFormProductRow } from '@/composables/usePlContractToPlan'
import { buildMissingHazardCertReadyMessage } from '@/composables/usePlToxicProductCertCheck'
import { applyAliasDisplayMeta, buildProductAliasOptions } from '@/utils/crm-product-brand'
import { useDecimalInputBinding } from '@/composables/useDecimalInput'
import {
@@ -311,6 +316,14 @@
const loading = ref(false)
const submitLoading = ref(false)
let archiveSession = 0
onBeforeUnmount(() => { archiveSession++; quotaSettlementDialog.value?.cancel() })
watch([innerVisible, () => props.planId], () => {
archiveSession++
submitLoading.value = false
quotaSettlementDialog.value?.cancel()
}, { flush: 'sync' })
const draftLoading = ref(false)
const activeTab = ref<'archive' | 'overview'>('archive')
const tabsRef = ref<InstanceType<typeof PlPlanViewTabs> | null>(null)
@@ -1528,34 +1541,35 @@
return
}
if (!isAdjustMode.value) {
const certMessage = buildMissingHazardCertReadyMessage(plan.value, productRows.value)
if (certMessage) {
await ElMessageBox.alert(`${certMessage},请至【危化品证上传】页面操作。`, '无法归档', {
type: 'warning'
})
return
}
}
if (hasFeedbackAttachmentUploading()) {
ElMessage.warning('附件正在上传,请稍候再保存')
return
}
if (submitLoading.value) return
const session = archiveSession, targetId = props.planId
const current = () => session === archiveSession && targetId === props.planId && innerVisible.value
const archiveBody: PlanArchiveBody = JSON.parse(JSON.stringify(buildArchiveBody()))
submitLoading.value = true
try {
await submitArchiveWithOverageConfirm()
if (productRows.value.some(p => Number(p.isToxic) === 1)) {
const value = await quotaSettlementDialog.value?.open(targetId, isAdjustMode.value)
if (!current() || !value) return
Object.assign(archiveBody, value)
}
if (!current()) return
await submitArchiveWithOverageConfirm(targetId, archiveBody, current)
if (!current()) return
ElMessage.success(isAdjustMode.value ? '保存成功' : '归档成功')
tabsRef.value?.reload()
emit('success')
innerVisible.value = false
} catch (e: unknown) {
if ((e as { cancelled?: boolean }).cancelled) return
if (!current() || (e as { cancelled?: boolean }).cancelled) return
const message = e instanceof Error ? e.message : isAdjustMode.value ? '保存失败' : '归档失败'
ElMessage.error(message)
} finally {
submitLoading.value = false
if (session === archiveSession) submitLoading.value = false
}
}
@@ -1574,10 +1588,25 @@
deliveryBlocks.value.forEach((block) => mark(block.products))
}
async function submitArchiveWithOverageConfirm(confirmOverage = false): Promise<void> {
async function submitArchiveWithOverageConfirm(targetId: string, frozenBody: PlanArchiveBody, current: () => boolean, confirmOverage = false): Promise<void> {
try {
await planApi.archive(props.planId, { ...buildArchiveBody(), confirmOverage })
const archiveBody = { ...frozenBody, confirmOverage }
const signature = JSON.stringify({ planId: targetId, archiveBody })
if (signature !== quotaArchiveAttempt.signature) quotaArchiveAttempt = { signature, id: crypto.randomUUID() }
const response = await planApi.archive(targetId, { ...archiveBody, operationId: quotaArchiveAttempt.id })
if (!current()) return
const saved = pickBxData<Plan & { quotaSettlementError?: string }>(response)
if (saved?.quotaSettlementError) {
// 业务异常已作为一次请求提交;补齐条件后允许新尝试,不回放旧异常。
quotaArchiveAttempt = { signature: '', id: '' }
const message = `实际数量已保存,额度结转未完成:${saved.quotaSettlementError}`
await ElMessageBox.alert(message, '用证结转异常', { type: 'warning' })
const error = new Error(message) as Error & { cancelled?: boolean }
error.cancelled = true
throw error
}
} catch (e: unknown) {
if (!current()) return
const overage = extractArchiveLineOverageDetail(e)
if (!overage || confirmOverage) throw e
applyArchiveOverageHighlight(overage.items)
@@ -1587,7 +1616,7 @@
;(cancelled as Error & { cancelled?: boolean }).cancelled = true
throw cancelled
}
await submitArchiveWithOverageConfirm(true)
if (current()) await submitArchiveWithOverageConfirm(targetId, frozenBody, current, true)
}
}
</script>
@@ -1,5 +1,6 @@
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<PlPlanQuotaDialog ref="quotaDialog" />
<MobilePlPlanForm v-if="isPageVariant" :controller="mobileController">
<template #load>
<el-form label-position="top" label-width="100px" class="pl-dialog-form">
@@ -615,6 +616,9 @@
</template>
<script setup lang="ts">
import PlPlanQuotaDialog from '@/components/business/pl-plan-quota-dialog/index.vue'
const quotaDialog = ref<InstanceType<typeof PlPlanQuotaDialog>>()
let arrangeAttempt = { signature: '', id: '' }
import PlanArrangeSheets from '@/views/m/pl/plan/PlanArrangeSheets.vue'
const arrangeSheetsRef = ref<InstanceType<typeof PlanArrangeSheets> | null>(null)
const mobileSavedPlanId = ref('')
@@ -734,7 +738,6 @@
import { normalizeProductUnitValue } from '@/utils/crm-product-display'
import { formatPlVehiclePlateOptionLabel } from '@/utils/pl-display'
import {
buildMissingHazardCertReadyMessage,
enrichPlanProductsHazardFromCrm
} from '@/composables/usePlToxicProductCertCheck'
import { usePlFreightCalc, resolveFreightUnitLabel } from '@/composables/usePlFreightCalc'
@@ -2624,14 +2627,10 @@
const rawProducts = Array.isArray(plan.products) ? plan.products : []
const enrichedProducts = await enrichPlanProductsHazardFromCrm(rawProducts)
if (!isPageSubmitCurrent(generation)) return false
const certMessage = buildMissingHazardCertReadyMessage(plan, enrichedProducts)
if (certMessage) {
if (isPageVariant.value) await arrangePresenter({ title: '无法安排运输', message: `${certMessage},请至【危化品证上传】页面操作。` })
else await ElMessageBox.alert(`${certMessage},请至【危化品证上传】页面操作。`, '无法安排运输', {
type: 'warning'
})
return false
}
const quotaConfiguration = enrichedProducts.some(p => Number(p.isToxic) === 1)
? await quotaDialog.value?.open(planId, true, { targetLicensePlate: currentVehiclePlate.value, targetTrailerNo: selectedVehicle.value?.trailerNo || null })
: undefined
if (enrichedProducts.some(p => Number(p.isToxic) === 1) && !quotaConfiguration) return false
const isRearrange = plan.transportStatus === 'arranged'
const dibangSelected = planHasAnyDibangSelected(plan, loadForm.value, deliveryForms.value)
@@ -2674,8 +2673,10 @@
getUnitLabel
})
const signature = JSON.stringify({planId, payload, quotaConfiguration})
if (signature !== arrangeAttempt.signature) arrangeAttempt = { signature, id: crypto.randomUUID() }
try {
await submitPlanArrange(planId, payload, isPageVariant.value ? arrangePresenter : undefined)
await submitPlanArrange(planId, { ...payload, operationId: arrangeAttempt.id, quotaConfiguration }, isPageVariant.value ? arrangePresenter : undefined)
if (!isPageSubmitCurrent(generation)) return false
} catch {
return false
@@ -0,0 +1,639 @@
<template>
<el-dialog
v-model="visible"
:title="`计划用证 · ${plan?.planNo || ''}`"
width="1080px"
class="dialog-form-layout quota-dialog"
align-center
:close-on-click-modal="false"
:close-on-press-escape="!busy"
:show-close="!busy"
@closed="!visible && cancel()"
>
<div v-loading="loading">
<el-alert
type="info"
:closable="false"
:title="
forSupplement
? '仅为超过原预占的实际量选择补充证件。保留原来源与分配顺序,提交归档时重新校验;本次选择不扣额度。'
: '绑定不扣额度。正式安排时按当前合同、证件与来源重新校验并预占;合法使用证明可后补。'
"
/>
<template v-if="plan">
<p>当前车号:{{ plan.licensePlate || '待安排' }}</p>
<p
v-if="!forArrange && !forSupplement && plan.canSaveConfiguration === false"
class="form-tip"
>已安排计划请从调整运输提交用证变更;已归档计划仅查看占用。</p
>
<section class="view-section">
<h3>1. 明确唯一计量侧与装送配对</h3>
<p v-if="!groups.length">当前计划没有易制毒产品,无需购买证、运输证额度。</p>
<div v-for="group in groups" :key="group.id" class="view-section">
<strong>{{ group.name }}</strong>
<el-radio-group
:model-value="sides[group.id]"
:disabled="busy || forSupplement"
@update:model-value="setSide(group.id, $event as string)"
>
<el-radio v-if="group.load.length" value="load">按装货计量</el-radio>
<el-radio v-if="group.delivery.length" value="delivery">按送货计量</el-radio>
</el-radio-group>
<div
v-for="source in group[sides[group.id] as 'load' | 'delivery'] || []"
:key="source.sourceStopProductId"
class="view-section"
>
<p
>{{ source.partyName || '未填写单位' }} · {{ source.quantity }} {{ source.unit }} ·
{{ source.model }}</p
>
<el-select
v-if="opposite(group).length"
v-model="pairs[source.sourceStopProductId]"
multiple
:disabled="busy || forSupplement"
placeholder="勾选对应另一侧产品行(必选)"
style="width: 100%"
@change="invalidate"
>
<el-option
v-for="other in opposite(group)"
:key="other.sourceStopProductId"
:value="other.sourceStopProductId"
:label="`${other.partyName || '未填写单位'} · ${other.quantity} ${other.unit} · ${other.sourceStopProductId.slice(-6)}`"
/>
</el-select>
</div>
</div>
</section>
<section v-if="groups.length" class="view-section">
<h3>2. 选择合同产品适用的证件</h3>
<el-form label-position="top" :disabled="busy"
><div class="form-grid-2">
<el-form-item label="购买证"
><el-select
v-model="config.purchaseCertIds"
multiple
filterable
@change="invalidate"
><el-option
v-for="c in purchases"
:key="c.id"
:value="c.id"
:label="certLabel(c)" /></el-select
></el-form-item>
<el-form-item label="运输证"
><el-select
v-model="config.transportCertIds"
multiple
filterable
@change="invalidate"
><el-option
v-for="c in transports"
:key="c.id"
:value="c.id"
:label="certLabel(c)" /></el-select
></el-form-item> </div
></el-form>
<el-button :loading="busy" @click="loadContext"
><el-icon><Refresh /></el-icon>读取当前来源与核对条件</el-button
>
<template v-if="context">
<div v-for="(source, i) in context.sources" :key="i" class="view-section">
<p
>{{ source.source_stop_type === 'load' ? '装货' : '送货' }}计量:{{
source.quantity
}}
{{ source.unit }};车号 {{ source.snapshot.vehicle || '未填写' }}</p
>
<p v-for="stop in source.snapshot.stops" :key="stop.id"
>{{ stop.supplier_name || stop.customer_name || '未填写单位' }} ·
{{ stop.address || '未填写地址' }}</p
>
</div>
<div v-for="item in selected" :key="item.kind + item.cert.id" class="view-section">
<h4>{{ item.kind === 'purchase' ? '购买证' : '运输证' }} · {{ item.cert.certNo }}</h4>
<p
>{{ item.cert.buyerName || item.cert.shipperName }} →
{{ item.cert.sellerName || item.cert.consigneeName }};有效期
{{ item.cert.validFrom }} 至 {{ item.cert.validTo }};{{
item.cert.validUseText
}}</p
>
<p v-if="item.kind === 'transport'"
>{{ item.cert.vehicleNumbersJson?.join('、') }} ·
{{ item.cert.routeText || '未填写路线' }}</p
>
<el-checkbox
v-model="condition(item.kind, item.cert).partiesConfirmed"
:disabled="busy"
>已核对证面参与方与上述实际装送单位适用</el-checkbox
>
<el-checkbox
v-if="item.kind === 'transport'"
v-model="condition(item.kind, item.cert).routeConfirmed"
:disabled="busy"
>已核对车号、运输路线与装送条件适用</el-checkbox
>
<el-input
v-model="condition(item.kind, item.cert).note"
:disabled="busy"
placeholder="填写核对依据或适用说明(必填)"
/>
</div>
</template>
</section>
<section v-if="groups.length" class="view-section">
<h3>3. 不同单位人工换算(同单位无需填写)</h3>
<p v-if="forSupplement" class="form-tip"
>这里只填写超出原预占部分的来源量及证面量;原预占内的实际量在上一层核对。不得重复计算两部分。</p
>
<div
v-for="(row, i) in config.manualAllocations"
:key="i"
class="view-section form-grid-2"
>
<el-select v-model="row.sourceId" :disabled="busy" placeholder="计量来源"
><el-option
v-for="source in measured"
:key="source.sourceStopProductId"
:value="`${source.sourceStopType}:${source.sourceStopProductId}`"
:label="`${source.productName} · ${source.partyName || ''} · ${source.quantity} ${source.unit}`"
/></el-select>
<el-select
:model-value="`${row.permitKind}:${row.permitId}`"
:disabled="busy"
placeholder="证件"
@update:model-value="selectManualCert(row, $event)"
><el-option
v-for="item in selected"
:key="item.kind + item.cert.id"
:value="`${item.kind}:${item.cert.id}`"
:label="`${item.cert.certNo}(${item.cert.quantityUnit})`"
/></el-select>
<el-input
v-model="row.sourceQuantity"
:disabled="busy"
placeholder="来源数量"
/><el-input
v-model="row.permitQuantity"
:disabled="busy"
placeholder="换算后的证面数量"
/>
<el-input v-model="row.note" :disabled="busy" placeholder="换算依据(必填)" />
<el-button :disabled="busy" @click="config.manualAllocations.splice(i, 1)"
><el-icon><Delete /></el-icon>移除此项</el-button
>
</div>
<el-button
:disabled="busy"
@click="
config.manualAllocations.push({
permitKind: 'purchase',
sourceId: '',
permitId: '',
sourceQuantity: '',
permitQuantity: '',
note: ''
})
"
><el-icon><Plus /></el-icon>添加人工换算</el-button
>
</section>
<section v-if="!forSupplement" class="view-section"
><h3>4. 预览分配</h3>
<el-button :loading="busy" @click="preview"
><el-icon><Search /></el-icon>重新计算</el-button
>
<template v-if="result"
><el-tag
:type="
result.status === 'available' || result.status === 'not_required'
? 'success'
: 'warning'
"
>{{ statusLabels[result.status] || result.status }}</el-tag
><p v-for="reason in result.reasons" :key="reason">{{ reason }}</p>
<div
v-for="row in result.diagnostics || []"
:key="row.certType + row.unit"
class="view-section"
>
<strong
>{{ row.certType === 'purchase' ? '购买证' : '运输证' }} · 需求 {{ row.demand }}
{{ row.unit }}</strong
>
<p v-if="row.availableUpperBound !== null">
适用余额至多 {{ row.availableUpperBound }} {{ row.unit }};缺口至少
{{ row.gapLowerBound }} {{ row.unit }}
</p>
<p>{{ row.reason }}</p>
</div>
<el-table :data="allocations" stripe
><el-table-column prop="kind" label="证种" min-width="90" /><el-table-column
prop="certNo"
label="证号"
min-width="160" /><el-table-column
prop="sourceId"
label="计量来源"
min-width="190" /><el-table-column
prop="sourceQuantity"
label="来源量"
min-width="100" /><el-table-column
prop="permitQuantity"
label="证面量"
min-width="100" /><el-table-column
prop="permitUnit"
label="证面单位"
min-width="100" /><el-table-column
prop="allocationSeq"
label="结转顺序"
min-width="100"
/></el-table>
</template>
<p class="form-tip">预览不占用额度;正式保存前余额变化将重新校验。</p>
</section>
<section v-if="plan.usages.length" class="view-section"
><h3>已有占用与结转</h3
><el-table :data="plan.usages" stripe
><el-table-column prop="certId" label="证件" min-width="180" /><el-table-column
prop="usageStatus"
label="状态"
min-width="120"
><template #default="{ row }"
><el-tag :type="row.usageStatus === 'exception' ? 'danger' : 'info'">{{
usageLabels[row.usageStatus] || row.usageStatus
}}</el-tag></template
></el-table-column
><el-table-column prop="reservedQty" label="预占量" min-width="120" /><el-table-column
prop="usedQty"
label="使用量"
min-width="120" /></el-table
></section>
</template>
</div>
<template #footer
><el-button :disabled="busy" @click="cancel"
><el-icon><Close /></el-icon>取消</el-button
><el-button
type="primary"
:disabled="
loading || !plan || (!forArrange && !forSupplement && plan.canSaveConfiguration === false)
"
:loading="busy"
@click="accept"
><el-icon><Check /></el-icon
>{{
forSupplement ? '确认补充分配候选' : forArrange ? '确认本次用证配置' : '保存配置'
}}</el-button
></template
>
</el-dialog>
</template>
<script setup lang="ts">
import { useUserStore } from '@/store/modules/user'
import { Check, Close, Delete, Plus, Refresh, Search } from '@element-plus/icons-vue'
import {
planQuotaApi,
quotaCertApi,
type PlanQuota,
type QuotaConfiguration,
type QuotaContext,
type QuotaPreview,
type QuotaCert,
type CertType,
type QuotaSourceOption,
type QuotaPreviewVehicle,
type ManualQuotaQuantity
} from '@/api/pl/quota-cert'
const visible = ref(false),
loading = ref(false),
busy = ref(false),
forArrange = ref(false),
forSupplement = ref(false)
const plan = ref<PlanQuota>(),
purchases = ref<QuotaCert[]>([]),
transports = ref<QuotaCert[]>([])
const empty = (): QuotaConfiguration => ({
sourceMapping: null,
purchaseCertIds: [],
transportCertIds: [],
manualAllocations: [],
conditions: []
})
const config = ref<QuotaConfiguration>(empty()),
context = ref<QuotaContext>(),
result = ref<QuotaPreview>()
const sides = reactive<Record<string, string>>({}),
pairs = reactive<Record<string, string[]>>({})
let previewVehicle: QuotaPreviewVehicle = {}
let epoch = 0,
resolve: ((value: QuotaConfiguration | undefined) => void) | undefined
const groups = computed(() => {
const values = new Map<
string,
{ id: string; name: string; load: QuotaSourceOption[]; delivery: QuotaSourceOption[] }
>()
for (const row of plan.value?.sourceOptions || []) {
if (!values.has(row.planProductId))
values.set(row.planProductId, {
id: row.planProductId,
name: row.productName,
load: [],
delivery: []
})
values.get(row.planProductId)![row.sourceStopType].push(row)
}
return [...values.values()]
})
const measured = computed(() =>
groups.value.flatMap((g) => g[sides[g.id] as 'load' | 'delivery'] || [])
)
const selected = computed(() => [
...purchases.value
.filter((c) => config.value.purchaseCertIds.includes(c.id))
.map((cert) => ({ kind: 'purchase' as const, cert })),
...transports.value
.filter((c) => config.value.transportCertIds.includes(c.id))
.map((cert) => ({ kind: 'transport' as const, cert }))
])
const usageLabels: Record<string, string> = {
reserved: '已预占',
in_transit: '执行中',
settled: '已核销',
released: '已释放',
exception: '结转异常',
draft: '草稿'
}
const statusLabels: Record<string, string> = {
available: '当前额度可用',
not_required: '无需两证额度',
needs_confirmation: '待核对条件',
insufficient: '额度不足',
calculation_incomplete: '计算未完成',
needs_configuration: '待完善配置'
}
const allocations = computed(() =>
['purchase', 'transport'].flatMap((kind) =>
(
result.value?.[kind === 'purchase' ? 'purchaseAllocations' : 'transportAllocations'] || []
).map((row) => ({
...row,
kind: kind === 'purchase' ? '购买证' : '运输证',
certNo:
selected.value.find((i) => i.kind === kind && i.cert.id === row.certId)?.cert.certNo ||
row.certId
}))
)
)
function certLabel(c: QuotaCert) {
return `${c.certNo} · 可用 ${c.availableQty} ${c.quantityUnit}`
}
function opposite(group: (typeof groups.value)[number]) {
return group[sides[group.id] === 'load' ? 'delivery' : 'load']
}
function invalidate() {
context.value = undefined
result.value = undefined
config.value.conditions = []
}
function setSide(id: string, side: string) {
sides[id] = side
invalidate()
}
function payload() {
return {
...config.value,
sourceMapping: measured.value.map((s) => ({
sourceStopType: s.sourceStopType,
sourceStopProductId: s.sourceStopProductId,
relatedStopProductIds: pairs[s.sourceStopProductId] || []
}))
}
}
function condition(kind: CertType, cert: QuotaCert) {
let c = config.value.conditions.find((i) => i.certType === kind && i.certId === cert.id)
if (!c) {
c = {
certType: kind,
certId: cert.id,
certRevision: cert.revision,
sourceFingerprint: context.value?.sourceFingerprint || '',
partiesConfirmed: false,
routeConfirmed: false,
note: ''
}
config.value.conditions.push(c)
}
return c
}
function selectManualCert(row: ManualQuotaQuantity, value: string) {
const [kind, ...id] = value.split(':')
row.permitKind = kind as CertType
row.permitId = id.join(':')
}
async function loadContext() {
if (!plan.value || busy.value) return
busy.value = true
const current = epoch
try {
const value = await planQuotaApi.context(plan.value.planId, {
...payload(),
...previewVehicle
})
if (current !== epoch) return
context.value = value
config.value.conditions = config.value.conditions.filter(
(c) =>
c.sourceFingerprint === value.sourceFingerprint &&
selected.value.some(
(i) =>
i.kind === c.certType && i.cert.id === c.certId && i.cert.revision === c.certRevision
)
)
selected.value.forEach((i) => condition(i.kind, i.cert))
} finally {
if (current === epoch) busy.value = false
}
}
async function preview() {
if (!plan.value || busy.value) return
busy.value = true
const current = epoch
try {
const value = await planQuotaApi.preview(plan.value.planId, {
...payload(),
...previewVehicle
})
if (current === epoch) result.value = value
} finally {
if (current === epoch) busy.value = false
}
}
async function accept() {
if (!plan.value || busy.value) return
const current = epoch,
id = plan.value.planId
const isCurrent = () => current === epoch && plan.value?.planId === id && visible.value
if (forArrange.value) {
await preview()
if (!isCurrent()) return
if (!['available', 'not_required'].includes(result.value?.status || '')) return
}
const value = payload()
if (forSupplement.value) {
if (
(!value.purchaseCertIds.length && !value.transportCertIds.length) ||
!context.value ||
selected.value.some(({ kind, cert }) => {
const c = value.conditions.find((c) => c.certType === kind && c.certId === cert.id)
return (
!c ||
c.certRevision !== cert.revision ||
c.sourceFingerprint !== context.value?.sourceFingerprint ||
!c.partiesConfirmed ||
(kind === 'transport' && !c.routeConfirmed) ||
!c.note.trim()
)
})
) {
ElMessage.warning('请选择需补量的证件,并读取当前来源后逐证确认参与方、路线及依据')
return
}
}
if (forArrange.value || forSupplement.value) {
resolve?.(value)
resolve = undefined
visible.value = false
return
}
busy.value = true
try {
await planQuotaApi.save(id, value)
if (!isCurrent()) return
ElMessage.success('用证配置已保存')
resolve?.(value)
resolve = undefined
visible.value = false
} finally {
if (current === epoch) busy.value = false
}
}
function cancel() {
if (busy.value) return
epoch++
visible.value = false
resolve?.(undefined)
resolve = undefined
}
async function open(
id: string,
arrange = false,
vehicle: QuotaPreviewVehicle = {},
supplement = false
): Promise<QuotaConfiguration | undefined> {
if (busy.value) return
resolve?.(undefined)
const current = ++epoch
visible.value = true
loading.value = true
plan.value = undefined
context.value = undefined
result.value = undefined
forArrange.value = arrange
forSupplement.value = supplement
previewVehicle = vehicle
Object.keys(sides).forEach((k) => delete sides[k])
Object.keys(pairs).forEach((k) => delete pairs[k])
try {
const [p, b, t] = await Promise.all([
planQuotaApi.get(id),
quotaCertApi.list('purchase'),
quotaCertApi.list('transport')
])
if (current !== epoch) return
plan.value = p
purchases.value = b
transports.value = t
config.value = { ...empty(), ...p.configuration }
if (supplement)
config.value = {
...config.value,
purchaseCertIds: [],
transportCertIds: [],
manualAllocations: [],
conditions: []
}
for (const group of groups.value) {
const old = config.value.sourceMapping?.find((s) =>
group[s.sourceStopType].some((r) => r.sourceStopProductId === s.sourceStopProductId)
)
sides[group.id] =
old?.sourceStopType ||
(group.load.length && !group.delivery.length
? 'load'
: group.delivery.length && !group.load.length
? 'delivery'
: '')
}
for (const row of config.value.sourceMapping || [])
pairs[row.sourceStopProductId] = [...row.relatedStopProductIds]
return await new Promise((r) => {
resolve = r
loading.value = false
})
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() => JSON.stringify(config.value.manualAllocations),
() => {
result.value = undefined
}
)
function invalidateSession() {
epoch++
visible.value = false
plan.value = undefined
context.value = undefined
result.value = undefined
config.value = empty()
loading.value = false
busy.value = false
resolve?.(undefined)
resolve = undefined
}
const sessionUser = useUserStore()
watch(
() => JSON.stringify([sessionUser.accessToken, sessionUser.getUserInfo]),
invalidateSession,
{ flush: 'sync' }
)
defineExpose({ open, invalidateSession })
onBeforeUnmount(() => {
epoch++
resolve?.(undefined)
})
</script>
<style scoped>
.quota-dialog :deep(.el-select) {
width: 100%;
}
.view-section {
margin-top: 16px;
}
.view-section h4 {
margin: 12px 0;
}
.view-section .el-checkbox {
white-space: normal;
height: auto;
min-height: 36px;
}
.view-section .el-input {
margin-top: 8px;
}
</style>
@@ -0,0 +1,242 @@
<template>
<PlPlanQuotaDialog ref="supplementDialog" />
<el-dialog
v-model="visible"
title="实际用证量核对"
width="880px"
class="dialog-form-layout"
align-center
:close-on-click-modal="false"
@closed="!visible && cancel()"
>
<p class="form-tip"
>异单位按实际量重新填写,不沿用安排时换算比例。每个来源、每类证件的分配合计必须与本次实际数量一致;0
也须明确填写。</p
>
<p v-if="!rows.length" class="form-tip"
>当前原分配均为同单位,系统按本次各来源实际数量和原顺序结转。</p
>
<el-checkbox v-model="allowSupplement">实际量超出原预占,需要补充分配</el-checkbox>
<template v-if="allowSupplement">
<p class="form-tip"
>下方填写原分配部分的实际来源量和本次实际证面量。超出原来源量的部分在补充候选中填写;仅证面量增加时选择对应原证补差。来源量增加需双证覆盖,系统不沿用换算比例。补充校验失败将保存真实数量及异常,保持原账。</p
>
<el-button :loading="choosing" @click="chooseSupplement"
><el-icon><Plus /></el-icon
>{{ supplementConfiguration ? '重新选择补充证件' : '选择补充证件并核对条件' }}</el-button
>
<p v-if="supplementConfiguration"
>已选购买证 {{ supplementConfiguration.purchaseCertIds.length }} 张、运输证
{{ supplementConfiguration.transportCertIds.length }} 张;提交时重新校验余额和条件。</p
>
</template>
<section v-for="row in rows" :key="row.key" class="view-section">
<h3>{{ row.certNo }} · {{ row.kind === 'purchase' ? '购买证' : '运输证' }}</h3>
<p>{{ row.productName }} · {{ row.sourceLabel }} · 结转顺序 {{ row.seq }}</p>
<p
>安排分配:{{ row.plannedSource }} {{ row.sourceUnit }} → {{ row.plannedPermit }}
{{ row.permitUnit }}</p
>
<el-form label-position="top"
><div class="form-grid-2">
<el-form-item :label="`本证分配的实际来源量(${row.sourceUnit})`"
><el-input v-model="row.value.sourceQuantity" placeholder="包括真实 0"
/></el-form-item>
<el-form-item :label="`实际证面量(${row.permitUnit})`"
><el-input v-model="row.value.permitQuantity" placeholder="包括真实 0"
/></el-form-item>
<el-form-item label="本次换算依据" class="form-col-span-2"
><el-input v-model="row.value.note" type="textarea"
/></el-form-item> </div
></el-form>
</section>
<el-form v-if="adjustment || allowSupplement" label-position="top">
<el-form-item label="实际用量更正/补分配理由(必填)"
><el-input v-model="reason" type="textarea"
/></el-form-item>
<el-form-item label="更正依据说明(与凭据至少填写一项)"
><el-input v-model="sourceNote" type="textarea"
/></el-form-item>
<el-form-item label="更正凭据"
><AttachmentUploadField
ref="attachments"
:key="epoch"
v-model="evidenceUrls"
folder="pl/quota-adjustment"
/></el-form-item>
</el-form>
<template #footer
><el-button @click="cancel"
><el-icon><Close /></el-icon>取消</el-button
><el-button type="primary" :disabled="choosing" @click="accept"
><el-icon><Check /></el-icon>确认实际用证量</el-button
></template
>
</el-dialog>
</template>
<script setup lang="ts">
import { Check, Close, Plus } from '@element-plus/icons-vue'
import {
planQuotaApi,
type ManualQuotaQuantity,
type QuotaConfiguration
} from '@/api/pl/quota-cert'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import PlPlanQuotaDialog from '@/components/business/pl-plan-quota-dialog/index.vue'
import { useUserStore } from '@/store/modules/user'
interface Result {
quotaAllowSupplement: boolean
quotaConfiguration?: QuotaConfiguration
quotaManualActuals: ManualQuotaQuantity[]
quotaReason: string
quotaSourceNote: string
quotaEvidenceUrls: string
}
const visible = ref(false),
adjustment = ref(false),
reason = ref(''),
sourceNote = ref(''),
evidenceUrls = ref('')
const attachments = ref<InstanceType<typeof AttachmentUploadField>>()
const supplementDialog = ref<InstanceType<typeof PlPlanQuotaDialog>>()
const allowSupplement = ref(false),
choosing = ref(false),
targetPlanId = ref('')
const supplementConfiguration = ref<QuotaConfiguration>()
const rows = ref<
{
key: string
kind: string
certNo: string
productName: string
sourceLabel: string
sourceUnit: string
permitUnit: string
plannedSource: string
plannedPermit: string
seq: number
value: ManualQuotaQuantity
}[]
>([])
let epoch = 0,
resolve: ((value: Result | undefined) => void) | undefined
async function open(planId: string, adjust = false): Promise<Result | undefined> {
resolve?.(undefined)
const current = ++epoch
targetPlanId.value = planId
allowSupplement.value = false
choosing.value = false
supplementConfiguration.value = undefined
const plan = await planQuotaApi.get(planId)
if (current !== epoch) return
const values = plan.usages
.filter((u) => u.usageStatus !== 'released')
.flatMap((u) =>
(u.items || []).map((i: any) => ({
u,
i,
source: `${i.sourceStopType}:${i.sourceStopProductId}`,
key: `${u.certType}:${i.sourceStopType}:${i.sourceStopProductId}`
}))
)
const foreign = new Set(
values.filter((v) => v.i.sourceUnit !== v.u.quantityUnit).map((v) => v.key)
)
rows.value = values
.filter((v) => foreign.has(v.key))
.map(({ u, i, source }) => ({
key: i.id,
kind: u.certType,
certNo: u.certNoSnapshot,
productName:
plan.sourceOptions.find((s) => s.sourceStopProductId === i.sourceStopProductId)
?.productName || '',
sourceLabel: `${i.sourceStopType === 'load' ? '装货' : '送货'} ${i.sourceStopProductId.slice(-6)}`,
sourceUnit: i.sourceUnit,
permitUnit: u.quantityUnit,
plannedSource: i.allocatedSourceQty,
plannedPermit: i.plannedCertQty,
seq: i.allocationSeq,
value: {
permitKind: u.certType,
permitId: u.certId,
sourceId: source,
sourceQuantity: '',
permitQuantity: '',
note: ''
}
}))
adjustment.value = adjust
reason.value = ''
sourceNote.value = ''
evidenceUrls.value = ''
visible.value = true
return new Promise((r) => (resolve = r))
}
function cancel() {
epoch++
supplementDialog.value?.invalidateSession()
visible.value = false
resolve?.(undefined)
resolve = undefined
}
async function chooseSupplement() {
if (choosing.value) return
const current = epoch
choosing.value = true
try {
const value = await supplementDialog.value?.open(targetPlanId.value, false, {}, true)
if (current === epoch && visible.value && value) supplementConfiguration.value = value
} finally {
if (current === epoch) choosing.value = false
}
}
function accept() {
if (choosing.value) return
if (allowSupplement.value && !supplementConfiguration.value) {
ElMessage.warning('请先选择补充证件并核对条件')
return
}
const decimal = /^\d{1,12}(\.\d{1,6})?$/
if (
rows.value.some(
(r) =>
!decimal.test(String(r.value.sourceQuantity)) ||
!decimal.test(String(r.value.permitQuantity)) ||
!r.value.note.trim()
)
) {
ElMessage.warning('请逐行填写非负实际量和换算依据,最多六位小数')
return
}
if (
(adjustment.value || allowSupplement.value) &&
(!reason.value.trim() || (!sourceNote.value.trim() && !evidenceUrls.value))
) {
ElMessage.warning('请填写更正理由和依据')
return
}
if (attachments.value?.hasUploading()) {
ElMessage.warning('请等待凭据上传完成')
return
}
resolve?.({
quotaAllowSupplement: allowSupplement.value,
quotaConfiguration: allowSupplement.value ? supplementConfiguration.value : undefined,
quotaManualActuals: rows.value.map((r) => ({ ...r.value })),
quotaReason: reason.value,
quotaSourceNote: sourceNote.value,
quotaEvidenceUrls: evidenceUrls.value
})
resolve = undefined
visible.value = false
}
defineExpose({ open, cancel })
const user = useUserStore()
watch(
() => JSON.stringify([user.accessToken, user.getUserInfo]),
() => cancel(),
{ flush: 'sync' }
)
onBeforeUnmount(() => cancel())
</script>