feat: 保存运输证件、报销付款和开发流程的当前实现。

补齐证书齐备、证件折算、移动用证和合同绑定,并带上报销批量发放、付款备注以及个人开发流程升级,便于继续讨论已安排计划的调整规则。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-04 21:42:33 +08:00
1 parent 7325a0aa52
commit 8e9536332a
202 files changed
+19200 -2054

No files matched your search

+36 -29
View File
@@ -24,7 +24,7 @@
import { toggleTransition } from './utils/ui/animation'
import { checkStorageCompatibility } from './utils/storage'
import { initializeTheme } from './hooks/core/useTheme'
import { refreshFilterCollapse, setupFilterCollapseObserver } from './utils/ui/filter-collapse'
import { refreshFilterCollapse } from './utils/ui/filter-collapse'
import { setupListTableRowSelect } from './utils/ui/list-table-row-select'
const userStore = useUserStore()
@@ -35,9 +35,9 @@
en: en
}
let buttonIconObserver: MutationObserver | null = null
let panelTitleObserver: MutationObserver | null = null
let filterCollapseObserver: MutationObserver | null = null
let automaticUiObserver: MutationObserver | null = null
let automaticUiRefreshQueued = false
let automaticUiFrame = 0
let teardownListTableRowSelect: (() => void) | null = null
const iconClassByText: Array<[RegExp, string]> = [
@@ -56,11 +56,12 @@
const refreshButtonAutoIcons = () => {
const selectors = [
'.page-container .el-button:not(.is-circle):not(.el-button--text):not(:has(.el-icon))',
'.console-container .el-button:not(.is-circle):not(.el-button--text):not(:has(.el-icon))'
'.page-container .el-button:not(.is-circle):not(.el-button--text)',
'.console-container .el-button:not(.is-circle):not(.el-button--text)'
]
const buttons = document.querySelectorAll<HTMLElement>(selectors.join(','))
buttons.forEach((button) => {
if (button.querySelector('.el-icon')) return
autoIconClassList.forEach((className) => button.classList.remove(className))
// 区域/状态 Tab 仅展示文案,不参与按钮自动图标
if (button.classList.contains('region-tab-btn')) return
@@ -110,7 +111,7 @@
const panelTitleClassList = [...panelTitleIconByText.map(([, cls]) => cls), 'auto-title-list']
const panelTitleBarClass = 'title-bar-heading'
const panelTitleBarTextRules = [/^(购买证与运输证|合法使用证明|计划用证|证件建档|合同用证|证件用量|计划段次用证|合同证件与额度)$/]
const panelTitleBarTextRules = [/^(购买证与运输证|合法使用证明|计划用证|证件建档|合同用证|证件用量|计划段次用证|证书齐备|合同证件与额度)$/]
const panelTitleHeadingSelector =
'.page-container .panel-top h2, .page-container .panel-top h3, .page-container .storage-content-header h3, .page-container .storage-aside__head h2, .page-container .user-dept-aside__head h2, .console-container .panel-top h2'
@@ -156,37 +157,43 @@
checkStorageCompatibility()
toggleTransition(false)
systemUpgrade()
const refreshAutomaticUi = () => {
automaticUiObserver?.disconnect()
try {
refreshButtonAutoIcons()
refreshPanelTitleIcons()
refreshFilterCollapse()
} finally {
automaticUiObserver?.observe(document.body, { childList: true, subtree: true })
}
}
const scheduleAutomaticUiRefresh = () => {
if (automaticUiRefreshQueued) return
automaticUiRefreshQueued = true
automaticUiFrame = requestAnimationFrame(() => {
automaticUiRefreshQueued = false
refreshAutomaticUi()
})
}
refreshButtonAutoIcons()
refreshPanelTitleIcons()
refreshFilterCollapse()
buttonIconObserver = new MutationObserver(() => {
refreshButtonAutoIcons()
automaticUiObserver = new MutationObserver(() => {
scheduleAutomaticUiRefresh()
})
buttonIconObserver.observe(document.body, {
childList: true,
subtree: true
})
panelTitleObserver = new MutationObserver(() => {
refreshPanelTitleIcons()
})
panelTitleObserver.observe(document.body, {
childList: true,
subtree: true
})
filterCollapseObserver = setupFilterCollapseObserver()
automaticUiObserver.observe(document.body, { childList: true, subtree: true })
teardownListTableRowSelect = setupListTableRowSelect()
})
onBeforeUnmount(() => {
buttonIconObserver?.disconnect()
buttonIconObserver = null
panelTitleObserver?.disconnect()
panelTitleObserver = null
filterCollapseObserver?.disconnect()
filterCollapseObserver = null
if (automaticUiFrame) cancelAnimationFrame(automaticUiFrame)
automaticUiObserver?.disconnect()
automaticUiObserver = null
automaticUiRefreshQueued = false
automaticUiFrame = 0
teardownListTableRowSelect?.()
teardownListTableRowSelect = null
})
+14
View File
@@ -267,6 +267,13 @@ export const paymentApi = {
pay(id: BxId, data?: { payRemark?: string; actualAmount?: number }) {
return bxRequest.post(`/payments/${id}/pay`, data)
},
batchPay(data: {
payRemark?: string
items: Array<{ id: BxId; actualAmount: number }>
attachmentIds?: Array<BxId>
}) {
return bxRequest.post('/payments/batch-pay', data)
},
offset(id: BxId, data: { advanceId: BxId; offsetAmount: number; remark?: string }) {
return bxRequest.post(`/payments/${id}/offset`, data)
},
@@ -304,6 +311,13 @@ export const paymentApi = {
issueAdvance(advanceId: BxId, data: { issueRemark?: string; actualAmount?: number }) {
return bxRequest.post(`/payments/advance/${advanceId}/issue`, data)
},
batchIssueAdvance(data: {
issueRemark?: string
items: Array<{ id: BxId; actualAmount: number }>
attachmentIds?: Array<BxId>
}) {
return bxRequest.post('/payments/advance/batch-issue', data)
},
advanceOffsetRecords(advanceId: BxId) {
return bxRequest.get(`/payments/advance/${advanceId}/offset-records`)
},
+8 -5
View File
@@ -740,7 +740,7 @@ export interface PlanCreateFullPayload {
followUserId?: string
followUserName?: string
remark?: string
saveMode?: 'draft' | 'formal'
saveMode?: 'draft' | 'formal' | 'rearrange'
supplierContracts?: PlanContractLink[]
demanderContracts?: PlanContractLink[]
load?: PlanLoad
@@ -1043,8 +1043,10 @@ export const planApi = {
request.post<Plan>(`/transport/plan/${id}/force-follow-status`, { followStatus }),
getArrangeInfo: (id: string) =>
request.get<PlanArrangeInfo>(`/transport/plan/${id}/arrange-info`),
archive: (id: string, data?: PlanArchiveBody) =>
request.post<Plan>(`/transport/plan/${id}/archive`, data),
archive: (id: string, data?: PlanArchiveBody, config?: { skipErrorMessage?: boolean }) =>
request.post<Plan>(`/transport/plan/${id}/archive`, data, config),
markQuotaCertReady: (id: string) =>
request.post(`/transport/plan/${id}/quota-cert-ready`, {}, { skipErrorMessage: true }),
archiveDraft: (id: string, data: PlanArchiveBody) =>
request.post<Plan>(`/transport/plan/${id}/archive-draft`, data),
updateDriverFeedback: (id: string, data: PlanDriverFeedbackUpdateBody) =>
@@ -2288,9 +2290,10 @@ export const vehicleFuelRegisterApi = {
{},
{ params }
),
plateMonthSummary: () =>
plateMonthSummary: (month?: string) =>
request.get<VehicleFuelPlateMonthSummaryResponse>(
'/transport/vehicle-fuel-register/plate-month-summary'
'/transport/vehicle-fuel-register/plate-month-summary',
{ params: month ? { month } : undefined }
)
}
+131 -10
View File
@@ -20,7 +20,7 @@ export interface CertBody {
validUseText: string
entryMode: 'manual' | 'image_parse'
attachmentUrls?: string | null
status?: 'draft' | 'suspended' | 'void'
status?: 'draft' | 'suspended' | 'closed' | 'void'
remark?: string | null
orderNum?: number | null
buyerName?: string | null
@@ -49,7 +49,7 @@ export interface CertBody {
}
export interface QuotaCert extends Omit<CertBody, 'status'> {
id: string
status: 'draft' | 'active' | 'suspended' | 'void'
status: 'draft' | 'active' | 'suspended' | 'closed' | 'void'
bindingsEditable?: boolean
referencesEditable?: boolean
revision: number
@@ -60,6 +60,7 @@ export interface QuotaCert extends Omit<CertBody, 'status'> {
openingConfirmed: boolean
usagePolicy: 'once' | 'multiple' | 'needs_confirmation'
createTime?: string
certType?: CertType
}
export interface ScopeProduct {
id?: string
@@ -83,14 +84,24 @@ export interface ContractOption {
contractNo: string
contractName: string
contractType?: string
customerId?: string
customerName?: string
status?: string
signDate?: string | null
productSummary?: string
}
export interface ContractProduct {
id: string
productId: string
productName: string
productNo?: string
categoryName?: string
brandName?: string
model?: string
unit?: string
quantity?: string | number
packageSpec?: string
deliveryMethod?: string
}
export interface LegalDocument {
id: string
@@ -141,13 +152,22 @@ export const quotaCertApi = {
verify: (kind: CertType, id: string, body: { operationId: string; reason: string }) =>
request.post(`${base}/${kind}/${id}/verify`, body).then(pickBxData<QuotaCert>),
recognize: (kind: CertType, attachmentUrl: string) =>
request.post(`${base}/${kind}/recognize`, { attachmentUrl }, { timeout: 90000 }).then(
pickBxData<{
candidates: Partial<CertBody>
invalidFields: Record<string, string>
requiresConfirmation: boolean
}>
),
request
.post(
`${base}/${kind}/recognize`,
{ attachmentUrl },
{
timeout: 90000,
skipErrorMessage: true
}
)
.then(
pickBxData<{
candidates: Partial<CertBody>
invalidFields: Record<string, string>
requiresConfirmation: boolean
}>
),
contracts: (keyword = '') =>
request.get(`${base}/contracts`, { params: { keyword } }).then(pickBxData<ContractOption[]>),
products: (id: string) =>
@@ -184,11 +204,17 @@ export interface StopLegalDocument {
planNo: string
planDate?: string
licensePlate?: string
productNames?: string
supplierName?: string
customerName?: string
followStatus?: string
transportStatus: string
archiveStatus: string
requiredCount: number
uploadedCount: number
documentStatus: 'pending' | 'uploaded' | 'not_required'
legalUseCertUrl?: string | null
planProductIds?: string[]
items: StopLegalDocumentItem[]
legacyProducts: {
id: string
@@ -202,6 +228,14 @@ export const legalDocumentApi = {
listStops: (params: {
keyword?: string
planNo?: string
planDateFrom?: string
planDateTo?: string
licensePlate?: string
productNames?: string
supplierName?: string
customerName?: string
followStatusIn?: string
progress?: string
status?: 'pending' | 'uploaded'
contractId?: string
page?: number
@@ -244,6 +278,7 @@ export interface QuotaSourceOption {
sourceStopProductId: string
planProductId: string
productName: string
productNo?: string
model?: string
quantity: string | number
unit: string
@@ -288,6 +323,8 @@ export interface PlanQuota {
planNo: string
licensePlate?: string
canSaveConfiguration?: boolean
arrangeBlockMessage?: string
quotaCertWaived?: boolean
configuration: Partial<QuotaConfiguration>
sourceOptions: QuotaSourceOption[]
usages: Record<string, any>[]
@@ -317,8 +354,54 @@ export interface QuotaPreview extends Partial<QuotaContext> {
purchaseAllocations?: Record<string, any>[]
transportAllocations?: Record<string, any>[]
}
export interface CertReadyPlan {
id: string
planNo: string
planDate?: string | null
licensePlate?: string | null
supplierName?: string | null
customerName?: string | null
productNames?: string
followStatus?: string | null
quotaCertWaived: boolean
quotaCertWaivedByName?: string | null
quotaCertWaivedTime?: string | null
}
export const certReadyApi = {
list: (params: {
keyword?: string
waived?: string
planNo?: string
planDateFrom?: string
planDateTo?: string
licensePlate?: string
productNames?: string
supplierName?: string
customerName?: string
followStatusIn?: string
quotaCertWaivedIn?: string
quotaCertWaivedByName?: string
quotaCertWaivedTimeFrom?: string
quotaCertWaivedTimeTo?: string
page: number
pageSize: number
}) =>
request
.get(`${base}/plans/cert-ready`, { params })
.then(pickBxData<{ total: number; list: CertReadyPlan[] }>),
mark: (id: string) =>
request.post(`${base}/plans/${id}/cert-ready`).then(pickBxData<CertReadyPlan>)
}
export const planQuotaApi = {
get: (id: string) => request.get(`${base}/plans/${id}/usage`).then(pickBxData<PlanQuota>),
get: (id: string, arrangeCheck = false) =>
request
.get(
`${base}/plans/${id}/usage`,
arrangeCheck ? { params: { arrangeCheck: true } } : undefined
)
.then(pickBxData<PlanQuota>),
context: (id: string, body: QuotaConfiguration & QuotaPreviewVehicle) =>
request.post(`${base}/plans/${id}/context`, body).then(pickBxData<QuotaContext>),
preview: (id: string, body: QuotaConfiguration & QuotaPreviewVehicle) =>
@@ -380,6 +463,9 @@ export interface CertificateStatisticsSummary {
status: string
validFrom: string | null
validTo: string | null
salePartyName?: string | null
buyPartyName?: string | null
validUseText?: string | null
}
export interface StatisticsProduct {
id: string
@@ -399,6 +485,7 @@ export interface StatisticsBinding {
bindingId: string | null
linkStatus: string | null
scopeRevision: number | null
referenced?: boolean
contractReservedQty: QuotaQuantity
contractUsedQty: QuotaQuantity
products: StatisticsProduct[]
@@ -435,11 +522,45 @@ export interface CertificateStatistics extends CertificateStatisticsSummary {
}
export interface StatisticsQuery {
contractNo?: string
contractName?: string
contractTypeIn?: string
certCountOp?: string
certCount?: string
certCountMin?: string
certCountMax?: string
certNo?: string
keyword?: string
page?: number
pageSize?: number
certType?: CertType
certTypeIn?: string
productNameOnCert?: string
quantityUnitIn?: string
statusIn?: string
validFromFrom?: string
validFromTo?: string
validToFrom?: string
validToTo?: string
totalQtyOp?: string
totalQty?: string
totalQtyMin?: string
totalQtyMax?: string
reservedQtyOp?: string
reservedQty?: string
reservedQtyMin?: string
reservedQtyMax?: string
usedQtyOp?: string
usedQty?: string
usedQtyMin?: string
usedQtyMax?: string
availableQtyOp?: string
availableQty?: string
availableQtyMin?: string
availableQtyMax?: string
salePartyName?: string
buyPartyName?: string
validUseText?: string
expiryAlertIn?: string
}
export const quotaStatisticsApi = {
contracts: (params: StatisticsQuery) =>
@@ -175,8 +175,9 @@
</div>
</div>
</div>
<slot name="beside" />
</div>
<span v-if="!disabled && !compact" class="upload-hint">{{ hint }}</span>
<span v-if="hint && !disabled && !compact" class="upload-hint">{{ hint }}</span>
<el-dialog
v-model="previewVisible"
@@ -1552,8 +1552,8 @@
const archiveBody: PlanArchiveBody = JSON.parse(JSON.stringify(buildArchiveBody()))
submitLoading.value = true
try {
if (productRows.value.some(p => Number(p.isToxic) === 1)) {
const value = await quotaSettlementDialog.value?.open(targetId, isAdjustMode.value)
if (isAdjustMode.value && productRows.value.some(p => Number(p.isToxic) === 1)) {
const value = await quotaSettlementDialog.value?.open(targetId, true)
if (!current() || !value) return
Object.assign(archiveBody, value)
}
@@ -1566,13 +1566,62 @@
innerVisible.value = false
} catch (e: unknown) {
if (!current() || (e as { cancelled?: boolean }).cancelled) return
const message = e instanceof Error ? e.message : isAdjustMode.value ? '保存失败' : '归档失败'
const message = archiveFailureMessage(e, isAdjustMode.value ? '保存失败' : '归档失败')
if (message.includes('不能归档')) {
await showArchiveQuotaBlockDialog(message)
return
}
ElMessage.error(message)
} finally {
if (session === archiveSession) submitLoading.value = false
}
}
function archiveFailureMessage(error: unknown, fallback: string) {
const detail = (error as { response?: { data?: { detail?: unknown; msg?: unknown } } })?.response?.data
const raw = detail?.detail ?? detail?.msg
if (typeof raw === 'string' && raw.trim()) return raw
if (error instanceof Error && error.message && !error.message.startsWith('Request failed')) return error.message
return fallback
}
function escapeArchiveBlockText(value: string) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
async function showArchiveQuotaBlockDialog(message: string, title = '不能归档') {
const html = `<p class="pl-arrange-block-text">${escapeArchiveBlockText(message)}</p>`
if (title !== '用证没有完成') {
await ElMessageBox.alert(html, title, {
type: 'warning',
confirmButtonText: '知道了',
dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false
}).catch(() => undefined)
return undefined
}
const readyHtml = `${html}<p class="pl-arrange-block-text">如果购买证、运输证还没上传,可以标记证书齐备。标记后这次归档不再校验,也不扣减这两证的额度。</p>`
try {
await ElMessageBox.confirm(readyHtml, title, {
type: 'warning',
confirmButtonText: '证书齐备',
cancelButtonText: '知道了',
dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false,
distinguishCancelAndClose: true
})
return 'ready' as const
} catch {
return undefined
}
}
function applyArchiveOverageHighlight(items: Array<Record<string, unknown>>) {
const ids = new Set(
items.map((item) => String(item.stopProductId || '').trim()).filter(Boolean)
@@ -1593,14 +1642,24 @@
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 })
const response = await planApi.archive(
targetId,
{ ...archiveBody, operationId: quotaArchiveAttempt.id },
{ skipErrorMessage: true }
)
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 message = saved.quotaSettlementError
const choice = await showArchiveQuotaBlockDialog(message, '用证没有完成')
if (choice === 'ready' && current()) {
await planApi.markQuotaCertReady(targetId)
if (!current()) return
await submitArchiveWithOverageConfirm(targetId, frozenBody, current, confirmOverage)
return
}
const error = new Error(message) as Error & { cancelled?: boolean }
error.cancelled = true
throw error
@@ -1796,6 +1855,20 @@
</style>
<style lang="scss">
.el-message-box.pl-arrange-block-msgbox {
width: 520px;
max-width: 92vw;
.pl-arrange-block-text {
margin: 0;
color: #c2410c;
font-size: 15px;
font-weight: 600;
line-height: 1.7;
white-space: pre-wrap;
}
}
.el-dialog.pl-plan-archive-dialog.dialog-form-layout {
width: min(2400px, calc(100vw - 24px)) !important;
max-width: min(2400px, calc(100vw - 24px));
@@ -1,6 +1,5 @@
<!-- 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">
@@ -616,8 +615,6 @@
</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)
@@ -664,6 +661,8 @@
type Vehicle,
type VehiclePersonnelRow
} from '@/api/pl'
import { planQuotaApi, type QuotaSourceOption } from '@/api/pl/quota-cert'
import { toxicArrangeBlockMessage } from '@/utils/pl-quota-cert-waiver'
import { arrangeBlockedMessage, isExecutionStarted } from '@/utils/pl-plan-action-guards'
import {
usePlRemoteCarrierOptions,
@@ -2597,10 +2596,46 @@
return `${driver.personnelName}${phone}${suffix}`
}
function escapeArrangeBlockText(value: string) {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
async function showArrangeBlockDialog(message: string) {
const html = `<p class="pl-arrange-block-text">${escapeArrangeBlockText(message)}</p>`
await ElMessageBox.alert(html, '无法安排运输', {
type: 'warning',
confirmButtonText: '知道了',
dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false
}).catch(() => undefined)
}
function toxicContractCertBindingMessage(rows: QuotaSourceOption[]) {
const missing = new Map<string, string>()
for (const row of rows) {
if (isPlInternalCustomerName(row.partyName)) continue
const certificates = row.certificates || []
const ready =
certificates.some((cert) => cert.certType === 'purchase') &&
certificates.some((cert) => cert.certType === 'transport')
if (ready) continue
const key = row.contractId || row.contractNo || row.productName || row.sourceStopProductId
missing.set(key, row.contractNo || '未编号合同')
}
if (!missing.size) return ''
return `合同${[...missing.values()].join('、')}尚未绑定购买证和运输证,请先到合同中绑定后再安排运输`
}
async function performArrangeAfterSave(
planId: string,
generation = pageLoadGeneration
): Promise<boolean> {
generation = pageLoadGeneration,
options?: { skipConfirm?: boolean }
): Promise<boolean | 'cert-binding'> {
if (!isPageSubmitCurrent(generation)) return false
const arrangePresenter = createArrangePresenter(generation)
const detailRes = await planApi.get(planId)
@@ -2627,33 +2662,44 @@
const rawProducts = Array.isArray(plan.products) ? plan.products : []
const enrichedProducts = await enrichPlanProductsHazardFromCrm(rawProducts)
if (!isPageSubmitCurrent(generation)) 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)
let historical = { hasHistoricalDibang: false, hasHistoricalSiteLinks: false }
if (isRearrange) {
historical = await loadArrangeHistoricalFlags(planId)
if (enrichedProducts.some((product) => Number(product.isToxic) === 1)) {
const quota = await planQuotaApi.get(planId, true)
if (!isPageSubmitCurrent(generation)) return false
const rows = (quota?.stopProducts || []).filter((row) => row.isToxic)
const unbound = rows.length
? toxicContractCertBindingMessage(rows)
: '易制毒产品尚未绑定购买证和运输证,请先到合同中绑定后再安排运输'
const bound = toxicArrangeBlockMessage(quota, unbound)
if (bound) {
if (isPageVariant.value) await arrangePresenter({ title: '无法安排运输', message: bound })
else await showArrangeBlockDialog(bound)
return 'cert-binding'
}
}
try {
await confirmBeforePlanArrange({
isRearrange,
plan,
hasHistoricalDibang: historical.hasHistoricalDibang,
hasHistoricalSiteLinks: historical.hasHistoricalSiteLinks,
hasAnyDibangSelected: dibangSelected,
presenter: isPageVariant.value ? arrangePresenter : undefined
})
if (!isPageSubmitCurrent(generation)) return false
} catch (error) {
if (!isPageSubmitCurrent(generation)) return false
if (error === 'cancel') return false
throw error
const isRearrange = plan.transportStatus === 'arranged'
if (!options?.skipConfirm) {
const dibangSelected = planHasAnyDibangSelected(plan, loadForm.value, deliveryForms.value)
let historical = { hasHistoricalDibang: false, hasHistoricalSiteLinks: false }
if (isRearrange) {
historical = await loadArrangeHistoricalFlags(planId)
if (!isPageSubmitCurrent(generation)) return false
}
try {
await confirmBeforePlanArrange({
isRearrange,
plan,
hasHistoricalDibang: historical.hasHistoricalDibang,
hasHistoricalSiteLinks: historical.hasHistoricalSiteLinks,
hasAnyDibangSelected: dibangSelected,
presenter: isPageVariant.value ? arrangePresenter : undefined
})
if (!isPageSubmitCurrent(generation)) return false
} catch (error) {
if (!isPageSubmitCurrent(generation)) return false
if (error === 'cancel') return false
throw error
}
}
const payload = buildArrangePayloadFromPlanForm({
@@ -2673,10 +2719,14 @@
getUnitLabel
})
const signature = JSON.stringify({planId, payload, quotaConfiguration})
const signature = JSON.stringify({ planId, payload })
if (signature !== arrangeAttempt.signature) arrangeAttempt = { signature, id: crypto.randomUUID() }
try {
await submitPlanArrange(planId, { ...payload, operationId: arrangeAttempt.id, quotaConfiguration }, isPageVariant.value ? arrangePresenter : undefined)
await submitPlanArrange(
planId,
{ ...payload, operationId: arrangeAttempt.id },
isPageVariant.value ? arrangePresenter : undefined
)
if (!isPageSubmitCurrent(generation)) return false
} catch {
return false
@@ -3427,7 +3477,44 @@
mirrorPlanProductsFromLoad()
const commonPayload = {
...buildPlanCommonPayload({ allowClearTransport: isEdit.value }),
saveMode: 'formal' as const
saveMode: (
mode === 'rearrange' ||
(mode === 'saveAndArrange' && loadedTransportStatus.value === 'arranged')
? 'rearrange'
: 'formal'
) as 'formal' | 'rearrange'
}
if (commonPayload.saveMode === 'rearrange') {
const current = loadedPlanSnapshot.value
if (!current?.id) {
ElMessage.error('计划尚未加载完成,无法调整运输')
return
}
if (isExecutionStarted(current)) {
ElMessage.warning(arrangeBlockedMessage(current))
return
}
const historical = await loadArrangeHistoricalFlags(current.id)
if (!isPageSubmitCurrent(generation)) return
try {
await confirmBeforePlanArrange({
isRearrange: true,
plan: current,
hasHistoricalDibang: historical.hasHistoricalDibang,
hasHistoricalSiteLinks: historical.hasHistoricalSiteLinks,
hasAnyDibangSelected: planHasAnyDibangSelected(
current,
loadForm.value,
deliveryForms.value
),
presenter: isPageVariant.value ? createArrangePresenter(generation) : undefined
})
} catch (error) {
if (!isPageSubmitCurrent(generation)) return
if (error === 'cancel') return
throw error
}
if (!isPageSubmitCurrent(generation)) return
}
let planId = props.planId || ''
const wasCreate = !isEdit.value
@@ -3463,15 +3550,17 @@
if ((mode === 'saveAndArrange' || mode === 'rearrange') && planId) {
if (isPageVariant.value) mobileSavedPlanId.value = planId
const arranged = await performArrangeAfterSave(planId, generation)
const arranged = await performArrangeAfterSave(planId, generation, {
skipConfirm: commonPayload.saveMode === 'rearrange'
})
if (!isPageSubmitCurrent(generation)) return
if (!arranged) {
if (arranged !== true) {
// 计划已落库;关闭新建窗,避免停留在创建态再次点击又生成一张
if (wasCreate) {
if (arranged !== 'cert-binding' && wasCreate) {
ElMessage.warning(
'计划已创建成功,但未能安排运输。请至列表查看;若因危化证未就绪,请先完成【危化品证上传】后再安排。'
)
} else {
} else if (arranged !== 'cert-binding') {
ElMessage.warning('计划已保存,但未能安排运输。请稍后在列表中重试安排。')
}
innerVisible.value = false
@@ -4354,6 +4443,19 @@
</style>
<style lang="scss">
.el-message-box.pl-arrange-block-msgbox {
width: 520px;
max-width: 92vw;
.pl-arrange-block-text {
margin: 0;
color: #c2410c;
font-size: 15px;
font-weight: 600;
line-height: 1.7;
}
}
.el-dialog.pl-contract-line-picker-dialog {
.pkg-spec-wrap-col .cell {
white-space: normal;
@@ -2,34 +2,130 @@
<el-dialog
v-model="visible"
:title="`计划用证 · ${plan?.planNo || ''}`"
width="1080px"
width="1240px"
class="dialog-form-layout quota-dialog"
align-center
append-to-body
: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"
<div class="quota-meta">
<span>当前车号</span>
<strong>{{ plan.licensePlate || '待安排' }}</strong>
</div>
<p v-if="viewOnly && plan.canSaveConfiguration === false" class="quota-note"
>已安排计划请从调整运输提交用证变更;已归档计划仅查看占用。</p
>
<section class="view-section">
<h3>{{ isPerStop ? '1. 全部装送段用证需求' : '1. 原口径:唯一计量侧与装送配对' }}</h3>
<el-table v-if="isPerStop" :data="measured" stripe>
<template v-if="viewOnly">
<h3 class="dialog-section-title">全部装送段用证需求</h3>
<div class="quota-table-wrap">
<el-table class="quota-table" :data="plan.sourceOptions" stripe border>
<el-table-column label="段产品" min-width="220"
><template #default="{ row }">{{
sourceLabel(`${row.sourceStopType}:${row.sourceStopProductId}`, plan.sourceOptions)
}}</template></el-table-column
>
<el-table-column prop="contractNo" label="关联合同" min-width="170"
><template #default="{ row }">{{ row.contractNo || '未关联合同' }}</template></el-table-column
>
<el-table-column prop="partyName" label="装送单位" min-width="180" />
<el-table-column label="需用量" min-width="120"
><template #default="{ row }"
>{{ qtyText(row.quantity) }} {{ unitText(row.unit) }}</template
></el-table-column
>
<el-table-column label="购买证" min-width="210"
><template #default="{ row }"
><div class="cert-tags">
<el-tag
v-for="cert in certsOf(row, 'purchase')"
:key="cert.certId"
class="cert-face-tag"
effect="plain"
@click="showCertFace(cert)"
>{{ cert.certNo }}</el-tag
>
<el-tag v-if="!certsOf(row, 'purchase').length" type="info" effect="plain"
>未绑定</el-tag
>
</div></template
></el-table-column
>
<el-table-column label="运输证" min-width="210"
><template #default="{ row }"
><div class="cert-tags">
<el-tag
v-for="cert in certsOf(row, 'transport')"
:key="cert.certId"
class="cert-face-tag"
effect="plain"
@click="showCertFace(cert)"
>{{ cert.certNo }}</el-tag
>
<el-tag v-if="!certsOf(row, 'transport').length" type="info" effect="plain"
>未绑定</el-tag
>
</div></template
></el-table-column
>
</el-table>
</div>
<p v-if="!groups.length" class="quota-note">当前计划没有易制毒产品,无需购买证、运输证额度。</p>
<section v-if="faceTabs.length" class="quota-face">
<h3 class="dialog-section-title">关联证件证面</h3>
<el-tabs v-model="faceTab" class="quota-face-tabs">
<el-tab-pane v-for="tab in faceTabs" :key="tab.key" :label="tab.label" :name="tab.key">
<p v-if="!tab.cert" class="quota-note">没有读到这张证的证面档案。</p>
<template v-else>
<section
v-for="(group, groupIndex) in faceGroups(tab.cert, tab.kind)"
:key="groupIndex"
class="quota-face-group"
>
<h4 v-if="group.title">{{ group.title }}</h4>
<ViewKvTable :fields="group.fields" mode="dual" />
</section>
<section v-if="tab.kind === 'transport'" class="quota-face-group">
<h4>证面引用</h4>
<el-table
v-if="tab.cert.purchaseRefs?.length"
:data="tab.cert.purchaseRefs"
stripe
border
>
<el-table-column label="引用类型" min-width="160">
<template #default="{ row }">{{
refLabels[row.referenceType] || row.referenceType || '—'
}}</template>
</el-table-column>
<el-table-column prop="referenceNo" label="购买许可/备案/出口许可证号" min-width="240" />
<el-table-column label="对应购买证" min-width="180">
<template #default="{ row }">{{
purchases.find((item) => item.id === row.purchaseCertId)?.certNo ||
(row.purchaseCertId ? '无查看权限或已失效' : '未关联')
}}</template>
</el-table-column>
</el-table>
<p v-else class="quota-note">没有证面引用。</p>
</section>
<section v-if="tab.cert.attachmentUrls" class="quota-face-group">
<h4>证件附件</h4>
<AttachmentUploadField :model-value="tab.cert.attachmentUrls" disabled />
</section>
</template>
</el-tab-pane>
</el-tabs>
</section>
</template>
<section v-else class="view-section">
<h3 class="dialog-section-title">{{
isPerStop ? '全部装送段用证需求' : '原口径:唯一计量侧与装送配对'
}}</h3>
<el-table v-if="isPerStop" :data="measured" stripe border>
<el-table-column label="段产品" min-width="200"
><template #default="{ row }">{{
sourceLabel(`${row.sourceStopType}:${row.sourceStopProductId}`, measured)
@@ -39,9 +135,19 @@
<el-table-column prop="partyName" label="单位" min-width="160" />
<el-table-column label="需用量" min-width="120"
><template #default="{ row }"
>{{ row.quantity }} {{ row.unit }}</template
>{{ qtyText(row.quantity) }} {{ unitText(row.unit) }}</template
></el-table-column
>
<el-table-column v-if="viewOnly" label="购买证" min-width="180"
><template #default="{ row }">{{
certText(row, 'purchase')
}}</template></el-table-column
>
<el-table-column v-if="viewOnly" label="运输证" min-width="180"
><template #default="{ row }">{{
certText(row, 'transport')
}}</template></el-table-column
>
</el-table>
<p v-if="!groups.length">当前计划没有易制毒产品,无需购买证、运输证额度。</p>
<div v-for="group in isPerStop ? [] : groups" :key="group.id" class="view-section">
@@ -60,8 +166,13 @@
class="view-section"
>
<p
>{{ source.partyName || '未填写单位' }} · {{ source.quantity }} {{ source.unit }} ·
{{ source.model }}</p
>{{ source.partyName || '未填写单位' }} · {{ qtyText(source.quantity) }}
{{ unitText(source.unit) }} · {{ source.model }}</p
>
<p v-if="viewOnly"
>购买证:{{ certText(source, 'purchase') }};运输证:{{
certText(source, 'transport')
}}</p
>
<el-select
v-if="opposite(group).length"
@@ -76,13 +187,60 @@
v-for="other in opposite(group)"
:key="other.sourceStopProductId"
:value="other.sourceStopProductId"
:label="`${other.partyName || '未填写单位'} · ${other.quantity} ${other.unit} · ${other.productName}`"
:label="`${other.partyName || '未填写单位'} · ${qtyText(other.quantity)} ${unitText(other.unit)} · ${other.productName}`"
/>
</el-select>
</div>
</div>
</section>
<section v-if="groups.length" class="view-section">
<section v-if="viewOnly && conversions.length" class="conversion-section">
<h3 class="dialog-section-title">单位不一致,填写换算系数</h3>
<p class="quota-note"
>只列出计划单位和证面单位不同的段次。系数表示 1 个计划单位等于多少证面单位,计划数量保持不变。</p
>
<article v-for="group in conversionGroups" :key="group.sourceId" class="conversion-group">
<header class="conversion-group-head">
<h4>{{ sourceLabel(group.sourceId, measured) }}</h4>
<p
>计划数量 {{ qtyText(group.source.quantity) }}
{{ unitText(group.source.unit) }}</p
>
</header>
<div class="conversion-grid">
<section v-for="row in group.rows" :key="conversionKey(row)" class="conversion-card">
<div class="conversion-card-head">
<el-tag
size="small"
effect="plain"
:type="row.cert.certType === 'purchase' ? 'success' : 'primary'"
>{{ row.cert.certType === 'purchase' ? '购买证' : '运输证' }}</el-tag
>
<strong>{{ row.cert.certNo }}</strong>
</div>
<label>换算系数</label>
<div class="conversion-factor">
<span>1 {{ unitText(row.source.unit) }} =</span>
<el-input
v-model="coefficients[conversionKey(row)]"
:disabled="busy || plan.canSaveConfiguration === false"
placeholder="系数"
/>
<span>{{ unitText(row.cert.quantityUnit) }}</span>
</div>
<p class="conversion-preview" :class="{ 'is-empty': !conversionPreview(row) }">{{
conversionPreview(row) ? `证面数量 ${conversionPreview(row)}` : '填写系数后显示证面数量'
}}</p>
<label>换算依据</label>
<el-input
v-model="conversionInput(row).note"
:disabled="busy || plan.canSaveConfiguration === false"
placeholder="选填"
/>
</section>
</div>
</article>
</section>
<section v-if="groups.length && !viewOnly" class="view-section">
<h3>2. 选择合同产品适用的证件</h3>
<el-form label-position="top" :disabled="busy"
><div class="form-grid-2">
@@ -118,9 +276,9 @@
<div v-for="(source, i) in context.sources" :key="i" class="view-section">
<p
>{{ source.source_stop_type === 'load' ? '装货' : '送货' }}计量:{{
source.quantity
qtyText(source.quantity)
}}
{{ source.unit }};车号 {{ source.snapshot.vehicle || '未填写' }}</p
{{ unitText(source.unit) }};车号 {{ source.snapshot.vehicle || '未填写' }}</p
>
<p v-for="stop in source.snapshot.stops" :key="stop.id"
>{{ stop.supplier_name || stop.customer_name || '未填写单位' }} ·
@@ -159,7 +317,7 @@
</div>
</template>
</section>
<section v-if="groups.length" class="view-section">
<section v-if="groups.length && !viewOnly" class="view-section">
<h3>3. 不同单位人工换算(同单位无需填写)</h3>
<p v-if="forSupplement" class="form-tip"
>这里只填写超出原预占部分的来源量及证面量;原预占内的实际量在上一层核对。不得重复计算两部分。</p
@@ -174,7 +332,7 @@
v-for="source in measured"
:key="source.sourceStopProductId"
:value="`${source.sourceStopType}:${source.sourceStopProductId}`"
:label="`${source.productName} · ${source.partyName || ''} · ${source.quantity} ${source.unit}`"
:label="`${source.productName} · ${source.partyName || ''} · ${qtyText(source.quantity)} ${unitText(source.unit)}`"
/></el-select>
<el-select
:model-value="`${row.permitKind}:${row.permitId}`"
@@ -185,7 +343,7 @@
v-for="item in selected"
:key="item.kind + item.cert.id"
:value="`${item.kind}:${item.cert.id}`"
:label="`${item.cert.certNo}(${item.cert.quantityUnit})`"
:label="`${item.cert.certNo}(${unitText(item.cert.quantityUnit)})`"
/></el-select>
<el-input
v-model="row.sourceQuantity"
@@ -196,7 +354,7 @@
:disabled="busy"
placeholder="换算后的证面数量"
/>
<el-input v-model="row.note" :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
>
@@ -216,7 +374,7 @@
><el-icon><Plus /></el-icon>添加人工换算</el-button
>
</section>
<section v-if="!forSupplement" class="view-section"
<section v-if="!forSupplement && !viewOnly" class="view-section"
><h3>4. 预览分配</h3>
<el-button :loading="busy" @click="preview"
><el-icon><Search /></el-icon>重新计算</el-button
@@ -236,12 +394,13 @@
class="view-section"
>
<strong
>{{ row.certType === 'purchase' ? '购买证' : '运输证' }} · 需求 {{ row.demand }}
{{ row.unit }}</strong
>{{ row.certType === 'purchase' ? '购买证' : '运输证' }} · 需求
{{ qtyText(row.demand) }} {{ unitText(row.unit) }}</strong
>
<p v-if="row.availableUpperBound !== null">
适用余额至多 {{ row.availableUpperBound }} {{ row.unit }};缺口至少
{{ row.gapLowerBound }} {{ row.unit }}
适用余额至多 {{ qtyText(row.availableUpperBound) }}
{{ unitText(row.unit) }};缺口至少 {{ qtyText(row.gapLowerBound) }}
{{ unitText(row.unit) }}
</p>
<p>{{ readableReason(row.reason) }}</p>
<p>{{
@@ -258,19 +417,21 @@
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"
><template #default="{ row }">{{
qtyText(row.sourceQuantity)
}}</template></el-table-column
><el-table-column prop="permitQuantity" label="证面量" min-width="100"
><template #default="{ row }">{{
qtyText(row.permitQuantity)
}}</template></el-table-column
><el-table-column prop="permitUnit" label="证面单位" min-width="100"
><template #default="{ row }">{{
unitText(row.permitUnit)
}}</template></el-table-column
><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
@@ -284,40 +445,61 @@
usageLabels[row.usageStatus] || row.usageStatus
}}</el-tag></template
></el-table-column
><el-table-column
prop="quantityUnit"
label="证面单位"
min-width="100" /><el-table-column
prop="reservedQty"
label="预占量"
min-width="120" /><el-table-column
prop="usedQty"
label="使用量"
min-width="120" /></el-table
></section>
><el-table-column prop="quantityUnit" label="证面单位" min-width="100"
><template #default="{ row }">{{
unitText(row.quantityUnit)
}}</template></el-table-column
><el-table-column prop="reservedQty" label="预占量" min-width="120"
><template #default="{ row }">{{
qtyText(row.reservedQty)
}}</template></el-table-column
><el-table-column prop="usedQty" label="使用量" min-width="120"
><template #default="{ row }">{{ qtyText(row.usedQty) }}</template></el-table-column
></el-table
></section
>
</template>
</div>
<template #footer
><el-button :disabled="busy" @click="cancel"
><el-icon><Close /></el-icon>取消</el-button
><el-icon><Close /></el-icon
>{{ viewOnly && !conversions.length ? '关闭' : '取消' }}</el-button
><el-button
v-if="!viewOnly || (conversions.length && plan?.canSaveConfiguration !== false)"
type="primary"
:disabled="
loading || !plan || (!forArrange && !forSupplement && plan.canSaveConfiguration === false)
"
:loading="busy"
@click="accept"
@click="viewOnly ? saveConversion() : accept()"
><el-icon><Check /></el-icon
>{{
forSupplement ? '确认补充分配候选' : forArrange ? '确认本次用证配置' : '保存配置'
forSupplement ? '确认补充分配候选' : forArrange ? '确认本次用证配置' : '保存换算'
}}</el-button
></template
>
</el-dialog>
</template>
<script setup lang="ts">
import { perStop, measuredSources, configurationPayload, sourceLabel } from './stop-model'
import {
perStop,
measuredSources,
configurationPayload,
sourceLabel,
unitConversions,
coefficientFromQuantities,
permitQuantityFromCoefficient
} from './stop-model'
import { useUserStore } from '@/store/modules/user'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import ViewKvTable from '@/components/business/system-view-dialog/ViewKvTable.vue'
import type { ViewField } from '@/components/business/system-view-dialog/types'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import {
certFormGroups,
formatCertQty
} from '@/views/pl/quota-cert/model'
import { Check, Close, Delete, Plus, Refresh, Search } from '@element-plus/icons-vue'
import {
planQuotaApi,
@@ -351,7 +533,8 @@
context = ref<QuotaContext>(),
result = ref<QuotaPreview>()
const sides = reactive<Record<string, string>>({}),
pairs = reactive<Record<string, string[]>>({})
pairs = reactive<Record<string, string[]>>({}),
coefficients = reactive<Record<string, string>>({})
let previewVehicle: QuotaPreviewVehicle = {}
let revision = 0
let epoch = 0,
@@ -374,7 +557,26 @@
return [...values.values()]
})
const isPerStop = computed(() => perStop(plan.value))
const viewOnly = computed(() => !forArrange.value && !forSupplement.value)
const measured = computed(() => measuredSources(plan.value, sides))
const conversions = computed(() =>
viewOnly.value ? unitConversions(plan.value, measured.value) : []
)
const conversionGroups = computed(() => {
const grouped = new Map<
string,
{ sourceId: string; source: QuotaSourceOption; rows: typeof conversions.value }
>()
for (const row of conversions.value) {
const current = grouped.get(row.sourceId)
if (current) current.rows.push(row)
else grouped.set(row.sourceId, { sourceId: row.sourceId, source: row.source, rows: [row] })
}
for (const group of grouped.values()) {
group.rows.sort((a, b) => Number(a.cert.certType !== 'purchase') - Number(b.cert.certType !== 'purchase'))
}
return [...grouped.values()]
})
const selected = computed(() => [
...purchases.value
.filter((c) => config.value.purchaseCertIds.includes(c.id))
@@ -383,6 +585,110 @@
.filter((c) => config.value.transportCertIds.includes(c.id))
.map((cert) => ({ kind: 'transport' as const, cert }))
])
const faceTab = ref('')
const certStatusLabels: Record<string, string> = {
draft: '待核对',
active: '已启用',
suspended: '已停用',
closed: '已核销',
void: '已作废'
}
const refLabels: Record<string, string> = {
purchase_permit: '购买许可证',
purchase_filing: '购买备案证明',
export_permit: '出口许可证',
unknown: '待确认'
}
const longFaceKeys = new Set([
'buyerAddress',
'sellerAddress',
'shipperAddress',
'carrierAddressPhone',
'routeText',
'purchasePurpose',
'packagingText',
'remark'
])
const faceTabs = computed(() => {
const seen = new Set<string>()
const tabs: {
key: string
label: string
kind: CertType
certNo: string
cert: QuotaCert | null
}[] = []
const push = (kind: string, id: string, certNo: string) => {
if (kind !== 'purchase' && kind !== 'transport') return
const key = `${kind}:${id || certNo}`
if ((!id && !certNo) || seen.has(key)) return
seen.add(key)
const pool = kind === 'purchase' ? purchases.value : transports.value
const cert = pool.find((item) => item.id === id) || null
const number = cert?.certNo || certNo || '证号未提供'
tabs.push({
key,
kind,
cert,
certNo: number,
label: `${kind === 'purchase' ? '购买证' : '运输证'} ${number}`
})
}
for (const row of plan.value?.stopProducts || []) {
for (const cert of row.certificates || []) push(cert.certType, cert.certId, cert.certNo)
}
for (const usage of plan.value?.usages || []) {
push(String(usage.certType || ''), String(usage.certId || ''), String(usage.certNoSnapshot || ''))
}
tabs.sort(
(a, b) =>
Number(a.kind !== 'purchase') - Number(b.kind !== 'purchase') ||
a.certNo.localeCompare(b.certNo)
)
return tabs
})
watch(faceTabs, (tabs) => {
if (!tabs.some((tab) => tab.key === faceTab.value)) faceTab.value = tabs[0]?.key || ''
})
function showCertFace(cert: { certType: string; certId: string; certNo: string }) {
faceTab.value = `${cert.certType}:${cert.certId || cert.certNo}`
}
function faceValue(cert: QuotaCert, key: string) {
if (key === 'status') return certStatusLabels[cert.status] || cert.status || '—'
if (key === 'totalQty') {
const qty = qtyText(cert.totalQty)
const unit = unitText(cert.quantityUnit)
return unit && qty !== '—' ? `${qty} ${unit}` : qty
}
if (key === 'quantityUnit') return unitText(cert.quantityUnit) || '—'
if (key === 'remark') return String(cert.remark || '').trim() || '—'
const raw = cert[key as keyof QuotaCert]
if (raw == null || raw === '') return '—'
return typeof raw === 'string' || typeof raw === 'number' ? String(raw) : '—'
}
function faceGroups(cert: QuotaCert, kind: CertType) {
const groups = certFormGroups(kind).map((group, index) => {
const fields: ViewField[] = group.fields.map((field) => ({
label: field[1],
value:
field[0] === 'vehicleNumbersJson'
? cert.vehicleNumbersJson?.filter(Boolean).join('、') || '—'
: faceValue(cert, field[0]),
span:
longFaceKeys.has(field[0]) || field[0] === 'vehicleNumbersJson'
? ('full' as const)
: undefined
}))
if (index === 0) fields.unshift({ label: '状态', value: faceValue(cert, 'status') })
return { title: group.title, fields }
})
groups[groups.length - 1].fields.push({
label: '系统备注',
value: faceValue(cert, 'remark'),
span: 'full'
})
return groups
}
const usageLabels: Record<string, string> = {
reserved: '已预占',
in_transit: '执行中',
@@ -413,8 +719,111 @@
}))
)
)
function qtyText(value: unknown) {
return formatCertQty(value)
}
function inputQty(value: unknown) {
const text = qtyText(value)
return text === '—' ? '' : text
}
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
function boundCerts(row: QuotaSourceOption) {
return (
plan.value?.stopProducts?.find(
(item) =>
item.sourceStopType === row.sourceStopType &&
item.sourceStopProductId === row.sourceStopProductId
)?.certificates || []
)
}
function certsOf(row: QuotaSourceOption, kind: CertType) {
return boundCerts(row).filter((cert) => cert.certType === kind)
}
function certText(row: QuotaSourceOption, kind: CertType) {
const list = boundCerts(row).filter((cert) => cert.certType === kind)
return list.length
? list
.map((cert) => cert.certNo)
.join('、')
: '未绑定'
}
function conversionKey(row: { sourceId: string; cert: { certType: string; certId: string } }) {
return `${row.sourceId}:${row.cert.certType}:${row.cert.certId}`
}
function resetCoefficients() {
for (const key of Object.keys(coefficients)) delete coefficients[key]
}
function syncViewConversions() {
const previous = config.value.manualAllocations
config.value.manualAllocations = conversions.value.map((row) => {
const old = previous.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
)
return (
old || {
permitKind: row.cert.certType,
sourceId: row.sourceId,
permitId: row.cert.certId,
sourceQuantity: inputQty(row.source.quantity),
permitQuantity: '',
note: ''
}
)
})
const keys = new Set(conversions.value.map((row) => conversionKey(row)))
for (const key of Object.keys(coefficients)) if (!keys.has(key)) delete coefficients[key]
for (const row of conversions.value) {
const key = conversionKey(row)
if (coefficients[key]) continue
const saved = config.value.manualAllocations.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
)
coefficients[key] = coefficientFromQuantities(saved?.sourceQuantity, saved?.permitQuantity)
}
}
function conversionPreview(row: (typeof conversions.value)[number]) {
const permit = permitQuantityFromCoefficient(
row.source.quantity,
coefficients[conversionKey(row)]
)
return permit ? `${qtyText(permit)} ${unitText(row.cert.quantityUnit)}` : ''
}
function conversionInput(row: (typeof conversions.value)[number]) {
return config.value.manualAllocations.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
)!
}
async function saveConversion() {
if (!viewOnly.value || !conversions.value.length || !plan.value || busy.value) return
for (const row of conversions.value) {
const input = conversionInput(row)
const permit = permitQuantityFromCoefficient(
row.source.quantity,
coefficients[conversionKey(row)]
)
if (!permit || !input) {
ElMessage.warning('请填写大于 0 的换算系数')
return
}
input.sourceQuantity = inputQty(row.source.quantity)
input.permitQuantity = permit
}
await accept()
}
function certLabel(c: QuotaCert) {
return `${c.certNo} · 可用 ${c.availableQty} ${c.quantityUnit}`
return `${c.certNo} · 可用 ${qtyText(c.availableQty)} ${unitText(c.quantityUnit)}`
}
function opposite(group: (typeof groups.value)[number]) {
return group[sides[group.id] === 'load' ? 'delivery' : 'load']
@@ -539,7 +948,7 @@
try {
await planQuotaApi.save(id, value)
if (!isCurrent()) return
ElMessage.success('用证配置已保存')
ElMessage.success('换算已保存')
resolve?.(value)
resolve = undefined
visible.value = false
@@ -573,6 +982,7 @@
previewVehicle = vehicle
Object.keys(sides).forEach((k) => delete sides[k])
Object.keys(pairs).forEach((k) => delete pairs[k])
resetCoefficients()
try {
const [p, b, t] = await Promise.all([
planQuotaApi.get(id),
@@ -606,6 +1016,7 @@
}
for (const row of config.value.sourceMapping || [])
pairs[row.sourceStopProductId] = [...row.relatedStopProductIds]
if (!arrange && !supplement) syncViewConversions()
return await new Promise((r) => {
resolve = r
loading.value = false
@@ -629,6 +1040,7 @@
context.value = undefined
result.value = undefined
config.value = empty()
resetCoefficients()
loading.value = false
busy.value = false
resolve?.(undefined)
@@ -650,6 +1062,67 @@
.quota-dialog :deep(.el-select) {
width: 100%;
}
.quota-meta {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 16px;
color: var(--mint-text-secondary, #475569);
}
.quota-meta strong {
color: var(--mint-text, #0f172a);
font-size: 15px;
}
.quota-note {
margin: 0 0 14px;
color: var(--mint-text-muted, #64748b);
font-size: 13px;
line-height: 1.6;
}
.dialog-section-title {
margin-top: 4px;
}
.quota-table-wrap {
overflow-x: auto;
margin-bottom: 8px;
}
.quota-table {
width: 100%;
min-width: 1080px;
}
.cert-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.cert-face-tag {
cursor: pointer;
}
.quota-face {
margin-top: 18px;
}
.quota-face-tabs :deep(.el-tabs__header) {
margin-bottom: 12px;
}
.quota-face-tabs :deep(.el-tabs__item) {
font-size: 14px;
}
.quota-face-tabs :deep(.el-tabs__item.is-active) {
color: #10b981;
}
.quota-face-tabs :deep(.el-tabs__active-bar) {
background-color: #10b981;
}
.quota-face-group {
margin-top: 14px;
}
.quota-face-group h4 {
margin: 0 0 8px;
color: var(--mint-text, #0f172a);
font-size: 14px;
font-weight: 600;
line-height: 1.5;
}
.view-section {
margin-top: 16px;
}
@@ -664,4 +1137,76 @@
.view-section .el-input {
margin-top: 8px;
}
.conversion-section {
margin-top: 20px;
}
.conversion-group {
margin-top: 12px;
padding: 14px 16px 16px;
border: 1px solid var(--mint-border, #e5e7eb);
border-radius: 8px;
background: #fff;
}
.conversion-group-head h4 {
margin: 0;
font-size: 14px;
font-weight: 600;
line-height: 1.5;
}
.conversion-group-head p {
margin: 4px 0 0;
color: var(--mint-text-secondary, #475569);
font-size: 13px;
}
.conversion-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
margin-top: 12px;
}
.conversion-card {
padding: 12px;
border: 1px solid var(--mint-border, #e5e7eb);
border-radius: 8px;
background: var(--mint-bg-page, #f7faf8);
}
.conversion-card-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.conversion-card-head strong {
min-width: 0;
overflow-wrap: anywhere;
font-size: 14px;
}
.conversion-card label {
display: block;
margin-bottom: 6px;
color: var(--mint-text-secondary, #475569);
font-size: 13px;
}
.conversion-factor {
display: flex;
align-items: center;
gap: 8px;
}
.conversion-factor .el-input {
width: 120px;
}
.conversion-preview {
min-height: 20px;
margin: 8px 0 12px;
color: var(--mint-primary-dark, #059669);
font-size: 13px;
}
.conversion-preview.is-empty {
color: var(--mint-text-muted, #94a3b8);
}
@media (max-width: 800px) {
.conversion-grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -1,4 +1,6 @@
import type { PlanQuota, QuotaConfiguration, QuotaSourceOption } from '@/api/pl/quota-cert'
import { normalizeProductUnitValue } from '@/utils/crm-product-display'
import { formatCertQty } from '@/views/pl/quota-cert/model'
export const perStop = (plan?: PlanQuota) =>
(plan?.measurementVersion || plan?.configuration.measurementVersion) === 'per_stop_v2'
@@ -27,6 +29,93 @@ export function configurationPayload(
}
}
export function sameCertUnit(left?: string | null, right?: string | null) {
const planUnit = String(left || '').trim()
const certUnit = String(right || '').trim()
if (!planUnit || !certUnit) return false
return normalizeProductUnitValue(planUnit) === normalizeProductUnitValue(certUnit)
}
export function coefficientFromQuantities(source: unknown, permit: unknown) {
const sourceQty = Number(source)
const permitQty = Number(permit)
if (!sourceQty || !Number.isFinite(sourceQty) || !Number.isFinite(permitQty) || permitQty <= 0)
return ''
const value = permitQty / sourceQty
return Number.isFinite(value) && value > 0 ? String(Number(value.toPrecision(12))) : ''
}
export function permitQuantityFromCoefficient(quantity: unknown, coefficient: unknown) {
const qty = Number(quantity)
const factor = Number(String(coefficient ?? '').trim())
if (!Number.isFinite(qty) || !(factor > 0)) return ''
const value = qty * factor
return Number.isFinite(value) ? String(Number(value.toPrecision(12))) : ''
}
export function unitConversions(plan: PlanQuota | undefined, sources: QuotaSourceOption[]) {
return sources.flatMap((source) => {
const certs =
plan?.stopProducts?.find(
(row) =>
row.sourceStopType === source.sourceStopType &&
row.sourceStopProductId === source.sourceStopProductId
)?.certificates || []
return certs
.filter((cert) => cert.quantityUnit && source.unit && !sameCertUnit(source.unit, cert.quantityUnit))
.map((cert) => ({
sourceId: `${source.sourceStopType}:${source.sourceStopProductId}`,
source,
cert
}))
})
}
export interface LegacyProductGroup {
id: string
name: string
load: QuotaSourceOption[]
delivery: QuotaSourceOption[]
}
export function legacyGroups(plan?: PlanQuota): LegacyProductGroup[] {
const values = new Map<string, LegacyProductGroup>()
for (const row of plan?.sourceOptions || []) {
const current = values.get(row.planProductId) || {
id: row.planProductId,
name: row.productName,
load: [],
delivery: []
}
current[row.sourceStopType].push(row)
values.set(row.planProductId, current)
}
return [...values.values()]
}
/** 原口径打开时恢复已保存的计量侧和另一侧配对;两侧都有且未保存时留空,等用户选择。 */
export function initialLegacySelection(plan?: PlanQuota) {
const sides: Record<string, string> = {}
const pairs: Record<string, string[]> = {}
for (const row of plan?.sourceOptions || []) pairs[row.sourceStopProductId] = []
for (const row of plan?.configuration?.sourceMapping || []) {
pairs[row.sourceStopProductId] = [...(row.relatedStopProductIds || [])]
}
for (const group of legacyGroups(plan)) {
const old = plan?.configuration?.sourceMapping?.find((item) =>
group[item.sourceStopType].some((row) => row.sourceStopProductId === item.sourceStopProductId)
)
sides[group.id] =
old?.sourceStopType ||
(group.load.length && !group.delivery.length
? 'load'
: group.delivery.length && !group.load.length
? 'delivery'
: '')
}
return { sides, pairs }
}
export function sourceLabel(id: string, sources: QuotaSourceOption[]) {
const source = sources.find((s) => `${s.sourceStopType}:${s.sourceStopProductId}` === id)
return source
@@ -34,7 +123,10 @@ export function sourceLabel(id: string, sources: QuotaSourceOption[]) {
: '来源已不可用'
}
export function stopUsageRows(plan: PlanQuota) {
export function stopUsageRows(
plan: PlanQuota,
labelUnit: (unit?: string | null) => string = (unit) => unit || '—'
) {
return (plan.stopProducts || plan.sourceOptions.map((s) => ({ ...s, isToxic: true }))).map(
(source) => {
const text = (kind: string) => {
@@ -58,8 +150,8 @@ export function stopUsageRows(plan: PlanQuota) {
i.sourceStopProductId === source.sourceStopProductId
)
.map((i: any) => {
const unit = i.quantityUnit || u.quantityUnit || '—'
return `${u.certNoSnapshot || '证号未提供'} · 预占 ${i.reservedQty ?? '—'} ${unit} · 已用 ${i.usedQty ?? '—'} ${unit}`
const unit = labelUnit(i.quantityUnit || u.quantityUnit)
return `${u.certNoSnapshot || '证号未提供'} · 预占 ${formatCertQty(i.reservedQty)} ${unit} · 已用 ${formatCertQty(i.usedQty)} ${unit}`
})
)
const bound = (source.certificates || []).filter(
@@ -78,7 +170,8 @@ export function stopUsageRows(plan: PlanQuota) {
)
lines.push(
...bound.map(
(c) => `${c.certNo} · 已绑定 · 预占 0 ${c.quantityUnit} · 已用 0 ${c.quantityUnit}`
(c) =>
`${c.certNo} · 已绑定 · 预占 ${formatCertQty(0)} ${labelUnit(c.quantityUnit)} · 已用 ${formatCertQty(0)} ${labelUnit(c.quantityUnit)}`
)
)
if (source.bindingsReadable === false) lines.push('合同或证件不可读取')
@@ -26,7 +26,7 @@
>
<span class="pl-stop-feedback-ticket__text">{{ product.productName || '产品' }}</span>
<span class="pl-stop-feedback-ticket__text pl-stop-feedback-ticket__text--qty">
{{ formatDriverProductQty(product) }}
{{ formatDriverQty(product) }}
</span>
</div>
</div>
@@ -79,9 +79,9 @@
<span class="pl-stop-feedback-ticket__text">{{ product.productName || '产品' }}</span>
<span class="pl-stop-feedback-ticket__text pl-stop-feedback-ticket__text--qty">
<span class="pl-stop-feedback-ticket__val pl-stop-feedback-ticket__val--highlight">{{
formatSiteProductQty(product).qty
formatSiteQty(product).qty
}}</span>
<span class="pl-stop-feedback-ticket__unit">{{ formatSiteProductQty(product).unit }}</span>
<span class="pl-stop-feedback-ticket__unit">{{ formatSiteQty(product).unit }}</span>
</span>
</div>
</div>
@@ -225,8 +225,10 @@
import { formatKgToTon } from '@/components/business/db/db-related-view'
import type { PlanFormProductRow } from '@/composables/usePlContractToPlan'
import type { PlPlanTransportDibangRow } from '@/composables/usePlPlanViewDetail'
import { useDictStore } from '@/store/modules/dict'
import { formatDateTime } from '@/utils/format'
import { isPlInternalCustomerName } from '@/utils/pl-internal-customer'
import { formatDriverProductQty, formatSiteProductQty } from './qty-display'
const props = withDefaults(
defineProps<{
@@ -268,9 +270,14 @@
'update:siteAttachmentUrls': [value: string]
}>()
const dictStore = useDictStore()
const driverAttachRef = ref<InstanceType<typeof AttachmentUploadField> | null>(null)
const siteAttachRef = ref<InstanceType<typeof AttachmentUploadField> | null>(null)
function resolveUnitLabel(dictType: string, value: string) {
return dictStore.getLabel(dictType, value)
}
const isInternalCustomer = computed(() => isPlInternalCustomerName(props.customerName))
const showSiteCard = computed(() => isInternalCustomer.value)
@@ -382,18 +389,12 @@
return text || '—'
}
function formatDriverProductQty(product: NonNullable<TransportStopFeedback['products']>[number]) {
const qty = product.actualQty
const unit = product.unit || '吨'
if (qty == null) return '—'
return `${qty} ${unit}`
function formatDriverQty(product: NonNullable<TransportStopFeedback['products']>[number]) {
return formatDriverProductQty(product, resolveUnitLabel)
}
function formatSiteProductQty(product: NonNullable<TransportStopFeedback['products']>[number]) {
const qty = product.actualQty ?? product.quantity
const unit = product.unit || '吨'
if (qty == null) return { qty: '—', unit: '' }
return { qty: String(qty), unit: ` ${unit}` }
function formatSiteQty(product: NonNullable<TransportStopFeedback['products']>[number]) {
return formatSiteProductQty(product, resolveUnitLabel)
}
function resolvePlanProductRow(row: PlPlanTransportDibangRow) {
@@ -0,0 +1,35 @@
import { getProductUnitLabel } from '@/utils/crm-product-display'
type UnitLabelResolver = (dictType: string, value: string) => string
export function feedbackUnitLabel(
unit: string | null | undefined,
getLabel: UnitLabelResolver
): string {
const raw = String(unit || '').trim()
if (!raw) return '吨'
const label = getProductUnitLabel(getLabel, raw).trim()
return !label || label === '—' ? raw : label
}
export function formatDriverProductQty(
product: { actualQty?: number | null; unit?: string | null },
getLabel: UnitLabelResolver
): string {
const qty = product.actualQty
if (qty == null) return '—'
return `${qty} ${feedbackUnitLabel(product.unit, getLabel)}`
}
export function formatSiteProductQty(
product: {
actualQty?: number | null
quantity?: number | null
unit?: string | null
},
getLabel: UnitLabelResolver
): { qty: string; unit: string } {
const qty = product.actualQty ?? product.quantity
if (qty == null) return { qty: '—', unit: '' }
return { qty: String(qty), unit: ` ${feedbackUnitLabel(product.unit, getLabel)}` }
}
@@ -74,15 +74,16 @@
>单位<span class="pl-stop-field-required" aria-hidden="true">*</span></span
>
<DictSelect
v-if="sharedEditable"
v-if="sharedEditable && !unitLocked(row)"
v-model="row.unit"
class="pl-plan-product-cell-control pl-stop-product-dual-dict"
dict-type="crm_product_unit"
placeholder="单位"
/>
<template v-else>
<span class="pl-stop-product-dual-item__readonly">{{
resolveDictLabel('crm_product_unit', row.unit)
<span class="pl-stop-product-dual-item__readonly">{{ unitLabel(row) }}</span>
<span v-if="row.contractUnitNote" class="pl-stop-unit-note">{{
row.contractUnitNote
}}</span>
</template>
</div>
@@ -370,7 +371,7 @@
</template>
<template #default="{ row }">
<DictSelect
v-if="sharedEditable"
v-if="sharedEditable && !unitLocked(row)"
v-model="row.unit"
class="pl-plan-product-cell-control"
dict-type="crm_product_unit"
@@ -380,6 +381,9 @@
<template v-else>
<DictTag v-if="row.unit" dict-type="crm_product_unit" :value="row.unit" />
<span v-else>—</span>
<span v-if="row.contractUnitNote" class="pl-stop-unit-note">{{
row.contractUnitNote
}}</span>
</template>
</template>
</el-table-column>
@@ -592,12 +596,15 @@
resolveStopUnitPrice
} from '@/utils/pl-plan-stop-form'
import {
alignStopProductUnitToContract,
allowedPackageSpecsForStopProduct,
collectStopContractIds,
contractLineChoicesForProduct,
normalizePackageSpec,
stopProductUnitLocked,
type ContractProductRowLite
} from '@/utils/pl-plan-contract-product'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { getDeliveryMethodLabel } from '@/composables/usePlContractToPlan'
import {
applyBrandSelectChange,
@@ -745,8 +752,41 @@
row.contractId = choice.contractId
row.contractProductId = choice.id
row.contractNo = choice.contractNo
if (choice.unit) {
row.unit = choice.unit
row.contractUnitNote = ''
}
}
function unitLocked(row: PlanStopProductFormRow) {
return stopProductUnitLocked(row)
}
function unitLabel(row: PlanStopProductFormRow) {
return getProductUnitLabel((dictType, value) => dictStore.getLabel(dictType, value), row.unit)
}
function unitFieldLabel(row: PlanStopProductFormRow) {
const label = unitLabel(row)
const note = String(row.contractUnitNote || '').trim()
return note ? `${label}。${note}` : label
}
watch(
() =>
(props.products || [])
.map((row) => `${row.contractProductId || ''}:${row.unit || ''}`)
.join('|') +
'#' +
(props.contractProductRows || []).map((row) => `${row.id || ''}:${row.unit || ''}`).join('|'),
() => {
for (const row of props.products || []) {
if (!alignStopProductUnitToContract(row, props.contractProductRows)) continue
row.contractUnitNote = `合同单位是${unitLabel(row)},请按该单位核对计划数量`
}
}
)
const untaggedContractHint = computed(() => {
const names = (props.products || []).filter(rowNeedsContractLine).map((row) => {
const name = String(row.standardProductName || row.productName || row.productNo || '未命名产品').trim()
@@ -991,7 +1031,7 @@
arrangeQtyCache.value = next
return ensureArrangeQty(row)
}
const mobileController = reactive({ retryMobileArrangeQty, onPackageChange, props, sharedEditable, aliasBrandManageable, canRemove, showAvailableQty, packageOptionsFor, useContractPackageSelect, resolvePackageDisplay, resolveProductContractNo, rowNeedsContractLine, contractLineChoices, bindContractLine, untaggedContractHint, resolveDictLabel, dictStore, handleAliasChange, handleBrandChange, handleAliasBrandManaged, openAliasBrandManage, aliasBrandManageVisible, aliasBrandManageProductId, aliasBrandManageProductName, aliasBrandManageMode, formatAvailableDisplay, canOpenArrangeQty, ensureArrangeQty, readArrangeQty, isPlanQtyOverAvailable, handleRemove, formatBrandConstraintLabel, formatStopQty, formatStopPrice, resolveStopActualQty, resolveStopUnitPrice, formatStopArchiveAmount })
const mobileController = reactive({ retryMobileArrangeQty, onPackageChange, props, sharedEditable, aliasBrandManageable, canRemove, showAvailableQty, packageOptionsFor, useContractPackageSelect, resolvePackageDisplay, resolveProductContractNo, rowNeedsContractLine, contractLineChoices, bindContractLine, unitLocked, unitFieldLabel, untaggedContractHint, resolveDictLabel, dictStore, handleAliasChange, handleBrandChange, handleAliasBrandManaged, openAliasBrandManage, aliasBrandManageVisible, aliasBrandManageProductId, aliasBrandManageProductName, aliasBrandManageMode, formatAvailableDisplay, canOpenArrangeQty, ensureArrangeQty, readArrangeQty, isPlanQtyOverAvailable, handleRemove, formatBrandConstraintLabel, formatStopQty, formatStopPrice, resolveStopActualQty, resolveStopUnitPrice, formatStopArchiveAmount })
</script>
<style scoped lang="scss">
@@ -1092,6 +1132,14 @@
border-radius: 8px;
}
.pl-stop-unit-note {
display: block;
margin-top: 4px;
font-size: 12px;
line-height: 1.4;
color: #92400e;
}
.pl-stop-contract-gap {
margin: 0 0 8px;
padding: 8px 12px;
@@ -9,17 +9,17 @@
:close-on-click-modal="false"
@closed="!visible && cancel()"
>
<p class="form-tip"
>异单位按实际量重新填写,不沿用安排时换算比例。每个来源、每类证件的分配合计必须与本次实际数量一致;0
也须明确填写。</p
<p v-if="rows.length" class="form-tip"
>下面只列出计划单位和证面单位不同的分配。请填写本次实际计划量和证面量,并写明换算依据。填 0
也要写上。</p
>
<p v-if="!rows.length" class="form-tip"
>当前原分配均为同单位,系统按本次各来源实际数量和原顺序结转。</p
<p v-else class="form-tip"
>证面数量按安排时保存的换算系数和本次实际数量自动计算,不用再填换算。</p
>
<el-checkbox v-model="allowSupplement">实际量超出原预占,需要补充分配</el-checkbox>
<el-checkbox v-model="allowSupplement">已用证件剩余额度不够,需要再选其他证件</el-checkbox>
<template v-if="allowSupplement">
<p class="form-tip"
>下方填写原分配部分的实际来源量和本次实际证面量。超出原来源量的部分在补充候选中填写;仅证面量增加时选择对应原证补差。来源量增加需双证覆盖,系统不沿用换算比例。补充校验失败将保存真实数量及异常,保持原账。</p
>已经使用的证件还能扣的额度不够时,再选择其他购买证和运输证。原证件能覆盖的部分会先扣完。</p
>
<el-button :loading="choosing" @click="chooseSupplement"
><el-icon><Plus /></el-icon
@@ -30,25 +30,27 @@
{{ 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
<section v-for="row in rows" :key="row.key" class="settlement-card">
<h3>{{ row.kind === 'purchase' ? '购买证' : '运输证' }} {{ row.certNo }}</h3>
<p class="settlement-meta">{{ row.productName }}</p>
<p class="settlement-meta">{{ row.sourceLabel }}<template v-if="row.seq"> · 扣证顺序 {{ row.seq }}</template></p>
<p class="settlement-meta"
>安排时 {{ row.plannedSource }} {{ row.sourceUnitLabel }},证面
{{ row.plannedPermit }} {{ row.permitUnitLabel }}</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>
<el-form label-position="top">
<div class="form-grid-2">
<el-form-item :label="`本次实际计划量(${row.sourceUnitLabel})`">
<el-input v-model="row.value.sourceQuantity" placeholder="0" />
</el-form-item>
<el-form-item :label="`本次实际证面量(${row.permitUnitLabel})`">
<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="实际用量更正/补分配理由(必填)"
@@ -110,8 +112,8 @@
certNo: string
productName: string
sourceLabel: string
sourceUnit: string
permitUnit: string
sourceUnitLabel: string
permitUnitLabel: string
plannedSource: string
plannedPermit: string
seq: number
@@ -127,49 +129,22 @@
allowSupplement.value = false
choosing.value = false
supplementConfiguration.value = undefined
const plan = await planQuotaApi.get(planId)
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: ''
}
}))
rows.value = []
adjustment.value = adjust
reason.value = ''
sourceNote.value = ''
evidenceUrls.value = ''
if (!adjust && !rows.value.length) {
return {
quotaAllowSupplement: false,
quotaManualActuals: [],
quotaReason: '',
quotaSourceNote: '',
quotaEvidenceUrls: ''
}
}
visible.value = true
return new Promise((r) => (resolve = r))
}
@@ -240,3 +215,19 @@
)
onBeforeUnmount(() => cancel())
</script>
<style scoped>
.settlement-card {
margin-top: 16px;
padding: 12px 16px 4px;
border: 1px solid var(--el-border-color);
border-radius: 8px;
}
.settlement-card h3 {
margin: 0 0 8px;
font-size: 15px;
}
.settlement-meta {
margin: 0 0 4px;
line-height: 1.6;
}
</style>
+5 -5
View File
@@ -131,11 +131,11 @@
},
'/m/pl/plan-cert': {
mode: 'list',
title: '计划用证',
search: '计划编号 / 供方 / 需方',
tabs: [],
filters: ['用证状态'],
caption: '正在加载计划'
title: '运输证件管理',
search: '证件编号 / 品名',
tabs: ['证件建档', '合同用证', '证件用量', '计划段次用证', '证书齐备'],
filters: [],
caption: '正在加载运输证件管理'
}
}
+34 -5
View File
@@ -59,7 +59,7 @@ export const plRoutes: AppRouteRecord[] = [
id: 'PL_GROUP_CERT',
name: 'PlCertUpload',
path: 'cert-upload',
meta: { title: '计划用证', keepAlive: false },
meta: { title: '运输证件管理', keepAlive: false },
children: [
{
id: 'PL_QUOTA_CERT',
@@ -89,6 +89,28 @@ export const plRoutes: AppRouteRecord[] = [
component: '/pl/plan-cert/index',
meta: { title: '计划段次用证', keepAlive: false, menuCode: 'pl:plan-cert:list' }
},
{
id: 'PL_CERT_READY',
name: 'PlCertReady',
path: 'cert-ready',
component: '/pl/cert-ready/index',
meta: { title: '证书齐备', keepAlive: false, menuCode: 'pl:plan-cert:list' }
},
{
id: 'PL_REDIRECT_LEGAL_USE_OLD',
name: 'PlLegalUseDocumentOldRedirect',
path: 'legal-use-document',
redirect: '/pl/legal-use-module/legal-use-document',
meta: { title: '合法使用证明', isHide: true }
}
]
},
{
id: 'PL_GROUP_LEGAL',
name: 'PlLegalUseModule',
path: 'legal-use-module',
meta: { title: '合法使用证明', keepAlive: false },
children: [
{
id: 'PL_LEGAL_USE_DOCUMENT',
name: 'PlLegalUseDocument',
@@ -135,14 +157,14 @@ export const plRoutes: AppRouteRecord[] = [
id: 'PL_GROUP_DOC',
name: 'PlDocumentReminderModule',
path: 'document-reminder-module',
meta: { title: '证件提醒', keepAlive: false },
meta: { title: '人车证件提醒', keepAlive: false },
children: [
{
id: 'PL_DOC_REMINDER',
name: 'PlDocumentReminder',
path: 'document-reminder',
component: '/pl/inventory/document-reminder',
meta: { title: '证件提醒', keepAlive: false, menuCode: 'pl:document:list' }
meta: { title: '人车证件提醒', keepAlive: false, menuCode: 'pl:document:list' }
}
]
},
@@ -257,7 +279,14 @@ export const plRoutes: AppRouteRecord[] = [
name: 'PlPlanCertRedirect',
path: 'plan-cert',
redirect: '/pl/cert-upload/plan-cert',
meta: { title: '计划用证', isHide: true }
meta: { title: '运输证件管理', isHide: true }
},
{
id: 'PL_REDIRECT_CERT_READY',
name: 'PlCertReadyRedirect',
path: 'cert-ready',
redirect: '/pl/cert-upload/cert-ready',
meta: { title: '证书齐备', isHide: true }
},
{
id: 'PL_REDIRECT_FREIGHT',
@@ -523,7 +552,7 @@ export const plRoutes: AppRouteRecord[] = [
name: 'PlDocumentReminderRedirect',
path: 'document-reminder',
redirect: '/pl/document-reminder-module/document-reminder',
meta: { title: '证件提醒', isHide: true }
meta: { title: '人车证件提醒', isHide: true }
}
]
},
+31 -1
View File
@@ -151,7 +151,37 @@ export const staticRoutes: AppRouteRecordRaw[] = [
path: '/m/pl/plan-cert',
name: 'MpPlPlanCert',
component: () => import('@views/m/pl/plan-cert/index.vue'),
meta: { title: '计划用证', isHideTab: true, isMpWebview: true }
meta: { title: '运输证件管理', isHideTab: true, isMpWebview: true }
},
{
path: '/m/pl/plan-cert/archive/:kind/create',
name: 'MpPlPlanCertArchiveCreate',
component: () => import('@views/m/pl/plan-cert/archive-form.vue'),
meta: { title: '新增证件', isHideTab: true, isMpWebview: true }
},
{
path: '/m/pl/plan-cert/archive/:kind/:id/edit',
name: 'MpPlPlanCertArchiveEdit',
component: () => import('@views/m/pl/plan-cert/archive-form.vue'),
meta: { title: '编辑证件', isHideTab: true, isMpWebview: true }
},
{
path: '/m/pl/plan-cert/archive/:kind/:id',
name: 'MpPlPlanCertArchive',
component: () => import('@views/m/pl/plan-cert/archive-detail.vue'),
meta: { title: '证件建档', isHideTab: true, isMpWebview: true }
},
{
path: '/m/pl/plan-cert/contract/:id',
name: 'MpPlPlanCertContract',
component: () => import('@views/m/pl/plan-cert/contract-detail.vue'),
meta: { title: '合同用证', isHideTab: true, isMpWebview: true }
},
{
path: '/m/pl/plan-cert/usage/:kind/:id',
name: 'MpPlPlanCertUsage',
component: () => import('@views/m/pl/plan-cert/usage-detail.vue'),
meta: { title: '证件用量', isHideTab: true, isMpWebview: true }
},
{
path: '/m/pl/plan-cert/:id',
+4
View File
@@ -1021,5 +1021,9 @@
.el-form-item__content {
min-width: 0;
}
[class*='form-grid-'] + .dialog-section-title {
margin-top: 20px;
}
}
+28 -8
View File
@@ -123,7 +123,9 @@ html body .mp-wv-header__row .el-tag.el-tag--info {
.mp-quote-list,
.mp-contract-list,
.mp-plan-list,
.mp-plan-cert-list {
.mp-plan-cert-page,
.mp-plan-cert-list,
.mp-legal-doc-list {
/* 绿头与筛选零间距;标题行除安全区外不再额外上边距 */
.mp-wv-header {
margin-bottom: 0;
@@ -174,6 +176,12 @@ html body .mp-wv-header__row .el-tag.el-tag--info {
.van-dropdown-menu__title--active:after {
border-color: transparent transparent #fff #fff;
}
.van-dropdown-menu__item:only-child {
flex: 0 0 auto;
justify-content: flex-start;
padding-left: 2px;
}
}
.mp-wv-header__row {
@@ -355,34 +363,37 @@ html body .mp-wv-header__row .el-tag.el-tag--info {
}
}
/* 危化品证:标题不换行,放不下时在绿头内左右滑;下划线留在文字下方且不被裁切 */
.mp-plan-cert-list .mp-wv-header .mp-customer-view-tabs.van-tabs {
/* 运输证件管理:五个标题按文字宽度显示,放不下时横向滑动,不截断。 */
.mp-plan-cert-page .mp-wv-header .mp-customer-view-tabs.van-tabs {
--van-tabs-line-height: 44px;
.van-tabs__wrap {
height: 44px;
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
}
.van-tabs__nav {
box-sizing: border-box;
width: max-content !important;
min-width: 100%;
height: 44px;
padding: 0;
}
.van-tab {
flex: 0 0 auto !important;
flex: 1 0 auto !important;
align-items: center;
width: auto;
min-width: max-content;
height: 44px;
min-height: 44px;
padding: 0 12px;
padding: 0 6px;
}
.van-tab__text {
overflow: visible;
text-overflow: clip;
white-space: nowrap;
}
@@ -400,7 +411,8 @@ html body .mp-wv-header__row .el-tag.el-tag--info {
.mp-quote-list .mp-quote-list-card,
.mp-contract-list .mp-wv-flat-card,
.mp-plan-list .mp-wv-flat-card,
.mp-plan-cert-list .mp-wv-flat-card {
.mp-plan-cert-list .mp-wv-flat-card,
.mp-legal-doc-list .mp-wv-flat-card {
padding: 14px 14px 12px;
margin-bottom: 12px;
cursor: pointer;
@@ -769,7 +781,8 @@ html body .mp-wv-header__row .el-tag.el-tag--info {
.mp-contract-list .mp-wv-flat-card,
.mp-plan-list .mp-wv-flat-card,
.mp-plan-cert-list .mp-wv-flat-card {
.mp-plan-cert-list .mp-wv-flat-card,
.mp-legal-doc-list .mp-wv-flat-card {
.mp-wv-flat-card__meta {
margin-top: 4px;
font-size: 12px;
@@ -1140,6 +1153,13 @@ html body .mp-wv-header__row .el-tag.el-tag--info {
min-width: 0;
word-break: break-word;
}
> span.status-tag {
flex: 0 0 auto;
width: fit-content;
max-width: 100%;
align-self: center;
}
}
.mp-wv-card__destinations {
+9 -2
View File
@@ -63,8 +63,11 @@ export function getProductUnitLabel(
getLabel: (dictType: string, value: string) => string,
unit: string | null | undefined
): string {
if (!unit) return '—'
return getLabel('crm_product_unit', unit) || unit
const raw = String(unit || '').trim()
if (!raw) return '—'
const fromDict = getLabel('crm_product_unit', raw)
if (fromDict && fromDict !== raw && fromDict !== '—') return fromDict
return PRODUCT_UNIT_VALUE_TO_LABEL[raw] || fromDict || raw
}
/** CRM 计量单位「吨」的字典值及历史直存文案 */
@@ -87,6 +90,10 @@ const PRODUCT_UNIT_LABEL_TO_VALUE: Record<string, string> = {
台: 'unit'
}
const PRODUCT_UNIT_VALUE_TO_LABEL: Record<string, string> = Object.fromEntries(
Object.entries(PRODUCT_UNIT_LABEL_TO_VALUE).map(([label, value]) => [value, label])
)
/**
* 表单写入 / 提交用:统一为 crm_product_unit 字典值。
* 空值默认 dun;历史直存「吨」等中文标签映射为对应 value。
@@ -0,0 +1,26 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { SX_SEAL_URL, YD_SEAL_URL, rewriteContractSealSources } from './contract-seal-assets.ts'
describe('rewriteContractSealSources', () => {
it('points saved seal images at the small public files', () => {
const html = [
'<img src="/src/assets/images/yz.png" alt="印章" />',
'<img src="https://w.shanxiachem.com/src/assets/images/yd.png" alt="印章" />',
'<img src="/assets/yz-Ab12cd.png" alt="印章" />',
'<img src="/logo.gif" alt="logo" />'
].join('')
const out = rewriteContractSealSources(html)
assert.equal(out.includes('/src/assets/images/yz.png'), false)
assert.equal(out.includes('/src/assets/images/yd.png'), false)
assert.equal(out.includes('/assets/yz-Ab12cd.png'), false)
assert.equal(out.includes(`src="${SX_SEAL_URL}"`), true)
assert.equal(out.includes(`src="${YD_SEAL_URL}"`), true)
assert.equal(out.includes('/logo.gif'), true)
})
it('leaves the small seal url unchanged', () => {
const html = `<img src="${SX_SEAL_URL}" alt="印章" /><p>正文</p>`
assert.equal(rewriteContractSealSources(html), html)
})
})
@@ -0,0 +1,20 @@
/** 富文本里的印章小图。页面只显示约 140px,源图宽 280px,避免再解码 2MB 原图。 */
export const SX_SEAL_URL = '/seals/yz.png'
export const YD_SEAL_URL = '/seals/yd.png'
const SX_FILE = /(?:^|\/)yz(?:-[A-Za-z0-9_-]+)?\.png(?:[?#].*)?$/i
const YD_FILE = /(?:^|\/)yd(?:-[A-Za-z0-9_-]+)?\.png(?:[?#].*)?$/i
const IMG_SRC_RE = /(<img\b[^>]*\bsrc=["'])([^"']+)(["'])/gi
const isSmallSeal = (src: string, url: string) => src === url || src.endsWith(url)
/** 已保存模板里的原图、绝对地址和打包哈希文件名,打开编辑器前换成小图。 */
export const rewriteContractSealSources = (html: string): string => {
if (!html) return html
return html.replace(IMG_SRC_RE, (full, prefix: string, src: string, suffix: string) => {
if (isSmallSeal(src, SX_SEAL_URL) || isSmallSeal(src, YD_SEAL_URL)) return full
if (SX_FILE.test(src)) return `${prefix}${SX_SEAL_URL}${suffix}`
if (YD_FILE.test(src)) return `${prefix}${YD_SEAL_URL}${suffix}`
return full
})
}
+10 -2
View File
@@ -6,6 +6,13 @@ import axios, { type AxiosRequestConfig, type InternalAxiosRequestConfig } from
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
declare module 'axios' {
interface AxiosRequestConfig {
/** 为 true 时不弹出全局错误,由调用方自行提示 */
skipErrorMessage?: boolean
}
}
export interface BxApiResponse<T = unknown> {
code: number
msg: string
@@ -63,7 +70,8 @@ const bxAxios = axios.create({
})
/** FastAPI @router.get("/") 集合根须带尾斜杠,否则 307 重定向到绝对 URL 会丢 Authorization */
const BX_COLLECTION_ROOT = /^\/(transport\/(order|plan|freight)|reimburses|advances|payments|workflows|expense-items)$/
const BX_COLLECTION_ROOT =
/^\/(transport\/(order|plan|freight)|reimburses|advances|payments|workflows|expense-items)$/
function normalizeBxUrl(url?: string): string | undefined {
if (!url || url.endsWith('/')) return url
@@ -147,7 +155,7 @@ bxAxios.interceptors.response.use(
if (err.response?.status === 401) {
const userStore = useUserStore()
await userStore.logOut()
} else {
} else if (!err.config?.skipErrorMessage) {
const detail = err.response?.data?.detail || err.response?.data?.msg
const message =
typeof detail === 'string'
@@ -1,8 +1,10 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import {
alignStopProductUnitToContract,
allowedPackageSpecsForStopProduct,
collectContractProductRows
collectContractProductRows,
stopProductUnitLocked
} from './pl-plan-contract-product'
const hydrochloricAcid = collectContractProductRows([
@@ -48,3 +50,33 @@ describe('allowedPackageSpecsForStopProduct', () => {
)
})
})
describe('stop product unit from contract', () => {
const lines = [
{ id: 'line-1', productId: 'acid', unit: '吨' },
{ id: 'line-1', productId: 'acid', unit: '' }
]
it('locks the unit only after a contract line is bound', () => {
assert.equal(stopProductUnitLocked({ contractProductId: '' }), false)
assert.equal(stopProductUnitLocked({ contractProductId: 'line-1' }), true)
})
it('rewrites a different unit to the contract unit', () => {
const row = { contractProductId: 'line-1', unit: 'kg' }
assert.equal(alignStopProductUnitToContract(row, lines), true)
assert.equal(row.unit, 'dun')
})
it('treats 吨 and dun as the same unit', () => {
const row = { contractProductId: 'line-1', unit: 'dun' }
assert.equal(alignStopProductUnitToContract(row, lines), false)
assert.equal(row.unit, 'dun')
})
it('leaves an unbound row unit unchanged', () => {
const row = { contractProductId: '', unit: 'kg' }
assert.equal(alignStopProductUnitToContract(row, lines), false)
assert.equal(row.unit, 'kg')
})
})
@@ -1,4 +1,5 @@
import { resolvePackageSpecsFromPayload } from '@/utils/crm-package-spec'
import { normalizeProductUnitValue } from '@/utils/crm-product-display'
/** 从合同明细行收集 CRM productId */
export function collectContractProductIds(
@@ -45,6 +46,7 @@ export type ContractLineChoice = {
contractId: string
contractNo: string
label: string
unit: string
}
/** 同一产品在当前合同里的明细行,供历史行原位补合同编号。 */
@@ -68,6 +70,7 @@ export function contractLineChoicesForProduct(
id,
contractId,
contractNo,
unit: String(row.unit || '').trim() ? normalizeProductUnitValue(row.unit) : '',
label: specs.length ? `${contractNo} ${specs.join('、')}` : contractNo
})
}
@@ -212,6 +215,42 @@ export function allowedPackageSpecsForStopProduct(
return packageSpecsForProduct(boundRows, pid)
}
/** 已绑定合同产品行时,单位跟合同走,不能再改。 */
export function stopProductUnitLocked(row: { contractProductId?: string | null }): boolean {
return Boolean(String(row.contractProductId || '').trim())
}
/** 合同明细上的单位。同一明细被按包装拆成多行时,取第一条有单位的记录。 */
export function boundContractProductUnit(
rows: ContractProductRowLite[] | null | undefined,
contractProductId?: string | null
): string {
const boundId = String(contractProductId || '').trim()
if (!boundId) return ''
for (const row of rows || []) {
if (String(row.id || '').trim() !== boundId) continue
const unit = String(row.unit || '').trim()
if (unit) return normalizeProductUnitValue(unit)
}
return ''
}
/**
* 把已绑定行的单位改成合同单位。
* 返回 true 表示本次改写了单位,调用方应提示按合同单位核对数量。
*/
export function alignStopProductUnitToContract(
row: { contractProductId?: string | null; unit?: string | null },
rows: ContractProductRowLite[] | null | undefined
): boolean {
if (!stopProductUnitLocked(row)) return false
const contractUnit = boundContractProductUnit(rows, row.contractProductId)
if (!contractUnit) return false
if (normalizeProductUnitValue(row.unit) === contractUnit) return false
row.unit = contractUnit
return true
}
export function isPackageAllowedForContractProduct(
rows: ContractProductRowLite[] | null | undefined,
productId: string,
+2
View File
@@ -45,6 +45,8 @@ export interface PlanStopProductFormRow {
contractId?: string
contractProductId?: string
contractNo?: string
/** 打开旧单时单位曾与合同不一致,提示按合同单位核对数量。不提交。 */
contractUnitNote?: string
}
/** 段次查看/归档:装货段取 inbound,送货段取 outbound */
@@ -0,0 +1,19 @@
/** 已标记证书齐备时,只保留服务端仍要拦住的来源问题,不再用本地两证缺口补一条拦截。 */
export function toxicArrangeBlockMessage(
quota: { quotaCertWaived?: boolean; arrangeBlockMessage?: string } | null | undefined,
unboundMessage: string
) {
const serverMessage = (quota?.arrangeBlockMessage || '').trim()
if (quota?.quotaCertWaived) return serverMessage
return serverMessage || unboundMessage
}
export function certReadyErrorText(error: unknown, fallback: string) {
const detail = (error as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail
return typeof detail === 'string' && detail.trim() ? detail : fallback
}
export function formatCertReadyTime(value?: string | null) {
if (!value) return '—'
return value.replace('T', ' ').slice(0, 16)
}
@@ -3,7 +3,8 @@ import { describe, it } from 'node:test'
import {
applyColumnWidthDelta,
applyRowHeightDelta,
clampColumnWidthsToMax
clampColumnWidthsToMax,
isInsideEdgeBand
} from './tinymce-table-edge-resize.ts'
describe('applyColumnWidthDelta', () => {
@@ -35,6 +36,14 @@ describe('clampColumnWidthsToMax', () => {
})
})
describe('isInsideEdgeBand', () => {
it('stays false until the pointer is inside the edge band', () => {
assert.equal(isInsideEdgeBand(9, true, 8), false)
assert.equal(isInsideEdgeBand(8, false, 8), false)
assert.equal(isInsideEdgeBand(8, true, 8), true)
})
})
describe('applyRowHeightDelta', () => {
it('keeps row height at or above 20px', () => {
assert.equal(applyRowHeightDelta(30, 10), 40)
@@ -11,6 +11,13 @@ export const MIN_ROW_PX = 20
export const A4_CONTENT_WIDTH_PX = 680
const EDGE_PX = 8
/** 只有指针已经进入边线热区,才需要继续判断列号。列号要扫整张表。 */
export const isInsideEdgeBand = (
distanceToEdge: number,
insideCrossAxis: boolean,
edgePx = EDGE_PX
): boolean => insideCrossAxis && distanceToEdge <= edgePx
const HANDLE_PX = 8
const LAYER_ID = 'sx-edge-resize-layer'
const HANDLE_CLASS = 'sx-edge-resize-handle'
@@ -233,6 +240,7 @@ const handleMeta = new WeakMap<
export const setupTableEdgeResize = (editor: any): void => {
let state: DragState | null = null
let layer: HTMLElement | null = null
let hover: { cell: HTMLTableCellElement; kind: 'col' | 'row' } | null = null
const docOf = (): Document | null => (editor.getDoc?.() as Document | null) ?? null
const bodyOf = (): HTMLElement | null => (editor.getBody?.() as HTMLElement | null) ?? null
@@ -300,17 +308,26 @@ export const setupTableEdgeResize = (editor: any): void => {
const fromBottom = Math.abs(event.clientY - rect.bottom)
const insideY = event.clientY >= rect.top - EDGE_PX && event.clientY <= rect.bottom + EDGE_PX
const insideX = event.clientX >= rect.left - EDGE_PX && event.clientX <= rect.right + EDGE_PX
const canCol = row.rowIndex === 0 && (cell.colSpan || 1) === 1 && fromRight <= EDGE_PX && insideY
const canRow = columnOrigin(table, cell) === 0 && fromBottom <= EDGE_PX && insideX
const nearRight = isInsideEdgeBand(fromRight, insideY)
const nearBottom = isInsideEdgeBand(fromBottom, insideX)
if (!nearRight && !nearBottom) return null
const canCol = nearRight && row.rowIndex === 0 && (cell.colSpan || 1) === 1
const canRow = nearBottom && columnOrigin(table, cell) === 0
if (canCol && canRow) return { cell, kind: fromRight <= fromBottom ? 'col' : 'row' }
if (canCol) return { cell, kind: 'col' }
if (canRow) return { cell, kind: 'row' }
return null
}
const clearHover = () => {
if (!hover && !layer?.childElementCount) return
hover = null
clearHandle()
}
const onMouseMove = (event: MouseEvent) => {
if (isReadonly(editor)) {
clearHandle()
clearHover()
return
}
if (state) {
@@ -331,9 +348,11 @@ export const setupTableEdgeResize = (editor: any): void => {
if (target?.classList?.contains(HANDLE_CLASS)) return
const edge = edgeCell(event)
if (!edge) {
clearHandle()
clearHover()
return
}
if (hover && hover.cell === edge.cell && hover.kind === edge.kind) return
hover = { cell: edge.cell, kind: edge.kind }
placeHandle(edge.cell, edge.kind)
}
@@ -400,6 +419,7 @@ export const setupTableEdgeResize = (editor: any): void => {
layer?.remove()
layer = null
state = null
hover = null
}
editor.on('BeforeGetContent', () => {
-11
View File
@@ -134,14 +134,3 @@ export const refreshFilterCollapse = (): void => {
})
}
export const setupFilterCollapseObserver = (): MutationObserver => {
refreshFilterCollapse()
const observer = new MutationObserver(() => {
refreshFilterCollapse()
})
observer.observe(document.body, {
childList: true,
subtree: true
})
return observer
}
+135 -2
View File
@@ -20,6 +20,9 @@
<el-button class="btn-main" type="primary" @click="handleToolbarIssue">
<el-icon><Check /></el-icon>发放
</el-button>
<el-button class="btn-ghost" @click="openBatchIssueDialog">
<el-icon><Document /></el-icon>批量发放
</el-button>
<el-button
v-if="hasActiveFilters"
class="btn-ghost"
@@ -634,6 +637,63 @@
</template>
</el-dialog>
<!-- 批量发放 -->
<el-dialog
v-model="dialogs.batchIssue"
title="批量发放"
width="960px"
class="dialog-form-layout"
align-center
destroy-on-close
:close-on-click-modal="false"
>
<el-form label-position="top" class="bx-dialog-form">
<h4 class="dialog-section-title">已选备用金</h4>
<el-table :data="batchLines" class="list-table" stripe max-height="320">
<el-table-column type="index" label="序号" width="68" align="center" header-align="center" />
<el-table-column prop="applyCode" label="申请单号" min-width="150" align="center" header-align="center" />
<el-table-column prop="applicantName" label="申请人" min-width="90" align="center" header-align="center" />
<el-table-column
prop="reason"
label="申请原因"
min-width="160"
align="left"
header-align="center"
show-overflow-tooltip
/>
<el-table-column label="发放金额(元)" min-width="130" align="right" header-align="center" class-name="col-money">
<template #default="{ row }">
{{ formatMoney(row.payAmount) }}
</template>
</el-table-column>
<el-table-column label="实际发放金额(元)" min-width="160" align="center" header-align="center">
<template #default="{ row }">
<el-input v-model="row.actualAmount" placeholder="请输入实际发放金额" />
</template>
</el-table-column>
</el-table>
<el-form-item label="发放备注" class="batch-issue-remark">
<el-input v-model="batchIssueRemark" type="textarea" :rows="3" placeholder="请输入发放备注" />
</el-form-item>
<h4 class="dialog-section-title">发放附件(必填)</h4>
<BxAttachmentUpload
ref="batchAttachmentRef"
v-model="batchFiles"
biz-type="advance_issue"
biz-id="0"
hint="同一批备用金共用这些发放凭证,至少 1 个附件。"
/>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="dialogs.batchIssue = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="loadingMap.batchIssueSubmit" @click="submitBatchIssue">
<el-icon><Check /></el-icon>确认发放
</el-button>
</template>
</el-dialog>
<!-- 查看详情 -->
<el-dialog
v-model="dialogs.view"
@@ -720,7 +780,7 @@ import ListQuickSearchInput from '@/components/business/list-quick-search-input/
import { reactive, ref, computed, onMounted, nextTick, provide } from 'vue'
import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight'
import { ElMessage } from 'element-plus'
import { Check, Close, Filter } from '@element-plus/icons-vue'
import { Check, Close, Document, Filter } from '@element-plus/icons-vue'
import { paymentApi, advanceApi,
fetchAdvanceColumnFacetValues
} from '@/api/bx'
@@ -737,7 +797,7 @@ import { bxViewKv } from '@/utils/bx/view-kv'
import type { StatsRowColumn } from '@/utils/list-column-stats'
import { advanceIssueColumnFilterDefs } from './columnFilterDefs'
type DialogKey = 'issue' | 'view'
type DialogKey = 'issue' | 'batchIssue' | 'view'
const listColumnDefs = [
{ prop: 'applyTime', label: '申请时间' },
@@ -821,6 +881,7 @@ const issuedStatsRowColumns = computed(() =>
const loadingMap = reactive<Record<string, boolean>>({})
const dialogs = reactive<Record<DialogKey, boolean>>({
issue: false,
batchIssue: false,
view: false
})
@@ -955,6 +1016,19 @@ const viewIssueKvFields = computed<ViewField[]>(() => {
const actualAmount = ref<number | string>('')
const uploadedFiles = ref<BxAttachmentItem[]>([])
const issueAttachmentRef = ref<InstanceType<typeof BxAttachmentUpload> | null>(null)
const batchIssueRemark = ref('')
const batchFiles = ref<BxAttachmentItem[]>([])
const batchAttachmentRef = ref<InstanceType<typeof BxAttachmentUpload> | null>(null)
const batchLines = ref<
Array<{
id: string
applyCode: string
applicantName: string
reason: string
payAmount: string
actualAmount: string
}>
>([])
const viewAttachments = ref<BxAttachmentItem[]>([])
const approvalNodes = ref<Array<any>>([])
const approvalHistory = ref<Array<any>>([])
@@ -1013,6 +1087,61 @@ function openIssueDialog(row: any) {
dialogs.issue = true
}
function openBatchIssueDialog() {
if (selectedRows.value.length === 0) {
ElMessage.warning('请先勾选待发放记录')
return
}
batchLines.value = selectedRows.value.map((row) => {
const payAmount = String(row.amount ?? '')
return {
id: String(row.id),
applyCode: row.applyCode || '',
applicantName: row.applicantName || '',
reason: row.reason || '',
payAmount,
actualAmount: payAmount
}
})
batchIssueRemark.value = ''
batchFiles.value = []
dialogs.batchIssue = true
}
async function submitBatchIssue() {
if (batchFiles.value.length === 0) {
ElMessage.warning('请至少上传 1 个发放附件')
return
}
if (batchAttachmentRef.value?.hasUploading()) {
ElMessage.warning('附件上传中,请稍候')
return
}
const items = batchLines.value.map((line) => ({
id: line.id,
actualAmount: Number(line.actualAmount)
}))
if (items.some((item) => !Number.isFinite(item.actualAmount) || item.actualAmount < 0)) {
ElMessage.warning('请填写有效的实际发放金额')
return
}
loadingMap.batchIssueSubmit = true
try {
await paymentApi.batchIssueAdvance({
issueRemark: batchIssueRemark.value,
items,
attachmentIds: batchFiles.value.map((file) => file.id)
})
ElMessage.success('发放成功')
dialogs.batchIssue = false
await refresh()
} catch (e: any) {
ElMessage.error(e.message || '发放失败')
} finally {
loadingMap.batchIssueSubmit = false
}
}
async function submitIssue() {
if (uploadedFiles.value.length === 0) {
ElMessage.warning('请至少上传 1 个发放附件')
@@ -1083,4 +1212,8 @@ async function openView(row: any) {
.bx-list-table-wrap {
min-width: 0;
}
.batch-issue-remark {
margin-top: 16px;
}
</style>
+131 -1
View File
@@ -21,6 +21,9 @@
<el-button class="btn-main" type="primary" @click="handleToolbarIssue">
<el-icon><Money /></el-icon>发放
</el-button>
<el-button class="btn-ghost" @click="openBatchIssueDialog">
<el-icon><Document /></el-icon>批量发放
</el-button>
<el-button class="btn-ghost" @click="handleToolbarOffset">
<el-icon><Switch /></el-icon>冲抵备用金
</el-button>
@@ -681,6 +684,63 @@
</template>
</el-dialog>
<!-- 批量发放 -->
<el-dialog
v-model="dialogs.batchIssue"
title="批量发放"
width="960px"
class="dialog-form-layout"
align-center
destroy-on-close
:close-on-click-modal="false"
>
<el-form label-position="top" class="bx-dialog-form">
<h4 class="dialog-section-title">已选报销单</h4>
<el-table :data="batchLines" class="list-table" stripe max-height="320">
<el-table-column type="index" label="序号" width="68" align="center" header-align="center" />
<el-table-column prop="applyCode" label="单号" min-width="150" align="center" header-align="center" />
<el-table-column prop="applicantName" label="申请人" min-width="90" align="center" header-align="center" />
<el-table-column
prop="title"
label="报销标题"
min-width="160"
align="left"
header-align="center"
show-overflow-tooltip
/>
<el-table-column label="发放金额(元)" min-width="130" align="right" header-align="center" class-name="col-money">
<template #default="{ row }">
{{ formatMoney(row.payAmount) }}
</template>
</el-table-column>
<el-table-column label="实际发放金额(元)" min-width="160" align="center" header-align="center">
<template #default="{ row }">
<el-input v-model="row.actualAmount" placeholder="请输入实际发放金额" />
</template>
</el-table-column>
</el-table>
<el-form-item label="备注" class="batch-issue-remark">
<el-input v-model="batchIssueRemark" type="textarea" :rows="3" placeholder="请输入备注" />
</el-form-item>
<h4 class="dialog-section-title">发放附件</h4>
<BxAttachmentUpload
ref="batchAttachmentRef"
v-model="batchFiles"
biz-type="reimburse_pay"
biz-id="0"
hint="同一批报销单共用这些发放凭证。"
/>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="dialogs.batchIssue = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="loadingMap.batchIssueSubmit" @click="submitBatchIssue">
<el-icon><Check /></el-icon>确认发放
</el-button>
</template>
</el-dialog>
<!-- 冲抵备用金 -->
<el-dialog
v-model="dialogs.offset"
@@ -876,6 +936,7 @@ import { useListTableViewportHeight } from '@/composables/useListTableViewportHe
import { ElMessage, ElMessageBox } from 'element-plus'
import {
Money,
Document,
Switch,
Close,
Check,
@@ -900,7 +961,7 @@ import { bxViewKv, bxViewKvMoney } from '@/utils/bx/view-kv'
import type { StatsRowColumn } from '@/utils/list-column-stats'
import { paymentColumnFilterDefs } from './columnFilterDefs'
type DialogKey = 'viewDetail' | 'issue' | 'offset' | 'processedDetail'
type DialogKey = 'viewDetail' | 'issue' | 'batchIssue' | 'offset' | 'processedDetail'
const listColumnDefs = [
{ prop: 'applyTime', label: '申请时间' },
@@ -989,6 +1050,7 @@ const loadingMap = reactive<Record<string, boolean>>({})
const dialogs = reactive<Record<DialogKey, boolean>>({
viewDetail: false,
issue: false,
batchIssue: false,
offset: false,
processedDetail: false
})
@@ -1126,6 +1188,19 @@ const viewPayKvFields = computed<ViewField[]>(() => {
})
const issueRemark = ref('')
const actualAmount = ref('')
const batchIssueRemark = ref('')
const batchFiles = ref<BxAttachmentItem[]>([])
const batchAttachmentRef = ref<InstanceType<typeof BxAttachmentUpload> | null>(null)
const batchLines = ref<
Array<{
id: string
applyCode: string
applicantName: string
title: string
payAmount: string
actualAmount: string
}>
>([])
const offsetRemark = ref('')
const uploadedFiles = ref<BxAttachmentItem[]>([])
const issueAttachmentRef = ref<InstanceType<typeof BxAttachmentUpload> | null>(null)
@@ -1343,6 +1418,57 @@ function openIssueDialog(row: any) {
dialogs.issue = true
}
function openBatchIssueDialog() {
if (selectedRows.value.length === 0) {
ElMessage.warning('请先勾选待处理记录')
return
}
batchLines.value = selectedRows.value.map((row) => {
const payAmount = String(row.amount ?? '')
return {
id: String(row.id),
applyCode: row.applyCode || '',
applicantName: row.applicantName || '',
title: row.title || '',
payAmount,
actualAmount: payAmount
}
})
batchIssueRemark.value = ''
batchFiles.value = []
dialogs.batchIssue = true
}
async function submitBatchIssue() {
if (batchAttachmentRef.value?.hasUploading()) {
ElMessage.warning('附件上传中,请稍候')
return
}
const items = batchLines.value.map((line) => ({
id: line.id,
actualAmount: Number(line.actualAmount)
}))
if (items.some((item) => !Number.isFinite(item.actualAmount) || item.actualAmount < 0)) {
ElMessage.warning('请填写有效的实际发放金额')
return
}
loadingMap.batchIssueSubmit = true
try {
await paymentApi.batchPay({
payRemark: batchIssueRemark.value,
items,
attachmentIds: batchFiles.value.map((file) => file.id)
})
ElMessage.success('发放成功')
dialogs.batchIssue = false
await refresh()
} catch (e: any) {
ElMessage.error(e.message || '发放失败')
} finally {
loadingMap.batchIssueSubmit = false
}
}
async function submitIssue() {
if (issueAttachmentRef.value?.hasUploading()) {
ElMessage.warning('附件上传中,请稍候')
@@ -1589,4 +1715,8 @@ function processedStatusTagType(
.bx-list-table-wrap {
min-width: 0;
}
.batch-issue-remark {
margin-top: 16px;
}
</style>
@@ -24,13 +24,6 @@
>{{ dictStore.getLabel('crm_contract_status', detailContract?.status) }}</el-tag>
</div>
<div class="detail-actions">
<el-button
v-if="canViewQuotaCert && detailContract?.id"
class="btn-ghost"
@click="router.push({ name: 'PlQuotaCert', query: { contractId: String(detailContract.id) } })"
>
<el-icon><DocumentChecked /></el-icon>适用证件与产品
</el-button>
<el-button
v-if="manageActions"
class="btn-ghost"
@@ -934,6 +927,7 @@
append-to-body
class="dialog-form-layout generate-print-dialog"
modal-class="order-module-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<template #header>
@@ -1090,6 +1084,7 @@ import jsPDF from 'jspdf';
import { fitRichTextTablesToMaxWidth } from '@/utils/tinymce-table-excel-resize';
import { applySavedProductTableLayout, stampSavedProductTableLayout } from '@/utils/crm/contract-table-layout';
import { appendContractPageWatermarks, contractWatermarkPrintCss } from '@/utils/crm/contract-watermark';
import { SX_SEAL_URL, YD_SEAL_URL, rewriteContractSealSources } from '@/utils/crm/contract-seal-assets';
import { countContractPdfPages } from '@/utils/crm/contract-pdf-pages';
import {
downloadCrmAttachment,
@@ -1980,7 +1975,8 @@ const hasSelfPickupProduct = (products?: Array<{ deliveryMethod?: string }> | nu
/** 替换模板中的占位符为数据库最新数据(运费取合同自身 freight) */
const replacePlaceholders = (htmlContent: string, contractData: ContractVO | undefined): string => {
if (!htmlContent || !contractData) return htmlContent;
if (!htmlContent) return htmlContent;
if (!contractData) return rewriteContractSealSources(htmlContent);
let result = htmlContent;
@@ -2310,10 +2306,10 @@ const replacePlaceholders = (htmlContent: string, contractData: ContractVO | und
const getSealImageByCompanyName = (companyName: string | undefined): string => {
if (!companyName) return '';
if (companyName.includes('云栋') || companyName.includes('安徽云栋化工有限公司')) {
return '/src/assets/images/yd.png';
return YD_SEAL_URL;
}
if (companyName.includes('山峡') || companyName.includes('安庆市山峡化工有限公司')) {
return supplierCode === 'SX' ? '/src/assets/images/yz.png' : '/src/assets/images/yd.png';
return supplierCode === 'SX' ? SX_SEAL_URL : YD_SEAL_URL;
}
return '';
};
@@ -2329,7 +2325,7 @@ const replacePlaceholders = (htmlContent: string, contractData: ContractVO | und
result = result.replace(/\{\{partyASeal\}\}/gi, getSealHtml(contractData.partyA));
result = result.replace(/\{\{partyBSeal\}\}/gi, getSealHtml(contractData.partyB));
return applySavedProductTableLayout(result);
return rewriteContractSealSources(applySavedProductTableLayout(result));
};
/** 替换模板第五条内容 */
@@ -2526,20 +2522,20 @@ const generateContractTemplate = (contractData: ContractVO | undefined): string
// 根据公司名称决定印章文件
// 判断函数:根据公司名称返回对应的印章文件路径
const getSealImageByCompanyName = (companyName: string | undefined): string => {
if (!companyName) return '/src/assets/images/yz.png'; // 默认
if (!companyName) return SX_SEAL_URL; // 默认
// 如果是云栋公司,使用 yd.png
if (companyName.includes('云栋') || companyName.includes('安徽云栋化工有限公司')) {
return '/src/assets/images/yd.png';
return YD_SEAL_URL;
}
// 如果是山峡公司,根据供方编码决定
if (companyName.includes('山峡') || companyName.includes('安庆市山峡化工有限公司')) {
return supplierCode === 'SX' ? '/src/assets/images/yz.png' : '/src/assets/images/yd.png';
return supplierCode === 'SX' ? SX_SEAL_URL : YD_SEAL_URL;
}
// 默认使用 yz.png
return '/src/assets/images/yz.png';
return SX_SEAL_URL;
};
// 获取单位字典标签的辅助函数
@@ -2967,10 +2963,10 @@ const getSupplierCodeFromContractNo = (contractNo?: string): string => {
const resolveSealImageByCompanyName = (companyName: string | undefined, supplierCode: string): string => {
if (!companyName) return '';
if (companyName.includes('云栋') || companyName.includes('安徽云栋化工有限公司')) {
return '/src/assets/images/yd.png';
return YD_SEAL_URL;
}
if (companyName.includes('山峡') || companyName.includes('安庆市山峡化工有限公司')) {
return supplierCode === 'SX' ? '/src/assets/images/yz.png' : '/src/assets/images/yd.png';
return supplierCode === 'SX' ? SX_SEAL_URL : YD_SEAL_URL;
}
return '';
};
+9 -6
View File
@@ -1150,6 +1150,7 @@
width="1200px"
append-to-body
class="generate-print-dialog"
destroy-on-close
:close-on-click-modal="false"
>
<template #header>
@@ -1244,6 +1245,7 @@ import { jsPDF } from 'jspdf';
import { fitRichTextTablesToMaxWidth } from '@/utils/tinymce-table-excel-resize';
import { applySavedProductTableLayout, stampSavedProductTableLayout } from '@/utils/crm/contract-table-layout';
import { appendContractPageWatermarks, contractWatermarkPrintCss } from '@/utils/crm/contract-watermark';
import { SX_SEAL_URL, YD_SEAL_URL, rewriteContractSealSources } from '@/utils/crm/contract-seal-assets';
const router = useRouter();
const route = useRoute();
@@ -1616,7 +1618,8 @@ const hasSelfPickupProduct = (products?: Array<{ deliveryMethod?: string }> | nu
* 用于每次打开富文本时动态更新数据
*/
const replacePlaceholders = (htmlContent: string, contractData: ContractVO | undefined): string => {
if (!htmlContent || !contractData) return htmlContent;
if (!htmlContent) return htmlContent;
if (!contractData) return rewriteContractSealSources(htmlContent);
let result = htmlContent;
@@ -1895,7 +1898,7 @@ const replacePlaceholders = (htmlContent: string, contractData: ContractVO | und
}
}
return applySavedProductTableLayout(result);
return rewriteContractSealSources(applySavedProductTableLayout(result));
};
/**
@@ -2280,7 +2283,7 @@ const generateContractTemplate = (contractData: ContractVO | undefined): string
<div style="flex: 1; padding-right: 10px; border: 1px solid #000; padding: 8px; line-height: 1.3; font-size: 12px; position: relative;">
<div style="font-weight: bold; margin-bottom: 5px; padding-bottom: 5px; border-bottom: 1px solid #000;">供方</div>
<!-- 印章图片:根据partyA是否为山峡公司来判断是否调换,如果partyA不是山峡公司,则不显示印章 -->
${contractData.partyA && (contractData.partyA.includes('山峡') || contractData.partyA.includes('安庆市山峡化工有限公司')) ? '<img src="/src/assets/images/yz.png" alt="印章" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 140px; height: 140px; opacity: 0.85; z-index: 10;" />' : ''}
${contractData.partyA && (contractData.partyA.includes('山峡') || contractData.partyA.includes('安庆市山峡化工有限公司')) ? '<img src="' + SX_SEAL_URL + '" alt="印章" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 140px; height: 140px; opacity: 0.85; z-index: 10;" />' : ''}
<div style="margin-bottom: 0;">单位名称(章):${contractData.partyA || '安庆市山峡化工有限公司'}</div>
<div style="margin-bottom: 0;">单位地址:${contractData.partyAAddress || '安徽省安庆市迎江大道5号'}</div>
<div style="margin-bottom: 0;">法定代表人:${contractData.partyALegalPerson || ''}</div>
@@ -2292,7 +2295,7 @@ const generateContractTemplate = (contractData: ContractVO | undefined): string
<div style="flex: 1; padding-left: 10px; border: 1px solid #000; padding: 8px; line-height: 1.3; font-size: 12px; position: relative;">
<div style="font-weight: bold; margin-bottom: 5px; padding-bottom: 5px; border-bottom: 1px solid #000;">需方</div>
<!-- 印章图片:如果partyB是山峡公司,则显示印章(说明供需方已调换) -->
${contractData.partyB && (contractData.partyB.includes('山峡') || contractData.partyB.includes('安庆市山峡化工有限公司')) ? '<img src="/src/assets/images/yz.png" alt="印章" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 140px; height: 140px; opacity: 0.85; z-index: 10;" />' : ''}
${contractData.partyB && (contractData.partyB.includes('山峡') || contractData.partyB.includes('安庆市山峡化工有限公司')) ? '<img src="' + SX_SEAL_URL + '" alt="印章" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 140px; height: 140px; opacity: 0.85; z-index: 10;" />' : ''}
<div style="margin-bottom: 0;">单位名称(章):${contractData.partyB || contractData.customerName || ''}</div>
<div style="margin-bottom: 0;">单位地址:${contractData.partyBAddress || ''}</div>
<div style="margin-bottom: 0;">法定代表人:${contractData.partyBLegalPerson || ''}</div>
@@ -2835,10 +2838,10 @@ const getSupplierCodeFromContractNo = (contractNo?: string): string => {
const resolveSealImageByCompanyName = (companyName: string | undefined, supplierCode: string): string => {
if (!companyName) return '';
if (companyName.includes('云栋') || companyName.includes('安徽云栋化工有限公司')) {
return '/src/assets/images/yd.png';
return YD_SEAL_URL;
}
if (companyName.includes('山峡') || companyName.includes('安庆市山峡化工有限公司')) {
return supplierCode === 'SX' ? '/src/assets/images/yz.png' : '/src/assets/images/yd.png';
return supplierCode === 'SX' ? SX_SEAL_URL : YD_SEAL_URL;
}
return '';
};
@@ -622,6 +622,7 @@
append-to-body
class="dialog-form-layout generate-print-dialog"
modal-class="order-module-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<template #header>
@@ -894,8 +895,7 @@ import request from '@/utils/http';
import TinyMceEditor from '@/components/TinyMceEditor/index.vue';
import { getSupplierInfo, type SupplierInfoVO } from '@/api/crm/supplierInfo';
import logoImg from '@/assets/images/logo.gif';
import yzImg from '@/assets/images/yz.png';
import ydImg from '@/assets/images/yd.png';
import { SX_SEAL_URL, YD_SEAL_URL, rewriteContractSealSources } from '@/utils/crm/contract-seal-assets';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { countContractPdfPages as countQuotePdfPages } from '@/utils/crm/contract-pdf-pages';
@@ -2634,7 +2634,7 @@ const generateQuoteTemplate = (quote: QuoteVO, supplierInfo?: SupplierInfoVO): s
const showLogo = supplierCode === 'SX';
const brandName = showLogo ? '山峡' : supplierShortName || supplierName || '山峡';
const quoteTitle = `${brandName}${quoteTypeLabel}报价单`;
const sealImg = supplierCode === 'SX' ? yzImg : supplierCode === 'YD' ? ydImg : null;
const sealImg = supplierCode === 'SX' ? SX_SEAL_URL : supplierCode === 'YD' ? YD_SEAL_URL : null;
const dynamicProductSection = buildQuoteDynamicProductSection(quote);
return `
@@ -2822,7 +2822,7 @@ const handleGenerateQuote = async (row?: QuoteVO) => {
console.log('HTML内容预览:', htmlContent.substring(0, 200));
// 先设置内容,再打开对话框(每次打开默认显示红章)
quoteContent.value = htmlContent;
quoteContent.value = rewriteContractSealSources(htmlContent);
showRedSeal.value = true;
console.log('quoteContent已设置');
@@ -2845,7 +2845,7 @@ const QUOTE_SEAL_IMG_STYLE =
'position: absolute; left: 50%; top: calc(50% - 50px); transform: translate(-50%, -50%); width: 120px; max-width: 120px; max-height: 120px; height: auto; object-fit: contain; z-index: 10; pointer-events: none; opacity: 0.9;';
const buildQuoteSealHtml = (supplierCode: string): string => {
const sealImg = supplierCode === 'SX' ? yzImg : supplierCode === 'YD' ? ydImg : null;
const sealImg = supplierCode === 'SX' ? SX_SEAL_URL : supplierCode === 'YD' ? YD_SEAL_URL : null;
if (!sealImg) return '';
return `<img src="${sealImg}" alt="印章" style="${QUOTE_SEAL_IMG_STYLE}" />`;
};
@@ -121,21 +121,18 @@
prepareContractHtmlForDocx
} from '@/utils/crm/contract-html-to-docx'
import { deliverContractFile } from './deliverContractFile'
import sxSealUrl from '@/assets/images/yz.png'
import ydSealUrl from '@/assets/images/yd.png'
import logoUrl from '@/assets/images/logo.gif'
import {
SX_SEAL_URL as sxSealUrl,
YD_SEAL_URL as ydSealUrl,
rewriteContractSealSources
} from '@/utils/crm/contract-seal-assets'
const normalizePrintAssets = (html: string) =>
html.replace(
/(?:https?:\/\/[^\s"'<>]+)?\/src\/assets\/images\/(yz\.png|yd\.png|logo\.gif)/g,
(_match, name) =>
({ 'yz.png': sxSealUrl, 'yd.png': ydSealUrl, 'logo.gif': logoUrl })[name] || _match
rewriteContractSealSources(html).replace(
/(?:https?:\/\/[^\s"'<>]+)?\/src\/assets\/images\/logo\.gif/g,
logoUrl
)
const restoreStoredAssets = (html: string) =>
[
[sxSealUrl, 'yz.png'],
[ydSealUrl, 'yd.png'],
[logoUrl, 'logo.gif']
].reduce((content, [url, name]) => content.split(url).join(`/src/assets/images/${name}`), html)
const restoreStoredAssets = (html: string) => html.split(logoUrl).join('/src/assets/images/logo.gif')
const loadingText = ref('')
const props = defineProps<{ contractId: string }>()
onMounted(() => {
@@ -1,41 +1,100 @@
<template>
<MpWebviewShell @ready="init">
<MpBusinessHeader
title="合法使用证明"
searchable
:keyword="keyword"
search-placeholder="输入计划编号"
@update:keyword="keyword = $event"
@search="load"
@back="goToMiniWorkbench"
/>
<main class="mp-h5-list-content">
<van-dropdown-menu
><van-dropdown-item v-model="status" :options="statusOptions" @change="load"
/></van-dropdown-menu>
<p class="form-tip">易制爆产品的合法使用证明可在安排、归档后补传,不影响额度预占。</p>
<p v-if="error" role="alert">{{ error }}</p>
<van-loading v-if="loading" />
<section v-for="row in rows" :key="row.id" class="mp-wv-section"
><h3>{{ row.planNo }}</h3
><p>{{ row.products.map((p) => p.productName).join('、') }}</p
><van-tag
:type="row.products.every((p) => p.documentStatus === 'uploaded') ? 'success' : 'warning'"
>{{ row.products.filter((p) => p.documentStatus === 'pending').length }} 项待补</van-tag
><van-button block plain type="primary" @click="open(row.id)">{{
canUpload ? '维护资料' : '查看资料'
}}</van-button></section
<div class="mp-legal-doc-list">
<MpBusinessHeader
title="合法使用证明"
searchable
:keyword="keyword"
search-placeholder="输入计划编号"
search-label="搜索合法使用证明"
back-label="返回工作台"
@update:keyword="keyword = $event"
@search="search"
@back="goToMiniWorkbench"
>
<van-empty v-if="!loading && !rows.length && !error" description="暂无符合条件的计划" />
</main>
<template #after-search>
<van-dropdown-menu class="mp-customer-dd">
<van-dropdown-item v-model="status" :options="uploadOptions" @change="search" />
</van-dropdown-menu>
</template>
</MpBusinessHeader>
<main class="mp-h5-list-content">
<p class="mp-legal-doc-note">易制爆产品的合法使用证明可在安排、归档后补传,不影响额度预占。</p>
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="allowed ? load() : init()">重试</button>
</p>
<div v-if="!authReady || (loading && !rows.length)" class="mp-legal-doc-loading">
<van-loading />
</div>
<div v-else-if="!allowed && !error" class="mp-wv-empty">
<div class="mp-wv-empty__title">无合法使用证明查看权限</div>
</div>
<template v-else>
<article
v-for="row in rows"
:key="row.id"
class="mp-wv-card mp-wv-flat-card"
@click="open(row.id)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.planNo || '—' }}</div>
<div class="mp-wv-card__sub">
{{ planWhen(row.planDate) }} · {{ row.licensePlate || '—' }}
</div>
</div>
<span class="status-tag" :class="`status-tag--${statusTag(row.documentStatus)}`">
{{ statusLabel(row.documentStatus) }}
</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>易制爆产品</span><span>{{ row.productNames || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>供方</span><span>{{ row.supplierName || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>需方</span><span>{{ row.customerName || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>跟进状态</span>
<span class="status-tag" :class="`status-tag--${followTag(row.followStatus)}`">
{{ followLabel(row.followStatus) }}
</span>
</div>
<div class="mp-wv-card__kv-row">
<span>已上传 / 应上传</span>
<span>{{ row.uploadedCount || 0 }} / {{ row.requiredCount || 0 }}</span>
</div>
</div>
<div class="mp-wv-card-actions mp-wv-card-actions--single" @click.stop>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="open(row.id)">
{{ canUpload ? '维护资料' : '查看资料' }}
</button>
</div>
</article>
<div v-if="rows.length && rows.length < total" class="mp-legal-doc-more">
<button class="mp-wv-btn" type="button" :disabled="loading" @click="more">
{{ loading ? '正在加载…' : '加载更多' }}
</button>
</div>
<p v-else-if="rows.length" class="mp-legal-doc-more">共 {{ total }} 条</p>
<div v-if="!loading && !rows.length && !error" class="mp-wv-empty">
<div class="mp-wv-empty__title">暂无符合条件的计划</div>
<div class="mp-wv-empty__desc">可调整资料状态后再试</div>
</div>
</template>
</main>
</div>
<van-popup
:show="visible"
position="bottom"
round
teleport="body"
:close-on-click-overlay="!saving"
:style="{ height: '70vh', '--van-primary-color': 'var(--el-color-primary)' }"
class="mp-h5-sheet"
class="mp-h5-sheet mp-legal-doc-sheet"
@update:show="close"
>
<van-nav-bar
@@ -43,34 +102,61 @@
left-text="关闭"
@click-left="close(false)"
/>
<div class="mp-h5-list-content"
><section
v-for="p in detail?.products || []"
:key="`${session}:${p.id}`"
class="mp-wv-section"
><h3>{{ p.productName }} {{ p.model }}</h3>
<p v-for="context in p.contexts || []" :key="context.stopProductId"
>{{ context.stopType === 'load' ? '装货' : '送货' }}:{{
context.partyName || '未填写单位'
}}
· {{ context.address || '未填写地址' }} · 合同
{{ context.contractNo || '未关联或无查看权限' }}</p
<div class="mp-legal-doc-sheet__body mp-h5-detail-page mp-legal-doc-list">
<div v-if="detailLoading" class="mp-legal-doc-loading mp-legal-doc-loading--sheet">
<van-loading />
</div>
<template v-else-if="detail">
<p class="mp-legal-doc-note">一份运输计划共用一套合法使用证明。</p>
<article
v-for="item in detail.items || []"
:key="itemKey(item)"
class="mp-wv-card mp-wv-flat-card"
>
<AttachmentUploadField
:ref="(el) => setUpload(p.id, el)"
v-model="p.legalUseCertUrl"
:disabled="!canUpload || saving"
folder="pl/legal-use-document" /></section
><van-button
v-if="canUpload"
block
type="primary"
:loading="saving"
:disabled="saving"
@click="save"
>保存资料</van-button
></div
>
<div class="mp-wv-card__head">
<div class="mp-wv-card__no">
{{ item.stopType === 'load' ? '装货' : '送货' }} {{ item.stopOrder }}
</div>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>产品</span><span>{{ item.productName || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>规格</span><span>{{ item.model || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>单位</span><span>{{ unitText(item.unit) }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>合同编号</span><span>{{ item.contractNo || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>本段主体</span><span>{{ item.partyName || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>本段位置</span><span>{{ item.address || '—' }}</span>
</div>
</div>
</article>
<p v-if="!(detail.items || []).length" class="mp-legal-doc-note">当前计划没有装送段明细。</p>
<section :key="detail.id" class="mp-wv-section">
<h3>合法使用证明</h3>
<AttachmentUploadField
:ref="(el) => setUpload(detail.id, el)"
v-model="draft"
:disabled="!canUpload || saving"
hint=""
folder="pl/legal-use-document"
/>
</section>
</template>
</div>
<footer v-if="canUpload && detail && !detailLoading">
<button class="mp-wv-btn mp-wv-btn--primary" type="button" :disabled="saving" @click="save">
{{ saving ? '正在保存…' : '保存资料' }}
</button>
</footer>
</van-popup>
</MpWebviewShell>
</template>
@@ -79,68 +165,172 @@
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import { fetchGetMenuCodes } from '@/api/auth'
import { legalDocumentApi, type LegalDocument } from '@/api/pl/quota-cert'
import { legalDocumentApi, type StopLegalDocument } from '@/api/pl/quota-cert'
import { useDictStore } from '@/store/modules/dict'
import { useUserStore } from '@/store/modules/user'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { getPlPlanFollowStatusLabel, getPlPlanFollowStatusTagType } from '@/utils/pl-display'
import { goToMiniWorkbench } from '@/utils/mp-webview'
import '@/styles/mp-webview.scss'
const status = ref('')
const statusOptions = [
{ text: '全部资料', value: '' },
import '../../crm/customer/customer.scss'
const status = ref<'' | 'pending' | 'uploaded'>('pending')
const uploadOptions = [
{ text: '全部上传情况', value: '' },
{ text: '待上传', value: 'pending' },
{ text: '已上传', value: 'uploaded' }
]
const keyword = ref(''),
rows = ref<LegalDocument[]>([]),
detail = ref<LegalDocument>(),
rows = ref<StopLegalDocument[]>([]),
detail = ref<StopLegalDocument>(),
draft = ref(''),
visible = ref(false),
allowed = ref(false),
authReady = ref(false),
canUpload = ref(false),
loading = ref(false),
detailLoading = ref(false),
saving = ref(false),
error = ref(''),
session = ref(0)
session = ref(0),
page = ref(1),
total = ref(0)
const user = useUserStore(),
uploads = new Map<string, InstanceType<typeof AttachmentUploadField>>()
let shellReady = false
let epoch = 0,
listVersion = 0
const pageSize = 20
function planWhen(value?: string | null) {
const text = String(value || '').trim()
if (!text) return '—'
return text.length > 10 ? text.slice(0, 10) : text
}
function followLabel(status?: string) {
return getPlPlanFollowStatusLabel(status) || '—'
}
function followTag(status?: string) {
const type = getPlPlanFollowStatusTagType(status)
return type === 'danger' ? 'danger' : type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'info'
}
function statusLabel(value?: string) {
return value === 'uploaded' ? '已上传' : value === 'not_required' ? '无需上传' : '待上传'
}
function statusTag(value?: string) {
return value === 'uploaded' ? 'success' : value === 'not_required' ? 'info' : 'warning'
}
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '—' : label
}
function itemKey(item: { stopType: string; stopProductId: string }) {
return `${item.stopType}:${item.stopProductId}`
}
function setUpload(id: string, el: any) {
if (el) uploads.set(id, el)
else uploads.delete(id)
}
function query() {
return {
page: page.value,
pageSize,
keyword: keyword.value,
status: status.value || undefined
}
}
async function init() {
shellReady = true
const current = epoch
const p = await fetchGetMenuCodes()
if (current !== epoch) return
canUpload.value =
!!p.all || !!p.isSuperAdmin || (p.menuCodes || []).includes('pl:plan-cert:upload')
await load()
loading.value = true
error.value = ''
try {
const p = await fetchGetMenuCodes()
if (current !== epoch) return
const codes = p?.menuCodes || []
const all = !!p?.all || !!p?.isSuperAdmin
allowed.value = all || codes.includes('pl:legal-use-document:list')
canUpload.value = allowed.value && (all || codes.includes('pl:plan-cert:upload'))
authReady.value = true
if (!allowed.value) {
rows.value = []
total.value = 0
loading.value = false
return
}
await load()
} catch {
if (current === epoch) {
loading.value = false
authReady.value = true
error.value = '权限加载失败,请重试'
}
}
}
function search() {
if (authReady.value && !allowed.value) return
page.value = 1
void load()
}
async function load() {
const current = epoch,
version = ++listVersion
page.value = 1
rows.value = []
total.value = 0
loading.value = true
error.value = ''
try {
const value = await legalDocumentApi.list({
keyword: keyword.value,
status: status.value || undefined
})
if (current === epoch && version === listVersion) rows.value = value
const value = await legalDocumentApi.listStops(query())
if (current === epoch && version === listVersion) {
rows.value = value?.list || []
total.value = value?.total || 0
}
} catch {
if (current === epoch && version === listVersion) error.value = '资料加载失败,请重新搜索'
} finally {
if (current === epoch && version === listVersion) loading.value = false
}
}
async function more() {
if (loading.value || rows.value.length >= total.value) return
const current = epoch,
version = ++listVersion
page.value += 1
loading.value = true
error.value = ''
try {
const value = await legalDocumentApi.listStops(query())
if (current === epoch && version === listVersion) {
rows.value = rows.value.concat(value?.list || [])
total.value = value?.total || 0
}
} catch {
if (current === epoch && version === listVersion) {
page.value = Math.max(1, page.value - 1)
error.value = '资料加载失败,请重新搜索'
}
} finally {
if (current === epoch && version === listVersion) loading.value = false
}
}
async function open(id: string) {
if (saving.value) return
const current = ++session.value,
auth = epoch
const value = await legalDocumentApi.get(id)
if (current !== session.value || auth !== epoch) return
detail.value = value
detailLoading.value = true
visible.value = true
try {
const value = await legalDocumentApi.getStops(id)
if (current !== session.value || auth !== epoch) return
detail.value = value
draft.value = value?.legalUseCertUrl || ''
} catch {
if (current === session.value && auth === epoch) {
visible.value = false
detail.value = undefined
}
} finally {
if (current === session.value && auth === epoch) detailLoading.value = false
}
}
function close(value: boolean) {
if (saving.value) return
@@ -148,6 +338,8 @@
if (!value) {
session.value++
detail.value = undefined
draft.value = ''
detailLoading.value = false
}
}
async function save() {
@@ -156,21 +348,31 @@
ElMessage.warning('请等待附件上传完成')
return
}
const ids = detail.value.planProductIds || []
if (!ids.length) {
ElMessage.warning('当前计划没有需要维护的易制爆产品')
return
}
const current = session.value,
auth = epoch,
id = detail.value.id
id = detail.value.id,
url = draft.value || ''
saving.value = true
try {
await legalDocumentApi.save(
id,
detail.value.products.map((p) => ({ id: p.id, legalUseCertUrl: p.legalUseCertUrl }))
ids.map((productId) => ({ id: productId, legalUseCertUrl: url }))
)
if (current !== session.value || auth !== epoch) return
visible.value = false
detail.value = undefined
draft.value = ''
session.value++
ElMessage.success('合法使用证明已保存')
await load()
} catch {
if (current === session.value && auth === epoch)
ElMessage.error('保存失败,已保留填写内容,请重试')
} finally {
if (auth === epoch) saving.value = false
}
@@ -181,9 +383,15 @@
epoch++
session.value++
rows.value = []
total.value = 0
page.value = 1
detail.value = undefined
draft.value = ''
visible.value = false
detailLoading.value = false
saving.value = false
allowed.value = false
authReady.value = false
canUpload.value = false
uploads.clear()
error.value = ''
@@ -197,3 +405,70 @@
session.value++
})
</script>
<style scoped lang="scss">
.mp-legal-doc-loading {
display: flex;
align-items: center;
justify-content: center;
min-height: calc(100dvh - 240px);
}
.mp-legal-doc-loading--sheet {
min-height: 240px;
}
.mp-legal-doc-note {
margin: 0 0 10px;
color: #6b7b74;
font-size: 13px;
line-height: 1.5;
}
.mp-legal-doc-more {
margin: 4px 0 12px;
color: #6b7b74;
font-size: 13px;
text-align: center;
}
.mp-legal-doc-more .mp-wv-btn {
width: 100%;
}
.mp-legal-doc-list .mp-wv-flat-card {
.mp-wv-card__no {
font-size: 17px;
}
.mp-wv-card__sub,
.mp-wv-card__kv-row {
font-size: 14px;
}
.status-tag {
font-size: 13px;
}
.mp-wv-card-actions .mp-wv-btn {
font-size: 15px;
}
}
.mp-legal-doc-sheet {
display: flex;
flex-direction: column;
max-height: 88dvh;
overflow: hidden;
background: #f5f8f7;
--van-primary-color: #0a9f6d;
--van-nav-bar-text-color: #0a9f6d;
--van-nav-bar-icon-color: #0a9f6d;
}
.mp-legal-doc-sheet__body {
min-height: 0;
overflow: auto;
padding: 10px 12px 12px;
}
.mp-legal-doc-sheet footer {
flex-shrink: 0;
padding: 10px 12px calc(10px + env(safe-area-inset-bottom));
border-top: 1px solid #dcebe4;
background: #fff;
}
.mp-legal-doc-sheet footer .mp-wv-btn {
width: 100%;
height: 30px;
border-radius: 8px;
}
</style>
@@ -0,0 +1,196 @@
<template>
<main class="mp-h5-list-content mp-plan-cert-list" :class="{ 'mp-cert-has-fab': canEdit }">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="load">重试</button>
</p>
<van-loading v-if="loading" />
<article
v-for="row in visibleRows"
:key="row.certType + row.id"
class="mp-wv-card mp-wv-flat-card"
@click="open(row)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.certNo }}</div>
<div class="mp-wv-card__sub">{{ row.certType === 'transport' ? '运输证' : '购买证' }}</div>
</div>
<span class="status-tag" :class="`status-tag--${statusTag(row.status)}`">{{ statusLabel(row.status) }}</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>销售单位</span><span>{{ salePartyName(row) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>购买单位</span><span>{{ buyPartyName(row) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>有效次数</span><span>{{ row.validUseText || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>是否预警</span>
<span v-if="warningText(row)" class="status-tag status-tag--danger">{{ warningText(row) }}</span>
<span v-else>—</span>
</div>
<div class="mp-wv-card__kv-row"><span>品名</span><span>{{ row.productNameOnCert || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>数量</span><span>{{ qty(row.totalQty) }} {{ unit(row.quantityUnit) }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>可用余额</span><span>{{ qty(row.availableQty) }} {{ unit(row.quantityUnit) }}</span>
</div>
</div>
<div class="mp-wv-card-actions" @click.stop>
<button class="mp-wv-btn" type="button" @click="open(row)">查看</button>
<button v-if="canEdit" class="mp-wv-btn mp-wv-btn--primary" type="button" @click="edit(row)">编辑</button>
<button
v-if="canEdit && row.status !== 'void' && row.status !== 'closed'"
class="mp-wv-btn"
type="button"
@click="confirmRow = row"
>
{{ row.openingConfirmed ? '复核' : '期初确认' }}
</button>
</div>
</article>
<van-empty v-if="!loading && !error && !visibleRows.length" description="暂无证件" />
<ArchiveForm
v-if="editor.open"
popup
:model-kind="editor.kind"
:model-id="editor.id"
@close="editor.open = false"
@saved="load"
/>
<CertConfirmSheet :row="confirmRow" @close="confirmRow = null" @saved="load" />
<template v-if="canEdit">
<div class="mp-wv-speed-mask" :class="{ open: speedOpen }" @click="speedOpen = false" />
<div class="mp-wv-speed-dial" :class="{ open: speedOpen }">
<div v-if="createActions.length > 1" class="mp-wv-speed-menu">
<button
v-if="createActions.includes('transport')"
class="mp-wv-speed-item"
type="button"
@click="create('transport')"
>
新增运输证
</button>
<button class="mp-wv-speed-item primary" type="button" @click="create('purchase')">新增购买证</button>
</div>
<button class="mp-wv-speed-main" type="button" aria-label="新增证件" @click="onCreate">+</button>
</div>
</template>
</main>
</template>
<script setup lang="ts">
import { fetchGetMenuCodes } from '@/api/auth'
import { quotaCertApi, type CertType, type QuotaCert } from '@/api/pl/quota-cert'
import ArchiveForm from './archive-form.vue'
import CertConfirmSheet from './CertConfirmSheet.vue'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { buyPartyName, expiryWarning, salePartyName } from '@/views/pl/quota-cert/cert-list-face'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certStatusLabels } from './face-model'
const props = defineProps<{
keyword: string
kind: string
status: string
expiringSoon?: boolean
}>()
const emit = defineEmits<{ 'expiring-count': [count: number] }>()
const router = useRouter()
const loading = ref(false)
const canEdit = ref(false)
const error = ref('')
const confirmRow = ref<QuotaCert | null>(null)
const speedOpen = ref(false)
const editor = reactive({ open: false, kind: 'purchase' as CertType, id: '' })
const createActions = computed(() => {
const actions: CertType[] = []
if (!props.kind || props.kind === 'purchase') actions.push('purchase')
if (!props.kind || props.kind === 'transport') actions.push('transport')
return actions
})
const rows = ref<QuotaCert[]>([])
const visibleRows = computed(() =>
rows.value.filter((row) => {
if (props.kind && row.certType !== props.kind) return false
return !props.expiringSoon || Boolean(expiryWarning(row.validTo))
})
)
const expiringCount = computed(() => rows.value.filter((row) => expiryWarning(row.validTo)).length)
watch(expiringCount, (count) => emit('expiring-count', count), { immediate: true })
let epoch = 0
function statusLabel(value: string) {
return certStatusLabels[value] || value || '—'
}
function statusTag(value: string) {
if (value === 'active') return 'success'
if (value === 'void') return 'danger'
if (value === 'suspended' || value === 'closed') return 'warning'
return 'info'
}
function warningText(row: QuotaCert) {
return expiryWarning(row.validTo)?.label || ''
}
function qty(value: unknown) {
return formatCertQty(value)
}
function unit(value?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, value)
return !label || label === '—' ? '' : label
}
function open(row: QuotaCert) {
void router.push(`/m/pl/plan-cert/archive/${row.certType || 'purchase'}/${row.id}`)
}
function editNew(certType: CertType) {
speedOpen.value = false
editor.kind = certType
editor.id = ''
editor.open = true
}
function onCreate() {
if (createActions.value.length === 1) {
editNew(createActions.value[0])
return
}
speedOpen.value = !speedOpen.value
}
function create(certType: CertType) {
editNew(certType)
}
function edit(row: QuotaCert) {
editor.kind = row.certType === 'transport' ? 'transport' : 'purchase'
editor.id = row.id
editor.open = true
}
onMounted(async () => {
const permissions = await fetchGetMenuCodes().catch(() => null)
canEdit.value =
!!permissions?.all ||
!!permissions?.isSuperAdmin ||
(permissions?.menuCodes || []).includes('pl:quota-cert:edit')
})
async function load() {
const current = ++epoch
loading.value = true
error.value = ''
try {
const params = { keyword: props.keyword || undefined, status: props.status || undefined }
const kinds: CertType[] = props.kind ? [props.kind as CertType] : ['purchase', 'transport']
const lists = await Promise.all(kinds.map((item) => quotaCertApi.list(item, params)))
if (current !== epoch) return
rows.value = kinds.flatMap((item, index) =>
lists[index].map((row) => ({ ...row, certType: row.certType || item }))
)
} catch {
if (current === epoch) error.value = '证件加载失败,请重试'
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() => [props.keyword, props.kind, props.status].join('\0'),
() => void load(),
{ immediate: true }
)
</script>
<style lang="scss" src="./cert-mobile.scss"></style>
@@ -0,0 +1,140 @@
<template>
<van-popup
:show="!!row"
position="bottom"
round
teleport="body"
class="mp-cert-confirm-sheet"
:close-on-click-overlay="!saving"
@update:show="onShow"
>
<van-nav-bar
:title="row?.openingConfirmed ? '复核证件' : '期初核对'"
left-text="关闭"
@click-left="!saving && emit('close')"
/>
<div v-if="row" class="mp-cert-confirm-sheet__body mp-cert-form">
<p class="plan-empty-hint">{{ row.certNo }} · {{ row.openingConfirmed ? '复核已启用的证件' : '核对历史用量后启用' }}</p>
<template v-if="!row.openingConfirmed">
<van-field v-model="opening.usedQty" label="历史已用量" label-align="top" type="number" :disabled="saving" />
<van-cell title="一次有效证已有使用记录" center>
<template #right-icon>
<van-switch v-model="opening.singleUseConsumed" :disabled="saving" size="20px" />
</template>
</van-cell>
<van-field v-model="opening.sourceNote" label="历史来源说明" label-align="top" type="textarea" rows="2" :disabled="saving" />
<p class="plan-empty-hint">核对凭据</p>
<AttachmentUploadField v-model="opening.evidenceUrls" folder="pl/quota-cert" :disabled="saving" hint="" />
</template>
<van-field v-model="opening.reason" label="核对说明" label-align="top" type="textarea" rows="2" :disabled="saving" />
</div>
<footer>
<button class="mp-wv-btn" type="button" :disabled="saving" @click="emit('close')">取消</button>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" :disabled="saving" @click="submit">
{{ saving ? '正在提交…' : '确认启用' }}
</button>
</footer>
</van-popup>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import { quotaCertApi, type CertType, type QuotaCert } from '@/api/pl/quota-cert'
import './cert-mobile.scss'
const props = defineProps<{ row?: QuotaCert | null }>()
const emit = defineEmits<{ close: []; saved: [] }>()
const saving = ref(false)
const opening = reactive({
operationId: '',
usedQty: '0',
singleUseConsumed: false,
reason: '',
sourceNote: '',
evidenceUrls: ''
})
watch(
() => props.row?.id,
() => {
opening.operationId = crypto.randomUUID()
opening.usedQty = '0'
opening.singleUseConsumed = false
opening.reason = ''
opening.sourceNote = ''
opening.evidenceUrls = ''
}
)
function onShow(value: boolean) {
if (!value && !saving.value) emit('close')
}
async function submit() {
if (!props.row || saving.value) return
const kind = (props.row.certType === 'transport' ? 'transport' : 'purchase') as CertType
opening.reason = opening.reason.trim()
saving.value = true
try {
if (props.row.openingConfirmed) {
await quotaCertApi.verify(kind, props.row.id, {
operationId: opening.operationId,
reason: opening.reason
})
} else {
await quotaCertApi.confirm(kind, props.row.id, { ...opening })
}
ElMessage.success(props.row.openingConfirmed ? '证件已复核' : '期初已确认')
emit('saved')
emit('close')
} catch {
ElMessage.error('核对没有提交,请重试')
} finally {
saving.value = false
}
}
</script>
<style scoped>
.mp-cert-confirm-sheet {
display: flex;
flex-direction: column;
max-height: 88dvh;
background: #f5f8f7;
--van-primary-color: #0a9f6d;
--van-nav-bar-text-color: #0a9f6d;
--van-switch-on-background: #0a9f6d;
}
.mp-cert-confirm-sheet__body {
min-height: 0;
padding: 14px 12px 16px;
overflow: auto;
}
.mp-cert-confirm-sheet__body.mp-cert-form > :deep(.van-field:not(.van-search__field)),
.mp-cert-confirm-sheet__body > :deep(.van-cell:not(.van-field)),
.mp-cert-confirm-sheet__body > :deep(.attachment-upload),
.mp-cert-confirm-sheet__body > .plan-empty-hint {
margin-top: 16px;
margin-bottom: 0;
}
.mp-cert-confirm-sheet__body > .plan-empty-hint:first-child {
margin-top: 0;
}
.mp-cert-confirm-sheet__body.mp-cert-form :deep(.van-field .van-field__label) {
margin-bottom: 8px;
}
.plan-empty-hint {
font-size: 13px;
color: #6b7b74;
}
footer {
display: flex;
gap: 8px;
padding: 10px 12px calc(10px + env(safe-area-inset-bottom));
border-top: 1px solid #dcebe4;
background: #fff;
}
footer .mp-wv-btn {
flex: 1;
height: 30px;
border-radius: 8px;
}
</style>
@@ -0,0 +1,510 @@
<template>
<div>
<div v-if="loading" class="mp-cert-page-loading"><van-loading /></div>
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="load">重试</button>
</p>
<template v-else-if="plan">
<section class="mp-wv-section mp-cert-quota">
<p class="mp-wv-card__meta">当前车号 {{ plan.licensePlate || '待安排' }}</p>
<p v-if="plan.canSaveConfiguration === false" class="plan-empty-hint">
已安排计划请从调整运输提交用证变更;已归档计划仅查看占用。
</p>
<h3>全部装送段用证</h3>
<p v-if="!sourceOptions.length" class="plan-empty-hint">当前计划没有易制毒产品,无需购买证、运输证。</p>
<article v-for="row in sourceOptions" :key="row.sourceStopType + row.sourceStopProductId" class="mp-cert-stop">
<h4>{{ stopTitle(row) }}</h4>
<div class="detail-field-grid">
<div class="mp-wv-kv"><span>关联合同</span><span>{{ row.contractNo || '未关联合同' }}</span></div>
<div class="mp-wv-kv"><span>装送单位</span><span>{{ row.partyName || '—' }}</span></div>
<div class="mp-wv-kv"><span>需用量</span><span>{{ qtyText(row.quantity) }} {{ unitText(row.unit) }}</span></div>
<div class="mp-wv-kv">
<span>购买证</span>
<span><template v-if="bound(row, 'purchase').length"><button v-for="cert in bound(row, 'purchase')" :key="cert.certId" class="mp-cert-face-link" type="button" @click="showCertFace(cert)">{{ cert.certNo }}</button></template><template v-else>未绑定</template></span>
</div>
<div class="mp-wv-kv">
<span>运输证</span>
<span><template v-if="bound(row, 'transport').length"><button v-for="cert in bound(row, 'transport')" :key="cert.certId" class="mp-cert-face-link" type="button" @click="showCertFace(cert)">{{ cert.certNo }}</button></template><template v-else>未绑定</template></span>
</div>
</div>
</article>
</section>
<section v-if="conversionGroups.length" class="mp-wv-section mp-cert-form">
<h3>单位不一致,填写换算系数</h3>
<p class="plan-empty-hint">
只列出计划单位和证面单位不同的段次。系数表示 1 个计划单位等于多少证面单位,计划数量保持不变。
</p>
<article v-for="group in conversionGroups" :key="group.sourceId" class="mp-cert-stop">
<h4>{{ sourceLabel(group.sourceId, measured) }}</h4>
<p class="plan-empty-hint">
计划数量 {{ qtyText(group.source.quantity) }} {{ unitText(group.source.unit) }}
</p>
<div v-for="row in group.rows" :key="conversionKey(row)" class="mp-cert-factor">
<strong>{{ row.cert.certType === 'purchase' ? '购买证' : '运输证' }} {{ row.cert.certNo }}</strong>
<van-field
v-model="coefficients[conversionKey(row)]"
label="换算系数"
label-align="top"
type="number"
:disabled="saving || plan.canSaveConfiguration === false"
:placeholder="`1 ${unitText(row.source.unit)} = ? ${unitText(row.cert.quantityUnit)}`"
/>
<p class="plan-empty-hint">
{{ conversionPreview(row) ? `证面数量 ${conversionPreview(row)}` : '填写系数后显示证面数量' }}
</p>
<van-field
v-model="allocationOf(row).note"
label="换算依据"
label-align="top"
:disabled="saving || plan.canSaveConfiguration === false"
placeholder="选填"
/>
</div>
</article>
<button
class="mp-wv-btn mp-wv-btn--primary mp-wv-btn--block"
type="button"
:disabled="saving || plan.canSaveConfiguration === false"
@click="saveConversion"
>
保存换算
</button>
</section>
<section v-if="plan.usages.length" class="mp-wv-section">
<h3>已有占用与结转</h3>
<article v-for="(row, index) in plan.usages" :key="`${row.certId || row.certNoSnapshot || index}:${index}`" class="mp-cert-stop">
<div class="detail-field-grid">
<div class="mp-wv-kv"><span>证件</span><span>{{ row.certNoSnapshot || '—' }}</span></div>
<div class="mp-wv-kv">
<span>状态</span>
<span class="status-tag" :class="row.usageStatus === 'exception' ? 'status-tag--danger' : 'status-tag--info'">
{{ usageLabels[row.usageStatus] || row.usageStatus || '—' }}
</span>
</div>
<div class="mp-wv-kv"><span>证面单位</span><span>{{ unitText(row.quantityUnit) || '—' }}</span></div>
<div class="mp-wv-kv"><span>预占量</span><span>{{ qtyText(row.reservedQty) }}</span></div>
<div class="mp-wv-kv"><span>使用量</span><span>{{ qtyText(row.usedQty) }}</span></div>
</div>
</article>
</section>
<section v-if="isPerStop && faceCards.length" class="mp-wv-section">
<h3>关联证件证面</h3>
<article v-for="face in faceCards" :id="faceDomId(face.key)" :key="face.key" class="mp-cert-face-card">
<h4>{{ face.label }}</h4>
<p v-if="!face.cert" class="plan-empty-hint">没有读到这张证的证面档案。</p>
<template v-else>
<div v-for="(group, groupIndex) in groupsOf(face.cert, face.kind)" :key="groupIndex">
<h3 v-if="group.title">{{ group.title }}</h3>
<div class="detail-field-grid">
<div
v-for="field in group.fields"
:key="field.label"
class="mp-wv-kv"
:class="{ 'detail-wide': field.wide }"
>
<span>{{ field.label }}</span><span>{{ field.value }}</span>
</div>
</div>
</div>
<template v-if="face.kind === 'transport'">
<h3>证面引用</h3>
<p v-if="!face.cert.purchaseRefs?.length" class="plan-empty-hint">没有证面引用。</p>
<article
v-for="(refRow, index) in face.cert.purchaseRefs || []"
:key="refRow.id || index"
class="mp-cert-stop"
>
<div class="detail-field-grid">
<div class="mp-wv-kv">
<span>引用类型</span><span>{{ refLabels[refRow.referenceType] || refRow.referenceType || '—' }}</span>
</div>
<div class="mp-wv-kv"><span>购买许可/备案/出口许可证号</span><span>{{ refRow.referenceNo || '—' }}</span></div>
<div class="mp-wv-kv detail-wide">
<span>对应购买证</span>
<span>{{ purchaseNo(refRow.purchaseCertId) }}</span>
</div>
</div>
</article>
</template>
<template v-if="face.cert.attachmentUrls">
<h3>证件附件</h3>
<AttachmentUploadField :model-value="face.cert.attachmentUrls" disabled />
</template>
</template>
</article>
</section>
</template>
</div>
</template>
<script setup lang="ts">
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import {
planQuotaApi,
quotaCertApi,
type CertType,
type PlanQuota,
type QuotaCert,
type ManualQuotaQuantity,
type QuotaConfiguration,
type QuotaSourceOption
} from '@/api/pl/quota-cert'
import {
coefficientFromQuantities,
configurationPayload,
initialLegacySelection,
measuredSources,
permitQuantityFromCoefficient,
sourceLabel,
unitConversions
} from '@/components/business/pl-plan-quota-dialog/stop-model'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certFaceGroups, certStatusLabels, refLabels } from './face-model'
import '../plan/plan-read-fields.scss'
import './cert-mobile.scss'
const props = defineProps<{ planId: string }>()
const loading = ref(false)
const error = ref('')
const plan = ref<PlanQuota>()
const certs = ref<Record<string, QuotaCert | null>>({})
const purchases = ref<QuotaCert[]>([])
const saving = ref(false)
const allocations = ref<ManualQuotaQuantity[]>([])
const coefficients = reactive<Record<string, string>>({})
const sides = reactive<Record<string, string>>({})
const pairs = reactive<Record<string, string[]>>({})
let epoch = 0
const usageLabels: Record<string, string> = {
reserved: '已预占',
in_transit: '执行中',
settled: '已核销',
released: '已释放',
exception: '结转异常',
draft: '草稿'
}
const measured = computed(() => measuredSources(plan.value, sides))
const sourceOptions = computed(() => plan.value?.sourceOptions || [])
const faceCards = computed(() => {
const seen = new Set<string>()
const tabs: { key: string; label: string; kind: CertType; cert: QuotaCert | null }[] = []
const push = (kind: string, id: string, certNo: string) => {
if ((kind !== 'purchase' && kind !== 'transport') || !id || seen.has(`${kind}:${id}`)) return
seen.add(`${kind}:${id}`)
const cert = certs.value[`${kind}:${id}`] ?? null
const number = cert?.certNo || certNo || '证号未提供'
tabs.push({
key: `${kind}:${id}`,
kind,
cert,
label: `${kind === 'purchase' ? '购买证' : '运输证'} ${number}`
})
}
for (const row of plan.value?.stopProducts || []) {
for (const cert of row.certificates || []) push(cert.certType, cert.certId, cert.certNo)
}
for (const usage of plan.value?.usages || []) {
push(String(usage.certType || ''), String(usage.certId || ''), String(usage.certNoSnapshot || ''))
}
tabs.sort((a, b) => Number(a.kind !== 'purchase') - Number(b.kind !== 'purchase'))
return tabs
})
const conversions = computed(() => unitConversions(plan.value, measured.value))
const conversionGroups = computed(() => {
const groups = new Map<
string,
{ sourceId: string; source: QuotaSourceOption; rows: ReturnType<typeof unitConversions> }
>()
for (const row of conversions.value) {
const current = groups.get(row.sourceId) || { sourceId: row.sourceId, source: row.source, rows: [] }
current.rows.push(row)
groups.set(row.sourceId, current)
}
return [...groups.values()]
})
function faceDomId(key: string) {
return `cert-face-${key.replace(/:/g, '-')}`
}
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
function qtyText(value: unknown) {
return formatCertQty(value)
}
function stopTitle(row: QuotaSourceOption) {
return sourceLabel(`${row.sourceStopType}:${row.sourceStopProductId}`, sourceOptions.value)
}
function showCertFace(cert: { certType: string; certId: string }) {
const key = `${cert.certType}:${cert.certId}`
if (!faceCards.value.some((item) => item.key === key)) return
void nextTick(() => document.getElementById(faceDomId(key))?.scrollIntoView({ block: 'start' }))
}
function applySelection(value: PlanQuota) {
const next = initialLegacySelection(value)
for (const key of Object.keys(sides)) delete sides[key]
for (const key of Object.keys(pairs)) delete pairs[key]
Object.assign(sides, next.sides)
for (const [key, ids] of Object.entries(next.pairs)) pairs[key] = ids
}
function bound(row: QuotaSourceOption, kind: CertType) {
return (
plan.value?.stopProducts?.find(
(item) =>
item.sourceStopType === row.sourceStopType && item.sourceStopProductId === row.sourceStopProductId
)?.certificates || []
).filter((cert) => cert.certType === kind)
}
function display(cert: QuotaCert, key: string) {
if (key === 'status') return certStatusLabels[cert.status] || cert.status || '—'
if (key === 'totalQty') {
const qty = qtyText(cert.totalQty)
const unit = unitText(cert.quantityUnit)
return unit && qty !== '—' ? `${qty} ${unit}` : qty
}
if (key === 'quantityUnit') return unitText(cert.quantityUnit) || '—'
if (key === 'remark') return String(cert.remark || '').trim() || '—'
const raw = cert[key as keyof QuotaCert]
if (raw == null || raw === '') return '—'
return typeof raw === 'string' || typeof raw === 'number' ? String(raw) : '—'
}
function groupsOf(cert: QuotaCert, kind: CertType) {
return certFaceGroups(cert, kind, display)
}
function conversionKey(row: { sourceId: string; cert: { certType: string; certId: string } }) {
return `${row.sourceId}:${row.cert.certType}:${row.cert.certId}`
}
function inputQty(value: unknown) {
const text = qtyText(value)
return text === '—' ? '' : text
}
function allocationOf(row: (typeof conversions.value)[number]) {
return (
allocations.value.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
) || { note: '' }
)
}
function conversionPreview(row: (typeof conversions.value)[number]) {
const permit = permitQuantityFromCoefficient(row.source.quantity, coefficients[conversionKey(row)])
return permit ? `${qtyText(permit)} ${unitText(row.cert.quantityUnit)}` : ''
}
function syncConversions(value: PlanQuota, keepCurrent = false) {
const rows = unitConversions(value, measuredSources(value, sides))
const previous = (keepCurrent ? allocations.value : value.configuration.manualAllocations) || []
allocations.value = rows.map((row) => {
const saved = previous.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
)
return (
saved || {
permitKind: row.cert.certType,
sourceId: row.sourceId,
permitId: row.cert.certId,
sourceQuantity: inputQty(row.source.quantity),
permitQuantity: '',
note: ''
}
)
})
for (const key of Object.keys(coefficients)) delete coefficients[key]
for (const row of rows) {
const saved = allocations.value.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
)
coefficients[conversionKey(row)] = coefficientFromQuantities(saved?.sourceQuantity, saved?.permitQuantity)
}
}
async function saveConversion() {
if (!plan.value || saving.value || plan.value.canSaveConfiguration === false) return
const rows = conversions.value
const manual: ManualQuotaQuantity[] = []
for (const row of rows) {
const input = allocations.value.find(
(item) =>
item.sourceId === row.sourceId &&
item.permitKind === row.cert.certType &&
item.permitId === row.cert.certId
)
const permit = permitQuantityFromCoefficient(row.source.quantity, coefficients[conversionKey(row)])
if (!permit || !input) {
ElMessage.warning('请填写大于 0 的换算系数')
return
}
manual.push({
...input,
sourceQuantity: inputQty(row.source.quantity),
permitQuantity: permit,
note: String(input.note || '')
})
}
const current = plan.value.configuration
const body: QuotaConfiguration = configurationPayload(
plan.value,
{
measurementVersion: current.measurementVersion,
sourceMapping: current.sourceMapping ?? null,
purchaseCertIds: current.purchaseCertIds || [],
transportCertIds: current.transportCertIds || [],
manualAllocations: manual,
conditions: current.conditions || []
},
measured.value,
pairs
)
saving.value = true
try {
await planQuotaApi.save(plan.value.planId, body)
ElMessage.success('换算已保存')
await load()
} catch {
ElMessage.error('换算保存失败,请重试')
} finally {
saving.value = false
}
}
function purchaseNo(id?: string | null) {
if (!id) return '未关联'
return purchases.value.find((item) => item.id === id)?.certNo || '无查看权限或已失效'
}
async function load() {
const current = ++epoch
loading.value = true
error.value = ''
try {
const value = await planQuotaApi.get(props.planId)
if (current !== epoch) return
plan.value = value
applySelection(value)
syncConversions(value)
const ids = new Map<string, CertType>()
for (const row of value.stopProducts || []) {
for (const cert of row.certificates || []) {
if (cert.certId) ids.set(`${cert.certType}:${cert.certId}`, cert.certType)
}
}
for (const usage of value.usages || []) {
const kind = String(usage.certType || '')
const id = String(usage.certId || '')
if ((kind === 'purchase' || kind === 'transport') && id) ids.set(`${kind}:${id}`, kind)
}
const loaded = await Promise.all(
[...ids.entries()].map(async ([key, kind]) => {
try {
return [key, await quotaCertApi.get(kind, key.slice(kind.length + 1))] as const
} catch {
return [key, null] as const
}
})
)
if (current !== epoch) return
certs.value = Object.fromEntries(loaded)
if ([...ids.values()].includes('transport')) {
purchases.value = await quotaCertApi.list('purchase').catch(() => [])
}
} catch (reason) {
if (current === epoch) {
const status = (reason as { response?: { status?: number } })?.response?.status
error.value =
status === 403 || status === 404
? '计划或证件不可读取,无法展示完整用证详情'
: '用证详情加载失败,请重试'
}
} finally {
if (current === epoch) loading.value = false
}
}
watch(() => props.planId, () => void load(), { immediate: true })
watch(
() => JSON.stringify(sides),
() => {
if (plan.value) syncConversions(plan.value, true)
}
)
</script>
<style scoped>
.mp-cert-stop {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #eef4f1;
}
.mp-cert-stop h4 {
margin: 0;
font-size: 14px;
font-weight: 600;
color: #1f2a26;
}
.plan-empty-hint {
margin: 8px 0 0;
color: #6b7b74;
font-size: 13px;
}
.mp-cert-factor {
margin-top: 8px;
}
.mp-cert-factor strong {
font-size: 14px;
color: #1f2a26;
}
.mp-cert-quota {
--van-primary-color: #0a9f6d;
--van-radio-checked-icon-color: #0a9f6d;
--van-checkbox-checked-icon-color: #0a9f6d;
}
.mp-cert-pair {
margin-top: 8px;
color: #1f2a26;
font-size: 14px;
line-height: 1.5;
}
.mp-cert-pair p {
margin: 0 0 6px;
}
.mp-cert-face-link {
margin: 0 8px 0 0;
padding: 0;
color: #087f57;
font-size: 14px;
font-weight: 600;
background: none;
border: 0;
}
.mp-cert-quota :deep(.van-radio),
.mp-cert-quota :deep(.van-checkbox) {
margin-top: 8px;
align-items: flex-start;
}
.mp-wv-btn--block {
margin-top: 12px;
}
.mp-cert-face-card {
margin-top: 12px;
padding: 12px;
background: #f7faf8;
border: 1px solid #dcebe4;
border-radius: 12px;
}
.mp-cert-face-card h4 {
margin: 0 0 8px;
color: #087f57;
font-size: 15px;
font-weight: 700;
line-height: 1.4;
word-break: break-all;
}
</style>
@@ -0,0 +1,179 @@
<template>
<van-popup
:show="open"
position="bottom"
teleport="body"
class="mp-cert-history-sheet"
:close-on-click-overlay="!saving"
@update:show="onShow"
>
<van-nav-bar title="额度流水与总量更正" left-text="关闭" @click-left="!saving && emit('close')" />
<div class="mp-cert-history-sheet__body mp-plan-cert-list">
<van-loading v-if="loading" />
<p v-else-if="error" class="plan-empty-hint" role="alert">{{ error }}</p>
<template v-else>
<p v-if="cert" class="plan-empty-hint">
核定 {{ qty(cert.totalQty) }} {{ unit(cert.quantityUnit) }};预占 {{ qty(cert.reservedQty) }};已使用
{{ qty(cert.usedQty) }}
</p>
<article v-for="row in logs" :key="row.id" class="mp-wv-card mp-wv-flat-card">
<div class="mp-wv-card__head">
<div class="mp-wv-card__no">{{ eventLabels[row.eventType] || row.eventType }}</div>
<span class="mp-wv-card__sub">{{ row.createTime || '—' }}</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>总量变化</span><span>{{ qty(row.totalDelta) }}</span></div>
<div class="mp-wv-card__kv-row"><span>预占变化</span><span>{{ qty(row.reservedDelta) }}</span></div>
<div class="mp-wv-card__kv-row"><span>已用变化</span><span>{{ qty(row.usedDelta) }}</span></div>
<div class="mp-wv-card__kv-row"><span>原因</span><span>{{ row.reason || '—' }}</span></div>
</div>
</article>
<p v-if="!logs.length" class="plan-empty-hint">暂无额度流水。</p>
<section v-if="canEdit && cert" class="mp-wv-section mp-cert-form">
<h3>更正核定总量</h3>
<van-field v-model="body.totalQty" :label="`更正后总量${unit(cert.quantityUnit) ? `(${unit(cert.quantityUnit)})` : ''}`" label-align="top" :disabled="saving" />
<van-field v-model="body.reason" label="更正理由" label-align="top" :disabled="saving" />
<van-field v-model="body.sourceNote" label="依据说明" label-align="top" type="textarea" rows="2" :disabled="saving" />
<p class="plan-empty-hint">依据说明和更正凭据至少填一项。</p>
<AttachmentUploadField ref="upload" v-model="body.evidenceUrls" folder="pl/quota-adjustment" :disabled="saving" hint="" />
<button class="mp-wv-btn mp-wv-btn--primary mp-cert-parse" type="button" :disabled="saving" @click="save">
{{ saving ? '正在保存…' : '保存总量更正' }}
</button>
</section>
</template>
</div>
</van-popup>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import {
quotaAdjustmentApi,
quotaCertApi,
type CertType,
type QuotaCert
} from '@/api/pl/quota-cert'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { useDictStore } from '@/store/modules/dict'
import './cert-mobile.scss'
const props = defineProps<{ open: boolean; kind: CertType; certId: string; canEdit: boolean }>()
const emit = defineEmits<{ close: []; saved: [] }>()
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const cert = ref<QuotaCert>()
const logs = ref<Record<string, any>[]>([])
const upload = ref<{ hasUploading: () => boolean }>()
const body = reactive({ totalQty: '', reason: '', sourceNote: '', evidenceUrls: '' })
const eventLabels: Record<string, string> = {
opening: '确认期初',
reserve: '安排预占',
resize: '调整预占',
release: '释放预占',
settle: '实际核销',
adjust: '实际量更正',
total_adjust: '核定总量更正',
verify: '信息复核'
}
let epoch = 0
let attempt = { signature: '', id: '' }
function qty(value: unknown) {
return formatCertQty(value)
}
function unit(value?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, value)
return !label || label === '—' ? '' : label
}
function inputQty(value: unknown) {
const text = formatCertQty(value)
return text === '—' ? '' : text
}
function onShow(value: boolean) {
if (!value && !saving.value) emit('close')
}
async function load() {
const current = ++epoch
loading.value = true
error.value = ''
try {
const [row, items] = await Promise.all([
quotaCertApi.get(props.kind, props.certId),
quotaAdjustmentApi.logs(props.kind, props.certId)
])
if (current !== epoch) return
cert.value = row
logs.value = items || []
body.totalQty = inputQty(row.totalQty)
body.reason = ''
body.sourceNote = ''
body.evidenceUrls = ''
} catch {
if (current === epoch) error.value = '额度流水加载失败,请重试'
} finally {
if (current === epoch) loading.value = false
}
}
async function save() {
if (!cert.value || saving.value) return
if (
!/^\d{1,12}(\.\d{1,6})?$/.test(body.totalQty) ||
!body.reason.trim() ||
(!body.sourceNote.trim() && !body.evidenceUrls)
) {
ElMessage.warning('请填写有效总量、更正理由与依据')
return
}
if (upload.value?.hasUploading()) {
ElMessage.warning('请等待凭据上传完成')
return
}
const signature = JSON.stringify({ id: cert.value.id, ...body })
if (signature !== attempt.signature) attempt = { signature, id: crypto.randomUUID() }
saving.value = true
try {
await quotaAdjustmentApi.total(props.kind, cert.value.id, { ...body, operationId: attempt.id })
ElMessage.success('总量更正已保存')
emit('saved')
await load()
} catch {
ElMessage.error('总量更正没有保存,请重试')
} finally {
saving.value = false
}
}
watch(
() => props.open,
(value) => {
if (value) void load()
else epoch++
}
)
</script>
<style scoped>
.mp-cert-history-sheet {
display: flex;
flex-direction: column;
height: 100dvh;
max-height: 100dvh;
background: #f5f8f7;
--van-primary-color: #0a9f6d;
--van-nav-bar-text-color: #0a9f6d;
}
.mp-cert-history-sheet__body {
min-height: 0;
overflow: auto;
padding: 10px 12px calc(16px + env(safe-area-inset-bottom));
}
.plan-empty-hint {
margin: 0 0 10px;
color: #6b7b74;
font-size: 13px;
line-height: 1.5;
}
.mp-cert-parse {
margin-top: 12px;
}
</style>
@@ -0,0 +1,437 @@
<template>
<van-popup
v-model:show="visible"
position="bottom"
round
teleport="body"
class="mp-cert-link-sheet"
:close-on-click-overlay="!saving"
>
<van-nav-bar
:title="mode === 'create' ? '新增关联证件' : '编辑适用产品'"
left-text="关闭"
@click-left="!saving && (visible = false)"
/>
<div class="mp-cert-link-sheet__body">
<template v-if="mode === 'create'">
<div class="mp-cert-link-kinds">
<button
class="mp-wv-btn"
:class="{ 'mp-wv-btn--primary': certType === 'purchase' }"
type="button"
:disabled="saving"
@click="setType('purchase')"
>
购买证
</button>
<button
class="mp-wv-btn"
:class="{ 'mp-wv-btn--primary': certType === 'transport' }"
type="button"
:disabled="saving"
@click="setType('transport')"
>
运输证
</button>
</div>
<van-search
v-model="keyword"
placeholder="证件编号或品名"
shape="round"
@search="searchCerts(keyword)"
/>
<article v-if="certId" class="mp-cert-link-card">
<strong>{{ certNo || '证号未提供' }}</strong>
<button type="button" :disabled="saving" @click="clearCert">更换证件</button>
</article>
<template v-else>
<p v-if="certError" class="mp-cert-link-note" role="alert">{{ certError }}</p>
<van-loading v-else-if="opening || certLoading" />
<p v-else-if="!certOptions.length" class="mp-cert-link-note">没有可关联的证件。</p>
<button
v-for="item in certOptions"
:key="item.id"
type="button"
class="mp-cert-link-card"
:disabled="saving || certChoiceState(item, certType, takenIds) !== 'open'"
@click="pickCert(item)"
>
{{ certChoiceLabel(item, certType, takenIds) }}
</button>
</template>
</template>
<p v-else class="mp-cert-link-note">{{ currentLabel }}</p>
<template v-if="certId">
<h3>适用产品</h3>
<p class="mp-cert-link-note">已保存的产品不能删除,只能设为不可用。未保存的产品可以移除。</p>
<p v-if="certStatus === 'void'" class="mp-cert-link-note">作废证件不能新增或恢复产品。</p>
<p v-else-if="certStatus === 'closed'" class="mp-cert-link-note">已核销证件不能新增或恢复产品。</p>
<p v-if="linesError" class="mp-cert-link-note" role="alert">{{ linesError }}</p>
<van-loading v-else-if="linesLoading" />
<p v-else-if="!draft.length" class="mp-cert-link-note">还没有适用产品。</p>
<article v-for="product in draft" :key="product.contractProductId" class="mp-cert-link-card">
<strong>{{ productName(product.contractProductId) }}</strong>
<p>{{ product.scopeStatus === 'inactive' ? '不可用' : '可用' }}</p>
<button
v-if="product.id"
class="mp-wv-btn"
type="button"
:disabled="saving || !canRestoreProduct(certStatus, product.scopeStatus)"
@click="toggleProduct(product.contractProductId)"
>
{{ product.scopeStatus === 'inactive' ? '恢复可用' : '设为不可用' }}
</button>
<button v-else class="mp-wv-btn" type="button" :disabled="saving" @click="removeProduct(product.contractProductId)">
移除
</button>
</article>
<button
v-if="certStatus !== 'void' && certStatus !== 'closed'"
class="mp-wv-btn mp-wv-btn--block"
type="button"
:disabled="saving || linesLoading"
@click="openPicker"
>
选择产品
</button>
</template>
</div>
<footer>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" :disabled="!canSave" @click="save">
{{ saving ? '正在保存…' : mode === 'create' ? '保存关联' : '保存产品' }}
</button>
</footer>
</van-popup>
<van-popup v-model:show="pickerVisible" position="bottom" round teleport="body" class="mp-cert-link-sheet">
<van-nav-bar title="选择合同产品" left-text="关闭" @click-left="pickerVisible = false" />
<div class="mp-cert-link-sheet__body">
<p v-if="!pickerRows.length" class="mp-cert-link-note">合同里没有可再添加的产品。</p>
<button
v-for="row in pickerRows"
:key="row.id"
type="button"
class="mp-cert-link-card"
:class="{ 'is-selected': picked.has(row.id) }"
@click="togglePicked(row.id)"
>
<strong>{{ row.productName || '合同产品' }}</strong>
<p>{{ row.model || '—' }} · {{ unitLabel(row.unit) || '—' }}</p>
</button>
</div>
<footer>
<button class="mp-wv-btn" type="button" @click="pickerVisible = false">取消</button>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" :disabled="!picked.size" @click="confirmProducts">
确认添加
</button>
</footer>
</van-popup>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import {
quotaCertApi,
type CertBinding,
type CertType,
type ContractProduct,
type QuotaCert,
type ScopeProduct
} from '@/api/pl/quota-cert'
import { bindingPayload, replaceCertProducts } from '@/views/pl/quota-cert/model'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { useDictStore } from '@/store/modules/dict'
import {
addDraftProducts,
canRestoreProduct,
canSaveNewLink,
canSaveProductEdit,
certChoiceLabel,
certChoiceState,
nextScopeStatus,
removeDraftProduct
} from './cert-link-rules'
const emit = defineEmits<{ saved: [] }>()
const visible = ref(false)
const opening = ref(false)
const pickerVisible = ref(false)
const saving = ref(false)
const certLoading = ref(false)
const linesLoading = ref(false)
const certError = ref('')
const linesError = ref('')
const mode = ref<'create' | 'edit'>('create')
const contractId = ref('')
const certType = ref<CertType>('purchase')
const certId = ref('')
const certNo = ref('')
const certStatus = ref('')
const keyword = ref('')
const savedProducts = ref<ScopeProduct[]>([])
const draft = ref<ScopeProduct[]>([])
const certOptions = ref<QuotaCert[]>([])
const lines = ref<ContractProduct[]>([])
const takenIds = ref(new Set<string>())
const picked = ref(new Set<string>())
let epoch = 0
let searchTimer = 0
const currentLabel = computed(() =>
[certType.value === 'purchase' ? '购买证' : '运输证', certNo.value].filter(Boolean).join(' ')
)
const pickerRows = computed(() => {
const used = new Set(draft.value.map((product) => product.contractProductId))
return lines.value.filter((row) => row.id && !used.has(row.id))
})
const canSave = computed(() => {
if (saving.value || !contractId.value || !certId.value) return false
if (mode.value === 'create') {
return canSaveNewLink(draft.value) && !takenIds.value.has(`${certType.value}:${certId.value}`)
}
return canSaveProductEdit(savedProducts.value, draft.value)
})
function unitLabel(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
function productName(id: string) {
return lines.value.find((row) => row.id === id)?.productName || '合同产品'
}
function reset() {
epoch++
saving.value = false
opening.value = false
certLoading.value = false
linesLoading.value = false
certError.value = ''
linesError.value = ''
certId.value = ''
certNo.value = ''
certStatus.value = ''
keyword.value = ''
savedProducts.value = []
draft.value = []
certOptions.value = []
lines.value = []
takenIds.value = new Set()
picked.value = new Set()
pickerVisible.value = false
}
async function open(payload: {
contractId: string
mode: 'create' | 'edit'
certType?: CertType
certId?: string
certNo?: string
certStatus?: string
}) {
reset()
const current = ++epoch
mode.value = payload.mode
contractId.value = payload.contractId
certType.value = payload.certType || 'purchase'
certId.value = payload.certId || ''
certNo.value = payload.certNo || ''
certStatus.value = payload.certStatus || ''
visible.value = true
opening.value = true
try {
const [bindings, products] = await Promise.all([
quotaCertApi.bindings(payload.contractId),
quotaCertApi.products(payload.contractId)
])
if (current !== epoch) return
lines.value = products
takenIds.value = new Set(bindings.map((row) => `${row.certType}:${row.certId}`))
if (payload.mode === 'edit' && payload.certType && payload.certId) {
const currentBinding = bindings.find(
(row) => row.certType === payload.certType && row.certId === payload.certId
)
savedProducts.value = (currentBinding?.products || []).map((product) => ({ ...product }))
draft.value = savedProducts.value.map((product) => ({ ...product }))
}
if (payload.mode === 'create') await searchCerts('')
} catch {
if (current === epoch) {
visible.value = false
ElMessage.error('合同用证没有打开,请重试')
}
} finally {
if (current === epoch) opening.value = false
}
}
function setType(kind: CertType) {
if (saving.value || certType.value === kind) return
certType.value = kind
clearCert()
void searchCerts(keyword.value)
}
function clearCert() {
certId.value = ''
certNo.value = ''
certStatus.value = ''
savedProducts.value = []
draft.value = []
}
async function searchCerts(value = '') {
const current = epoch
const kind = certType.value
certOptions.value = []
certLoading.value = true
certError.value = ''
try {
const rows = await quotaCertApi.list(kind, { keyword: value })
if (current !== epoch || kind !== certType.value) return
certOptions.value = rows
} catch {
if (current === epoch) certError.value = '证件列表加载失败,请重试'
} finally {
if (current === epoch) certLoading.value = false
}
}
function pickCert(item: QuotaCert) {
if (certChoiceState(item, certType.value, takenIds.value) !== 'open') return
certId.value = item.id
certNo.value = item.certNo
certStatus.value = item.status
draft.value = []
savedProducts.value = []
}
function toggleProduct(id: string) {
const current = draft.value.find((product) => product.contractProductId === id)
if (!current?.id || !canRestoreProduct(certStatus.value, current.scopeStatus)) return
const status = nextScopeStatus(current.scopeStatus)
draft.value = draft.value.map((product) =>
product.contractProductId === id ? { ...product, scopeStatus: status } : product
)
}
function removeProduct(id: string) {
draft.value = removeDraftProduct(draft.value, id)
}
function openPicker() {
picked.value = new Set()
pickerVisible.value = true
}
function togglePicked(id: string) {
const next = new Set(picked.value)
if (next.has(id)) next.delete(id)
else next.add(id)
picked.value = next
}
function confirmProducts() {
draft.value = addDraftProducts(draft.value, [...picked.value])
pickerVisible.value = false
}
async function save() {
if (!canSave.value) return
if (mode.value === 'create' && takenIds.value.has(`${certType.value}:${certId.value}`)) {
ElMessage.warning('该证件已关联,请在对应证件里编辑')
return
}
const current = epoch
saving.value = true
try {
const existing = await quotaCertApi.bindings(contractId.value)
if (current !== epoch) return
const next: CertBinding[] = replaceCertProducts(
existing,
certType.value,
certId.value,
draft.value.map((product) => ({ ...product }))
)
await quotaCertApi.saveBindings(contractId.value, bindingPayload(next))
if (current !== epoch) return
ElMessage.success(mode.value === 'create' ? '证件已关联' : '适用产品已保存')
visible.value = false
emit('saved')
} catch {
ElMessage.error('没有保存,请重试')
} finally {
if (current === epoch) saving.value = false
}
}
watch(keyword, (value) => {
if (!visible.value || mode.value !== 'create' || certId.value) return
window.clearTimeout(searchTimer)
searchTimer = window.setTimeout(() => void searchCerts(value), 300)
})
defineExpose({ open })
</script>
<style scoped>
.mp-cert-link-sheet {
display: flex;
flex-direction: column;
max-height: 88dvh;
color: #1f2a26;
background: #f5f8f7;
}
.mp-cert-link-sheet__body {
min-height: 0;
overflow: auto;
padding: 0 10px 10px;
}
h3 {
margin: 12px 0 0;
font-size: 15px;
}
.mp-cert-link-kinds,
footer {
display: flex;
gap: 8px;
}
.mp-cert-link-kinds {
padding-top: 8px;
}
.mp-cert-link-kinds .mp-wv-btn,
footer .mp-wv-btn {
flex: 1;
height: 30px;
border-radius: 8px;
}
.mp-cert-link-card {
display: block;
width: 100%;
margin-top: 8px;
padding: 10px 12px;
border: 1px solid #dcebe4;
border-radius: 12px;
background: #fff;
color: #1f2a26;
text-align: left;
}
.mp-cert-link-card strong {
display: block;
}
.mp-cert-link-card p,
.mp-cert-link-note {
margin: 4px 0 0;
color: #6b7b74;
font-size: 13px;
line-height: 1.5;
}
.mp-cert-link-card .mp-wv-btn {
margin-top: 8px;
}
.mp-cert-link-card.is-selected {
border-color: #0a9f6d;
}
.mp-wv-btn--block {
width: 100%;
margin-top: 8px;
}
footer {
flex-shrink: 0;
padding: 10px 12px calc(10px + env(safe-area-inset-bottom));
border-top: 1px solid #dcebe4;
background: white;
}
button:disabled {
opacity: 0.45;
}
</style>
@@ -0,0 +1,129 @@
<template>
<main class="mp-h5-list-content mp-plan-cert-list">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="reload">重试</button>
</p>
<div v-else-if="authReady && !allowed" class="mp-wv-empty">
<div class="mp-wv-empty__title">无证件查看权限</div>
</div>
<van-list v-else v-model:loading="loading" :finished="finished" finished-text="" @load="load">
<article
v-for="row in rows"
:key="row.id"
class="mp-wv-card mp-wv-flat-card"
@click="open(row.id)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.contractNo || '未编号合同' }}</div>
<div class="mp-wv-card__sub">{{ row.contractName || '—' }}</div>
</div>
<span class="status-tag status-tag--info">{{ contractTypeLabel(row.contractType) }}</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>关联证件数</span><span>{{ row.certCount }}</span>
</div>
</div>
<div class="mp-wv-card-actions mp-wv-card-actions--single" @click.stop>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="open(row.id)">查看</button>
</div>
</article>
</van-list>
<van-empty
v-if="authReady && allowed && !loading && finished && !error && !rows.length"
description="暂无合同用证数据"
/>
</main>
</template>
<script setup lang="ts">
import { fetchGetMenuCodes } from '@/api/auth'
import { quotaStatisticsApi, type ContractStatisticsSummary } from '@/api/pl/quota-cert'
import { contractTypeLabel } from '@/views/pl/quota-statistics/labels'
const props = defineProps<{ keyword: string }>()
const router = useRouter()
const rows = ref<ContractStatisticsSummary[]>([])
const loading = ref(true)
const finished = ref(false)
const error = ref('')
const allowed = ref(false)
const authReady = ref(false)
const page = ref(1)
let epoch = 0
let checking = true
function open(id: string) {
void router.push(`/m/pl/plan-cert/contract/${id}`)
}
async function init() {
const current = epoch
try {
const permissions = await fetchGetMenuCodes()
if (current !== epoch) return
const codes = permissions?.menuCodes || []
allowed.value =
!!permissions?.all || !!permissions?.isSuperAdmin || codes.includes('pl:quota-cert:list')
authReady.value = true
checking = false
if (!allowed.value) {
finished.value = true
loading.value = false
return
}
await load()
} catch {
if (current !== epoch) return
checking = false
authReady.value = true
finished.value = true
loading.value = false
error.value = '权限加载失败,请重新打开页面'
}
}
function reload() {
if (!allowed.value) {
void init()
return
}
epoch++
page.value = 1
rows.value = []
loading.value = true
finished.value = false
error.value = ''
void load()
}
async function load() {
if (checking || !allowed.value) return
const current = epoch
loading.value = true
try {
const data = await quotaStatisticsApi.contracts({
page: page.value,
pageSize: 20,
keyword: props.keyword || undefined
})
if (current !== epoch) return
const list = data?.list || []
rows.value = page.value === 1 ? list : rows.value.concat(list)
finished.value = rows.value.length >= (data?.total || 0) || list.length < 20
page.value += 1
} catch {
if (current === epoch) {
error.value = '统计加载失败,请重试'
finished.value = true
}
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() => props.keyword,
() => {
if (!checking && allowed.value) reload()
}
)
void init()
</script>
@@ -0,0 +1,279 @@
<template>
<main class="mp-h5-list-content mp-plan-cert-list">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="reload">重试</button>
</p>
<van-list v-model:loading="loading" :finished="finished" finished-text="" @load="load">
<article
v-for="row in rows"
:key="row.id"
class="mp-wv-card mp-wv-flat-card"
:class="{ 'is-conversion': row.needsUnitConversion }"
@click="open(row.id)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.planNo }}</div>
<div class="mp-wv-card__sub">{{ row.licensePlate || '未安排车辆' }} · {{ row.planDate || '未定日期' }}</div>
</div>
<span class="status-tag" :class="`status-tag--${quotaTag(row.quotaStatus)}`">
{{ stateLabels[row.quotaStatus] || row.quotaStatus }}
</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>易制毒产品</span><span>{{ row.productNames || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>供方</span><span>{{ row.supplierName || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>需方</span><span>{{ row.customerName || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>跟进状态</span>
<span class="status-tag" :class="`status-tag--${followTag(row.followStatus)}`">
{{ followLabel(row.followStatus) }}
</span>
</div>
</div>
<button
class="mp-wv-flat-card__toggle"
type="button"
:aria-expanded="!!expanded[row.id]"
@click.stop="toggle(row.id)"
>
{{ expanded[row.id] ? '收起段次' : '段次明细' }}
<span class="mp-wv-flat-card__toggle-icon" aria-hidden="true">{{ expanded[row.id] ? '▴' : '▾' }}</span>
</button>
<div v-if="expanded[row.id]" class="mp-wv-flat-card__extra" @click.stop>
<p v-if="details[row.id]?.error" class="plan-empty-hint" role="alert">
{{ details[row.id].error }}
<button class="mp-wv-btn" type="button" @click="loadDetail(row.id)">重试</button>
</p>
<p v-else-if="!details[row.id]?.data" class="plan-empty-hint" role="status">正在加载段次信息…</p>
<template v-else>
<p class="mp-cert-measure">
<span
class="status-tag"
:class="perStop(details[row.id].data) ? 'status-tag--info' : 'status-tag--warning'"
>
{{ perStop(details[row.id].data) ? '各装送段分别计量' : '原口径:单侧计量' }}
</span>
</p>
<div
v-for="item in usageRows(details[row.id].data!)"
:key="item.sourceStopType + item.sourceStopProductId"
class="mp-cert-stop-brief"
>
<div class="mp-wv-card__no">
{{ item.sourceStopType === 'load' ? '装货' : '送货' }} {{ item.stopOrder || 1 }}
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>产品编号</span><span>{{ item.productNo || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>产品</span><span>{{ item.productName || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>规格</span><span>{{ item.model || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>合同</span><span>{{ item.contractNo || (item.contractId ? '不可读取' : '未关联') }}</span>
</div>
<div class="mp-wv-card__kv-row"><span>本段主体</span><span>{{ item.partyName || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>需用量</span><span>{{ qtyText(item.quantity) }} {{ unitText(item.unit) }}</span>
</div>
<div class="mp-wv-card__kv-row"><span>购买证</span><span>{{ item.purchase }}</span></div>
<div class="mp-wv-card__kv-row"><span>运输证</span><span>{{ item.transport }}</span></div>
</div>
</div>
<p v-if="!usageRows(details[row.id].data!).length" class="plan-empty-hint">
当前计划没有易制毒产品,无需购买证、运输证。
</p>
</template>
</div>
<div class="mp-wv-card-actions" @click.stop>
<span v-if="row.needsUnitConversion" class="mp-cert-conversion">需单位换算</span>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="open(row.id)">查看用证</button>
</div>
</article>
</van-list>
<van-empty
v-if="!loading && finished && !error && !rows.length"
:description="showAll ? '暂无计划用证' : '暂无需要单位换算的计划'"
/>
</main>
</template>
<script setup lang="ts">
import request, { pickBxData } from '@/utils/http/bx'
import type { Plan } from '@/api/pl'
import { planQuotaApi, type PlanQuota } from '@/api/pl/quota-cert'
import { perStop, stopUsageRows } from '@/components/business/pl-plan-quota-dialog/stop-model'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { getPlPlanFollowStatusLabel, getPlPlanFollowStatusTagType } from '@/utils/pl-display'
const props = defineProps<{
keyword: string
status: string
licensePlate: string
planDateFrom: string
planDateTo: string
showAll?: boolean
}>()
const router = useRouter()
const stateLabels: Record<string, string> = {
not_required: '无需两证',
needs_configuration: '待配置',
needs_validation: '待校验条件与余额',
reserved: '已持有预占',
settled: '已核销',
exception: '结转异常'
}
const rows = ref<
(Plan & {
quotaStatus: string
productNames?: string
supplierName?: string
customerName?: string
followStatus?: string
needsUnitConversion?: boolean
})[]
>([])
const loading = ref(false)
const finished = ref(false)
const error = ref('')
const page = ref(1)
const expanded = reactive<Record<string, boolean>>({})
const details = reactive<Record<string, { loading: boolean; data?: PlanQuota; error?: string }>>({})
let epoch = 0
function followLabel(status?: string) {
return getPlPlanFollowStatusLabel(status) || '—'
}
function followTag(status?: string) {
const type = getPlPlanFollowStatusTagType(status)
return type === 'danger' ? 'danger' : type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'info'
}
function quotaTag(value: string) {
if (value === 'settled' || value === 'reserved') return 'success'
if (value === 'exception') return 'danger'
if (value === 'not_required') return 'info'
return 'warning'
}
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
function qtyText(value: unknown) {
return formatCertQty(value)
}
function usageRows(plan: PlanQuota) {
return stopUsageRows(plan, unitText)
}
function detailError(error: unknown) {
const status = (error as { response?: { status?: number } })?.response?.status
return status === 403 || status === 404
? '计划或证件不可读取,无法展示完整用证详情'
: '段次用证加载失败,请重试'
}
function open(id: string) {
void router.push(`/m/pl/plan-cert/${id}`)
}
function clearDetails() {
for (const key of Object.keys(expanded)) delete expanded[key]
for (const key of Object.keys(details)) delete details[key]
}
function toggle(id: string) {
expanded[id] = !expanded[id]
if (expanded[id] && !details[id]?.data && !details[id]?.loading) void loadDetail(id)
}
async function loadDetail(id: string) {
const current = epoch
details[id] = { loading: true }
try {
const value = await planQuotaApi.get(id)
if (current !== epoch) return
details[id] = { loading: false, data: value }
} catch (reason) {
if (current !== epoch) return
details[id] = { loading: false, error: detailError(reason) }
}
}
function reload() {
epoch++
page.value = 1
rows.value = []
loading.value = true
finished.value = false
error.value = ''
clearDetails()
void load()
}
async function load() {
const current = epoch
loading.value = true
try {
const data = pickBxData<{ list: (Plan & { quotaStatus: string })[]; total: number }>(
await request.get('/transport/quota-certs/plans', {
params: {
page: page.value,
pageSize: 20,
keyword: props.keyword || undefined,
status: props.status || undefined,
licensePlate: props.licensePlate || undefined,
planDateFrom: props.planDateFrom || undefined,
planDateTo: props.planDateTo || undefined,
conversionOnly: props.showAll ? undefined : true
}
})
)
if (current !== epoch) return
const list = data?.list || []
rows.value = page.value === 1 ? list : rows.value.concat(list)
finished.value = rows.value.length >= (data?.total || 0) || list.length < 20
page.value += 1
} catch {
if (current === epoch) {
error.value = '计划用证加载失败,请重试'
finished.value = true
}
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() =>
[props.keyword, props.status, props.licensePlate, props.planDateFrom, props.planDateTo, props.showAll].join(
'\0'
),
() => reload()
)
</script>
<style scoped>
.mp-cert-measure {
margin: 4px 0 8px;
}
.mp-cert-stop-brief {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #eef4f1;
}
.mp-cert-stop-brief .mp-wv-card__no {
margin-bottom: 4px;
font-size: 15px;
}
.plan-empty-hint {
margin: 8px 0 0;
color: #6b7b74;
font-size: 13px;
line-height: 1.5;
}
.plan-empty-hint .mp-wv-btn {
margin-left: 8px;
}
.is-conversion .mp-wv-card__no,
.is-conversion .mp-wv-card__sub,
.is-conversion .mp-wv-card__kv-row > span:first-child,
.is-conversion .mp-wv-card__kv-row > span:last-child:not(.status-tag) {
color: #dc2626;
}
.mp-cert-conversion {
color: #dc2626;
font-size: 13px;
font-weight: 600;
}
</style>
@@ -0,0 +1,125 @@
<template>
<main class="mp-h5-list-content mp-plan-cert-list">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="reload">重试</button>
</p>
<van-list v-model:loading="loading" :finished="finished" finished-text="" @load="load">
<article v-for="row in rows" :key="row.id" class="mp-wv-card mp-wv-flat-card">
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.planNo }}</div>
<div class="mp-wv-card__sub">
{{ row.licensePlate || '未安排车辆' }} · {{ row.planDate || '未定日期' }}
</div>
</div>
<span class="status-tag" :class="row.quotaCertWaived ? 'status-tag--success' : 'status-tag--warning'">
{{ row.quotaCertWaived ? '已齐备' : '未齐备' }}
</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>易制毒产品</span><span>{{ row.productNames || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>供方</span><span>{{ row.supplierName || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>需方</span><span>{{ row.customerName || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>跟进状态</span><span>{{ getPlPlanFollowStatusLabel(row.followStatus || undefined) }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>确认人</span><span>{{ row.quotaCertWaivedByName || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row">
<span>确认时间</span><span>{{ formatCertReadyTime(row.quotaCertWaivedTime) }}</span>
</div>
</div>
<div v-if="!row.quotaCertWaived" class="mp-wv-card-actions mp-wv-card-actions--single">
<button
class="mp-wv-btn mp-wv-btn--primary"
type="button"
:disabled="markingId === row.id"
@click="mark(row)"
>
{{ markingId === row.id ? '正在确认…' : '证书齐备' }}
</button>
</div>
</article>
</van-list>
<van-empty v-if="!loading && finished && !error && !rows.length" description="暂无需要证书齐备的计划" />
</main>
</template>
<script setup lang="ts">
import { certReadyApi, type CertReadyPlan } from '@/api/pl/quota-cert'
import { certReadyErrorText, formatCertReadyTime } from '@/utils/pl-quota-cert-waiver'
import { getPlPlanFollowStatusLabel } from '@/utils/pl-display'
const props = defineProps<{ keyword: string; waived: string }>()
const rows = ref<CertReadyPlan[]>([])
const loading = ref(false)
const finished = ref(false)
const error = ref('')
const page = ref(1)
const markingId = ref('')
let epoch = 0
function reload() {
epoch++
page.value = 1
rows.value = []
loading.value = true
finished.value = false
error.value = ''
void load()
}
async function load() {
const current = epoch
loading.value = true
try {
const data = await certReadyApi.list({
page: page.value,
pageSize: 20,
keyword: props.keyword || undefined,
waived: props.waived || undefined
})
if (current !== epoch) return
const list = data?.list || []
rows.value = page.value === 1 ? list : rows.value.concat(list)
finished.value = rows.value.length >= (data?.total || 0) || list.length < 20
page.value += 1
} catch (reason) {
if (current === epoch) {
error.value = certReadyErrorText(reason, '证书齐备加载失败,请重试')
finished.value = true
}
} finally {
if (current === epoch) loading.value = false
}
}
async function mark(row: CertReadyPlan) {
try {
await ElMessageBox.confirm(
'确认后,这条运输计划在安排和归档时都不再校验购买证、运输证,也不扣减额度。',
'证书齐备',
{ type: 'warning', confirmButtonText: '确认齐备', cancelButtonText: '取消' }
)
} catch {
return
}
markingId.value = row.id
try {
await certReadyApi.mark(row.id)
ElMessage.success('已标记证书齐备')
reload()
} catch (reason) {
ElMessage.error(certReadyErrorText(reason, '标记证书齐备失败'))
} finally {
markingId.value = ''
}
}
watch(
() => [props.keyword, props.waived].join('\0'),
() => reload()
)
</script>
@@ -0,0 +1,161 @@
<template>
<main class="mp-h5-list-content mp-plan-cert-list">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="reload">重试</button>
</p>
<div v-else-if="authReady && !allowed" class="mp-wv-empty">
<div class="mp-wv-empty__title">无证件查看权限</div>
</div>
<van-list v-else v-model:loading="loading" :finished="finished" finished-text="" @load="load">
<article
v-for="row in rows"
:key="row.certType + row.certId"
class="mp-wv-card mp-wv-flat-card"
@click="open(row)"
>
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.certNo }}</div>
<div class="mp-wv-card__sub">{{ row.certType === 'transport' ? '运输证' : '购买证' }}</div>
</div>
<span class="status-tag" :class="`status-tag--${row.status === 'active' ? 'success' : 'info'}`">
{{ certListStatus(row.status) }}
</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>销售单位</span><span>{{ row.salePartyName || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>购买单位</span><span>{{ row.buyPartyName || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>有效次数</span><span>{{ row.validUseText || '—' }}</span></div>
<div class="mp-wv-card__kv-row">
<span>是否预警</span>
<span v-if="warningText(row)" class="status-tag status-tag--danger">{{ warningText(row) }}</span>
<span v-else>—</span>
</div>
<div class="mp-wv-card__kv-row">
<span>证载品名</span><span>{{ row.productNameOnCert || '—' }}</span>
</div>
<div class="mp-wv-card__kv-row"><span>单位</span><span>{{ unit(row.quantityUnit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>全证核定</span><span>{{ qty(row.totalQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>全证预占</span><span>{{ qty(row.reservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>全证已用</span><span>{{ qty(row.usedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>全证共享余额</span><span>{{ qty(row.availableQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>有效期起</span><span>{{ row.validFrom || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>有效期止</span><span>{{ row.validTo || '—' }}</span></div>
</div>
<div class="mp-wv-card-actions mp-wv-card-actions--single" @click.stop>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="open(row)">查看</button>
</div>
</article>
</van-list>
<van-empty
v-if="authReady && allowed && !loading && finished && !error && !rows.length"
description="暂无证件用量"
/>
</main>
</template>
<script setup lang="ts">
import { fetchGetMenuCodes } from '@/api/auth'
import { quotaStatisticsApi, type CertificateStatisticsSummary } from '@/api/pl/quota-cert'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certListStatus } from './usage-model'
import { expiryWarning } from '@/views/pl/quota-cert/cert-list-face'
const props = defineProps<{ keyword: string; kind: string }>()
const router = useRouter()
const rows = ref<CertificateStatisticsSummary[]>([])
const loading = ref(true)
const finished = ref(false)
const error = ref('')
const allowed = ref(false)
const authReady = ref(false)
const page = ref(1)
let epoch = 0
let checking = true
function warningText(row: CertificateStatisticsSummary) {
return expiryWarning(row.validTo)?.label || ''
}
function qty(value: unknown) {
return formatCertQty(value)
}
function unit(value?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, value)
return !label || label === '—' ? '' : label
}
function open(row: CertificateStatisticsSummary) {
void router.push(`/m/pl/plan-cert/usage/${row.certType}/${row.certId}`)
}
async function init() {
const current = epoch
try {
const permissions = await fetchGetMenuCodes()
if (current !== epoch) return
const codes = permissions?.menuCodes || []
allowed.value =
!!permissions?.all || !!permissions?.isSuperAdmin || codes.includes('pl:quota-cert:list')
authReady.value = true
checking = false
if (!allowed.value) {
finished.value = true
loading.value = false
return
}
await load()
} catch {
if (current !== epoch) return
checking = false
authReady.value = true
finished.value = true
loading.value = false
error.value = '权限加载失败,请重新打开页面'
}
}
function reload() {
if (!allowed.value) {
void init()
return
}
epoch++
page.value = 1
rows.value = []
loading.value = true
finished.value = false
error.value = ''
void load()
}
async function load() {
if (checking || !allowed.value) return
const current = epoch
loading.value = true
try {
const data = await quotaStatisticsApi.certificates({
page: page.value,
pageSize: 20,
keyword: props.keyword || undefined,
certTypeIn: props.kind ? props.kind : undefined
})
if (current !== epoch) return
const list = data?.list || []
rows.value = page.value === 1 ? list : rows.value.concat(list)
finished.value = rows.value.length >= (data?.total || 0) || list.length < 20
page.value += 1
} catch {
if (current === epoch) {
error.value = '证件用量加载失败,请重试'
finished.value = true
}
} finally {
if (current === epoch) loading.value = false
}
}
watch(
() => props.kind,
() => {
if (!checking && allowed.value) reload()
}
)
void init()
</script>
@@ -0,0 +1,266 @@
<template>
<MpWebviewShell @ready="ready = true">
<MpBusinessHeader title="证件建档" back-label="返回运输证件管理" @back="router.back()" />
<main v-if="ready" class="mp-h5-list-content mp-h5-detail-page">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="load">重试</button>
</p>
<div v-else-if="loading" class="mp-cert-page-loading"><van-loading /></div>
<template v-else-if="cert">
<section v-for="(group, groupIndex) in groups" :key="groupIndex" class="mp-wv-section">
<h3 v-if="group.title">{{ group.title }}</h3>
<div class="detail-field-grid">
<div
v-for="field in group.fields"
:key="field.label"
class="mp-wv-kv"
:class="{ 'detail-wide': field.wide }"
>
<span>{{ field.label }}</span><span>{{ field.value }}</span>
</div>
</div>
</section>
<section class="mp-wv-section mp-plan-cert-list">
<h3>绑定合同产品</h3>
<p v-if="!(cert.contractBindings || []).length" class="plan-empty-hint">尚未关联合同。</p>
<article
v-for="row in cert.contractBindings || []"
:key="row.id || row.contractId"
class="mp-wv-card mp-wv-flat-card mp-cert-bind"
>
<div class="mp-wv-card__head">
<div class="mp-wv-flat-card__titles">
<div class="mp-wv-card__no">{{ contractName(row.contractId) }}</div>
<div v-if="contractMeta(row.contractId)" class="mp-wv-card__sub">{{ contractMeta(row.contractId) }}</div>
</div>
<span class="status-tag" :class="row.linkStatus === 'inactive' ? 'status-tag--info' : 'status-tag--success'">
{{ row.linkStatus === 'inactive' ? '已停用' : '启用' }}
</span>
</div>
<p v-if="row.editLocked" class="plan-empty-hint">
已有用证,不能增删产品。产品可以设为不可用,历史用量仍保留。
</p>
<div v-for="product in row.products" :key="product.id || product.contractProductId" class="mp-cert-bind__line">
<span>{{ productLabel(product.contractProductId) }}</span>
<span class="status-tag" :class="product.scopeStatus === 'inactive' ? 'status-tag--warning' : 'status-tag--success'">
{{ product.scopeStatus === 'inactive' ? '不可用' : '可用' }}
</span>
<button
v-if="canToggle(product)"
class="mp-wv-btn"
:class="{ 'mp-wv-btn--primary': product.scopeStatus === 'inactive' }"
type="button"
:disabled="saving"
@click="toggleProduct(row.contractId, product)"
>
{{ product.scopeStatus === 'inactive' ? '恢复可用' : '设为不可用' }}
</button>
</div>
</article>
</section>
<section v-if="kind === 'transport'" class="mp-wv-section">
<h3>证面引用</h3>
<p v-if="!(cert.purchaseRefs || []).length" class="plan-empty-hint">没有证面引用。</p>
<article v-for="(row, index) in cert.purchaseRefs || []" :key="row.id || index" class="mp-cert-block">
<div class="detail-field-grid">
<div class="mp-wv-kv">
<span>引用类型</span><span>{{ refLabels[row.referenceType] || row.referenceType }}</span>
</div>
<div class="mp-wv-kv"><span>购买许可/备案/出口许可证号</span><span>{{ row.referenceNo || '—' }}</span></div>
<div class="mp-wv-kv detail-wide">
<span>对应购买证</span><span>{{ purchaseNo(row.purchaseCertId) }}</span>
</div>
</div>
</article>
</section>
<section v-if="cert.attachmentUrls" class="mp-wv-section">
<h3>证件附件</h3>
<AttachmentUploadField :model-value="cert.attachmentUrls" disabled />
</section>
<div class="mp-wv-fab-bar">
<button class="mp-wv-btn" type="button" @click="historyOpen = true">额度流水</button>
<button v-if="canEdit" class="mp-wv-btn mp-wv-btn--primary" type="button" @click="editorOpen = true">编辑</button>
</div>
<ArchiveForm
v-if="editorOpen"
popup
:model-kind="kind"
:model-id="certId"
@close="editorOpen = false"
@saved="load"
/>
<CertHistorySheet
:open="historyOpen"
:kind="kind"
:cert-id="certId"
:can-edit="canEdit"
@close="historyOpen = false"
@saved="load"
/>
</template>
</main>
</MpWebviewShell>
</template>
<script setup lang="ts">
import { fetchGetMenuCodes } from '@/api/auth'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import ArchiveForm from './archive-form.vue'
import CertHistorySheet from './CertHistorySheet.vue'
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import { ElMessage } from 'element-plus'
import { quotaCertApi, type CertType, type ContractOption, type QuotaCert, type ScopeProduct } from '@/api/pl/quota-cert'
import { bindingPayload, formatCertQty, replaceCertProducts } from '@/views/pl/quota-cert/model'
import { showCrmConfirmDialog } from '@/utils/mp-crm-confirm'
import { applyScopeStatus, canRestoreProduct, nextScopeStatus } from './cert-link-rules'
import './cert-mobile.scss'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certFaceGroups, certStatusLabels, refLabels } from './face-model'
import '../plan/plan-read-fields.scss'
import '@/styles/mp-webview.scss'
const route = useRoute()
const router = useRouter()
const ready = ref(false)
const canEdit = ref(false)
const editorOpen = ref(false)
const historyOpen = ref(false)
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const cert = ref<QuotaCert>()
const contracts = ref<Map<string, ContractOption>>(new Map())
const productNames = ref<Map<string, string>>(new Map())
const purchases = ref<QuotaCert[]>([])
const kind = computed(() => (route.params.kind === 'transport' ? 'transport' : 'purchase') as CertType)
const certId = computed(() => String(route.params.id || ''))
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
function display(row: QuotaCert, key: string) {
if (key === 'status') return certStatusLabels[row.status] || row.status || '—'
if (key === 'totalQty') {
const qty = formatCertQty(row.totalQty)
const unit = unitText(row.quantityUnit)
return unit && qty !== '—' ? `${qty} ${unit}` : qty
}
if (key === 'quantityUnit') return unitText(row.quantityUnit) || '—'
if (key === 'remark') return String(row.remark || '').trim() || '—'
const raw = row[key as keyof QuotaCert]
if (raw == null || raw === '') return '—'
return typeof raw === 'string' || typeof raw === 'number' ? String(raw) : '—'
}
const groups = computed(() => (cert.value ? certFaceGroups(cert.value, kind.value, display) : []))
function contractName(id: string) {
const item = contracts.value.get(id)
return item?.contractNo || item?.contractName || '合同信息不可用'
}
function contractMeta(id: string) {
const item = contracts.value.get(id)
if (!item) return ''
const name = item.contractName && item.contractName !== item.contractNo ? item.contractName : ''
return [name, item.customerName].filter(Boolean).join(' · ')
}
onMounted(async () => {
const permissions = await fetchGetMenuCodes().catch(() => null)
canEdit.value =
!!permissions?.all ||
!!permissions?.isSuperAdmin ||
(permissions?.menuCodes || []).includes('pl:quota-cert:edit')
})
function productLabel(id: string) {
return productNames.value.get(id) || '合同产品'
}
function canToggle(product: ScopeProduct) {
return (
cert.value?.bindingsEditable !== false &&
Boolean(product.id) &&
canRestoreProduct(cert.value?.status, product.scopeStatus)
)
}
async function toggleProduct(contractId: string, product: ScopeProduct) {
if (!cert.value || saving.value || !canToggle(product)) return
const status = nextScopeStatus(product.scopeStatus)
const name = productLabel(product.contractProductId)
try {
await showCrmConfirmDialog({
kind: 'default',
title: status === 'inactive' ? '设为不可用' : '恢复可用',
message:
status === 'inactive'
? `设为不可用后,${name} 不能再使用这张证安排新的运输。已经发生的用量仍保留。`
: `恢复后,${name} 可以再使用这张证安排新的运输。历史用量不变。`,
confirmButtonText: '确定'
})
} catch {
return
}
saving.value = true
try {
const existing = await quotaCertApi.bindings(contractId)
const matched = existing.find((row) => row.certType === kind.value && row.certId === certId.value)
if (!matched) {
ElMessage.warning('关联已变化,请刷新后再操作')
await load()
return
}
const products = applyScopeStatus(matched.products, product.contractProductId, status)
await quotaCertApi.saveBindings(
contractId,
bindingPayload(replaceCertProducts(existing, kind.value, certId.value, products))
)
ElMessage.success(status === 'inactive' ? '已设为不可用' : '已恢复可用')
await load()
} catch {
ElMessage.error('产品状态没有保存,请重试')
} finally {
saving.value = false
}
}
function purchaseNo(id?: string | null) {
if (!id) return '未关联'
return purchases.value.find((item) => item.id === id)?.certNo || '无查看权限或已失效'
}
async function load() {
loading.value = true
error.value = ''
try {
cert.value = await quotaCertApi.get(kind.value, certId.value)
const linked = await quotaCertApi.certificateContracts(kind.value, certId.value).catch(() => [])
contracts.value = new Map(linked.map((item) => [item.id, item]))
if (kind.value === 'transport') purchases.value = await quotaCertApi.list('purchase').catch(() => [])
const names = new Map<string, string>()
await Promise.all(
(cert.value.contractBindings || []).map(async (binding) => {
const products = await quotaCertApi.products(binding.contractId).catch(() => [])
for (const product of products) names.set(product.id, product.productName || product.model || '合同产品')
})
)
productNames.value = names
} catch {
error.value = '证件加载失败,请重试'
} finally {
loading.value = false
}
}
watch(ready, (value) => value && void load())
</script>
<style scoped>
.mp-cert-block {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #eef4f1;
}
.mp-cert-block h4,
.plan-empty-hint {
margin: 0;
font-size: 14px;
}
.plan-empty-hint {
color: #6b7b74;
}
</style>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,73 @@
import type { CertType } from '@/api/pl/quota-cert'
import { requiredFaceLabel } from '@/views/pl/quota-cert/model'
const requiredByKind: Record<CertType, string[]> = {
purchase: ['certNo', 'productNameOnCert', 'totalQty', 'quantityUnit', 'validUseText', 'buyerName', 'sellerName'],
transport: ['certNo', 'productNameOnCert', 'totalQty', 'quantityUnit', 'validUseText', 'shipperName']
}
export function missingCertLabel(kind: CertType, form: Record<string, unknown>) {
const key = requiredByKind[kind].find((field) => String(form[field] ?? '').trim() === '')
return key ? requiredFaceLabel(kind, key) : ''
}
export function attachmentCount(urls?: string | null) {
return String(urls || '')
.split(',')
.map((item) => item.trim())
.filter(Boolean).length
}
export function statusChoices(current: string) {
const options = [
['draft', '待核对'],
['active', '已启用'],
['suspended', '已停用'],
['closed', '已核销'],
['void', '已作废']
] as const
return options.filter(([value]) => {
if (current === 'void') return value === 'void'
if (current === 'closed') return value === 'closed'
if (value === current) return true
return value === 'suspended' || value === 'closed' || value === 'void'
})
}
export function keptPlates(locked: string[], next: string[]) {
const extras = next.map((item) => item.trim()).filter((item) => item && !locked.includes(item))
return [...locked, ...extras]
}
export function dropsLockedPlate(locked: string[], next: string[]) {
return locked.some((plate) => !next.includes(plate))
}
export function referenceRowLocked(
referencesEditable: boolean | undefined,
row: { id?: string; purchaseCertId?: string | null },
linkedIds: string[]
) {
return referencesEditable === false && Boolean(row.id) && linkedIds.includes(String(row.id))
}
export function productIdentity(products: { contractProductId: string }[]) {
return products
.map((product) => product.contractProductId)
.sort()
.join('\n')
}
export function scopeExpands(
certStatus: string | undefined,
isNewBinding: boolean,
before: { contractProductId: string; scopeStatus?: string | null }[],
after: { contractProductId: string; scopeStatus?: string | null }[]
) {
if (certStatus !== 'void' && certStatus !== 'closed') return false
if (isNewBinding) return true
return after.some((product) => {
const previous = before.find((item) => item.contractProductId === product.contractProductId)
return !previous || (previous.scopeStatus !== 'active' && (product.scopeStatus || 'active') === 'active')
})
}
@@ -0,0 +1,68 @@
import type { CertType, ScopeProduct } from '@/api/pl/quota-cert'
export type CertChoice = { id: string; status: string; certNo?: string; productNameOnCert?: string }
export function certChoiceState(item: CertChoice, kind: CertType, taken: Set<string>) {
if (item.status === 'void') return 'void' as const
if (item.status === 'closed') return 'closed' as const
if (taken.has(`${kind}:${item.id}`)) return 'taken' as const
return 'open' as const
}
export function certChoiceLabel(item: CertChoice, kind: CertType, taken: Set<string>) {
const name = [item.certNo, item.productNameOnCert].filter(Boolean).join(' · ') || '证号未提供'
const state = certChoiceState(item, kind, taken)
if (state === 'void') return `${name}(已作废)`
if (state === 'closed') return `${name}(已核销)`
if (state === 'taken') return `${name}(已关联)`
return name
}
export function scopeKey(products: ScopeProduct[]) {
return products
.map((product) => `${product.contractProductId}:${product.scopeStatus || 'active'}`)
.sort()
.join('\n')
}
export function canSaveNewLink(products: ScopeProduct[]) {
return products.some((product) => product.scopeStatus !== 'inactive')
}
export function canSaveProductEdit(before: ScopeProduct[], after: ScopeProduct[]) {
return scopeKey(before) !== scopeKey(after)
}
export function canRestoreProduct(certStatus: string | undefined, scopeStatus?: string | null) {
return !(scopeStatus === 'inactive' && (certStatus === 'void' || certStatus === 'closed'))
}
export function nextScopeStatus(scopeStatus?: string | null): 'active' | 'inactive' {
return scopeStatus === 'inactive' ? 'active' : 'inactive'
}
export function applyScopeStatus(
products: ScopeProduct[],
contractProductId: string,
scopeStatus: 'active' | 'inactive'
) {
return products.map((product) =>
product.contractProductId === contractProductId ? { ...product, scopeStatus } : product
)
}
export function addDraftProducts(current: ScopeProduct[], contractProductIds: string[]) {
const existing = new Set(current.map((product) => product.contractProductId))
const added = contractProductIds
.map((id) => id.trim())
.filter((id) => id && !existing.has(id))
.map((contractProductId) => ({ contractProductId, scopeStatus: 'active' as const }))
return [...current, ...added]
}
/** 已保存的产品行带 id,不能从集合里拿掉。 */
export function removeDraftProduct(products: ScopeProduct[], contractProductId: string) {
return products.filter(
(product) => Boolean(product.id) || product.contractProductId !== contractProductId
)
}
@@ -0,0 +1,160 @@
.mp-cert-archive-filters {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
.mp-customer-dd {
flex: 1;
min-width: 0;
}
}
.mp-cert-expiry {
flex-shrink: 0;
padding: 2px 8px;
margin-top: 4px;
font-size: 13px;
font-weight: 600;
line-height: 18px;
color: #ff4d4f;
white-space: nowrap;
cursor: pointer;
background: #fff;
border: 0;
border-radius: 999px;
&.is-active {
color: #fff;
background: #ff4d4f;
}
}
.mp-cert-page-loading {
display: flex;
align-items: center;
justify-content: center;
min-height: calc(100dvh - 132px);
}
.mp-plan-cert-list .mp-wv-flat-card {
.mp-wv-card__no {
font-size: 17px;
}
.mp-wv-card__sub,
.mp-wv-card__kv-row {
font-size: 14px;
}
.status-tag {
font-size: 13px;
}
.mp-wv-card-actions .mp-wv-btn {
font-size: 15px;
}
}
.mp-cert-has-fab {
padding-bottom: calc(84px + env(safe-area-inset-bottom));
}
.mp-cert-bind {
margin-top: 10px;
}
.mp-cert-bind__line {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
margin-top: 8px;
color: #1f2a26;
font-size: 14px;
> span:first-child {
flex: 1 1 120px;
min-width: 0;
}
.status-tag,
.mp-wv-btn {
flex: 0 0 auto;
}
}
.mp-cert-bind__line .mp-wv-btn.is-danger {
color: #b91c1c;
background: #fff7f7;
border-color: #fecaca;
}
.mp-cert-add {
width: 100%;
margin-top: 10px;
}
.mp-cert-form {
--van-primary-color: #0a9f6d;
--van-nav-bar-text-color: #0a9f6d;
--van-nav-bar-icon-color: #0a9f6d;
.van-field:not(.van-search__field) {
display: grid;
grid-template-columns: minmax(0, 1fr);
min-width: 0;
margin-top: 8px;
padding: 0;
background: transparent;
}
.van-field:not(.van-search__field) > .van-cell__title {
grid-column: 1 / -1;
}
.van-field:not(.van-search__field) > .van-cell__value {
grid-column: 1;
grid-row: 2;
}
.van-field:not(.van-search__field) > .van-cell__right-icon {
position: absolute;
right: 8px;
bottom: 5px;
margin: 0;
}
.van-field:not(.van-search__field) .van-field__label {
width: auto;
margin: 0 0 3px;
color: #1e293b;
font-size: 13px;
font-weight: 500;
line-height: 18px;
}
.van-field:not(.van-search__field) .van-field__body {
box-sizing: border-box;
min-height: 34px;
padding: 4px 8px;
border: 1px solid #e4ece7;
border-radius: 6px;
background: #f7faf8;
}
.van-field:not(.van-search__field) .van-field__control {
min-width: 0;
min-height: 24px;
line-height: 24px;
font-size: 14px;
}
.van-field:not(.van-search__field)::after {
display: none;
}
.van-field.van-cell--clickable .van-field__body {
padding-right: 28px;
}
}
@@ -0,0 +1,441 @@
<template>
<MpWebviewShell @ready="ready = true">
<MpBusinessHeader title="合同用证" back-label="返回运输证件管理" @back="router.back()" />
<main v-if="ready" class="mp-h5-list-content mp-h5-detail-page mp-plan-cert-list">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="retry">重试</button>
</p>
<div v-else-if="!authReady || loading" class="mp-cert-page-loading"><van-loading /></div>
<div v-else-if="!allowed" class="mp-wv-empty">
<div class="mp-wv-empty__title">无证件查看权限</div>
</div>
<template v-else-if="detail">
<section class="mp-wv-section">
<div class="mp-cert-contract-head">
<div class="mp-cert-contract-head__main">
<h3>{{ detail.contractNo || '未编号合同' }}</h3>
<p>{{ detail.contractName || '—' }}</p>
</div>
<button
v-if="canEdit"
class="mp-wv-btn mp-wv-btn--primary"
type="button"
:disabled="saving"
@click="openCreate"
>
新增
</button>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>合同类型</span><span>{{ contractTypeLabel(detail.contractType) }}</span>
</div>
</div>
</section>
<van-tabs v-model:active="view" class="mp-cert-face-tabs" shrink :ellipsis="false">
<van-tab title="关联证件" name="certs" />
<van-tab title="按产品" name="products" />
</van-tabs>
<template v-if="view === 'certs'">
<van-empty v-if="!certificates.length" description="暂无关联证件" />
<article v-for="cert in certificates" :key="cert.certType + cert.certId" class="mp-wv-section">
<div class="mp-wv-card__head">
<div>
<h3>{{ cert.certNo || '—' }}</h3>
<p>{{ cert.productNameOnCert || '未填写证面品名' }}</p>
<p>有效期:{{ cert.validFrom || '—' }} 至 {{ cert.validTo || '—' }}</p>
</div>
</div>
<div class="mp-cert-tags">
<span class="status-tag status-tag--info">{{ cert.certType === 'purchase' ? '购买证' : '运输证' }}</span>
<span class="status-tag" :class="`status-tag--${cert.linkStatus === 'active' ? 'success' : 'info'}`">
{{ linkLabel(cert.linkStatus) }}
</span>
<span class="status-tag" :class="`status-tag--${cert.status === 'active' ? 'success' : 'info'}`">
{{ certDetailStatus(cert.status) }}
</span>
</div>
<div class="mp-cert-inline-metrics">
<div v-for="item in certMetrics(cert)" :key="item.label" class="mp-wv-kv">
<span>{{ item.label }}</span>
<span v-if="item.alert" class="status-tag status-tag--danger">{{ item.value }}</span>
<span v-else>{{ item.value }}</span>
</div>
</div>
<div v-if="canEdit && cert.bindingId" class="mp-cert-link-actions">
<button
v-if="!cert.referenced"
class="mp-wv-btn mp-wv-btn--primary"
type="button"
:disabled="saving"
@click="openEdit(cert)"
>
编辑
</button>
<button
v-if="!cert.referenced"
class="mp-wv-btn is-danger"
type="button"
:disabled="saving"
@click="changeLink(cert, 'delete')"
>
删除
</button>
<button
v-if="cert.referenced && cert.linkStatus === 'active'"
class="mp-wv-btn"
type="button"
:disabled="saving"
@click="changeLink(cert, 'inactive')"
>
设为不可用
</button>
<button
v-if="
cert.referenced &&
cert.linkStatus !== 'active' &&
cert.status !== 'void' &&
cert.status !== 'closed'
"
class="mp-wv-btn mp-wv-btn--primary"
type="button"
:disabled="saving"
@click="changeLink(cert, 'active')"
>
恢复可安排
</button>
</div>
<p v-if="cert.bindingId && cert.referenced && cert.linkStatus === 'active'" class="plan-empty-hint">
这份关联已有运输计划用证,不能删除,也不能改产品。设为不可用后,不能再安排新的用证,已经发生的用量仍保留。
</p>
<p v-else-if="cert.bindingId && cert.referenced" class="plan-empty-hint">
这份关联已有运输计划用证,目前不可用,不能再安排新的用证。已经发生的用量仍保留。
</p>
<p v-else-if="!cert.bindingId" class="plan-empty-hint">
这条关联已经不在当前绑定里,历史用量仍可查看。
</p>
<p v-if="!(cert.products || []).length" class="plan-empty-hint">暂无合同产品范围</p>
<article
v-for="product in cert.products || []"
:key="product.id || product.contractProductId"
class="mp-cert-product"
>
<strong>{{ product.productName || '—' }}</strong>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>规格</span><span>{{ product.model || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>产品单位</span><span>{{ unit(product.unit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>额度单位</span><span>{{ unit(cert.quantityUnit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>预占</span><span>{{ qty(product.reservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>已用</span><span>{{ qty(product.usedQty) }}</span></div>
<div class="mp-wv-card__kv-row">
<span>范围状态</span>
<span class="status-tag" :class="`status-tag--${product.scopeStatus === 'active' ? 'success' : 'info'}`">
{{ scopeStatusLabel(product.scopeStatus) }}
</span>
</div>
</div>
</article>
</article>
</template>
<template v-else>
<van-empty v-if="!productRows.length" description="暂无绑定产品" />
<article v-for="row in productRows" :key="row.key" class="mp-wv-section">
<h3>{{ row.productName }}</h3>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>规格</span><span>{{ row.model }}</span></div>
<div class="mp-wv-card__kv-row"><span>产品单位</span><span>{{ unit(row.unit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>证件类型</span><span>{{ row.certKind }}</span></div>
<div class="mp-wv-card__kv-row"><span>证件编号</span><span>{{ row.certNo }}</span></div>
<div class="mp-wv-card__kv-row"><span>证面单位</span><span>{{ unit(row.certUnit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>产品预占</span><span>{{ qty(row.reservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>产品已用</span><span>{{ qty(row.usedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>全证核定</span><span>{{ qty(row.totalQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>全证预占</span><span>{{ qty(row.certReservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>销售单位</span><span>{{ row.salePartyName }}</span></div>
<div class="mp-wv-card__kv-row"><span>购买单位</span><span>{{ row.buyPartyName }}</span></div>
<div class="mp-wv-card__kv-row"><span>有效次数</span><span>{{ row.validUseText }}</span></div>
<div class="mp-wv-card__kv-row">
<span>是否预警</span>
<span v-if="row.expiryAlert" class="status-tag status-tag--danger">{{ row.expiryAlert }}</span>
<span v-else>—</span>
</div>
<div class="mp-wv-card__kv-row"><span>全证已用</span><span>{{ qty(row.certUsedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>共享余额</span><span>{{ qty(row.availableQty) }}</span></div>
<div class="mp-wv-card__kv-row">
<span>范围状态</span>
<span class="status-tag" :class="`status-tag--${row.scopeStatus === 'active' ? 'success' : 'info'}`">
{{ scopeStatusLabel(row.scopeStatus) }}
</span>
</div>
</div>
</article>
</template>
</template>
</main>
<CertLinkSheet ref="linkSheet" @saved="load" />
</MpWebviewShell>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { fetchGetMenuCodes } from '@/api/auth'
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import {
quotaCertApi,
quotaStatisticsApi,
type ContractStatistics,
type StatisticsProduct
} from '@/api/pl/quota-cert'
import { bindingPayload, formatCertQty } from '@/views/pl/quota-cert/model'
import { certFaceFields } from '@/views/pl/quota-cert/cert-list-face'
import { contractTypeLabel } from '@/views/pl/quota-statistics/labels'
import { showCrmConfirmDialog } from '@/utils/mp-crm-confirm'
import CertLinkSheet from './CertLinkSheet.vue'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { linkLabel, scopeStatusLabel } from './usage-model'
import { certDetailStatus, contractProductRows } from './contract-usage-model'
import '../plan/plan-read-fields.scss'
import '@/styles/mp-webview.scss'
import './cert-mobile.scss'
const route = useRoute()
const router = useRouter()
const ready = ref(false)
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const allowed = ref(false)
const canEdit = ref(false)
const authReady = ref(false)
const view = ref('certs')
const detail = ref<ContractStatistics>()
const linkSheet = ref<{ open: (payload: Record<string, string>) => Promise<void> }>()
const certificates = computed(() => (detail.value?.certificates || []) as ContractCert[])
const productRows = computed(() => (detail.value ? contractProductRows(detail.value) : []))
const contractId = computed(() => String(route.params.id || ''))
function qty(value: unknown) {
return formatCertQty(value)
}
function unit(value?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, value)
return !label || label === '—' ? '' : label
}
function qtyWithUnit(value: unknown, quantityUnit?: string | null) {
const text = qty(value)
const name = unit(quantityUnit)
return name ? `${text} ${name}` : text
}
function certMetrics(cert: ContractCert) {
const quantities = [
['全证核定', cert.totalQty],
['全证预占', cert.reservedQty],
['全证已用', cert.usedQty],
['全证共享余额', cert.availableQty],
['本合同预占', cert.contractReservedQty],
['本合同已用', cert.contractUsedQty]
].map(([label, value]) => ({
label: String(label),
value: qtyWithUnit(value, cert.quantityUnit),
alert: false
}))
return [...quantities.slice(0, 2), ...certFaceFields(cert), ...quantities.slice(2)]
}
async function init() {
loading.value = true
error.value = ''
try {
const permissions = await fetchGetMenuCodes()
const codes = permissions?.menuCodes || []
const all = !!permissions?.all || !!permissions?.isSuperAdmin
allowed.value = all || codes.includes('pl:quota-cert:list')
canEdit.value = allowed.value && (all || codes.includes('pl:quota-cert:edit'))
authReady.value = true
if (!allowed.value) {
loading.value = false
return
}
await load()
} catch {
authReady.value = true
loading.value = false
error.value = '权限加载失败,请重新打开页面'
}
}
async function load() {
if (!allowed.value) return
loading.value = true
error.value = ''
try {
detail.value = await quotaStatisticsApi.contract(contractId.value)
} catch {
error.value = '统计加载失败,请重试'
} finally {
loading.value = false
}
}
function retry() {
if (!authReady.value || !allowed.value) void init()
else void load()
}
type ContractCert = ContractStatistics['certificates'][number] & { products?: StatisticsProduct[] }
function openCreate() {
if (!canEdit.value || !detail.value?.id) return
void linkSheet.value?.open({
contractId: detail.value.id,
contractNo: detail.value.contractNo,
contractName: detail.value.contractName,
mode: 'create'
})
}
function openEdit(cert: ContractCert) {
if (!canEdit.value || !detail.value?.id || cert.referenced || !cert.bindingId) return
void linkSheet.value?.open({
contractId: detail.value.id,
contractNo: detail.value.contractNo,
contractName: detail.value.contractName,
mode: 'edit',
certType: cert.certType,
certId: cert.certId,
certNo: cert.certNo,
certStatus: cert.status
})
}
async function changeLink(cert: ContractCert, action: 'delete' | 'inactive' | 'active') {
if (!canEdit.value || !detail.value?.id || saving.value || !cert.bindingId) return
if (action === 'delete' && cert.referenced) return
if (action !== 'delete' && !cert.referenced) return
const message =
action === 'delete'
? `删除后,合同 ${detail.value.contractNo} 不能再使用 ${cert.certNo} 安排新的运输。只有从未被运输计划用过的关联才能删除。`
: action === 'inactive'
? `设为不可用后,合同 ${detail.value.contractNo} 不能再使用 ${cert.certNo} 安排新的运输。已经预占和核销的数量仍保留。`
: `恢复后,合同 ${detail.value.contractNo} 可以再使用 ${cert.certNo} 安排新的运输。历史用量不变。`
try {
await showCrmConfirmDialog({
kind: action === 'delete' ? 'danger' : 'default',
title: action === 'delete' ? '删除关联' : '调整关联',
message,
confirmButtonText: action === 'delete' ? '删除' : '确定'
})
} catch {
return
}
saving.value = true
try {
const existing = await quotaCertApi.bindings(detail.value.id)
const matched = existing.some((row) => row.certType === cert.certType && row.certId === cert.certId)
if (!matched) {
ElMessage.warning('关联已变化,请刷新后再操作')
await load()
return
}
const next =
action === 'delete'
? existing.filter((row) => !(row.certType === cert.certType && row.certId === cert.certId))
: existing.map((row) =>
row.certType === cert.certType && row.certId === cert.certId
? { ...row, linkStatus: action }
: row
)
await quotaCertApi.saveBindings(detail.value.id, bindingPayload(next))
ElMessage.success(action === 'delete' ? '关联已删除' : action === 'inactive' ? '已设为不可用' : '已恢复可安排')
await load()
} catch {
ElMessage.error('关联没有保存,请重试')
} finally {
saving.value = false
}
}
watch(ready, (value) => value && void init())
</script>
<style scoped>
.mp-cert-contract-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.mp-cert-contract-head__main {
flex: 1;
min-width: 0;
}
.mp-cert-contract-head .mp-wv-btn {
flex: 0 0 auto;
min-width: 72px;
margin-top: 0;
}
.mp-cert-link-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 12px;
}
.mp-cert-link-actions .mp-wv-btn {
flex: 0 0 auto;
min-width: 72px;
}
.mp-cert-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 8px;
}
.mp-cert-product {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #eef4f1;
}
.mp-cert-product strong {
color: #1f2a26;
font-size: 14px;
}
.plan-empty-hint,
.mp-wv-section > p {
margin: 4px 0 0;
color: #6b7b74;
font-size: 13px;
line-height: 1.5;
}
.mp-cert-face-tabs {
margin: 4px -4px 8px;
background: transparent;
--van-tabs-line-height: 44px;
--van-tabs-nav-background: transparent;
--van-tab-font-size: 13px;
--van-tab-text-color: #6b7b74;
--van-tab-active-text-color: #087f57;
--van-tabs-bottom-bar-color: #0a9f6d;
--van-tabs-bottom-bar-height: 2px;
}
.mp-cert-face-tabs :deep(.van-tabs__wrap) {
height: 44px;
}
.mp-cert-face-tabs :deep(.van-tabs__nav) {
background: transparent;
}
.mp-cert-face-tabs :deep(.van-tab) {
font-weight: 600;
}
.mp-cert-face-tabs :deep(.van-tab--active) {
font-weight: 700;
color: #087f57;
}
.mp-cert-face-tabs :deep(.van-tabs__line) {
height: 2px !important;
background: #0a9f6d !important;
border-radius: 2px;
}
.mp-cert-face-tabs :deep(.van-tabs__content) {
display: none;
}
.mp-cert-inline-metrics {
display: grid;
grid-template-columns: repeat(6, minmax(88px, 1fr));
gap: 0 10px;
margin: 8px 0 4px;
overflow-x: auto;
}
</style>
@@ -0,0 +1,38 @@
import type { ContractStatistics } from '@/api/pl/quota-cert'
import { certFaceFields, expiryWarning } from '@/views/pl/quota-cert/cert-list-face'
import { statusLabel } from '@/views/pl/quota-statistics/labels'
export function certDetailStatus(status?: string | null) {
return (
{ draft: '待核对', active: '证件已启用', suspended: '证件已停用', closed: '证件已核销', void: '证件已作废' }[
status || ''
] ||
statusLabel(status || '') ||
'—'
)
}
export function contractProductRows(detail: ContractStatistics) {
return (detail.certificates || []).flatMap((cert) =>
(cert.products || []).map((product) => ({
key: `${cert.certType}:${cert.certId}:${product.contractProductId || product.id}`,
productName: product.productName || '—',
model: product.model || '—',
unit: product.unit,
certKind: cert.certType === 'purchase' ? '购买证' : '运输证',
certNo: cert.certNo || '—',
certUnit: cert.quantityUnit,
reservedQty: product.reservedQty,
usedQty: product.usedQty,
totalQty: cert.totalQty,
certReservedQty: cert.reservedQty,
salePartyName: certFaceFields(cert)[0].value,
buyPartyName: certFaceFields(cert)[1].value,
validUseText: cert.validUseText || '—',
expiryAlert: expiryWarning(cert.validTo)?.label || '',
certUsedQty: cert.usedQty,
availableQty: cert.availableQty,
scopeStatus: product.scopeStatus
}))
)
}
+17 -2
View File
@@ -1,4 +1,19 @@
<template><PlanQuotaPage /></template>
<template>
<MpWebviewShell @ready="ready = true">
<MpBusinessHeader title="计划用证" back-label="返回运输证件管理" @back="router.back()" />
<main v-if="ready && planId" class="mp-h5-list-content mp-h5-detail-page">
<CertFacePanel :plan-id="planId" />
</main>
</MpWebviewShell>
</template>
<script setup lang="ts">
import PlanQuotaPage from './index.vue'
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import CertFacePanel from './CertFacePanel.vue'
import '@/styles/mp-webview.scss'
const route = useRoute()
const router = useRouter()
const ready = ref(false)
const planId = computed(() => (typeof route.params.id === 'string' ? route.params.id : ''))
</script>
@@ -0,0 +1,56 @@
import type { CertType, QuotaCert } from '@/api/pl/quota-cert'
import { certFormGroups } from '@/views/pl/quota-cert/model'
export const certStatusLabels: Record<string, string> = {
draft: '待核对',
active: '已启用',
suspended: '已停用',
closed: '已核销',
void: '已作废'
}
export const refLabels: Record<string, string> = {
purchase_permit: '购买许可证',
purchase_filing: '购买备案证明',
export_permit: '出口许可证',
unknown: '待确认'
}
const longFaceKeys = new Set([
'buyerAddress',
'sellerAddress',
'shipperAddress',
'carrierAddressPhone',
'routeText',
'purchasePurpose',
'packagingText',
'remark'
])
export type FaceField = { label: string; value: string; wide?: boolean }
export type FaceGroup = { title: string; fields: FaceField[] }
export function certFaceGroups(
cert: QuotaCert,
kind: CertType,
display: (cert: QuotaCert, key: string) => string
): FaceGroup[] {
const groups = certFormGroups(kind).map((group, index) => {
const fields = group.fields.map((field) => ({
label: field[1],
value:
field[0] === 'vehicleNumbersJson'
? cert.vehicleNumbersJson?.filter(Boolean).join('、') || '—'
: display(cert, field[0]),
wide: longFaceKeys.has(field[0]) || field[0] === 'vehicleNumbersJson'
}))
if (index === 0) fields.unshift({ label: '状态', value: display(cert, 'status') })
return { title: group.title, fields }
})
groups[groups.length - 1].fields.push({
label: '系统备注',
value: display(cert, 'remark'),
wide: true
})
return groups
}
+222 -16
View File
@@ -1,27 +1,219 @@
<template>
<MpWebviewShell @ready="ready = true"
><MpBusinessHeader
title="计划用证"
back-label="返回工作台"
@back="goToMiniWorkbench" /><PlanQuotaList
v-if="ready"
:key="session"
mobile
:plan-id="planId"
/></MpWebviewShell>
<MpWebviewShell @ready="ready = true">
<div v-if="ready" class="mp-plan-cert-page">
<MpBusinessHeader
v-model:keyword="keyword"
title="运输证件管理"
searchable
:search-placeholder="placeholder"
search-label="搜索运输证件管理"
back-label="返回工作台"
@back="goToMiniWorkbench"
@search="committed = keyword"
>
<template #before-search>
<van-tabs
v-model:active="tab"
class="mp-customer-view-tabs"
shrink
:ellipsis="false"
aria-label="运输证件管理"
@change="onTab"
>
<van-tab name="archive" title="证件建档" />
<van-tab name="contract" title="合同用证" />
<van-tab name="usage" title="证件用量" />
<van-tab name="plan" title="计划段次用证" />
<van-tab name="ready" title="证书齐备" />
</van-tabs>
</template>
<template #after-search>
<div v-if="tab === 'archive'" class="mp-cert-archive-filters">
<van-dropdown-menu class="mp-customer-dd">
<van-dropdown-item v-model="archiveKind" :options="kindOptions" />
<van-dropdown-item v-model="archiveStatus" :options="archiveStatusOptions" />
</van-dropdown-menu>
<button
type="button"
class="mp-cert-expiry"
:class="{ 'is-active': expiringSoon }"
@click="expiringSoon = !expiringSoon"
>
近7日到期({{ expiringCount }}个)
</button>
</div>
<van-dropdown-menu v-else-if="tab === 'usage'" class="mp-customer-dd">
<van-dropdown-item v-model="usageKind" :options="kindOptions" />
</van-dropdown-menu>
<van-dropdown-menu v-else-if="tab === 'ready'" class="mp-customer-dd">
<van-dropdown-item v-model="readyState" :options="readyStateOptions" />
</van-dropdown-menu>
<van-dropdown-menu v-else-if="tab === 'plan'" class="mp-customer-dd">
<van-dropdown-item v-model="planScope" :options="planScopeOptions" />
<van-dropdown-item v-model="planStatus" :options="planStatusOptions" />
<van-dropdown-item ref="planFilter" :title="planFilterTitle" @open="syncPlanFilterDraft">
<div class="mp-plan-quota-filter">
<van-field v-model="planPlateDraft" label="车号" placeholder="输入车号" clearable />
<PlanDateField v-model="planDateFromDraft" label="开始日期" clearable />
<PlanDateField v-model="planDateToDraft" label="结束日期" clearable />
<div class="mp-plan-quota-filter__actions">
<button class="mp-wv-btn" type="button" @click="clearPlanFilter">清除</button>
<button class="mp-wv-btn mp-wv-btn--primary" type="button" @click="applyPlanFilter">
确定
</button>
</div>
</div>
</van-dropdown-item>
</van-dropdown-menu>
</template>
</MpBusinessHeader>
<ArchiveTab
v-if="tab === 'archive'"
:key="session + committed"
:keyword="committed"
:kind="archiveKind"
:status="archiveStatus"
:expiring-soon="expiringSoon"
@expiring-count="expiringCount = $event"
/>
<ContractTab v-else-if="tab === 'contract'" :key="session + committed" :keyword="committed" />
<UsageTab
v-else-if="tab === 'usage'"
:key="session + committed"
:keyword="committed"
:kind="usageKind"
/>
<PlanTab
v-else-if="tab === 'plan'"
:key="session + committed"
:keyword="committed"
:status="planStatus"
:license-plate="planPlate"
:plan-date-from="planDateFrom"
:plan-date-to="planDateTo"
:show-all="showAllPlans"
/>
<ReadyTab v-else :key="session + committed" :keyword="committed" :waived="readyState" />
</div>
</MpWebviewShell>
</template>
<script setup lang="ts">
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import PlanQuotaList from '@/views/pl/plan-quota/index.vue'
import { useUserStore } from '@/store/modules/user'
import { goToMiniWorkbench } from '@/utils/mp-webview'
import PlanDateField from '../plan/PlanDateField.vue'
import ArchiveTab from './ArchiveTab.vue'
import ContractTab from './ContractTab.vue'
import UsageTab from './UsageTab.vue'
import PlanTab from './PlanTab.vue'
import ReadyTab from './ReadyTab.vue'
import { certStatusLabels } from './face-model'
import '@/styles/mp-webview.scss'
const route = useRoute(),
user = useUserStore(),
ready = ref(false),
session = ref(0)
const planId = computed(() => (typeof route.params.id === 'string' ? route.params.id : undefined))
import '../../crm/customer/customer.scss'
import './cert-mobile.scss'
const route = useRoute()
const router = useRouter()
const user = useUserStore()
const ready = ref(false)
const session = ref(0)
const keyword = ref('')
const committed = ref('')
const tabs = ['archive', 'contract', 'usage', 'plan', 'ready'] as const
const tab = ref<(typeof tabs)[number]>(
tabs.includes(route.query.tab as (typeof tabs)[number])
? (route.query.tab as (typeof tabs)[number])
: 'archive'
)
const archiveKind = ref('')
const expiringSoon = ref(false)
const expiringCount = ref(0)
const usageKind = ref('')
const archiveStatus = ref('')
const planStatus = ref('')
const planScope = ref('')
const showAllPlans = computed(() => planScope.value === '1')
const readyState = ref('')
const readyStateOptions = [
{ text: '全部齐备状态', value: '' },
{ text: '未齐备', value: '0' },
{ text: '已齐备', value: '1' }
]
const planPlate = ref('')
const planDateFrom = ref('')
const planDateTo = ref('')
const planPlateDraft = ref('')
const planDateFromDraft = ref('')
const planDateToDraft = ref('')
const planFilter = ref<{ toggle: (show?: boolean) => void }>()
const planFilterTitle = computed(() =>
planPlate.value || planDateFrom.value || planDateTo.value ? '已筛选' : '车号 / 日期'
)
function syncPlanFilterDraft() {
planPlateDraft.value = planPlate.value
planDateFromDraft.value = planDateFrom.value
planDateToDraft.value = planDateTo.value
}
function clearPlanFilter() {
planPlateDraft.value = ''
planDateFromDraft.value = ''
planDateToDraft.value = ''
planPlate.value = ''
planDateFrom.value = ''
planDateTo.value = ''
planFilter.value?.toggle(false)
}
function applyPlanFilter() {
const from = planDateFromDraft.value
const to = planDateToDraft.value
if (from && to && from > to) {
ElMessage.warning('计划日期起始不能晚于结束')
return
}
planPlate.value = planPlateDraft.value.trim()
planDateFrom.value = from
planDateTo.value = to
planFilter.value?.toggle(false)
}
const planScopeOptions = [
{ text: '需单位换算', value: '' },
{ text: '查看全部', value: '1' }
]
const kindOptions = [
{ text: '全部证种', value: '' },
{ text: '购买证', value: 'purchase' },
{ text: '运输证', value: 'transport' }
]
const archiveStatusOptions = [
{ text: '全部状态', value: '' },
...Object.entries(certStatusLabels).map(([value, text]) => ({ text, value }))
]
const planStatusOptions = [
{ text: '全部状态', value: '' },
{ text: '无需两证', value: 'not_required' },
{ text: '待配置', value: 'needs_configuration' },
{ text: '待校验条件与余额', value: 'needs_validation' },
{ text: '已持有预占', value: 'reserved' },
{ text: '已核销', value: 'settled' },
{ text: '结转异常', value: 'exception' }
]
const placeholder = computed(() =>
tab.value === 'contract'
? '合同编号 / 名称'
: tab.value === 'plan' || tab.value === 'ready'
? '计划编号'
: '证件编号 / 品名'
)
function onTab(name: string | number) {
const next = String(name)
if (!tabs.includes(next as (typeof tabs)[number])) return
keyword.value = ''
committed.value = ''
void router.replace({ query: { ...route.query, tab: next } })
}
watch(
() => JSON.stringify([user.accessToken, user.getUserInfo]),
() => {
@@ -31,3 +223,17 @@
{ flush: 'sync' }
)
</script>
<style scoped>
.mp-plan-quota-filter {
padding: 8px 12px 12px;
background: #fff;
}
.mp-plan-quota-filter__actions {
display: flex;
gap: 8px;
margin-top: 12px;
}
.mp-plan-quota-filter__actions .mp-wv-btn {
flex: 1;
}
</style>
@@ -0,0 +1,167 @@
<template>
<MpWebviewShell @ready="ready = true">
<MpBusinessHeader title="证件用量" back-label="返回运输证件管理" @back="router.back()" />
<main v-if="ready" class="mp-h5-list-content mp-h5-detail-page mp-plan-cert-list">
<p v-if="error" class="mp-wv-empty" role="alert">
{{ error }}
<button class="mp-wv-btn" type="button" @click="load">重试</button>
</p>
<div v-else-if="loading" class="mp-cert-page-loading"><van-loading /></div>
<template v-else-if="detail">
<section class="mp-wv-section">
<h3>{{ detail.certType === 'transport' ? '运输证' : '购买证' }} {{ detail.certNo }}</h3>
<div class="detail-field-grid">
<div class="mp-wv-kv"><span>证面品名</span><span>{{ detail.productNameOnCert || '—' }}</span></div>
<div class="mp-wv-kv">
<span>状态</span>
<span class="status-tag" :class="`status-tag--${detail.status === 'active' ? 'success' : 'info'}`">
{{ certListStatus(detail.status) }}
</span>
</div>
<div class="mp-wv-kv"><span>单位</span><span>{{ unit(detail.quantityUnit) || '—' }}</span></div>
<div class="mp-wv-kv"><span>全证核定</span><span>{{ qty(detail.totalQty) }}</span></div>
<div class="mp-wv-kv"><span>全证预占</span><span>{{ qty(detail.reservedQty) }}</span></div>
<div class="mp-wv-kv"><span>全证已用</span><span>{{ qty(detail.usedQty) }}</span></div>
<div class="mp-wv-kv"><span>全证共享余额</span><span>{{ qty(detail.availableQty) }}</span></div>
<div class="mp-wv-kv"><span>有效期起</span><span>{{ detail.validFrom || '—' }}</span></div>
<div class="mp-wv-kv"><span>有效期止</span><span>{{ detail.validTo || '—' }}</span></div>
<div class="mp-wv-kv">
<span>期初已用(独立记录)</span><span>{{ qtyWithUnit(detail.openingUsedQty) }}</span>
</div>
<div class="mp-wv-kv">
<span>未归属合同已用</span><span>{{ qtyWithUnit(detail.unattributedUsedQty) }}</span>
</div>
</div>
</section>
<section class="mp-wv-section">
<h3>关联合同</h3>
<p v-if="!(detail.contracts || []).length" class="plan-empty-hint">暂无关联合同</p>
<article v-for="(row, index) in detail.contracts || []" :key="`${row.bindingId || row.id}:${index}`" class="mp-cert-block">
<div class="mp-wv-card__head">
<div>
<div class="mp-wv-card__no">{{ row.contractNo || '合同信息不可用' }}</div>
<div class="mp-wv-card__sub">{{ row.contractName || '未填写合同名称' }}</div>
</div>
<span class="status-tag" :class="`status-tag--${row.linkStatus === 'active' ? 'success' : 'info'}`">
{{ linkLabel(row.linkStatus) }}
</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>本合同预占</span><span>{{ qtyWithUnit(row.contractReservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>本合同已用</span><span>{{ qtyWithUnit(row.contractUsedQty) }}</span></div>
</div>
<p v-if="!(row.products || []).length" class="plan-empty-hint">暂无合同产品范围</p>
<article v-for="product in row.products || []" :key="product.id" class="mp-cert-product">
<strong>{{ product.productName || '—' }}</strong>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"><span>规格</span><span>{{ product.model || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>产品单位</span><span>{{ unit(product.unit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>额度单位</span><span>{{ unit(detail.quantityUnit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>预占</span><span>{{ qty(product.reservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>已用</span><span>{{ qty(product.usedQty) }}</span></div>
<div class="mp-wv-card__kv-row">
<span>范围状态</span>
<span class="status-tag" :class="`status-tag--${product.scopeStatus === 'active' ? 'success' : 'info'}`">
{{ scopeStatusLabel(product.scopeStatus) }}
</span>
</div>
</div>
</article>
</article>
</section>
<section class="mp-wv-section">
<h3>计划段产品用量追踪</h3>
<p v-if="!tracking.length" class="plan-empty-hint">暂无用证明细</p>
<article v-for="row in tracking" :key="row.id" class="mp-cert-block">
<div class="mp-wv-card__no">{{ row.planNo || '—' }}</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row">
<span>段次</span><span>{{ row.stopType === 'load' ? '装货' : '送货' }}</span>
</div>
<div class="mp-wv-card__kv-row"><span>产品</span><span>{{ row.productName || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>合同编号</span><span>{{ row.contractNo }}</span></div>
<div class="mp-wv-card__kv-row"><span>规格</span><span>{{ row.productModel }}</span></div>
<div class="mp-wv-card__kv-row"><span>装货 / 送货主体</span><span>{{ row.partyName }}</span></div>
<div class="mp-wv-card__kv-row"><span>装货 / 送货地址</span><span>{{ row.address }}</span></div>
<div class="mp-wv-card__kv-row"><span>单位</span><span>{{ unit(row.quantityUnit) || '—' }}</span></div>
<div class="mp-wv-card__kv-row"><span>预占</span><span>{{ qty(row.reservedQty) }}</span></div>
<div class="mp-wv-card__kv-row"><span>已用</span><span>{{ qty(row.usedQty) }}</span></div>
<div class="mp-wv-card__kv-row">
<span>状态</span>
<span class="status-tag status-tag--info">{{ certListStatus(row.itemStatus) }}</span>
</div>
</div>
</article>
</section>
</template>
</main>
</MpWebviewShell>
</template>
<script setup lang="ts">
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import { quotaStatisticsApi, type CertificateStatistics, type CertType } from '@/api/pl/quota-cert'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certListStatus, linkLabel, scopeStatusLabel, usageTrackingRows } from './usage-model'
import '../plan/plan-read-fields.scss'
import '@/styles/mp-webview.scss'
import './cert-mobile.scss'
const route = useRoute()
const router = useRouter()
const ready = ref(false)
const loading = ref(false)
const error = ref('')
const detail = ref<CertificateStatistics>()
const kind = computed(() => (route.params.kind === 'transport' ? 'transport' : 'purchase') as CertType)
const certId = computed(() => String(route.params.id || ''))
const tracking = computed(() => (detail.value ? usageTrackingRows(detail.value) : []))
function qty(value: unknown) {
return formatCertQty(value)
}
function unit(value?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, value)
return !label || label === '—' ? '' : label
}
function qtyWithUnit(value: unknown) {
const text = qty(value)
const name = unit(detail.value?.quantityUnit)
return name ? `${text} ${name}` : text
}
async function load() {
loading.value = true
error.value = ''
try {
detail.value = await quotaStatisticsApi.certificate(kind.value, certId.value)
} catch {
error.value = '证件用量加载失败,请重试'
} finally {
loading.value = false
}
}
watch(ready, (value) => value && void load())
</script>
<style scoped>
.mp-cert-block {
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid #eef4f1;
}
.mp-cert-product {
margin-top: 8px;
padding: 8px 0 0;
}
.mp-cert-product strong {
color: #1f2a26;
font-size: 14px;
}
.plan-empty-hint {
margin: 8px 0 0;
color: #6b7b74;
font-size: 13px;
line-height: 1.5;
}
</style>
@@ -0,0 +1,28 @@
import type { CertificateStatistics } from '@/api/pl/quota-cert'
import { statusLabel } from '@/views/pl/quota-statistics/labels'
export function certListStatus(value?: string | null) {
return statusLabel(value || '') || '—'
}
export function linkLabel(status?: string | null) {
return status === 'active' ? '可安排用证' : '停止新增使用'
}
export function scopeStatusLabel(status?: string | null) {
return status === 'active' ? '有效' : status === 'inactive' ? '停用' : '历史解绑'
}
export function usageTrackingRows(detail: CertificateStatistics) {
return (detail.usageItems || []).map((item) => {
const contract = (detail.contracts || []).find((row) => row.id === item.contractId)
const product = contract?.products?.find((row) => row.contractProductId === item.contractProductId)
return {
...item,
contractNo: contract?.contractNo || '—',
productModel: product?.model || '—',
partyName: item.partyName || '—',
address: item.address || '—'
}
})
}
@@ -50,8 +50,8 @@
<van-cell title="型号" :label="row.model || '—'" />
<van-cell
title="单位"
:label="c.resolveDictLabel('crm_product_unit', row.unit)"
:is-link="c.sharedEditable"
:label="c.unitFieldLabel(row)"
:is-link="c.sharedEditable && !c.unitLocked(row)"
@click="choose(row, 'unit')"
/>
<van-cell
@@ -233,6 +233,7 @@
}
function choose(row: any, name: string) {
if (!c.sharedEditable) return
if (name === 'unit' && c.unitLocked(row)) return
target = row
field = name
const dict: Record<string, string> = {
@@ -273,6 +274,7 @@
c.bindContractLine(target, option.id)
return
}
if (field === 'unit' && c.unitLocked(target)) return
if (field === 'brandId') c.handleBrandChange(target, option.id)
else {
target[field] = option.id
@@ -118,6 +118,7 @@
p {
font-size: 14px;
line-height: 1.6;
white-space: pre-wrap;
}
dl {
display: grid;
+57 -3
View File
@@ -249,9 +249,17 @@
<section id="plan-sec-cert" class="mp-wv-section mp-h5-anchor">
<h3>危化品证书信息</h3>
<p>购买证、运输证按合同产品与共享额度校验;合法使用证明可后补。</p>
<van-button block plain type="primary" @click="router.push(`/m/pl/plan-cert/${plan.id}`)">查看用证配置与占用</van-button>
<van-button block plain type="primary" @click="router.push('/m/pl/legal-use-document')">维护合法使用证明</van-button>
<div class="plan-cert-actions">
<van-button block plain type="primary" @click="quotaOpen = true">查看用证</van-button>
<van-button
v-if="needsLegalUseDocument"
block
plain
type="primary"
@click="router.push('/m/pl/legal-use-document')"
>维护合法使用证明</van-button
>
</div>
</section>
<section id="plan-sec-freight" class="mp-wv-section mp-h5-anchor">
@@ -300,6 +308,20 @@
</button>
</div>
<van-popup
v-model:show="quotaOpen"
position="bottom"
round
teleport="body"
class="mp-plan-quota-sheet"
safe-area-inset-bottom
>
<van-nav-bar :title="quotaTitle" left-text="关闭" @click-left="quotaOpen = false" />
<div class="mp-plan-quota-sheet__body mp-h5-detail-page">
<CertFacePanel v-if="quotaOpen" :plan-id="plan.id" />
</div>
</van-popup>
<van-popup
v-model:show="moreOpen"
position="bottom"
@@ -445,6 +467,8 @@
import { resolveMpProductUnitLabel } from '@/utils/mp-pl-plan-display'
import PlanStopReadCard from './PlanStopReadCard.vue'
import CertFacePanel from '../plan-cert/CertFacePanel.vue'
import { resolveProductHazardFlags } from '@/composables/usePlToxicProductCertCheck'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import { freightFields, loadMobileDetailReads } from './mobileDetailDisplay'
import { inventoryApi } from '@/api/db/inventory'
@@ -511,6 +535,11 @@
const acting = ref(false)
const errorText = ref('')
const plan = ref<Plan | null>(null)
const quotaOpen = ref(false)
const needsLegalUseDocument = computed(() =>
(plan.value?.products || []).some((row) => resolveProductHazardFlags(row).isExplosive)
)
const quotaTitle = computed(() => `计划用证 · ${plan.value?.planNo || ''}`)
const deliveryIndex = ref(0)
const moreOpen = ref(false)
const voidOpen = ref(false)
@@ -1483,6 +1512,31 @@
border-color: #dc2626 !important;
}
.plan-cert-actions {
display: flex;
flex-direction: column;
gap: 10px;
}
.mp-plan-quota-sheet {
display: flex;
flex-direction: column;
height: 92dvh;
max-height: 92dvh;
overflow: hidden;
background: #f5f8f7;
--van-primary-color: #0a9f6d;
--van-nav-bar-text-color: #0a9f6d;
--van-nav-bar-icon-color: #0a9f6d;
}
.mp-plan-quota-sheet__body {
min-height: 0;
flex: 1;
overflow: auto;
padding: 10px 12px 16px;
}
.plan-detail-sheet {
:deep(.van-nav-bar__left) {
min-width: 44px;
+259
View File
@@ -0,0 +1,259 @@
<template>
<div class="page-container">
<section class="panel">
<div class="panel-top"><h2 class="title-bar-heading">证书齐备</h2></div>
<div class="list-toolbar">
<div class="list-toolbar-row">
<ListQuickSearchInput
v-model="keyword"
placeholder="计划编号"
@search="search"
@clear="search"
/>
<el-button v-if="keyword || hasActiveFilters" @click="reset">
<el-icon><RefreshLeft /></el-icon>清除筛选
</el-button>
<el-button :loading="loading" @click="load">
<el-icon><Refresh /></el-icon>刷新
</el-button>
</div>
</div>
<div class="list-body list-wrap">
<div ref="tableWrapRef" class="table-scroll">
<ListTable
ref="tableRef"
v-loading="loading"
:height="tableHeight"
table-key="pl-cert-ready"
:data="rows"
row-key="id"
stripe
class="list-table"
>
<el-table-column
v-for="column in columns"
:key="column.prop"
:prop="column.prop"
:label="column.label"
:min-width="column.minWidth"
>
<template #header>
<div class="col-header-with-filter">
<span class="col-header-with-filter__label">{{ column.label }}</span>
<ColumnHeaderFilter
:prop="column.prop"
:label="column.label"
:type="column.type"
:enable-sort="false"
:options="column.enumOptions || []"
:model-value="filters[column.prop] || null"
:is-active="isFilterActive(column.prop)"
@update:model-value="(value) => setFilterState(column.prop, value)"
/>
</div>
</template>
<template #default="{ row }">
<el-tag
v-if="column.prop === 'followStatus'"
size="small"
:type="getPlPlanFollowStatusTagType(row.followStatus)"
>
{{ getPlPlanFollowStatusLabel(row.followStatus) }}
</el-tag>
<el-tag
v-else-if="column.prop === 'quotaCertWaived'"
size="small"
:type="row.quotaCertWaived ? 'success' : 'warning'"
>
{{ row.quotaCertWaived ? '已齐备' : '未齐备' }}
</el-tag>
<span v-else-if="column.prop === 'quotaCertWaivedTime'">{{
formatCertReadyTime(row.quotaCertWaivedTime)
}}</span>
<span v-else>{{ row[column.prop] || '—' }}</span>
</template>
</el-table-column>
<el-table-column label="操作" min-width="260" fixed="right">
<template #default="{ row }">
<el-button
v-if="!row.quotaCertWaived"
type="primary"
:loading="markingId === row.id"
@click="mark(row)"
>
<el-icon><CircleCheck /></el-icon>证书齐备
</el-button>
<span v-else>已确认</span>
</template>
</el-table-column>
</ListTable>
</div>
<div ref="pagerRef" class="pagination list-pager-bar">
<el-pagination
v-model:current-page="page"
:page-size="20"
:total="total"
layout="total, prev, pager, next"
@current-change="load"
/>
</div>
</div>
</section>
</div>
</template>
<script setup lang="ts">
import { certReadyApi, type CertReadyPlan } from '@/api/pl/quota-cert'
import ColumnHeaderFilter from '@/components/business/column-header-filter/index.vue'
import ListQuickSearchInput from '@/components/business/list-quick-search-input/index.vue'
import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight'
import { useServerColumnFilters } from '@/composables/useServerColumnFilters'
import type { ColumnFilterDef } from '@/composables/useClientColumnFilters'
import { certReadyErrorText, formatCertReadyTime } from '@/utils/pl-quota-cert-waiver'
import {
PL_PLAN_FOLLOW_STATUS_OPTIONS,
getPlPlanFollowStatusLabel,
getPlPlanFollowStatusTagType
} from '@/utils/pl-display'
import { CircleCheck, Refresh, RefreshLeft } from '@element-plus/icons-vue'
const keyword = ref('')
const page = ref(1)
const total = ref(0)
const loading = ref(false)
const markingId = ref('')
const rows = ref<CertReadyPlan[]>([])
let epoch = 0
const columns: (ColumnFilterDef & { minWidth: number })[] = [
{ prop: 'planNo', label: '计划编号', type: 'text', queryKey: 'planNo', minWidth: 160 },
{
prop: 'planDate',
label: '计划日期',
type: 'datetime',
queryKeyFrom: 'planDateFrom',
queryKeyTo: 'planDateTo',
minWidth: 140
},
{ prop: 'licensePlate', label: '车号', type: 'text', queryKey: 'licensePlate', minWidth: 120 },
{
prop: 'productNames',
label: '易制毒产品',
type: 'text',
queryKey: 'productNames',
minWidth: 180
},
{ prop: 'supplierName', label: '供方', type: 'text', queryKey: 'supplierName', minWidth: 160 },
{ prop: 'customerName', label: '需方', type: 'text', queryKey: 'customerName', minWidth: 160 },
{
prop: 'followStatus',
label: '跟进状态',
type: 'enum',
queryKey: 'followStatus',
enumOptions: PL_PLAN_FOLLOW_STATUS_OPTIONS.filter((item) => item.value !== 'cancelled').map(
(item) => ({ value: item.value, label: item.label })
),
minWidth: 120
},
{
prop: 'quotaCertWaived',
label: '证书齐备',
type: 'enum',
queryKey: 'quotaCertWaived',
enumOptions: [
{ value: '0', label: '未齐备' },
{ value: '1', label: '已齐备' }
],
minWidth: 120
},
{
prop: 'quotaCertWaivedByName',
label: '确认人',
type: 'text',
queryKey: 'quotaCertWaivedByName',
minWidth: 120
},
{
prop: 'quotaCertWaivedTime',
label: '确认时间',
type: 'datetime',
queryKeyFrom: 'quotaCertWaivedTimeFrom',
queryKeyTo: 'quotaCertWaivedTimeTo',
minWidth: 170
}
]
const {
filters,
hasActiveFilters,
setFilterState,
clearAllFilters,
isFilterActive,
toQueryParams
} = useServerColumnFilters(columns, { onChange: search })
async function load() {
const current = ++epoch
loading.value = true
try {
const value = await certReadyApi.list({
keyword: keyword.value || undefined,
page: page.value,
pageSize: 20,
...toQueryParams()
})
if (current !== epoch) return
rows.value = value?.list || []
total.value = value?.total || 0
} catch (error) {
if (current === epoch) ElMessage.error(certReadyErrorText(error, '证书齐备列表加载失败'))
} finally {
if (current === epoch) loading.value = false
}
}
function search() {
page.value = 1
void load()
}
function reset() {
keyword.value = ''
if (hasActiveFilters.value) clearAllFilters()
else search()
}
async function mark(row: CertReadyPlan) {
try {
await ElMessageBox.confirm(
'确认后,这条运输计划在安排和归档时都不再校验购买证、运输证,也不扣减额度。确认人和时间会记在本行。',
'证书齐备',
{ type: 'warning', confirmButtonText: '确认齐备', cancelButtonText: '取消' }
)
} catch {
return
}
markingId.value = row.id
try {
await certReadyApi.mark(row.id)
ElMessage.success('已标记证书齐备')
await load()
} catch (error) {
ElMessage.error(certReadyErrorText(error, '标记证书齐备失败'))
} finally {
markingId.value = ''
}
}
const tableWrapRef = ref<HTMLElement | null>(null)
const pagerRef = ref<HTMLElement | null>(null)
const tableRef = ref()
const { tableHeight } = useListTableViewportHeight({
tableEl: tableWrapRef,
pagerEl: pagerRef,
tableRef,
enabled: computed(() => true)
})
onMounted(() => {
void load()
})
</script>
@@ -2,24 +2,14 @@
<section :class="embedded ? 'dialog-list-panel' : 'panel'">
<div v-if="!embedded" class="panel-top"><h2 class="title-bar-heading">合法使用证明</h2></div>
<div class="list-toolbar"
><div class="list-toolbar-row">
><div class="list-toolbar-row contract-list-toolbar-row">
<ListQuickSearchInput
v-model="keyword"
placeholder="计划编号"
@search="search"
@clear="search"
/>
<el-select
v-model="status"
clearable
placeholder="上传情况"
aria-label="上传情况"
style="width: 150px"
@change="search"
>
<el-option label="待上传" value="pending" /><el-option label="已上传" value="uploaded" />
</el-select>
<el-button v-if="keyword || status || hasActiveFilters" @click="reset"
<el-button v-if="canResetFilters" @click="reset"
><el-icon><RefreshLeft /></el-icon>清除筛选</el-button
>
<ListToolbarEndActions
@@ -83,67 +73,58 @@
></el-table-column
>
<el-table-column prop="productName" label="产品" min-width="140" />
<el-table-column label="上传情况" min-width="110"
><template #default="{ row: item }"
><el-tag size="small" :type="statusType(item.documentStatus)">{{
statusLabel(item.documentStatus)
}}</el-tag></template
></el-table-column
>
<el-table-column label="附件" min-width="220"
><template #default="{ row: item }"
><AttachmentUploadField
:model-value="item.legalUseCertUrl || ''"
disabled
compact /></template
></el-table-column>
<el-table-column prop="contractNo" label="合同编号" min-width="170" />
<el-table-column prop="partyName" label="本段主体" min-width="180" />
<el-table-column prop="model" label="规格" min-width="100" />
<el-table-column prop="unit" label="单位" min-width="80" />
<el-table-column prop="address" label="本段位置" min-width="220" />
<el-table-column prop="uploadedTime" label="上传时间" min-width="170" />
<el-table-column v-if="canUpload" label="操作" min-width="260" fixed="right"
><template #default="{ row: item }"
><el-button @click="open(row, item)"
><el-icon><Document /></el-icon>维护本段资料</el-button
></template
></el-table-column
<el-table-column label="单位" min-width="80"
><template #default="{ row: item }">{{
unitText(item.unit)
}}</template></el-table-column
>
<el-table-column prop="address" label="本段位置" min-width="220" />
</el-table>
<section v-if="details[row.id].data!.legacyProducts.length" class="view-section">
<h3>历史计划级资料</h3
><p class="form-tip">历史附件仅供查看,不计入运输段上传情况。</p>
<div v-for="product in details[row.id].data!.legacyProducts" :key="product.id">
<p>{{ product.productName }} {{ product.model || '' }}</p>
<AttachmentUploadField
:model-value="product.legalUseCertUrl || ''"
disabled
/>
</div>
<section class="view-section">
<h3>合法使用证明</h3>
<AttachmentUploadField
:ref="(el) => setUpload(row.id, el)"
v-model="drafts[row.id]"
folder="pl/legal-use-document"
:disabled="!canUpload || !!saving[row.id]"
/>
<el-button
v-if="canUpload"
type="primary"
:loading="!!saving[row.id]"
:disabled="!!uploaders[row.id]?.hasUploading()"
@click="savePlan(row.id)"
><el-icon><Check /></el-icon>保存</el-button
>
</section>
</template>
</div> </template
></el-table-column>
</div>
</template></el-table-column
>
<el-table-column
v-for="column in visibleDefs"
:key="column.prop"
:prop="column.prop"
:label="column.label"
min-width="150"
:min-width="column.prop === 'legalUseCertUrl' ? 240 : 150"
>
<template #header
><div class="col-header-with-filter"
><span class="col-header-with-filter__label">{{ column.label }}</span
><ColumnHeaderFilter
v-if="column.prop === 'planNo'"
prop="planNo"
label="计划编号"
type="text"
<template #header>
<span v-if="column.prop === 'legalUseCertUrl'">{{ column.label }}</span>
<div v-else class="col-header-with-filter"
><span class="col-header-with-filter__label">{{ column.label }}</span>
<ColumnHeaderFilter
:prop="column.prop"
:label="column.label"
:type="column.type"
:enable-sort="false"
:model-value="filters.planNo || null"
:is-active="isFilterActive('planNo')"
@update:model-value="(value) => setFilterState('planNo', value)" /></div
:options="column.enumOptions || []"
:model-value="filters[column.prop] || null"
:is-active="isFilterActive(column.prop)"
@update:model-value="(value) => setFilterState(column.prop, value)"
/> </div
></template>
<template #default="{ row }">
<el-tag
@@ -155,6 +136,23 @@
<span v-else-if="column.prop === 'progress'"
>{{ row.uploadedCount }} / {{ row.requiredCount }}</span
>
<el-tag
v-else-if="column.prop === 'followStatus'"
size="small"
:type="followTag(row.followStatus)"
>{{ followLabel(row.followStatus) }}</el-tag
>
<div v-else-if="column.prop === 'legalUseCertUrl'" class="legal-cert-cell" @click.stop>
<span v-if="row.documentStatus === 'not_required'">—</span>
<AttachmentUploadField
v-else
compact
:model-value="drafts[row.id] ?? row.legalUseCertUrl ?? ''"
folder="pl/legal-use-document"
:disabled="!canUpload || !!saving[row.id]"
@update:model-value="(value) => onCertDraft(row, value)"
/>
</div>
<span v-else>{{ row[column.prop] || '—' }}</span>
</template>
</el-table-column>
@@ -167,60 +165,15 @@
layout="total, prev, pager, next"
@current-change="load" /></div
></div>
<el-dialog
v-model="visible"
title="本段产品合法使用证明"
width="720px"
align-center
append-to-body
class="dialog-form-layout"
:close-on-click-modal="false"
>
<div v-loading="editorLoading">
<el-alert v-if="editorError" :title="editorError" type="error" :closable="false" />
<template v-if="editing"
><p
>{{ editing.stopType === 'load' ? '装货' : '送货' }} {{ editing.stopOrder }} ·
{{ editing.productName }} {{ editing.model }}</p
><p
>{{ editing.contractNo || '未关联合同' }} · {{ editing.partyName }} ·
{{ editing.address }}</p
>
<el-form label-position="top"
><el-form-item label="合法使用证明"
><AttachmentUploadField
:key="editorEpoch"
ref="upload"
v-model="editing.legalUseCertUrl"
folder="pl/legal-use-document"
:disabled="!canUpload || saving" /></el-form-item
></el-form>
</template>
</div>
<template #footer
><el-button @click="visible = false"
><el-icon><Close /></el-icon>关闭</el-button
><el-button
v-if="canUpload"
type="primary"
:loading="saving"
:disabled="editorLoading || !editing || !!upload?.hasUploading()"
@click="save"
><el-icon><Check /></el-icon>保存本段资料</el-button
></template
>
</el-dialog>
</section>
</template>
<script setup lang="ts">
import { Check, Close, Document, Refresh, RefreshLeft } from '@element-plus/icons-vue'
import { Check, Refresh, RefreshLeft } from '@element-plus/icons-vue'
import { fetchGetMenuCodes } from '@/api/auth'
import { useUserStore } from '@/store/modules/user'
import {
legalDocumentApi,
type StopLegalDocument,
type StopLegalDocumentItem
} from '@/api/pl/quota-cert'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { legalDocumentApi, type StopLegalDocument } from '@/api/pl/quota-cert'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import { useServerColumnFilters } from '@/composables/useServerColumnFilters'
import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight'
@@ -228,6 +181,11 @@
import ListQuickSearchInput from '@/components/business/list-quick-search-input/index.vue'
import ListToolbarEndActions from '@/components/business/list-toolbar-end-actions/index.vue'
import ColumnHeaderFilter from '@/components/business/column-header-filter/index.vue'
import {
PL_PLAN_FOLLOW_STATUS_OPTIONS,
getPlPlanFollowStatusLabel,
getPlPlanFollowStatusTagType
} from '@/utils/pl-display'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
const props = withDefaults(
defineProps<{ contractId?: string; embedded?: boolean; active?: boolean }>(),
@@ -239,72 +197,116 @@
loading = ref(false),
error = ref(''),
keyword = ref(''),
status = ref<'' | 'pending' | 'uploaded'>(''),
page = ref(1),
total = ref(0)
const rows = ref<StopLegalDocument[]>([])
const details = reactive<
Record<string, { loading: boolean; error: boolean; data?: StopLegalDocument }>
>({})
const visible = ref(false),
saving = ref(false),
editorLoading = ref(false),
editorError = ref(''),
editorEpoch = ref(0)
const editing = ref<StopLegalDocumentItem>(),
editingPlanId = ref('')
const upload = ref<InstanceType<typeof AttachmentUploadField>>()
const drafts = reactive<Record<string, string>>({})
const saving = reactive<Record<string, boolean>>({})
const uploaders = reactive<Record<string, { hasUploading?: () => boolean } | undefined>>({})
let authEpoch = 0,
listEpoch = 0
listEpoch = 0,
saveSerial = 0
const saveToken: Record<string, number> = {}
const uploadStatusOptions = [
{ value: 'pending', label: '待上传' },
{ value: 'uploaded', label: '已上传' }
]
const columns: ColumnFilterDef[] = [
['planNo', '计划编号'],
['planDate', '计划日期'],
['licensePlate', '车牌号'],
['progress', '已上传 / 应上传'],
['documentStatus', '上传情况']
].map(([prop, label]) => ({ prop, label, type: 'text', queryKey: prop }))
{ prop: 'planNo', label: '计划编号', type: 'text', queryKey: 'planNo' },
{
prop: 'planDate',
label: '计划日期',
type: 'datetime',
queryKeyFrom: 'planDateFrom',
queryKeyTo: 'planDateTo'
},
{ prop: 'licensePlate', label: '车牌号', type: 'text', queryKey: 'licensePlate' },
{ prop: 'productNames', label: '易制爆产品', type: 'text', queryKey: 'productNames' },
{ prop: 'supplierName', label: '供方', type: 'text', queryKey: 'supplierName' },
{ prop: 'customerName', label: '需方', type: 'text', queryKey: 'customerName' },
{
prop: 'followStatus',
label: '跟进状态',
type: 'enum',
queryKey: 'followStatus',
enumOptions: PL_PLAN_FOLLOW_STATUS_OPTIONS.filter((item) => item.value !== 'cancelled').map(
(item) => ({ value: item.value, label: item.label })
)
},
{ prop: 'progress', label: '已上传 / 应上传', type: 'text', queryKey: 'progress' },
{
prop: 'documentStatus',
label: '上传情况',
type: 'enum',
enumOptions: uploadStatusOptions
},
{ prop: 'legalUseCertUrl', label: '合法使用证明', type: 'text' }
]
const filterColumns = columns.filter((column) => column.prop !== 'legalUseCertUrl')
const { visibleColumns, checkAll, isIndeterminate, resetToDefault } = usePersistedListColumns(
'pl-stop-documents-v1',
'pl-stop-documents-v3',
columns
)
const visibleDefs = computed(() => columns.filter((c) => visibleColumns.value.includes(c.prop)))
const visibleDefs = computed(() =>
columns.filter((column) => visibleColumns.value.includes(column.prop))
)
const {
filters,
hasActiveFilters,
setFilterState,
clearAllFilters,
isFilterActive,
toQueryParams,
resetToInitial,
watchVisibleColumns
} = useServerColumnFilters(
columns.filter((c) => c.prop === 'planNo'),
{ onChange: search }
} = useServerColumnFilters(filterColumns, {
initialFilters: { documentStatus: { text: '', selected: ['pending'] } },
onChange: search
})
const selectedUploadStatuses = () => {
const selected = (filters.documentStatus as { selected?: string[] } | undefined)?.selected || []
return selected.filter((value) => value === 'pending' || value === 'uploaded')
}
const status = computed(() => {
const selected = selectedUploadStatuses()
return selected.length === 1 ? selected[0] : ''
})
const canResetFilters = computed(
() =>
!!keyword.value ||
['planNo', 'planDate', 'licensePlate', 'productNames', 'supplierName', 'customerName', 'followStatus', 'progress'].some(
(prop) => isFilterActive(prop)
) ||
status.value !== 'pending'
)
watchVisibleColumns(visibleColumns)
function followLabel(status?: string) {
return getPlPlanFollowStatusLabel(status) || '—'
}
function followTag(status?: string) {
return getPlPlanFollowStatusTagType(status) || 'info'
}
const statusLabel = (value: string) =>
value === 'uploaded' ? '已上传' : value === 'not_required' ? '无需上传' : '待上传'
const statusType = (value: string) =>
value === 'uploaded' ? 'success' : value === 'not_required' ? 'info' : 'warning'
const itemKey = (item: StopLegalDocumentItem) => `${item.stopType}:${item.stopProductId}`
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '—' : label
}
const itemKey = (item: { stopType: string; stopProductId: string }) =>
`${item.stopType}:${item.stopProductId}`
function setUpload(id: string, el: unknown) {
if (el) uploaders[id] = el as { hasUploading?: () => boolean }
else delete uploaders[id]
}
function clearDetails() {
Object.keys(details).forEach((key) => delete details[key])
Object.keys(drafts).forEach((key) => delete drafts[key])
Object.keys(saving).forEach((key) => delete saving[key])
Object.keys(uploaders).forEach((key) => delete uploaders[key])
}
function closeEditor() {
editorEpoch.value++
editing.value = undefined
editingPlanId.value = ''
upload.value = undefined
saving.value = false
editorLoading.value = false
editorError.value = ''
}
watch(
visible,
(value) => {
if (!value) closeEditor()
},
{ flush: 'sync' }
)
async function load() {
if (!allowed.value || !props.active) return
const current = ++listEpoch
@@ -313,11 +315,13 @@
loading.value = true
error.value = ''
try {
const columnQuery = toQueryParams()
delete columnQuery.documentStatusIn
const data = await legalDocumentApi.listStops({
page: page.value,
pageSize: 20,
keyword: keyword.value,
...toQueryParams(),
...columnQuery,
status: status.value || undefined,
contractId: props.contractId
})
@@ -341,81 +345,95 @@
details[row.id] = state
try {
const result = await legalDocumentApi.getStops(row.id, props.contractId)
if (current === listEpoch && details[row.id] === state) state.data = result
if (current === listEpoch && details[row.id] === state) {
if (!saving[row.id]) drafts[row.id] = result.legalUseCertUrl || ''
state.data = result
}
} catch {
if (current === listEpoch && details[row.id] === state) state.error = true
} finally {
if (current === listEpoch && details[row.id] === state) state.loading = false
}
}
function onCertDraft(row: StopLegalDocument, value: string) {
const previous = drafts[row.id] ?? row.legalUseCertUrl ?? ''
if (value === previous || !canUpload.value || saving[row.id] || !props.active) return
drafts[row.id] = value
void saveCert(row, value)
}
async function saveCert(row: StopLegalDocument, url: string) {
if (!allowed.value || !canUpload.value || saving[row.id] || !props.active) return
let ids = row.planProductIds || details[row.id]?.data?.planProductIds || []
if (!ids.length) {
try {
const result = await legalDocumentApi.getStops(row.id, props.contractId)
ids = result.planProductIds || []
if (!details[row.id]) {
details[row.id] = { loading: false, error: false, data: result }
}
} catch {
ElMessage.error('证明保存失败,请重试')
return
}
}
if (!ids.length) {
ElMessage.warning('当前计划没有需要维护的易制爆产品')
return
}
const token = ++saveSerial
saveToken[row.id] = token
const current = listEpoch
saving[row.id] = true
try {
await legalDocumentApi.save(
row.id,
ids.map((productId) => ({ id: productId, legalUseCertUrl: url }))
)
if (token !== saveToken[row.id] || current !== listEpoch || (drafts[row.id] || '') !== url) return
ElMessage.success('合法使用证明已保存')
void load()
} catch {
if (token === saveToken[row.id] && current === listEpoch) {
ElMessage.error('保存失败,已保留填写内容,请重试')
}
} finally {
if (token === saveToken[row.id]) saving[row.id] = false
}
}
function expand(row: StopLegalDocument, expanded: StopLegalDocument[]) {
if (expanded.some((r) => r.id === row.id) && !details[row.id]) void loadDetail(row)
}
async function open(
row: Pick<StopLegalDocument, 'id'>,
item: Pick<StopLegalDocumentItem, 'stopType' | 'stopProductId'>
) {
if (!allowed.value || !canUpload.value || !props.active) return
closeEditor()
visible.value = true
editorLoading.value = true
const current = editorEpoch.value
try {
const result = await legalDocumentApi.getStops(row.id, props.contractId)
if (current !== editorEpoch.value) return
const match = result.items.find(
(candidate) => itemKey(candidate) === itemKey(item as StopLegalDocumentItem)
)
if (!match) {
editorError.value = '本段产品已变更,请刷新列表'
return
}
editing.value = { ...match, legalUseCertUrl: match.legalUseCertUrl || '' }
editingPlanId.value = row.id
} catch {
if (current === editorEpoch.value) editorError.value = '资料加载失败,请关闭后重试'
} finally {
if (current === editorEpoch.value) editorLoading.value = false
}
}
async function save() {
if (
!visible.value ||
!editing.value ||
!allowed.value ||
!canUpload.value ||
saving.value ||
editorLoading.value
)
return
if (upload.value?.hasUploading()) {
async function savePlan(id: string) {
const data = details[id]?.data
if (!data || !allowed.value || !canUpload.value || saving[id] || !props.active) return
if (uploaders[id]?.hasUploading?.()) {
ElMessage.warning('请等待附件上传完成')
return
}
const current = editorEpoch.value,
item = editing.value
saving.value = true
editorError.value = ''
const ids = data.planProductIds || []
if (!ids.length) {
ElMessage.warning('当前计划没有需要维护的易制爆产品')
return
}
const token = ++saveSerial
saveToken[id] = token
const current = listEpoch
const url = drafts[id] || ''
saving[id] = true
try {
await legalDocumentApi.saveStops(
editingPlanId.value,
[
{
stopType: item.stopType,
stopProductId: item.stopProductId,
legalUseCertUrl: item.legalUseCertUrl
}
],
props.contractId
await legalDocumentApi.save(
id,
ids.map((productId) => ({ id: productId, legalUseCertUrl: url }))
)
if (current !== editorEpoch.value) return
ElMessage.success('本段资料已保存')
visible.value = false
if (token !== saveToken[id] || current !== listEpoch || (drafts[id] || '') !== url) return
ElMessage.success('合法使用证明已保存')
void load()
} catch {
if (current === editorEpoch.value) editorError.value = '保存失败,已保留填写内容,请重试'
if (token === saveToken[id] && current === listEpoch) {
ElMessage.error('保存失败,已保留填写内容,请重试')
}
} finally {
if (current === editorEpoch.value) saving.value = false
if (token === saveToken[id]) saving[id] = false
}
}
function search() {
@@ -424,9 +442,7 @@
}
function reset() {
keyword.value = ''
status.value = ''
clearAllFilters()
search()
resetToInitial()
}
async function init() {
const current = ++authEpoch
@@ -435,8 +451,6 @@
total.value = 0
page.value = 1
clearDetails()
visible.value = false
closeEditor()
allowed.value = false
canUpload.value = false
loading.value = false
@@ -467,7 +481,6 @@
onBeforeUnmount(() => {
authEpoch++
listEpoch++
closeEditor()
allowed.value = false
canUpload.value = false
rows.value = []
@@ -484,14 +497,39 @@
tableEl: tableWrapRef,
pagerEl: pagerRef,
tableRef,
enabled: computed(() => !props.embedded)
enabled: computed(() => (props.embedded ? !!props.active : true))
})
</script>
<style scoped>
.contract-list-toolbar-row {
flex-wrap: nowrap;
overflow: hidden;
min-width: 0;
> .el-button,
> .list-toolbar-end,
> .quick-search-input {
flex-shrink: 0;
}
> .quick-search-input {
width: 280px;
max-width: 280px;
flex: 0 0 280px;
}
}
.documents-expansion {
box-sizing: border-box;
max-width: 100%;
padding: 16px;
text-align: left;
}
.documents-expansion .el-button {
margin-top: 12px;
}
.legal-cert-cell {
min-width: 0;
}
</style>
+136 -23
View File
@@ -24,7 +24,9 @@
v-model="keyword"
placeholder="计划编号"
@search="search"
@clear="search" /><el-button v-if="hasActiveFilters || keyword" @click="reset"
@clear="search" /><label class="quota-all-switch" @click.prevent="showAll = !showAll"
><el-switch :model-value="showAll" /><span>查看全部</span></label
><el-button v-if="hasActiveFilters || keyword" @click="reset"
><el-icon><RefreshLeft /></el-icon>清除筛选</el-button
><ListToolbarEndActions
:loading="loading"
@@ -35,13 +37,17 @@
@refresh="load"
@reset-columns="resetToDefault" /></div
></div>
<p v-if="mobile" class="form-tip"
>按当前来源、合同产品范围和证件余额校验;实际安排时原子预占。</p
>
<div v-if="mobile" v-loading="loading"
><section v-for="row in rows" :key="row.id" class="mp-wv-section"
><section
v-for="row in rows"
:key="row.id"
class="mp-wv-section"
:class="{ 'quota-conversion-card': row.needsUnitConversion }"
><h3>{{ row.planNo }}</h3
><p>{{ row.licensePlate || '未安排车辆' }} · {{ row.planDate || '未定日期' }}</p
><p>易制毒产品:{{ row.productNames || '—' }}</p
><p>供方:{{ row.supplierName || '—' }} · 需方:{{ row.customerName || '—' }}</p
><p>跟进状态:{{ followLabel(row.followStatus) }}</p
><el-tag
:type="
row.quotaStatus === 'exception'
@@ -51,8 +57,9 @@
: 'info'
"
>{{ stateLabels[row.quotaStatus] }}</el-tag
><span v-if="row.needsUnitConversion" class="quota-conversion-mark">需单位换算</span
><el-button @click="open(row.id)"
><el-icon><Document /></el-icon>用证配置与占用</el-button
><el-icon><Document /></el-icon>查看用证</el-button
></section
></div
>
@@ -64,7 +71,9 @@
table-key="pl-plan-quota"
v-loading="loading"
:data="rows"
:empty-text="showAll ? '暂无数据' : '暂无需要单位换算的计划'"
row-key="id"
:row-class-name="conversionRowClass"
:expand-row-keys="expandedIds"
@expand-change="expand"
stripe
@@ -93,20 +102,39 @@
perStop(details[row.id].data) ? '各装送段分别计量' : '原口径:单侧计量'
}}</el-tag
>
<p class="form-tip"
>绑定不代表校验通过;购买证与运输证分别显示各自证面单位的预占和已用量。</p
>
<el-table :data="stopUsageRows(details[row.id].data!)" stripe>
<el-table-column prop="label" label="段产品" min-width="210" />
<el-table-column label="合同" min-width="150"
<el-table :data="stopUsageRows(details[row.id].data!, unitText)" stripe>
<el-table-column label="运输段" min-width="110"
><template #default="{ row: item }"
><el-tag size="small"
>{{ item.sourceStopType === 'load' ? '装货' : '送货' }}
{{ item.stopOrder || 1 }}</el-tag
></template
></el-table-column
>
<el-table-column prop="productNo" label="产品编号" min-width="140"
><template #default="{ row: item }">{{
item.productNo || '—'
}}</template></el-table-column
>
<el-table-column prop="productName" label="产品" min-width="180" />
<el-table-column prop="model" label="规格" min-width="120"
><template #default="{ row: item }">{{
item.model || '—'
}}</template></el-table-column
>
<el-table-column label="合同" min-width="170"
><template #default="{ row: item }">{{
item.contractNo || (item.contractId ? '不可读取' : '未关联')
}}</template></el-table-column
>
<el-table-column prop="partyName" label="单位" min-width="160" />
<el-table-column label="需用量" min-width="110"
<el-table-column prop="partyName" label="本段主体" min-width="180"
><template #default="{ row: item }">{{
item.partyName || '—'
}}</template></el-table-column
>
<el-table-column label="需用量" min-width="130"
><template #default="{ row: item }"
>{{ item.quantity }} {{ item.unit }}</template
>{{ formatCertQty(item.quantity) }} {{ unitText(item.unit) }}</template
></el-table-column
>
<el-table-column
@@ -156,12 +184,18 @@
: 'info'
"
>{{ stateLabels[row.quotaStatus] }}</el-tag
><el-tag
v-else-if="column.prop === 'followStatus'"
size="small"
:type="followTag(row.followStatus)"
>{{ followLabel(row.followStatus) }}</el-tag
><span v-else>{{ row[column.prop] || '—' }}</span></template
></el-table-column
><el-table-column label="操作" min-width="260" fixed="right"
><el-table-column label="操作" min-width="360" fixed="right"
><template #default="{ row }"
><span v-if="row.needsUnitConversion" class="quota-conversion-mark">需单位换算</span
><el-button @click="open(row.id)"
><el-icon><Document /></el-icon>用证配置与占用</el-button
><el-icon><Document /></el-icon>查看用证</el-button
></template
></el-table-column
></ListTable
@@ -199,7 +233,15 @@
import { type ColumnFilterDef } from '@/composables/useClientColumnFilters'
import { useUserStore } from '@/store/modules/user'
import { formatCertQty } from '@/views/pl/quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { Document, Search, RefreshLeft } from '@element-plus/icons-vue'
import {
PL_PLAN_FOLLOW_STATUS_OPTIONS,
getPlPlanFollowStatusLabel,
getPlPlanFollowStatusTagType
} from '@/utils/pl-display'
import { type Plan } from '@/api/pl'
import request from '@/utils/http/bx'
const stateLabels: Record<string, string> = {
@@ -210,15 +252,38 @@
settled: '已核销',
exception: '结转异常'
}
function followLabel(status?: string) {
return getPlPlanFollowStatusLabel(status) || '—'
}
function followTag(status?: string) {
return getPlPlanFollowStatusTagType(status) || 'info'
}
function conversionRowClass({ row }: { row: { needsUnitConversion?: boolean } }) {
return row.needsUnitConversion ? 'quota-conversion-row' : ''
}
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
const status = ref('')
import { pickBxData } from '@/utils/http/bx'
import PlPlanQuotaDialog from '@/components/business/pl-plan-quota-dialog/index.vue'
const props = defineProps<{ mobile?: boolean; planId?: string }>()
const showAll = ref(false)
const keyword = ref(''),
page = ref(1),
total = ref(0),
loading = ref(false),
rows = ref<(Plan & { quotaStatus: string })[]>([])
rows = ref<
(Plan & {
quotaStatus: string
productNames?: string
supplierName?: string
customerName?: string
followStatus?: string
needsUnitConversion?: boolean
})[]
>([])
const dialog = ref<InstanceType<typeof PlPlanQuotaDialog>>()
const expandedIds = ref<string[]>([])
const details = reactive<Record<string, { loading: boolean; data?: PlanQuota; error?: string }>>(
@@ -266,7 +331,8 @@
page: page.value,
pageSize: 20,
keyword: keyword.value,
status: status.value || undefined
status: status.value || undefined,
conversionOnly: showAll.value ? undefined : true
}
})
)
@@ -308,9 +374,27 @@
epoch++
})
const listColumnDefs: ColumnFilterDef[] = [
{ prop: 'planNo', label: '计划编号', type: 'text' },
{ prop: 'planDate', label: '计划日期', type: 'datetime' },
{ prop: 'licensePlate', label: '车号', type: 'text' },
{ prop: 'planNo', label: '计划编号', type: 'text', queryKey: 'planNo' },
{
prop: 'planDate',
label: '计划日期',
type: 'datetime',
queryKeyFrom: 'planDateFrom',
queryKeyTo: 'planDateTo'
},
{ prop: 'licensePlate', label: '车号', type: 'text', queryKey: 'licensePlate' },
{ prop: 'productNames', label: '易制毒产品', type: 'text', queryKey: 'productNames' },
{ prop: 'supplierName', label: '供方', type: 'text', queryKey: 'supplierName' },
{ prop: 'customerName', label: '需方', type: 'text', queryKey: 'customerName' },
{
prop: 'followStatus',
label: '跟进状态',
type: 'enum',
queryKey: 'followStatus',
enumOptions: PL_PLAN_FOLLOW_STATUS_OPTIONS.filter((item) => item.value !== 'cancelled').map(
(item) => ({ value: item.value, label: item.label })
)
},
{
prop: 'quotaStatus',
label: '用证校验',
@@ -319,7 +403,7 @@
}
]
const { visibleColumns, checkAll, isIndeterminate, resetToDefault } = usePersistedListColumns(
'pl-plan-quota-columns-v1',
'pl-plan-quota-columns-v2',
listColumnDefs
)
const visibleDefs = computed(() =>
@@ -339,6 +423,7 @@
page.value = 1
void load()
}
watch(showAll, () => search())
function reset() {
keyword.value = ''
status.value = ''
@@ -361,6 +446,34 @@
</script>
<style scoped>
.quota-all-switch {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--el-text-color-regular);
font-size: 13px;
white-space: nowrap;
cursor: pointer;
}
.quota-all-switch :deep(.el-switch) {
pointer-events: none;
}
.quota-conversion-mark {
margin-right: 8px;
color: #dc2626;
font-weight: 600;
}
.quota-conversion-card :deep(h3),
.quota-conversion-card :deep(p) {
color: #dc2626;
}
:deep(.quota-conversion-row) {
color: #dc2626;
}
:deep(.quota-conversion-row .cell),
:deep(.quota-conversion-row .el-link) {
color: #dc2626;
}
.quota-expansion {
box-sizing: border-box;
max-width: 100%;
+15
View File
@@ -918,6 +918,9 @@
<el-button class="btn-ghost" @click="handleCopy(viewingPlan)">
<el-icon><CopyDocument /></el-icon>复制
</el-button>
<el-button class="btn-ghost" @click="openPlanQuota(viewingPlan)">
<el-icon><Document /></el-icon>查看用证
</el-button>
<el-button
v-if="showArrangeTransport(viewingPlan)"
class="btn-ghost"
@@ -976,6 +979,8 @@
</template>
</PlPlanViewDialog>
<PlPlanQuotaDialog ref="planQuotaDialogRef" />
<ContractDetailDialog ref="contractDetailRef" :hide-product-price="hideProductPrice" />
<DbPoundSlipQrcodeDialog
@@ -1070,6 +1075,7 @@
CircleClose,
Close,
CopyDocument,
Document,
DocumentCopy,
Download,
Edit,
@@ -1128,6 +1134,9 @@
const PlPlanViewDialog = defineAsyncComponent(
() => import('@/components/business/pl-plan-view-dialog/index.vue')
)
const PlPlanQuotaDialog = defineAsyncComponent(
() => import('@/components/business/pl-plan-quota-dialog/index.vue')
)
import PlPlanTypeTabs from '@/components/business/pl-plan-type-tabs/index.vue'
import ListToolbarDateShortcuts from '@/components/core/list-toolbar-date-shortcuts/index.vue'
import { useDbInstantSearch } from '@/composables/useDbInstantSearch'
@@ -1234,6 +1243,12 @@ import { useColumnFacetOptions } from '@/composables/useColumnFacetOptions'
const viewVisible = ref(false)
const viewPlanId = ref('')
const viewDialogRef = ref<InstanceType<typeof PlPlanViewDialog>>()
const planQuotaDialogRef = ref<InstanceType<typeof PlPlanQuotaDialog>>()
function openPlanQuota(plan: Plan) {
if (!plan.id) return
void planQuotaDialogRef.value?.open(plan.id)
}
const inboundSlipPrintRef = ref<InstanceType<typeof PlInboundSlipPrintDialog>>()
const deliverySlipPrintRef = ref<InstanceType<typeof PlDeliverySlipPrintDialog>>()
const subpackSlipPrintRef = ref<InstanceType<typeof PlSubpackSlipPrintDialog>>()
@@ -0,0 +1,706 @@
<template>
<div class="cert-contract-binder">
<el-form v-if="mode === 'create'" label-position="top" class="form-grid-2">
<el-form-item label="客户">
<div class="customer-select-row">
<el-select
:model-value="customerId"
class="customer-select-row__select"
filterable
remote
clearable
:remote-method="searchCustomers"
:loading="customerLoading"
:disabled="saving"
placeholder="客户名称/拼音首字母"
@focus="handleCustomerFocus"
@update:model-value="changeCustomer"
>
<el-option
v-for="item in customerOptions"
:key="item.id"
:label="item.customerName"
:value="item.id"
>
<div class="customer-option-row">
<span>{{ item.customerName }}</span>
<span v-if="item.customerNo" class="customer-option-row__meta">{{
item.customerNo
}}</span>
</div>
</el-option>
</el-select>
<el-button
text
class="customer-select-row__search"
:disabled="saving"
@click="customerVisible = true"
>
<el-icon><Search /></el-icon>
</el-button>
</div>
</el-form-item>
<el-form-item label="合同">
<div class="cert-contract-trigger">
<el-button
class="btn-ghost"
:disabled="!customerId || saving"
@click="contractVisible = true"
>
<el-icon><Search /></el-icon>选择合同
</el-button>
<span
class="cert-contract-trigger__hint"
:class="{ 'is-warn': !customerId || !contractId }"
>
{{ contractHint }}
</span>
</div>
</el-form-item>
</el-form>
<div class="cert-contract-products-head">
<span>适用产品</span>
<span v-if="editable && !availabilityOnly" @click="openProductPicker">
<el-button class="btn-main" type="primary" size="small" :disabled="!contractId || saving">
<el-icon><Plus /></el-icon>选择产品
</el-button>
</span>
</div>
<el-table
v-loading="linesLoading"
:data="selectedRows"
class="list-table"
stripe
row-key="id"
empty-text="还没有适用产品"
>
<el-table-column v-if="showDraftDelete" label="删除" width="112" align="center">
<template #default="{ row }">
<el-button
v-if="!row.saved"
link
type="danger"
title="删除产品"
aria-label="删除产品"
:disabled="saving"
@click="removeProduct(row.id)"
>
<el-icon><Delete /></el-icon>删除
</el-button>
</template>
</el-table-column>
<el-table-column label="产品编号" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.productNo || '—' }}</template>
</el-table-column>
<el-table-column label="产品名称" min-width="140" show-overflow-tooltip>
<template #default="{ row }">{{ row.productName || '—' }}</template>
</el-table-column>
<el-table-column label="品牌" min-width="90" align="center" show-overflow-tooltip>
<template #default="{ row }">{{ row.brand }}</template>
</el-table-column>
<el-table-column label="别名" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ row.aliasName || '—' }}</template>
</el-table-column>
<el-table-column label="规格型号" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.model || '—' }}</template>
</el-table-column>
<el-table-column label="计量单位" min-width="80" align="center">
<template #default="{ row }">
<DictTag v-if="row.unit" dict-type="crm_product_unit" :value="row.unit" />
<span v-else>—</span>
</template>
</el-table-column>
<el-table-column label="包装规格" min-width="140" show-overflow-tooltip>
<template #default="{ row }">{{ row.packageText }}</template>
</el-table-column>
<el-table-column label="合同数量" min-width="96" align="right" show-overflow-tooltip>
<template #default="{ row }">{{ row.quantityText }}</template>
</el-table-column>
<el-table-column label="剩余数量" min-width="96" align="right">
<template #default="{ row }">{{ row.remainingText }}</template>
</el-table-column>
<el-table-column label="状态" width="88" align="center">
<template #default="{ row }">
<el-tag size="small" :type="row.scopeStatus === 'inactive' ? 'info' : 'success'">
{{ row.scopeStatus === 'inactive' ? '不可用' : '可用' }}
</el-tag>
</template>
</el-table-column>
<el-table-column v-if="showSavedActions" label="操作" width="156" align="center">
<template #default="{ row }">
<el-button
v-if="row.saved"
link
:disabled="saving || (row.scopeStatus === 'inactive' && !allowRestore)"
@click="toggleProduct(row.id)"
>
<el-icon
><component :is="row.scopeStatus === 'inactive' ? RefreshRight : CircleClose"
/></el-icon>
{{ row.scopeStatus === 'inactive' ? '恢复可用' : '设为不可用' }}
</el-button>
</template>
</el-table-column>
</el-table>
<div v-if="editable && !hideSave" class="cert-contract-binder__save">
<el-button type="primary" :loading="saving" :disabled="!canSave" @click="submit">
<el-icon><Check /></el-icon>{{ saveText || (mode === 'create' ? '保存关联' : '保存产品') }}
</el-button>
</div>
<CustomerSelector
v-if="mode === 'create'"
v-model:visible="customerVisible"
@confirm="confirmCustomer"
/>
<ContractSelector
v-if="mode === 'create'"
v-model:visible="contractVisible"
:customer-id="customerId"
:selectable-statuses="['approved', 'executing']"
hide-amount
@confirm="confirmContract"
/>
<el-dialog
v-model="pickerVisible"
title="选择合同产品行"
width="min(1760px, calc(100vw - 24px))"
align-center
append-to-body
destroy-on-close
class="dialog-form-layout quota-cert-line-picker-dialog"
modal-class="order-module-dialog-mask"
>
<el-table
v-loading="linesLoading"
:data="contractLines"
class="list-table"
max-height="420"
row-key="id"
@selection-change="pickerSelected = $event"
>
<el-table-column type="selection" width="48" />
<el-table-column label="合同编号" min-width="160" show-overflow-tooltip>
<template #default="{ row }">{{ row.contractNo || contractNo || '—' }}</template>
</el-table-column>
<el-table-column label="产品编号" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.productNo || '—' }}</template>
</el-table-column>
<el-table-column label="产品名称" min-width="120" show-overflow-tooltip>
<template #default="{ row }">{{
row.standardProductName || row.productName || '—'
}}</template>
</el-table-column>
<el-table-column label="品牌" min-width="90" align="center" show-overflow-tooltip>
<template #default="{ row }">{{
formatBrandConstraintLabel(row.brandMode, row.brandName)
}}</template>
</el-table-column>
<el-table-column label="别名" min-width="90" show-overflow-tooltip>
<template #default="{ row }">{{ row.aliasName || '—' }}</template>
</el-table-column>
<el-table-column label="规格型号" min-width="100" show-overflow-tooltip>
<template #default="{ row }">{{ row.model || row.productModel || '—' }}</template>
</el-table-column>
<el-table-column label="计量单位" min-width="80" align="center">
<template #default="{ row }">
<DictTag v-if="row.unit" dict-type="crm_product_unit" :value="row.unit" />
<span v-else>—</span>
</template>
</el-table-column>
<el-table-column label="包装规格" min-width="140">
<template #default="{ row }">{{ packageText(row) }}</template>
</el-table-column>
<el-table-column label="合同数量" min-width="96" align="right">
<template #default="{ row }">{{ quantityText(row.quantity) }}</template>
</el-table-column>
<el-table-column label="剩余数量" min-width="110" align="right">
<template #default="{ row }">{{
formatRemainingQtyLabel(row.remainingQty ?? null)
}}</template>
</el-table-column>
<el-table-column label="状态" min-width="80" align="center">
<template #default="{ row }">
<el-tag
v-if="row.status"
:type="dictStore.getTagType('crm_product_status', row.status)"
size="small"
>
{{ dictStore.getLabel('crm_product_status', row.status) }}
</el-tag>
<span v-else>—</span>
</template>
</el-table-column>
</el-table>
<template #footer>
<el-button @click="pickerVisible = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button type="primary" @click="confirmProducts">
<el-icon><Check /></el-icon>确定
</el-button>
</template>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import {
Check,
CircleClose,
Close,
Delete,
Plus,
RefreshRight,
Search
} from '@element-plus/icons-vue'
import { fetchCustomerOptions } from '@/api/crm/customer'
import type { ContractVO } from '@/api/crm/contract/types'
import { fetchProductDetail } from '@/api/crm/product'
import type { ScopeProduct } from '@/api/pl/quota-cert'
import ContractSelector from '@/components/business/contract-selector/index.vue'
import CustomerSelector from '@/components/CustomerSelector.vue'
import DictTag from '@/components/DictTag/index.vue'
import { applyAliasDisplayMeta, formatBrandConstraintLabel } from '@/utils/crm-product-brand'
import { formatRemainingQtyLabel, resolvePackageSpecsFromPayload } from '@/utils/crm-package-spec'
import { exactCustomerMatches, scopeProductsFromLines } from './contract-binder-rules'
import { formatCertQty } from './model'
import { getContractDetailCached } from '@/utils/crm-contract-detail-cache'
import type { ContractProductRowLite } from '@/utils/pl-plan-contract-product'
import { useDictStore } from '@/store/modules/dict'
const props = withDefaults(
defineProps<{
mode: 'create' | 'bound'
contractId?: string
contractNo?: string
contractName?: string
savedProducts?: ScopeProduct[]
editable?: boolean
availabilityOnly?: boolean
allowRestore?: boolean
saving?: boolean
saveText?: string
hideSave?: boolean
takenContractIds?: string[]
}>(),
{
contractId: '',
contractNo: '',
contractName: '',
savedProducts: () => [],
editable: false,
availabilityOnly: false,
allowRestore: true,
saving: false,
saveText: '',
hideSave: false,
takenContractIds: () => []
}
)
const emit = defineEmits<{
save: [
payload: {
contractId: string
contractNo: string
contractName: string
products: ScopeProduct[]
}
]
}>()
interface CustomerOptionRow {
id: string
customerName: string
customerNo?: string
}
const dictStore = useDictStore()
const customerId = ref('')
const customerName = ref('')
const customerOptions = ref<CustomerOptionRow[]>([])
const customerLoading = ref(false)
const customerVisible = ref(false)
const contractVisible = ref(false)
const localContractId = ref('')
const localContractNo = ref('')
const localContractName = ref('')
const draft = ref<ScopeProduct[]>([])
const contractLines = ref<ContractProductRowLite[]>([])
const linesLoading = ref(false)
const pickerVisible = ref(false)
const pickerSelected = ref<ContractProductRowLite[]>([])
let lineEpoch = 0
let customerEpoch = 0
const contractId = computed(() =>
props.mode === 'bound' ? props.contractId : localContractId.value
)
const contractNo = computed(() =>
props.mode === 'bound' ? props.contractNo : localContractNo.value
)
const contractHint = computed(() => {
if (!customerId.value) return '请先选择客户'
if (!contractId.value) return '请选择合同'
return [contractNo.value, localContractName.value].filter(Boolean).join(' · ')
})
function scopeKey(products: ScopeProduct[]) {
return products
.map((product) => `${product.contractProductId}:${product.scopeStatus || 'active'}`)
.sort()
.join('\n')
}
const savedKey = computed(() => scopeKey(props.savedProducts))
const draftKey = computed(() => scopeKey(draft.value))
const canSave = computed(() => {
if (!props.editable || props.saving || !contractId.value) return false
if (props.mode === 'create')
return draft.value.some((product) => product.scopeStatus !== 'inactive')
return draftKey.value !== savedKey.value
})
function packageText(row: ContractProductRowLite) {
const specs = resolvePackageSpecsFromPayload(row)
if (!specs.length) return '—'
return specs.map((spec) => dictStore.getLabel('crm_product_gg', spec) || spec).join('、')
}
function quantityText(value: unknown) {
return formatCertQty(value)
}
const selectedRows = computed(() =>
draft.value.map((scope) => {
const line = contractLines.value.find(
(item) => String(item.id || '') === scope.contractProductId
)
return {
id: scope.contractProductId,
saved: Boolean(scope.id),
scopeStatus: scope.scopeStatus || 'active',
productNo: line?.productNo || '',
productName: line?.standardProductName || line?.productName || '产品信息不可用',
brand: line ? formatBrandConstraintLabel(line.brandMode, line.brandName) : '—',
aliasName: line?.aliasName || '',
model: line?.model || line?.productModel || '',
unit: line?.unit || '',
packageText: line ? packageText(line) : '—',
quantityText: line ? quantityText(line.quantity) : '—',
remainingText: line ? formatRemainingQtyLabel(line.remainingQty ?? null) : '—'
}
})
)
const showDraftDelete = computed(
() => props.editable && !props.availabilityOnly && selectedRows.value.some((row) => !row.saved)
)
const showSavedActions = computed(
() => props.editable && selectedRows.value.some((row) => row.saved)
)
function extractCustomers(res: unknown): CustomerOptionRow[] {
const unwrapped = (res as { data?: unknown })?.data ?? res
if (Array.isArray(unwrapped)) return unwrapped as CustomerOptionRow[]
const payload = (unwrapped as { list?: CustomerOptionRow[]; rows?: CustomerOptionRow[] }) || {}
return payload.list || payload.rows || []
}
function rememberCustomer(customer?: Partial<CustomerOptionRow> | null) {
if (!customer?.id) return
const id = String(customer.id)
const current = customerOptions.value.find((item) => String(item.id) === id)
if (current) {
if (!customer.customerName) return
customerOptions.value = customerOptions.value.map((item) =>
String(item.id) === id
? { ...item, customerName: customer.customerName || item.customerName }
: item
)
return
}
customerOptions.value = [
{ id, customerName: customer.customerName || id, customerNo: customer.customerNo },
...customerOptions.value
]
}
function clearContractAndProducts() {
lineEpoch++
localContractId.value = ''
localContractNo.value = ''
localContractName.value = ''
draft.value = []
contractLines.value = []
linesLoading.value = false
pickerVisible.value = false
pickerSelected.value = []
}
function changeCustomer(id?: string) {
if (props.saving) return
if (!id) {
customerId.value = ''
customerName.value = ''
clearContractAndProducts()
return
}
if (String(id) === customerId.value) return
const customer = customerOptions.value.find((item) => String(item.id) === String(id))
customerId.value = String(id)
customerName.value = customer?.customerName || ''
clearContractAndProducts()
}
async function searchCustomers(query = '') {
const keyword = query.trim()
customerLoading.value = true
try {
const result = await fetchCustomerOptions(keyword ? { keyword, limit: 50 } : { limit: 20 })
customerOptions.value = extractCustomers(result)
rememberCustomer({ id: customerId.value, customerName: customerName.value })
} finally {
customerLoading.value = false
}
}
function handleCustomerFocus() {
if (!customerOptions.value.length) void searchCustomers()
}
function confirmCustomer(customer: { id?: string | number; customerName?: string }) {
if (!customer?.id) return
rememberCustomer({ id: String(customer.id), customerName: customer.customerName })
changeCustomer(String(customer.id))
}
async function matchBuyerCustomer(name: string) {
const buyer = name.trim()
if (!buyer || customerId.value || props.saving || props.mode !== 'create') return
const epoch = ++customerEpoch
customerLoading.value = true
try {
const result = await fetchCustomerOptions({ keyword: buyer, limit: 200 })
if (epoch !== customerEpoch || customerId.value) return
const matches = exactCustomerMatches(extractCustomers(result), buyer)
if (matches.length === 1) {
rememberCustomer(matches[0])
changeCustomer(String(matches[0].id))
return
}
ElMessage.warning(
matches.length
? '有多个客户与购买单位同名,请手工选择'
: '未找到与购买单位完全一致的客户,请手工选择'
)
} catch {
if (epoch === customerEpoch) ElMessage.warning('客户匹配失败,请手工选择')
} finally {
if (epoch === customerEpoch) customerLoading.value = false
}
}
async function confirmContract(contract: ContractVO) {
const id = String(contract.id || '')
if (!id) return
contractVisible.value = false
if (props.takenContractIds.includes(id)) {
ElMessage.warning('该合同已关联,请在下方调整产品')
return
}
if (id === localContractId.value) return
clearContractAndProducts()
localContractId.value = id
localContractNo.value = contract.contractNo || ''
localContractName.value = contract.contractName || ''
const lines = await loadLines(id)
if (!lines || contractId.value !== id) return
draft.value = scopeProductsFromLines(lines, props.savedProducts)
if (!draft.value.length) ElMessage.warning('该合同没有可带出的产品')
}
async function loadLines(id: string) {
const epoch = ++lineEpoch
linesLoading.value = true
try {
const detail = await getContractDetailCached(id)
if (epoch !== lineEpoch || contractId.value !== id) return null
const lines = ((detail.products || []) as ContractProductRowLite[]).map((row) => ({
...row,
contractId: id,
contractNo: detail.contractNo || row.contractNo
}))
const details = new Map<string, Record<string, unknown>>()
for (const line of lines) {
const productId = String(line.productId || '').trim()
if (!productId) continue
let product = details.get(productId)
if (!product) {
try {
const res = await fetchProductDetail({ id: productId })
product = ((res as { data?: Record<string, unknown> })?.data ?? res) as Record<
string,
unknown
>
} catch {
product = {}
}
details.set(productId, product || {})
}
if (product && Object.keys(product).length) {
applyAliasDisplayMeta(
line,
product as { productName?: string; aliases?: { aliasName?: string }[] }
)
if (!line.productNo)
line.productNo = String(product.productNo || product.product_no || '')
if (line.status == null || line.status === '')
line.status = String(product.status ?? '') || null
}
if (epoch !== lineEpoch || contractId.value !== id) return null
}
contractLines.value = lines
return lines
} catch {
if (epoch === lineEpoch) contractLines.value = []
return null
} finally {
if (epoch === lineEpoch) linesLoading.value = false
}
}
function openProductPicker() {
if (props.saving || props.availabilityOnly) return
if (!contractId.value) {
ElMessage.warning(props.mode === 'create' ? '请先选择合同后再选择产品' : '合同信息不可用')
return
}
pickerSelected.value = []
pickerVisible.value = true
if (!contractLines.value.length) void loadLines(contractId.value)
}
function confirmProducts() {
const selected = pickerSelected.value.filter((row) => String(row.id || '').trim())
if (!selected.length) {
ElMessage.warning('请选择合同产品行')
return
}
const existing = new Set(draft.value.map((product) => product.contractProductId))
const added = selected.filter((row) => !existing.has(String(row.id)))
if (!added.length) {
ElMessage.info('所选合同行已在适用产品中')
return
}
draft.value = [
...draft.value,
...added.map((row) => {
const id = String(row.id)
const saved = props.savedProducts.find((product) => product.contractProductId === id)
return saved ? { ...saved } : { contractProductId: id, scopeStatus: 'active' as const }
})
]
pickerVisible.value = false
}
function removeProduct(id: string) {
if (props.saving || props.availabilityOnly) return
const current = draft.value.find((product) => product.contractProductId === id)
if (!current || current.id) return
draft.value = draft.value.filter((product) => product.contractProductId !== id)
}
function toggleProduct(id: string) {
if (props.saving) return
const current = draft.value.find((product) => product.contractProductId === id)
if (!current || (current.scopeStatus === 'inactive' && !props.allowRestore)) return
draft.value = draft.value.map((product) =>
product.contractProductId === id
? {
...product,
scopeStatus: product.scopeStatus === 'inactive' ? 'active' : 'inactive'
}
: product
)
}
function snapshot() {
if (!contractId.value) return null
return {
contractId: contractId.value,
contractNo: contractNo.value || '',
contractName: props.mode === 'bound' ? props.contractName : localContractName.value,
products: draft.value.map((product) => ({ ...product })),
loading: linesLoading.value,
changed: props.mode === 'create' || draftKey.value !== savedKey.value
}
}
function submit() {
if (!canSave.value) return
emit('save', snapshot()!)
}
defineExpose({ matchBuyerCustomer, snapshot })
watch(
() => `${props.mode}|${props.contractId}|${savedKey.value}`,
() => {
if (props.mode !== 'bound') return
draft.value = props.savedProducts.map((product) => ({ ...product }))
if (props.contractId) void loadLines(props.contractId)
else clearContractAndProducts()
},
{ immediate: true }
)
</script>
<style scoped lang="scss">
.cert-contract-binder {
margin-top: 12px;
}
.customer-select-row {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
}
.customer-select-row__select {
flex: 1 1 auto;
min-width: 0;
}
.customer-select-row__search {
flex: 0 0 auto;
padding: 0 6px;
}
.customer-option-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.customer-option-row__meta {
color: #94a3b8;
font-size: 12px;
}
.cert-contract-trigger {
display: flex;
align-items: center;
gap: 12px;
min-height: 32px;
}
.cert-contract-trigger__hint {
color: var(--mint-text-muted, #64748b);
font-size: 13px;
line-height: 1.4;
&.is-warn {
color: #d97706;
}
}
.cert-contract-products-head {
display: flex;
align-items: center;
justify-content: space-between;
margin: 4px 0 8px;
color: #1e293b;
font-size: 14px;
font-weight: 600;
}
.cert-contract-binder__save {
display: flex;
justify-content: flex-end;
margin-top: 12px;
}
</style>
@@ -1,20 +1,19 @@
<template>
<el-dialog
v-model="visible"
title="合同适用证件"
title="调整适用产品"
width="1040px"
align-center
class="dialog-form-layout"
class="dialog-form-layout quota-cert-scope-dialog"
:close-on-click-modal="false"
>
<div v-loading="loading">
<el-alert
title="关联只定义适用范围。多个合同产品、车辆共用证件余额,正式安排时校验并预占。"
type="info"
:closable="false"
/>
<section class="view-section">
<h3>1. 选择山峡合同</h3>
<p class="scope-lead">
这里只决定这张证以后能用于该合同的哪些产品,不修改证面数量和余额。多个产品、多张证件共用同一份余额,真正安排运输时才会占用。
</p>
<section class="scope-section">
<h3 class="dialog-section-title">1. 合同</h3>
<p class="form-tip">选择要关联的山峡合同。从某张证进入时,合同已经选定。</p>
<el-select
v-model="contractId"
filterable
@@ -34,21 +33,31 @@
</el-select>
</section>
<template v-if="contractId && loadedContractId === contractId">
<section class="view-section">
<h3>2. 勾选合同产品行</h3>
<el-checkbox-group v-model="selectedProducts" :disabled="!canEdit || saving">
<section class="scope-section">
<h3 class="dialog-section-title">2. 可共用的合同产品</h3>
<p class="form-tip">先勾选产品。只有勾选过的产品,才能分配给下面的购买证或运输证。</p>
<el-checkbox-group
v-if="products.length"
v-model="selectedProducts"
class="scope-product-checks"
:disabled="!canEdit || saving"
>
<el-checkbox v-for="p in products" :key="p.id" :value="p.id">{{
productLabel(p)
}}</el-checkbox>
</el-checkbox-group>
<el-empty v-if="!products.length" description="该合同暂无有效产品明细" :image-size="64" />
<el-empty v-else description="该合同暂无有效产品明细" :image-size="64" />
</section>
<section class="view-section">
<h3>3. 分别选择证件及各自适用产品</h3>
<section class="scope-section">
<h3 class="dialog-section-title">3. 每张证件用于哪些产品</h3>
<p class="form-tip">
购买证和运输证分开设置。勾选表示这张证可以用于该产品;「暂停」只停止这个产品以后再用这张证。
</p>
<div class="form-grid-2">
<div v-for="kind in kinds" :key="kind.value">
<div v-for="kind in kinds" :key="kind.value" class="scope-kind">
<h4>{{ kind.label }}</h4>
<el-form label-position="top">
<el-form-item :label="kind.label">
<el-form-item :label="`选择${kind.label}`">
<el-select
:model-value="
bindings.filter((b) => b.certType === kind.value).map((b) => b.certId)
@@ -63,25 +72,31 @@
v-for="c in certificates[kind.value]"
:key="c.id"
:value="c.id"
:label="`${c.certNo} · 可用 ${c.availableQty} ${c.quantityUnit}`"
:label="certOptionLabel(c)"
:disabled="
c.status === 'void' &&
(c.status === 'void' || c.status === 'closed') &&
!bindings.some((b) => b.certType === kind.value && b.certId === c.id)
"
/>
</el-select>
</el-form-item>
</el-form>
<div
<article
v-for="b in bindings.filter((b) => b.certType === kind.value)"
:key="b.certId"
class="view-card"
class="scope-cert"
>
<h4>{{ certLabel(b) }}</h4>
<el-tag size="small" :type="b.linkStatus === 'inactive' ? 'info' : 'success'">{{
b.linkStatus === 'inactive' ? '已停用' : '可用范围'
}}</el-tag>
<header class="scope-cert__head">
<strong>{{ certLabel(b) }}</strong>
<el-tag size="small" :type="b.linkStatus === 'inactive' ? 'info' : 'success'">{{
b.linkStatus === 'inactive' ? '已停止新增' : '允许新增使用'
}}</el-tag>
</header>
<p v-if="kind.value === 'transport'" class="form-tip">{{
transportDetails(b.certId)
}}</p>
<el-checkbox-group
class="scope-product-checks"
:model-value="b.products.map((p) => p.contractProductId)"
:disabled="!canEdit || saving"
@update:model-value="(ids) => setProducts(b, ids)"
@@ -90,32 +105,35 @@
productLabel(p)
}}</el-checkbox>
</el-checkbox-group>
<div v-for="p in b.products" :key="p.contractProductId">
<div v-for="p in b.products" :key="p.contractProductId" class="scope-switch-row">
<span>{{ productName(p.contractProductId) }}</span>
<el-switch
v-model="p.scopeStatus"
active-value="active"
inactive-value="inactive"
:active-text="`${products.find((row) => row.id === p.contractProductId)?.productName || p.contractProductId}:产品范围启用`"
inactive-text="产品范围停用"
active-text="可用"
inactive-text="暂停"
:disabled="!canEdit || saving"
/>
</div>
<el-switch
v-model="b.linkStatus"
active-value="active"
inactive-value="inactive"
active-text="允许新增使用"
:disabled="!canEdit || saving"
/>
<p v-if="kind.value === 'transport'" class="form-tip">{{
transportDetails(b.certId)
}}</p>
</div>
<div class="scope-switch-row">
<span>以后还能继续安排</span>
<el-switch
v-model="b.linkStatus"
active-value="active"
inactive-value="inactive"
active-text="允许"
inactive-text="停止"
:disabled="!canEdit || saving"
/>
</div>
</article>
</div>
</div>
</section>
<section class="view-section">
<h3>4. 核对产品与证件关联</h3>
<section class="scope-section">
<h3 class="dialog-section-title">4. 保存前核对</h3>
<p class="form-tip">每一行是一个合同产品,右侧是目前允许使用它的证件。</p>
<el-table
:data="
products.filter((p) =>
@@ -126,7 +144,7 @@
class="list-table"
row-key="id"
>
<el-table-column label="合同产品行" min-width="200"
<el-table-column label="合同产品" min-width="220"
><template #default="{ row }">{{ productLabel(row) }}</template></el-table-column
>
<el-table-column
@@ -135,8 +153,8 @@
:label="kind.label"
min-width="220"
>
<template #default="{ row }"
><el-tag
<template #default="{ row }">
<el-tag
v-for="b in bindings.filter(
(b) =>
b.certType === kind.value &&
@@ -146,9 +164,19 @@
size="small"
:type="bindingProductEnabled(b, row.id) ? 'success' : 'info'"
>{{ certLabel(b)
}}{{ bindingProductEnabled(b, row.id) ? '' : '(停用)' }}</el-tag
></template
>
}}{{ bindingProductEnabled(b, row.id) ? '' : '(暂停)' }}</el-tag
>
<span
v-if="
!bindings.some(
(b) =>
b.certType === kind.value &&
b.products.some((p) => p.contractProductId === row.id)
)
"
>—</span
>
</template>
</el-table-column>
</el-table>
</section>
@@ -181,7 +209,10 @@
type ContractOption,
type ContractProduct
} from '@/api/pl/quota-cert'
import { bindingPayload, bindingProductEnabled } from './model'
import { bindingPayload, bindingProductEnabled, formatCertQty } from './model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
const dictStore = useDictStore()
const props = defineProps<{ canEdit: boolean; fixedContractId?: string }>()
const emit = defineEmits<{ saved: [] }>()
const visible = ref(false)
@@ -200,8 +231,24 @@
{ value: 'purchase', label: '购买证' },
{ value: 'transport', label: '运输证' }
]
const productLabel = (p: ContractProduct) =>
`${p.productName}${p.model ? ' / ' + p.model : ''} · ${p.quantity ?? '—'} ${p.unit || ''} · ${p.id.slice(-6)}`
function displayUnit(unit?: string | null) {
const raw = String(unit || '').trim()
if (!raw) return ''
const label = getProductUnitLabel(dictStore.getLabel, raw)
return !label || label === '—' ? raw : label
}
const productLabel = (p: ContractProduct) => {
const unit = displayUnit(p.unit)
const qty = p.quantity == null || p.quantity === '' ? '' : formatCertQty(p.quantity)
const amount = [qty === '—' ? '' : qty, unit].filter(Boolean).join(' ')
return `${p.productName || '产品'}${p.model ? ' / ' + p.model : ''}${amount ? ' · ' + amount : ''}`
}
const productName = (id: string) =>
products.value.find((row) => row.id === id)?.productName || '产品'
const certOptionLabel = (cert: QuotaCert) => {
const unit = displayUnit(cert.quantityUnit)
return `${cert.certNo} · 可用 ${formatCertQty(cert.availableQty)}${unit ? ' ' + unit : ''}`
}
const certLabel = (b: CertBinding) =>
certificates[b.certType].find((c) => c.id === b.certId)?.certNo || b.certId
const availableProducts = (b: CertBinding) =>
@@ -239,11 +286,22 @@
searching.value = true
try {
const result = await quotaCertApi.contracts(keyword)
if (session === sessionVersion && version === searchVersion) contracts.value = result
if (session === sessionVersion && version === searchVersion) {
const known = contracts.value.find((item) => item.id === contractId.value)
contracts.value =
known && !result.some((item) => item.id === known.id) ? [known, ...result] : result
}
} finally {
if (session === sessionVersion && version === searchVersion) searching.value = false
}
}
async function rememberContract(id: string) {
const version = sessionVersion
const value = await quotaStatisticsApi.contract(id)
if (version !== sessionVersion || !value?.id) return
const option = { id: value.id, contractNo: value.contractNo, contractName: value.contractName }
contracts.value = [option, ...contracts.value.filter((item) => item.id !== option.id)]
}
async function loadFixedContract(id: string) {
const version = sessionVersion
const value = await quotaStatisticsApi.contract(id)
@@ -270,7 +328,8 @@
const [purchase, transport] = await Promise.all([
quotaCertApi.list('purchase'),
quotaCertApi.list('transport'),
props.fixedContractId ? loadFixedContract(id) : searchContracts()
props.fixedContractId ? loadFixedContract(id) : searchContracts(),
id && !props.fixedContractId ? rememberContract(id) : Promise.resolve()
])
if (session !== sessionVersion) return
certificates.purchase = purchase
@@ -369,3 +428,77 @@
}
defineExpose({ open })
</script>
<style lang="scss">
.quota-cert-scope-dialog {
.scope-lead {
margin: 0 0 16px;
color: var(--mint-text-muted);
font-size: 13px;
line-height: 1.6;
}
.scope-section + .scope-section {
margin-top: 20px;
}
.dialog-section-title {
margin: 0 0 8px;
padding-left: 8px;
border-left: 3px solid var(--section-bar-border-color, #10b981);
color: var(--section-bar-title-color, #059669);
font-size: 14px;
font-weight: 600;
}
.form-tip {
margin: 0 0 10px;
}
.el-select {
width: 100%;
}
.scope-kind {
min-width: 0;
padding: 14px 16px;
border: 1px solid var(--border, #d9e8e2);
border-radius: 10px;
h4 {
margin: 0 0 12px;
font-size: 14px;
font-weight: 600;
}
}
.scope-cert {
margin-top: 12px;
padding: 12px;
border-radius: 8px;
background: #f8fafc;
}
.scope-cert__head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.scope-product-checks {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.scope-switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 10px;
}
}
</style>
@@ -10,36 +10,36 @@
:show-close="!saving"
>
<template v-if="cert">
<p
>核定 {{ cert.totalQty }} {{ cert.quantityUnit }};预占 {{ cert.reservedQty }};已使用
{{ cert.usedQty }}</p
>
<el-table :data="logs" stripe
><el-table-column prop="createTime" label="时间" min-width="170" /><el-table-column
prop="eventType"
label="业务事件"
min-width="140"
><template #default="{ row }"
><el-tag type="info" size="small">{{
eventLabels[row.eventType] || row.eventType
}}</el-tag></template
></el-table-column
><el-table-column prop="totalDelta" label="总量变化" min-width="120" /><el-table-column
prop="reservedDelta"
label="预占变化"
min-width="120" /><el-table-column
prop="usedDelta"
label="已用变化"
min-width="120" /><el-table-column prop="reason" label="原因" min-width="220"
/></el-table>
<section v-if="canEdit" class="view-section"
><h3>更正证面核定总量</h3
><p class="form-tip"
>新总量不得低于已用与预占之和。更正会留下流水并更新证面版本,后续用证需重新核对。</p
>
<p class="form-tip">
核定 {{ formatCertQty(cert.totalQty) }} {{ unitText(cert.quantityUnit) }};预占
{{ formatCertQty(cert.reservedQty) }};已使用 {{ formatCertQty(cert.usedQty) }}
</p>
<div class="list-body list-wrap">
<el-table :data="logs" stripe class="list-table">
<el-table-column prop="createTime" label="时间" min-width="170" />
<el-table-column prop="eventType" label="业务事件" min-width="140">
<template #default="{ row }">
<el-tag type="info" size="small">{{
eventLabels[row.eventType] || row.eventType
}}</el-tag>
</template>
</el-table-column>
<el-table-column label="总量变化" min-width="120" align="right">
<template #default="{ row }">{{ formatCertQty(row.totalDelta) }}</template>
</el-table-column>
<el-table-column label="预占变化" min-width="120" align="right">
<template #default="{ row }">{{ formatCertQty(row.reservedDelta) }}</template>
</el-table-column>
<el-table-column label="已用变化" min-width="120" align="right">
<template #default="{ row }">{{ formatCertQty(row.usedDelta) }}</template>
</el-table-column>
<el-table-column prop="reason" label="原因" min-width="220" show-overflow-tooltip />
</el-table>
</div>
<section v-if="canEdit" class="view-section">
<el-form label-position="top" :disabled="saving"
><div class="form-grid-2"
><el-form-item :label="`更正后总量(${cert.quantityUnit})`"
><el-form-item :label="`更正后总量(${unitText(cert.quantityUnit)})`"
><el-input v-model="body.totalQty" /></el-form-item
><el-form-item label="更正理由"><el-input v-model="body.reason" /></el-form-item
><el-form-item label="依据说明(与凭据至少一项)" class="form-col-span-2"
@@ -72,6 +72,17 @@
type CertType
} from '@/api/pl/quota-cert'
import AttachmentUploadField from '@/components/business/attachment-upload-field/index.vue'
import { formatCertQty } from './model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
function inputQty(value: unknown) {
const text = formatCertQty(value)
return text === '—' ? '' : text
}
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
defineProps<{ canEdit: boolean }>()
const emit = defineEmits<{ saved: [] }>()
const visible = ref(false),
@@ -109,7 +120,7 @@
cert.value = row
logs.value = values
Object.assign(body, {
totalQty: String(row.totalQty),
totalQty: inputQty(row.totalQty),
reason: '',
sourceNote: '',
evidenceUrls: ''
@@ -0,0 +1,50 @@
/** 列表里把购买证、运输证的证面主体收成同一组列。 */
export const EXPIRY_WARNING_DAYS = 7
export interface CertListFace {
certType?: string | null
sellerName?: string | null
buyerName?: string | null
shipperName?: string | null
consigneeName?: string | null
salePartyName?: string | null
buyPartyName?: string | null
validUseText?: string | null
validTo?: string | null
}
export function salePartyName(row: CertListFace) {
if (row.salePartyName) return row.salePartyName
return (row.certType === 'transport' ? row.shipperName : row.sellerName) || ''
}
export function buyPartyName(row: CertListFace) {
if (row.buyPartyName) return row.buyPartyName
return (row.certType === 'transport' ? row.consigneeName : row.buyerName) || ''
}
export function certFaceFields(row: CertListFace) {
const warning = expiryWarning(row.validTo)
return [
{ label: '销售单位', value: salePartyName(row) || '—' },
{ label: '购买单位', value: buyPartyName(row) || '—' },
{ label: '有效次数', value: row.validUseText || '—' },
{ label: '是否预警', value: warning?.label || '—', alert: Boolean(warning) }
]
}
export function expiryWarning(validTo?: string | null, today = new Date()) {
const target = calendarDate(validTo)
if (!target) return null
const start = new Date(today.getFullYear(), today.getMonth(), today.getDate())
const days = Math.round((target.getTime() - start.getTime()) / 86400000)
if (days < 0 || days > EXPIRY_WARNING_DAYS) return null
return { days, label: days === 0 ? '今天到期' : `${days}天后到期` }
}
function calendarDate(value?: string | null) {
const match = String(value || '').match(/^(\d{4})-(\d{2})-(\d{2})/)
if (!match) return null
return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]))
}
@@ -0,0 +1,116 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import {
bindingsFromPurchaseCerts,
contractsForCustomer,
exactCustomerMatches,
matchPurchaseCert,
scopeProductsFromLines
} from './contract-binder-rules'
test('购买单位只命中名称完全一致的客户', () => {
const customers = [
{ id: 'partial', customerName: '安庆市腾龙源科技' },
{ id: 'exact', customerName: ' 安庆市腾龙源科技有限公司 ' },
{ id: 'other', customerName: '安庆市山峡化工有限公司' }
]
assert.deepEqual(
exactCustomerMatches(customers, '安庆市腾龙源科技有限公司').map((item) => item.id),
['exact']
)
assert.deepEqual(exactCustomerMatches(customers, ' '), [])
assert.equal(exactCustomerMatches(customers, '腾龙源').length, 0)
})
test('选定客户后只保留该客户的合同', () => {
const contracts = [
{ id: 'a', customerId: 'c1', customerName: '安庆市腾龙源科技有限公司' },
{ id: 'b', customerId: 'c2', customerName: '安庆市腾龙源科技有限公司' },
{ id: 'c', customerName: ' 安庆市山峡化工有限公司 ' }
]
assert.deepEqual(
contractsForCustomer(contracts, { id: 'c1', customerName: '安庆市腾龙源科技有限公司' }).map(
(item) => item.id
),
['a']
)
assert.deepEqual(
contractsForCustomer(contracts, { customerName: '安庆市山峡化工有限公司' }).map(
(item) => item.id
),
['c']
)
assert.deepEqual(contractsForCustomer(contracts, { customerName: ' ' }), [])
})
test('引用证号只关联证号完全一致的一张购买证', () => {
const purchases = [
{ id: 'p1', certNo: ' G3426 ' },
{ id: 'p2', certNo: 'G34260' },
{ id: 'dup', certNo: 'SAME' },
{ id: 'dup2', certNo: 'SAME' }
]
assert.equal(matchPurchaseCert(purchases, 'G3426')?.id, 'p1')
assert.equal(matchPurchaseCert(purchases, 'G342'), null)
assert.equal(matchPurchaseCert(purchases, 'SAME'), null)
assert.equal(matchPurchaseCert(purchases, ' '), null)
})
test('购买证合同产品复制到运输证时去掉原ID并跳过已有合同', () => {
assert.deepEqual(
bindingsFromPurchaseCerts(
[
{
id: 'p1',
contractBindings: [
{
id: 'link',
contractId: 'c1',
products: [{ id: 'scope', contractProductId: 'line-1', scopeStatus: 'active' }]
},
{ contractId: 'kept', products: [{ contractProductId: 'kept-line' }] },
{ contractId: 'c-empty', products: [] }
]
},
{
id: 'p2',
contractBindings: [
{
contractId: 'c1',
products: [{ contractProductId: 'other' }]
},
{
contractId: 'c2',
linkStatus: 'inactive',
products: [{ contractProductId: 'line-2', scopeStatus: 'inactive' }]
}
]
}
],
['kept']
),
[
{
contractId: 'c1',
linkStatus: 'active',
products: [{ contractProductId: 'line-1', scopeStatus: 'active' }]
},
{
contractId: 'c2',
linkStatus: 'inactive',
products: [{ contractProductId: 'line-2', scopeStatus: 'inactive' }]
}
]
)
})
test('选择合同后带出全部产品,并保留已保存行', () => {
const products = scopeProductsFromLines(
[{ id: 'p1' }, { id: '' }, { id: 'p1' }, { id: 'p2' }],
[{ id: 'saved', contractProductId: 'p2', scopeStatus: 'inactive' }]
)
assert.deepEqual(products, [
{ contractProductId: 'p1', scopeStatus: 'active' },
{ id: 'saved', contractProductId: 'p2', scopeStatus: 'inactive' }
])
})
@@ -0,0 +1,112 @@
export interface NamedCustomer {
customerName?: string | null
}
export interface ContractLineIdentity {
id?: string | number | null
}
export interface BinderScopeProduct {
id?: string
contractProductId: string
scopeStatus?: 'active' | 'inactive'
}
/** 客户名称与购买单位去首尾空白后完全一致才算命中。 */
export function exactCustomerMatches<T extends NamedCustomer>(
customers: T[],
buyerName: string
): T[] {
const name = buyerName.trim()
if (!name) return []
return customers.filter((item) => (item.customerName || '').trim() === name)
}
export interface NamedContract {
customerId?: string | null
customerName?: string | null
}
/** 已选客户后,只保留该客户的合同。有客户 ID 时按 ID,否则按名称完全一致。 */
export function contractsForCustomer<T extends NamedContract>(
contracts: T[],
customer: { id?: string | null; customerName?: string | null }
): T[] {
const id = String(customer.id || '').trim()
const name = (customer.customerName || '').trim()
if (!id && !name) return []
return contracts.filter((item) => {
const itemId = String(item.customerId || '').trim()
if (id && itemId) return itemId === id
return !!name && (item.customerName || '').trim() === name
})
}
export interface PurchaseCertMatch {
id?: string
certNo?: string | null
contractBindings?: PurchaseContractBinding[]
}
export interface PurchaseContractBinding {
contractId?: string
linkStatus?: 'active' | 'inactive'
products?: BinderScopeProduct[]
}
/** 引用证号与购买证证号去首尾空白后完全一致,且仅有一张时才关联。 */
export function matchPurchaseCert<T extends { id?: string; certNo?: string | null }>(
purchases: T[],
referenceNo: string
): T | null {
const certNo = referenceNo.trim()
if (!certNo) return null
const matches = purchases.filter((item) => item.id && (item.certNo || '').trim() === certNo)
return matches.length === 1 ? matches[0] : null
}
/** 把购买证上的合同和产品复制成运输证的新绑定,不带走原记录 ID,已有合同不重复。 */
export function bindingsFromPurchaseCerts(
certs: PurchaseCertMatch[],
existingContractIds: string[] = []
): PurchaseContractBinding[] {
const taken = new Set(existingContractIds.filter(Boolean))
const bindings: PurchaseContractBinding[] = []
for (const cert of certs) {
for (const binding of cert.contractBindings || []) {
const contractId = (binding.contractId || '').trim()
if (!contractId || taken.has(contractId)) continue
const products = (binding.products || [])
.filter((product) => (product.contractProductId || '').trim())
.map((product) => ({
contractProductId: product.contractProductId,
scopeStatus: product.scopeStatus === 'inactive' ? 'inactive' : ('active' as const)
}))
if (!products.length) continue
taken.add(contractId)
bindings.push({
contractId,
linkStatus: binding.linkStatus === 'inactive' ? 'inactive' : 'active',
products
})
}
}
return bindings
}
/** 选择合同后带出全部产品行;已保存行保留原范围记录。 */
export function scopeProductsFromLines(
lines: ContractLineIdentity[],
saved: BinderScopeProduct[] = []
): BinderScopeProduct[] {
const seen = new Set<string>()
const products: BinderScopeProduct[] = []
for (const line of lines) {
const id = String(line.id || '').trim()
if (!id || seen.has(id)) continue
seen.add(id)
const current = saved.find((product) => product.contractProductId === id)
products.push(current ? { ...current } : { contractProductId: id, scopeStatus: 'active' })
}
return products
}
File diff suppressed because it is too large. Load diff
+194 -28
View File
@@ -1,43 +1,156 @@
import type { CertBinding, CertBody, CertType } from '@/api/pl/quota-cert'
import { normalizeProductUnitValue } from '@/utils/crm-product-display'
export type CertFaceField = readonly [string, string] | readonly [string, string, 'date']
export interface CertFaceGroup {
title: string
fields: CertFaceField[]
}
/** 运输证「运输物品」里这一格的原栏名。 */
export const purchasePermitLabel = '购买许可/备案/出口许可证号'
export const commonFields = [
['certNo', '证件编号'],
['issueDate', '发证日期', 'date'],
['productNameOnCert', '证面品名'],
['totalQty', '核定数量'],
['certNo', '编号'],
['issueDate', '核发日期', 'date'],
['productNameOnCert', '品名'],
['totalQty', '数量'],
['quantityUnit', '数量单位'],
['validFrom', '有效期起', 'date'],
['validTo', '有效期止', 'date'],
['validUseText', '有效次数原文']
['validFrom', '有效期限起', 'date'],
['validTo', '有效期限止', 'date'],
['validUseText', '有效次数']
] as const
export const purchaseFields = [
['buyerName', '购买单位'],
['buyerAddress', '购买单位地址'],
['buyerLegalRepresentative', '购买方法定代表人'],
['buyerPhone', '购买方电话'],
['sellerName', '销售单位'],
['sellerAddress', '销售单位地址'],
['sellerLegalRepresentative', '销售方法定代表人'],
['sellerPhone', '销售方电话'],
['purchasePurpose', '购买用途']
['buyerName', '名称或姓名'],
['buyerAddress', '住所/住址'],
['buyerLegalRepresentative', '法定代表人'],
['buyerPhone', '电话'],
['sellerName', '名称'],
['sellerAddress', '住所'],
['sellerLegalRepresentative', '法定代表人'],
['sellerPhone', '电话'],
['purchasePurpose', '用途']
] as const
export const transportFields = [
['shipperName', '托运单位'],
['shipperAddress', '托运单位地址'],
['shipperLegalRepresentative', '托运方法定代表人'],
['shipperPhone', '托运方电话'],
['packagingText', '包装原文'],
['carrierName', '承运单位'],
['carrierAddressPhone', '承运地址及电话'],
['shipperName', '名称或姓名'],
['shipperAddress', '住所或住址'],
['shipperLegalRepresentative', '法定代表人'],
['shipperPhone', '电话'],
['packagingText', '包装'],
['carrierName', '名称'],
['carrierAddressPhone', '住所/电话'],
['transportMode', '运输方式'],
['routeText', '运输路线原文'],
['consigneeName', '收货单位'],
['applicantName', '申请单位']
['routeText', '运输路线'],
['consigneeName', '名称/姓名'],
['applicantName', '名称/姓名']
] as const
function labeledFaceField(kind: CertType, field: CertFaceField): CertFaceField {
if (field[0] !== 'productNameOnCert') return field
return [field[0], kind === 'purchase' ? '购买物品' : '品名']
}
function pickFaceFields(
kind: CertType,
catalog: readonly CertFaceField[],
keys: string[]
): CertFaceField[] {
return keys.map((key) => {
const field = catalog.find((item) => item[0] === key)
if (!field) throw new Error(`未知证面字段 ${key}`)
return labeledFaceField(kind, field)
})
}
/** 表单、详情按证件原栏名分组。同名格子靠分组标题区分。 */
export function certFormGroups(kind: CertType): CertFaceGroup[] {
if (kind === 'purchase') {
const catalog = [...commonFields, ...purchaseFields]
return [
{ title: '', fields: pickFaceFields(kind, catalog, ['certNo', 'issueDate']) },
{
title: '购买单位或个人',
fields: pickFaceFields(kind, catalog, [
'buyerName',
'buyerAddress',
'buyerLegalRepresentative',
'buyerPhone'
])
},
{
title: '销售单位',
fields: pickFaceFields(kind, catalog, [
'sellerName',
'sellerAddress',
'sellerLegalRepresentative',
'sellerPhone'
])
},
{
title: '',
fields: pickFaceFields(kind, catalog, [
'productNameOnCert',
'purchasePurpose',
'totalQty',
'quantityUnit',
'validUseText',
'validFrom',
'validTo'
])
}
]
}
const catalog = [...commonFields, ...transportFields]
return [
{ title: '', fields: pickFaceFields(kind, catalog, ['certNo', 'issueDate']) },
{
title: '货主',
fields: pickFaceFields(kind, catalog, [
'shipperName',
'shipperAddress',
'shipperLegalRepresentative',
'shipperPhone'
])
},
{
title: '运输物品',
fields: pickFaceFields(kind, catalog, [
'productNameOnCert',
'totalQty',
'quantityUnit',
'packagingText'
])
},
{
title: '运输单位',
fields: [
...pickFaceFields(kind, catalog, ['carrierName', 'carrierAddressPhone', 'transportMode']),
['vehicleNumbersJson', '车号(次)'],
...pickFaceFields(kind, catalog, ['routeText'])
]
},
{ title: '收货单位', fields: pickFaceFields(kind, catalog, ['consigneeName']) },
{
title: '',
fields: pickFaceFields(kind, catalog, ['validFrom', 'validTo', 'validUseText'])
},
{ title: '申请单位', fields: pickFaceFields(kind, catalog, ['applicantName']) }
]
}
export function requiredFaceLabel(kind: CertType, key: string) {
for (const group of certFormGroups(kind)) {
const field = group.fields.find((item) => item[0] === key)
if (!field) continue
return group.title ? `${group.title}的${field[1]}` : field[1]
}
return key
}
export function newCert(kind: CertType): CertBody {
const body: Record<string, unknown> = {
entryMode: 'manual',
entryMode: 'image_parse',
attachmentUrls: '',
remark: '',
orderNum: null
@@ -55,10 +168,32 @@ export function newCert(kind: CertType): CertBody {
return body as unknown as CertBody
}
/** 删除当前证件附件后,清掉证面、合同绑定和证面引用,保留备注与录入方式。 */
export function clearCertAfterAttachmentRemoved<T extends Record<string, any>>(
kind: CertType,
form: T
): T {
const blank = newCert(kind) as unknown as Record<string, unknown>
const next: Record<string, unknown> = {
...blank,
entryMode: form.entryMode || blank.entryMode,
attachmentUrls: '',
remark: form.remark ?? '',
orderNum: form.orderNum ?? null,
contractBindings: [],
bindingsEditable: form.bindingsEditable !== false,
referencesEditable: form.referencesEditable !== false
}
if (form.status) next.status = form.status
if (form.id) next.id = form.id
return next as T
}
export function certPayload(kind: CertType, form: Record<string, any>): CertBody {
const result = newCert(kind) as unknown as Record<string, any>
for (const key of Object.keys(result)) if (key in form) result[key] = form[key]
if (['draft', 'suspended', 'void'].includes(form.status)) result.status = form.status
if (result.quantityUnit) result.quantityUnit = normalizeProductUnitValue(result.quantityUnit)
if (['draft', 'suspended', 'closed', 'void'].includes(form.status)) result.status = form.status
if (kind === 'transport')
result.purchaseRefs = (form.purchaseRefs || []).map((r: Record<string, unknown>) =>
Object.fromEntries(
@@ -105,6 +240,22 @@ export function mergeCandidates(
}
}
/** 只替换当前证件的产品范围,保留同一合同上其他证件的关联。 */
export function replaceCertProducts<
T extends { certType: string; certId: string; products: unknown[] }
>(bindings: T[], certType: string, certId: string, products: T['products']): T[] {
const others = bindings.filter(
(binding) => !(binding.certType === certType && binding.certId === certId)
)
const current = bindings.find(
(binding) => binding.certType === certType && binding.certId === certId
)
const next = current
? { ...current, products }
: ({ certType, certId, linkStatus: 'active', products } as T)
return [...others, next]
}
export function bindingPayload(bindings: CertBinding[]): CertBinding[] {
return bindings.map((b) => ({
...(b.id ? { id: b.id } : {}),
@@ -123,6 +274,21 @@ export function bindingPayload(bindings: CertBinding[]): CertBinding[] {
}))
}
/** 列表和详情展示用:保留 3 位小数,不改库存精度。 */
export function formatCertQty(value: unknown): string {
if (value === null || value === undefined || value === '') return '—'
const text = String(value).trim()
if (!/^-?\d+(\.\d+)?$/.test(text)) return text
const negative = text.startsWith('-')
const [rawInt, rawFrac = ''] = text.slice(negative ? 1 : 0).split('.')
const frac = (rawFrac + '0000').slice(0, 4)
let scaled = BigInt(rawInt + frac.slice(0, 3))
if (frac[3] >= '5') scaled += 1n
const body = scaled.toString().padStart(4, '0')
const intPart = body.slice(0, -3).replace(/^0+(?=\d)/, '')
return `${negative && scaled !== 0n ? '-' : ''}${intPart}.${body.slice(-3)}`
}
export function bindingProductEnabled(binding: CertBinding, productId: string): boolean {
return (
binding.linkStatus !== 'inactive' &&
@@ -0,0 +1,216 @@
<template>
<el-dialog
v-model="visible"
:title="mode === 'create' ? '新增关联证件' : '编辑适用产品'"
width="1040px"
align-center
class="dialog-form-layout quota-contract-cert-dialog"
:close-on-click-modal="false"
@closed="reset"
>
<el-form v-if="mode === 'create'" label-position="top" class="form-grid-2">
<el-form-item label="证件类型">
<el-select v-model="certType" :disabled="saving" @change="changeType">
<el-option label="购买证" value="purchase" />
<el-option label="运输证" value="transport" />
</el-select>
</el-form-item>
<el-form-item label="证件">
<el-select
v-model="certId"
filterable
remote
clearable
:remote-method="searchCerts"
:loading="certLoading"
:disabled="saving"
placeholder="证件编号或品名"
@focus="focusCerts"
@change="pickCert"
>
<el-option
v-for="item in certOptions"
:key="item.id"
:label="certOptionLabel(item)"
:value="item.id"
:disabled="
item.status === 'void' ||
item.status === 'closed' ||
takenIds.has(`${certType}:${item.id}`)
"
/>
</el-select>
</el-form-item>
</el-form>
<p v-else class="quota-contract-cert-dialog__current">{{ currentCertLabel }}</p>
<CertContractBinder
v-if="ready && certId && contractId"
:key="binderKey"
mode="bound"
:contract-id="contractId"
:contract-no="contractNo"
:contract-name="contractName"
:saved-products="savedProducts"
editable
:saving="saving"
:save-text="mode === 'create' ? '保存关联' : '保存产品'"
@save="save"
/>
</el-dialog>
</template>
<script setup lang="ts">
import {
quotaCertApi,
type CertBinding,
type CertType,
type QuotaCert,
type ScopeProduct
} from '@/api/pl/quota-cert'
import CertContractBinder from '../quota-cert/CertContractBinder.vue'
import { bindingPayload, replaceCertProducts } from '../quota-cert/model'
const emit = defineEmits<{ saved: [] }>()
const visible = ref(false)
const ready = ref(false)
const saving = ref(false)
const certLoading = ref(false)
const mode = ref<'create' | 'edit'>('create')
const contractId = ref('')
const contractNo = ref('')
const contractName = ref('')
const certType = ref<CertType>('purchase')
const certId = ref('')
const certNo = ref('')
const savedProducts = ref<ScopeProduct[]>([])
const certOptions = ref<QuotaCert[]>([])
const takenIds = ref(new Set<string>())
let epoch = 0
const binderKey = computed(
() =>
`${mode.value}|${certType.value}|${certId.value}|${savedProducts.value.map((row) => row.contractProductId).join(',')}`
)
const currentCertLabel = computed(() =>
[certType.value === 'purchase' ? '购买证' : '运输证', certNo.value].filter(Boolean).join(' ')
)
function certOptionLabel(item: QuotaCert) {
const name = [item.certNo, item.productNameOnCert].filter(Boolean).join(' · ')
if (item.status === 'void') return `${name}(已作废)`
if (item.status === 'closed') return `${name}(已核销)`
if (takenIds.value.has(`${certType.value}:${item.id}`)) return `${name}(已关联)`
return name
}
function reset() {
epoch++
ready.value = false
saving.value = false
certLoading.value = false
certId.value = ''
certNo.value = ''
savedProducts.value = []
certOptions.value = []
takenIds.value = new Set()
}
async function open(payload: {
contractId: string
contractNo?: string
contractName?: string
mode: 'create' | 'edit'
certType?: CertType
certId?: string
certNo?: string
}) {
reset()
const current = ++epoch
mode.value = payload.mode
contractId.value = payload.contractId
contractNo.value = payload.contractNo || ''
contractName.value = payload.contractName || ''
certType.value = payload.certType || 'purchase'
certId.value = payload.certId || ''
certNo.value = payload.certNo || ''
visible.value = true
try {
const bindings = await quotaCertApi.bindings(payload.contractId)
if (current !== epoch) return
takenIds.value = new Set(bindings.map((row) => `${row.certType}:${row.certId}`))
if (payload.mode === 'edit' && payload.certType && payload.certId) {
const currentBinding = bindings.find(
(row) => row.certType === payload.certType && row.certId === payload.certId
)
savedProducts.value = (currentBinding?.products || []).map((product) => ({ ...product }))
}
if (payload.mode === 'create') await searchCerts('')
if (current === epoch) ready.value = true
} catch {
if (current === epoch) visible.value = false
}
}
function changeType() {
certId.value = ''
certNo.value = ''
savedProducts.value = []
void searchCerts('')
}
function focusCerts() {
if (!certOptions.value.length) void searchCerts('')
}
async function searchCerts(keyword = '') {
const current = epoch
const kind = certType.value
certLoading.value = true
try {
const rows = await quotaCertApi.list(kind, { keyword })
if (current !== epoch || kind !== certType.value) return
certOptions.value = rows
} finally {
if (current === epoch) certLoading.value = false
}
}
function pickCert(id?: string) {
const cert = certOptions.value.find((item) => item.id === id)
certNo.value = cert?.certNo || ''
savedProducts.value = []
}
async function save(payload: { products: ScopeProduct[] }) {
if (saving.value || !contractId.value || !certId.value) return
if (mode.value === 'create' && !payload.products.length) {
ElMessage.warning('请选择适用产品')
return
}
if (mode.value === 'create' && takenIds.value.has(`${certType.value}:${certId.value}`)) {
ElMessage.warning('该证件已关联,请在对应页签中编辑')
return
}
const current = epoch
saving.value = true
try {
const existing = await quotaCertApi.bindings(contractId.value)
if (current !== epoch) return
const next: CertBinding[] = replaceCertProducts(
existing,
certType.value,
certId.value,
payload.products
)
await quotaCertApi.saveBindings(contractId.value, bindingPayload(next))
if (current !== epoch) return
ElMessage.success(mode.value === 'create' ? '证件已关联' : '适用产品已保存')
visible.value = false
emit('saved')
} finally {
if (current === epoch) saving.value = false
}
}
defineExpose({ open })
</script>
<style scoped>
.quota-contract-cert-dialog__current {
margin: 0 0 12px;
color: #1e293b;
font-weight: 600;
}
</style>
@@ -1,66 +1,194 @@
<template>
<div class="view-section">
<template v-if="mode === 'contract'">
<el-empty v-if="!contract?.certificates.length" description="暂无关联证件" :image-size="64" />
<section
v-for="cert in contract?.certificates"
:key="`${cert.certType}:${cert.certId}`"
class="view-section"
>
<h3>{{ cert.certNo }} · {{ cert.productNameOnCert }}</h3>
<el-tag size="small">{{ cert.certType === 'purchase' ? '购买证' : '运输证' }}</el-tag>
<el-tag size="small" :type="cert.linkStatus === 'active' ? 'success' : 'info'">{{
cert.linkStatus === 'active' ? '有效关联' : '历史 / 停用关联'
}}</el-tag>
<el-tag size="small" :type="cert.status === 'active' ? 'success' : 'info'">{{
statusLabel(cert.status)
}}</el-tag>
<p class="form-tip">有效期:{{ cert.validFrom || '—' }} 至 {{ cert.validTo || '—' }}</p>
<el-descriptions :column="3">
<el-descriptions-item label="全证核定"
>{{ cert.totalQty }} {{ cert.quantityUnit }}</el-descriptions-item
<el-tabs v-model="certTab">
<el-tab-pane
v-for="cert in contract?.certificates || []"
:key="certKey(cert)"
:name="certKey(cert)"
:label="certTabLabel(cert)"
>
<section class="quota-cert-summary">
<header class="quota-cert-summary__head">
<strong>{{ cert.certNo }}</strong>
<span>{{ cert.productNameOnCert || '未填写证面品名' }}</span>
<span class="quota-cert-summary__meta">
有效期:{{ cert.validFrom || '—' }} 至 {{ cert.validTo || '—' }}
</span>
<div class="quota-cert-summary__tags">
<el-tag size="small">{{
cert.certType === 'purchase' ? '购买证' : '运输证'
}}</el-tag>
<el-tag size="small" :type="cert.linkStatus === 'active' ? 'success' : 'info'">{{
linkLabel(cert.linkStatus)
}}</el-tag>
<el-tag size="small" :type="cert.status === 'active' ? 'success' : 'info'">{{
certStatusLabel(cert.status)
}}</el-tag>
</div>
</header>
<dl class="quota-cert-summary__metrics">
<div v-for="item in certMetrics(cert)" :key="item.label">
<dt>{{ item.label }}</dt>
<dd :class="{ 'is-wrap': item.wrap }">
<el-tag v-if="item.alert" type="danger" size="small">{{ item.value }}</el-tag>
<template v-else>{{ item.value }}</template>
</dd>
</div>
</dl>
<div v-if="canEdit && cert.bindingId" class="quota-cert-summary__actions">
<el-button v-if="!cert.referenced" @click="emit('edit', cert)">
<el-icon><Edit /></el-icon>编辑
</el-button>
<el-button v-if="!cert.referenced" @click="emit('remove', cert)">
<el-icon><Delete /></el-icon>删除
</el-button>
<el-button
v-if="cert.referenced && cert.linkStatus === 'active'"
@click="emit('disable', cert)"
>
<el-icon><CircleClose /></el-icon>设为不可用
</el-button>
<el-button
v-if="
cert.referenced &&
cert.linkStatus !== 'active' &&
cert.status !== 'void' &&
cert.status !== 'closed'
"
@click="emit('enable', cert)"
>
<el-icon><RefreshRight /></el-icon>恢复可安排
</el-button>
</div>
<p
v-if="cert.bindingId && cert.referenced && cert.linkStatus === 'active'"
class="form-tip"
>
这份关联已有运输计划用证,不能删除,也不能改产品。设为不可用后,不能再安排新的用证,已经发生的用量仍保留。
</p>
<p v-else-if="cert.bindingId && cert.referenced" class="form-tip">
这份关联已有运输计划用证,目前不可用,不能再安排新的用证。已经发生的用量仍保留。
</p>
<p v-else-if="!cert.bindingId" class="form-tip"
>这条关联已经不在当前绑定里,历史用量仍可查看。</p
>
<StatisticsProducts
:products="cert.products"
:quantity-unit="unitLabel(cert.quantityUnit)"
/>
</section>
</el-tab-pane>
<el-tab-pane label="按产品" name="by-product">
<el-table
:data="productStatRows"
stripe
class="list-table"
row-key="key"
empty-text="暂无绑定产品"
>
<el-descriptions-item label="全证预占"
>{{ cert.reservedQty }} {{ cert.quantityUnit }}</el-descriptions-item
>
<el-descriptions-item label="全证已用"
>{{ cert.usedQty }} {{ cert.quantityUnit }}</el-descriptions-item
>
<el-descriptions-item label="全证共享余额"
>{{ cert.availableQty }} {{ cert.quantityUnit }}</el-descriptions-item
>
<el-descriptions-item label="本合同预占"
>{{ cert.contractReservedQty }} {{ cert.quantityUnit }}</el-descriptions-item
>
<el-descriptions-item label="本合同已用"
>{{ cert.contractUsedQty }} {{ cert.quantityUnit }}</el-descriptions-item
>
</el-descriptions>
<StatisticsProducts :products="cert.products" :quantity-unit="cert.quantityUnit" />
</section>
<el-table-column prop="productName" label="产品" min-width="160" />
<el-table-column prop="model" label="规格" min-width="120" />
<el-table-column prop="unit" label="产品单位" min-width="100" />
<el-table-column prop="certKind" label="证件类型" min-width="100" />
<el-table-column prop="certNo" label="证件编号" min-width="160" />
<el-table-column prop="certUnit" label="证面单位" min-width="100" />
<el-table-column label="产品预占" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.reservedQty)
}}</template></el-table-column
>
<el-table-column label="产品已用" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.usedQty)
}}</template></el-table-column
>
<el-table-column label="全证核定" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.totalQty)
}}</template></el-table-column
>
<el-table-column label="全证预占" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.certReservedQty)
}}</template></el-table-column
>
<el-table-column prop="salePartyName" label="销售单位" min-width="160" />
<el-table-column prop="buyPartyName" label="购买单位" min-width="160" />
<el-table-column prop="validUseText" label="有效次数" min-width="110" />
<el-table-column label="是否预警" min-width="120"
><template #default="{ row }"
><el-tag v-if="row.expiryAlert" type="danger" size="small">{{
row.expiryAlert
}}</el-tag
><span v-else>—</span></template
></el-table-column
>
<el-table-column label="全证已用" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.certUsedQty)
}}</template></el-table-column
>
<el-table-column label="共享余额" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.availableQty)
}}</template></el-table-column
>
<el-table-column label="范围状态" min-width="110"
><template #default="{ row }"
><el-tag size="small" :type="row.scopeStatus === 'active' ? 'success' : 'info'">{{
scopeStatusLabel(row.scopeStatus)
}}</el-tag></template
></el-table-column
>
</el-table>
</el-tab-pane>
</el-tabs>
</template>
<template v-else-if="certificate">
<el-descriptions :column="2">
<el-descriptions-item label="期初已用(独立记录)"
>{{ certificate.openingUsedQty }} {{ certificate.quantityUnit }}</el-descriptions-item
>
<el-descriptions-item label="未归属合同已用"
>{{ certificate.unattributedUsedQty }}
{{ certificate.quantityUnit }}</el-descriptions-item
>
<el-descriptions-item label="期初已用(独立记录)">{{
qtyText(certificate.openingUsedQty, certificate.quantityUnit)
}}</el-descriptions-item>
<el-descriptions-item label="未归属合同已用">{{
qtyText(certificate.unattributedUsedQty, certificate.quantityUnit)
}}</el-descriptions-item>
</el-descriptions>
<el-empty v-if="!certificate.contracts.length" description="暂无关联合同" :image-size="64" />
<section v-for="item in certificate.contracts" :key="item.id" class="view-section">
<h3>{{ item.contractNo }} · {{ item.contractName }}</h3>
<el-tag size="small" :type="item.linkStatus === 'active' ? 'success' : 'info'">{{
item.linkStatus === 'active' ? '有效关联' : '历史 / 停用关联'
}}</el-tag>
<p
>本合同预占 {{ item.contractReservedQty }} / 已用 {{ item.contractUsedQty }}
{{ certificate.quantityUnit }}</p
<el-empty v-if="!linkedContractTabs.length" description="暂无关联合同" :image-size="64" />
<el-tabs v-else v-model="contractTab">
<el-tab-pane
v-for="tab in linkedContractTabs"
:key="tab.key"
:name="tab.key"
:label="tab.label"
>
<StatisticsProducts :products="item.products" :quantity-unit="certificate.quantityUnit" />
</section>
<section class="quota-cert-summary">
<header class="quota-cert-summary__head">
<strong>{{ tab.item.contractNo || '合同信息不可用' }}</strong>
<span>{{ tab.item.contractName || '未填写合同名称' }}</span>
<div class="quota-cert-summary__tags">
<el-tag size="small" :type="tab.item.linkStatus === 'active' ? 'success' : 'info'">
{{ linkLabel(tab.item.linkStatus) }}
</el-tag>
</div>
</header>
<dl class="quota-cert-summary__metrics is-pair">
<div>
<dt>本合同预占</dt>
<dd>{{ qtyText(tab.item.contractReservedQty, certificate.quantityUnit) }}</dd>
</div>
<div>
<dt>本合同已用</dt>
<dd>{{ qtyText(tab.item.contractUsedQty, certificate.quantityUnit) }}</dd>
</div>
</dl>
<StatisticsProducts
:products="tab.item.products"
:quantity-unit="unitLabel(certificate.quantityUnit)"
/>
</section>
</el-tab-pane>
</el-tabs>
<h3>计划段产品用量追踪</h3>
<el-table :data="usageRows" stripe class="list-table" row-key="id">
<el-table-column prop="planNo" label="计划编号" min-width="180" />
@@ -74,9 +202,19 @@
<el-table-column prop="productModel" label="规格" min-width="140" />
<el-table-column prop="partyName" label="装货 / 送货主体" min-width="180" />
<el-table-column prop="address" label="装货 / 送货地址" min-width="200" />
<el-table-column prop="quantityUnit" label="单位" min-width="90" />
<el-table-column prop="reservedQty" label="预占" min-width="120" />
<el-table-column prop="usedQty" label="已用" min-width="120" />
<el-table-column label="单位" min-width="90"
><template #default="{ row }">{{
unitLabel(row.quantityUnit) || '—'
}}</template></el-table-column
>
<el-table-column label="预占" min-width="120"
><template #default="{ row }">{{
formatCertQty(row.reservedQty)
}}</template></el-table-column
>
<el-table-column label="已用" min-width="120"
><template #default="{ row }">{{ formatCertQty(row.usedQty) }}</template></el-table-column
>
<el-table-column label="状态" min-width="120"
><template #default="{ row }"
><el-tag size="small">{{ statusLabel(row.itemStatus) }}</el-tag></template
@@ -87,19 +225,144 @@
</div>
</template>
<script setup lang="ts">
import { CircleClose, Delete, Edit, RefreshRight } from '@element-plus/icons-vue'
import type { ContractStatistics, CertificateStatistics } from '@/api/pl/quota-cert'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { formatCertQty } from '../quota-cert/model'
import { certFaceFields, expiryWarning } from '../quota-cert/cert-list-face'
import StatisticsProducts from './StatisticsProducts.vue'
import { statusLabel } from './labels'
const props = defineProps<{
mode: 'contract' | 'certificate'
detail: ContractStatistics | CertificateStatistics
const props = withDefaults(
defineProps<{
mode: 'contract' | 'certificate'
detail: ContractStatistics | CertificateStatistics
canEdit?: boolean
}>(),
{ canEdit: false }
)
const emit = defineEmits<{
edit: [cert: ContractStatistics['certificates'][number]]
remove: [cert: ContractStatistics['certificates'][number]]
disable: [cert: ContractStatistics['certificates'][number]]
enable: [cert: ContractStatistics['certificates'][number]]
}>()
const certTab = ref('')
const contractTab = ref('')
function certKey(cert: { certType: string; certId: string }) {
return `${cert.certType}:${cert.certId}`
}
function certTabLabel(cert: ContractStatistics['certificates'][number]) {
const kind = cert.certType === 'purchase' ? '购买证' : '运输证'
return `${kind} ${cert.certNo || ''}`.trim()
}
watch(
() =>
props.mode === 'contract'
? (props.detail as ContractStatistics).certificates.map(certKey).join('|')
: '',
() => {
if (props.mode !== 'contract') return
const names = (props.detail as ContractStatistics).certificates.map(certKey)
if (certTab.value !== 'by-product' && !names.includes(certTab.value))
certTab.value = names[0] || 'by-product'
},
{ immediate: true }
)
const contract = computed(() =>
props.mode === 'contract' ? (props.detail as ContractStatistics) : undefined
)
const certificate = computed(() =>
props.mode === 'certificate' ? (props.detail as CertificateStatistics) : undefined
)
const productStatRows = computed(() =>
(contract.value?.certificates || []).flatMap((cert) =>
(cert.products || []).map((product) => ({
key: `${certKey(cert)}:${product.contractProductId || product.id}`,
productName: product.productName || '—',
model: product.model || '—',
unit: unitLabel(product.unit) || '—',
certKind: cert.certType === 'purchase' ? '购买证' : '运输证',
certNo: cert.certNo || '—',
certUnit: unitLabel(cert.quantityUnit) || '—',
reservedQty: product.reservedQty,
usedQty: product.usedQty,
totalQty: cert.totalQty,
certReservedQty: cert.reservedQty,
salePartyName: certFaceFields(cert)[0].value,
buyPartyName: certFaceFields(cert)[1].value,
validUseText: cert.validUseText || '—',
expiryAlert: expiryWarning(cert.validTo)?.label || '',
certUsedQty: cert.usedQty,
availableQty: cert.availableQty,
scopeStatus: product.scopeStatus
}))
)
)
function scopeStatusLabel(status?: string | null) {
return status === 'active' ? '有效' : status === 'inactive' ? '停用' : '历史解绑'
}
const linkedContractTabs = computed(() => {
const rows = certificate.value?.contracts || []
const seen = new Map<string, number>()
return rows.map((item, index) => {
const count = (seen.get(item.id) || 0) + 1
seen.set(item.id, count)
const total = rows.filter((row) => row.id === item.id).length
const no = item.contractNo || '合同信息不可用'
return {
key: `${item.bindingId || 'none'}:${item.id}:${index}`,
label: total > 1 ? `${no}(${count})` : no,
item
}
})
})
watch(
() => linkedContractTabs.value.map((tab) => tab.key).join('|'),
() => {
if (props.mode !== 'certificate') return
const names = linkedContractTabs.value.map((tab) => tab.key)
if (!names.includes(contractTab.value)) contractTab.value = names[0] || ''
},
{ immediate: true }
)
function linkLabel(status?: string | null) {
return status === 'active' ? '可安排用证' : '停止新增使用'
}
function certStatusLabel(status?: string | null) {
return (
{ draft: '待核对', active: '证件已启用', suspended: '证件已停用', closed: '证件已核销', void: '证件已作废' }[
status || ''
] ||
statusLabel(status || '') ||
'—'
)
}
function unitLabel(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '' : label
}
function qtyText(value: unknown, unit?: string | null) {
const text = formatCertQty(value)
const name = unitLabel(unit)
return name ? `${text} ${name}` : text
}
function certMetrics(cert: ContractStatistics['certificates'][number]) {
const unit = cert.quantityUnit
const face = certFaceFields(cert).map((item) => ({
...item,
wrap: item.label === '销售单位' || item.label === '购买单位'
}))
const quantities = [
['全证核定', cert.totalQty],
['全证预占', cert.reservedQty],
['全证已用', cert.usedQty],
['全证共享余额', cert.availableQty],
['本合同预占', cert.contractReservedQty],
['本合同已用', cert.contractUsedQty]
].map(([label, value]) => ({ label: String(label), value: qtyText(value, unit), alert: false, wrap: false }))
return [...quantities.slice(0, 2), ...face, ...quantities.slice(2)]
}
const usageRows = computed(() =>
(certificate.value?.usageItems || []).map((item) => {
const contract = certificate.value?.contracts.find((row) => row.id === item.contractId)
@@ -116,3 +379,100 @@
})
)
</script>
<style scoped lang="scss">
.quota-cert-summary {
padding: 14px 16px;
border: 1px solid var(--border, #d9e8e2);
border-radius: 10px;
background: #fff;
& + & {
margin-top: 12px;
}
&__head {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
strong {
flex: none;
color: #1e293b;
font-size: 15px;
line-height: 1.4;
}
> span {
flex: none;
color: var(--mint-text-muted, #64748b);
font-size: 13px;
line-height: 1.4;
white-space: nowrap;
}
}
&__tags {
display: flex;
flex: none;
align-items: center;
gap: 6px;
margin-left: auto;
}
&__meta {
flex: none;
color: var(--mint-text-muted, #64748b);
font-size: 13px;
line-height: 1.4;
white-space: nowrap;
}
&__actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 0 0 12px;
}
&__metrics {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
&.is-pair {
grid-template-columns: repeat(2, minmax(180px, 240px));
}
gap: 8px 16px;
margin: 14px 0 16px;
div {
min-width: 0;
}
dt {
margin: 0 0 4px;
color: var(--mint-text-muted, #64748b);
font-size: 13px;
font-weight: 400;
line-height: 1.4;
white-space: nowrap;
}
dd {
margin: 0;
color: #1e293b;
font-size: 14px;
font-weight: 600;
line-height: 1.5;
white-space: nowrap;
&.is-wrap {
font-weight: 500;
white-space: normal;
overflow-wrap: anywhere;
}
}
}
}
</style>
@@ -4,21 +4,13 @@
><h2 class="title-bar-heading">{{ mode === 'contract' ? '合同用证' : '证件用量' }}</h2></div
>
<div v-if="!contractId" class="list-toolbar"
><div class="list-toolbar-row">
><div class="list-toolbar-row cert-list-toolbar-row">
<ListQuickSearchInput
v-model="keyword"
:placeholder="mode === 'contract' ? '合同编号 / 名称' : '证件编号 / 品名'"
@search="search"
@clear="search"
/>
<el-select
v-if="mode === 'certificate'"
v-model="certType"
aria-label="证件类型"
@change="search"
style="width: 150px"
><el-option label="购买证" value="purchase" /><el-option label="运输证" value="transport"
/></el-select>
<el-button v-if="keyword || hasActiveFilters" @click="reset"
><el-icon><RefreshLeft /></el-icon>清除筛选</el-button
>
@@ -32,9 +24,23 @@
@reset-columns="resetToDefault"
/> </div
></div>
<p class="form-tip"
>额度按单张证件核算;共享余额为全证余额,多个合同共用,不代表本合同独享额度。</p
>
<div v-if="contractId" class="list-toolbar">
<div class="list-toolbar-row contract-quota-toolbar">
<el-button
v-if="canEdit && fixedDetail"
class="btn-main"
type="primary"
@click="openCreate(fixedDetail)"
><el-icon><Plus /></el-icon>新增</el-button
>
<el-button v-if="canEdit" class="btn-main" type="primary" @click="openNewCert"
><el-icon><Plus /></el-icon>新增证件</el-button
>
<span class="contract-quota-toolbar__tip"
>额度按单张证件核算;共享余额为全证余额,多个合同共用,不代表本合同独享额度。</span
>
</div>
</div>
<el-alert v-if="error" :title="error" type="error" :closable="false"
><el-button @click="allowed ? load() : init()"
><el-icon><Refresh /></el-icon>重试</el-button
@@ -42,10 +48,15 @@
>
<div v-if="contractId" v-loading="loading">
<template v-if="fixedDetail">
<el-button v-if="canEdit" @click="edit(contractId)"
><el-icon><Edit /></el-icon>维护合同适用证件</el-button
>
<StatisticsDetail mode="contract" :detail="fixedDetail" />
<StatisticsDetail
mode="contract"
:can-edit="canEdit"
:detail="fixedDetail"
@edit="(cert) => openEdit(fixedDetail, cert)"
@remove="(cert) => changeLink(fixedDetail, cert, 'delete')"
@disable="(cert) => changeLink(fixedDetail, cert, 'inactive')"
@enable="(cert) => changeLink(fixedDetail, cert, 'active')"
/>
</template>
<el-empty
v-else-if="!loading && !error"
@@ -82,10 +93,30 @@
></el-alert
>
<template v-else-if="details[row.id]?.data">
<el-button v-if="mode === 'contract' && canEdit" @click="edit(row.id)"
><el-icon><Edit /></el-icon>维护合同适用证件</el-button
<el-button
v-if="mode === 'contract' && canEdit"
type="primary"
@click="openCreate(details[row.id].data as ContractStatistics)"
><el-icon><Plus /></el-icon>新增</el-button
>
<StatisticsDetail :mode="mode" :detail="details[row.id].data!" />
<StatisticsDetail
:mode="mode"
:can-edit="mode === 'contract' && canEdit"
:detail="details[row.id].data!"
@edit="(cert) => openEdit(details[row.id].data as ContractStatistics, cert)"
@remove="
(cert) =>
changeLink(details[row.id].data as ContractStatistics, cert, 'delete')
"
@disable="
(cert) =>
changeLink(details[row.id].data as ContractStatistics, cert, 'inactive')
"
@enable="
(cert) =>
changeLink(details[row.id].data as ContractStatistics, cert, 'active')
"
/>
</template>
</div> </template
></el-table-column>
@@ -100,25 +131,40 @@
><div class="col-header-with-filter"
><span class="col-header-with-filter__label">{{ column.label }}</span>
<ColumnHeaderFilter
v-if="column.prop === searchColumn"
:prop="column.prop"
:label="column.label"
type="text"
:type="column.type"
:enable-sort="false"
:options="
column.prop === 'quantityUnit' ? unitChoices() : column.enumOptions || []
"
:model-value="filters[column.prop] || null"
:is-active="isFilterActive(column.prop)"
@update:model-value="(v) => setFilterState(column.prop, v)"
/> </div
></template>
<template #default="{ row }"
><span v-if="column.prop === 'certType'">{{
row.certType === 'transport' ? '运输证' : '购买证'
}}</span
><el-tag
v-if="column.prop === 'status'"
v-else-if="column.prop === 'status'"
size="small"
:type="row.status === 'active' ? 'success' : 'info'"
>{{ statusLabel(row.status) }}</el-tag
><el-tag v-else-if="column.prop === 'contractType'" size="small">{{
contractTypeLabel(row.contractType)
}}</el-tag
><span v-else-if="column.prop === 'quantityUnit'">{{
unitText(row.quantityUnit)
}}</span
><el-tag v-else-if="column.prop === 'expiryAlert' && expiryText(row)" type="danger" size="small">{{
expiryText(row)
}}</el-tag
><span v-else-if="column.prop === 'expiryAlert'">—</span
><span v-else-if="isQtyColumn(column.prop)">{{
formatCertQty(row[column.prop])
}}</span
><span v-else>{{ row[column.prop] ?? '—' }}</span></template
>
</el-table-column>
@@ -131,25 +177,19 @@
layout="total, prev, pager, next"
@current-change="load" /></div
></div>
<ContractScopeDialog
v-if="allowed"
:key="sessionKey"
ref="scopeDialog"
:can-edit="canEdit"
:fixed-contract-id="editingContractId"
@saved="load"
/>
<ContractCertLinkDialog v-if="allowed" :key="sessionKey" ref="linkDialog" @saved="load" />
</section>
</template>
<script setup lang="ts">
import { Edit, Refresh, RefreshLeft } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { Plus, Refresh, RefreshLeft } from '@element-plus/icons-vue'
import { fetchGetMenuCodes } from '@/api/auth'
import { useUserStore } from '@/store/modules/user'
import {
quotaCertApi,
quotaStatisticsApi,
type ContractStatistics,
type CertificateStatistics,
type CertType
type CertificateStatistics
} from '@/api/pl/quota-cert'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import { useServerColumnFilters } from '@/composables/useServerColumnFilters'
@@ -158,10 +198,14 @@
import ListQuickSearchInput from '@/components/business/list-quick-search-input/index.vue'
import ListToolbarEndActions from '@/components/business/list-toolbar-end-actions/index.vue'
import ColumnHeaderFilter from '@/components/business/column-header-filter/index.vue'
import ContractScopeDialog from '../quota-cert/ContractScopeDialog.vue'
import { bindingPayload, formatCertQty } from '../quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import ContractCertLinkDialog from './ContractCertLinkDialog.vue'
import StatisticsDetail from './StatisticsDetail.vue'
import { createStatisticsLoader } from './loader'
import { statusLabel, contractTypeLabel } from './labels'
import { expiryWarning } from '../quota-cert/cert-list-face'
const props = withDefaults(
defineProps<{
mode: 'contract' | 'certificate'
@@ -172,6 +216,7 @@
{ active: true }
)
const user = useUserStore()
const router = useRouter()
const allowed = ref(false),
canEdit = ref(false),
loading = ref(false),
@@ -179,7 +224,6 @@
keyword = ref(''),
page = ref(1),
total = ref(0)
const certType = ref<CertType>('purchase')
const rows = ref<Record<string, any>[]>([])
const fixedDetail = ref<ContractStatistics>()
const details = reactive<
@@ -188,35 +232,115 @@
{ loading: boolean; error?: boolean; data?: ContractStatistics | CertificateStatistics }
>
>({})
const editingContractId = ref(''),
sessionKey = ref(0)
const scopeDialog = ref<InstanceType<typeof ContractScopeDialog>>()
const sessionKey = ref(0)
const linkDialog = ref<InstanceType<typeof ContractCertLinkDialog>>()
const linkSaving = ref(false)
const loader = createStatisticsLoader(quotaStatisticsApi)
let epoch = 0
const searchColumn = props.mode === 'contract' ? 'contractNo' : 'certNo'
const columns: ColumnFilterDef[] = (
function unitChoices() {
try {
return (useDictStore().getOptions('crm_product_unit') || []).map(
(item: { value: string; label: string }) => ({ value: item.value, label: item.label })
)
} catch {
return []
}
}
const contractTypeOptions = [
{ value: 'sale', label: '销售合同' },
{ value: 'purchase', label: '采购合同' },
{ value: 'framework_sale', label: '框架销售合同' },
{ value: 'framework_purchase', label: '框架采购合同' },
{ value: 'framework', label: '框架合同' }
]
const certStatusOptions = [
{ value: 'draft', label: '草稿' },
{ value: 'active', label: '有效' },
{ value: 'suspended', label: '停用' },
{ value: 'closed', label: '已核销' },
{ value: 'void', label: '作废' }
]
const text = (prop: string, label: string): ColumnFilterDef => ({
prop,
label,
type: 'text',
queryKey: prop
})
const number = (prop: string, label: string): ColumnFilterDef => ({
prop,
label,
type: 'number',
queryKey: prop
})
const columns: ColumnFilterDef[] =
props.mode === 'contract'
? [
['contractNo', '合同编号'],
['contractName', '合同名称'],
['contractType', '合同类型'],
['certCount', '关联证件数']
text('contractNo', '合同编号'),
text('contractName', '合同名称'),
{
prop: 'contractType',
label: '合同类型',
type: 'enum',
queryKey: 'contractType',
enumOptions: contractTypeOptions
},
number('certCount', '关联证件数')
]
: [
['certNo', '证件编号'],
['productNameOnCert', '证载品名'],
['quantityUnit', '单位'],
['totalQty', '全证核定'],
['reservedQty', '全证预占'],
['usedQty', '全证已用'],
['availableQty', '全证共享余额'],
['status', '状态'],
['validFrom', '有效期起'],
['validTo', '有效期止']
text('certNo', '证件编号'),
{
prop: 'certType',
label: '证件类型',
type: 'enum',
queryKey: 'certType',
enumOptions: [
{ value: 'purchase', label: '购买证' },
{ value: 'transport', label: '运输证' }
]
},
text('salePartyName', '销售单位'),
text('buyPartyName', '购买单位'),
text('validUseText', '有效次数'),
{
prop: 'expiryAlert',
label: '是否预警',
type: 'enum',
queryKey: 'expiryAlert',
enumOptions: [
{ value: 'yes', label: '7天内到期' },
{ value: 'no', label: '未预警' }
]
},
text('productNameOnCert', '证载品名'),
{ prop: 'quantityUnit', label: '单位', type: 'enum', queryKey: 'quantityUnit' },
number('totalQty', '全证核定'),
number('reservedQty', '全证预占'),
number('usedQty', '全证已用'),
number('availableQty', '全证共享余额'),
{
prop: 'status',
label: '状态',
type: 'enum',
queryKey: 'status',
enumOptions: certStatusOptions
},
{
prop: 'validFrom',
label: '有效期起',
type: 'datetime',
queryKeyFrom: 'validFromFrom',
queryKeyTo: 'validFromTo'
},
{
prop: 'validTo',
label: '有效期止',
type: 'datetime',
queryKeyFrom: 'validToFrom',
queryKeyTo: 'validToTo'
}
]
).map(([prop, label]) => ({ prop, label, type: 'text', queryKey: prop }))
const { visibleColumns, checkAll, isIndeterminate, resetToDefault } = usePersistedListColumns(
`pl-${props.mode}-statistics-v1`,
`pl-${props.mode}-statistics-${props.mode === 'certificate' ? 'v3' : 'v1'}`,
columns
)
const visibleDefs = computed(() => columns.filter((c) => visibleColumns.value.includes(c.prop)))
@@ -228,11 +352,23 @@
isFilterActive,
toQueryParams,
watchVisibleColumns
} = useServerColumnFilters(
columns.filter((c) => c.prop === searchColumn),
{ onChange: search }
)
} = useServerColumnFilters(columns, { onChange: search })
watchVisibleColumns(visibleColumns)
const qtyColumnProps = new Set(['totalQty', 'reservedQty', 'usedQty', 'availableQty'])
function expiryText(row: { validTo?: string | null }) {
return expiryWarning(row.validTo)?.label || ''
}
function isQtyColumn(prop: string) {
return qtyColumnProps.has(prop)
}
function unitText(unit?: string | null) {
try {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '—' : label
} catch {
return unit || '—'
}
}
function clearResults() {
loader.invalidate()
epoch++
@@ -261,8 +397,7 @@
page: page.value,
pageSize: 20,
keyword: keyword.value,
...toQueryParams(),
...(props.mode === 'certificate' ? { certType: certType.value } : {})
...toQueryParams()
}
})
if (current !== epoch || !data) return
@@ -309,10 +444,85 @@
clearAllFilters()
search()
}
async function edit(id: string) {
editingContractId.value = id
await nextTick()
void scopeDialog.value?.open(id)
function openNewCert() {
router.push({ name: 'PlQuotaCert', query: { create: '1' } })
}
function openCreate(detail?: ContractStatistics) {
if (!detail?.id) return
void linkDialog.value?.open({
contractId: detail.id,
contractNo: detail.contractNo,
contractName: detail.contractName,
mode: 'create'
})
}
function openEdit(
detail: ContractStatistics | undefined,
cert: ContractStatistics['certificates'][number]
) {
if (!detail?.id || cert.referenced || !cert.bindingId) return
void linkDialog.value?.open({
contractId: detail.id,
contractNo: detail.contractNo,
contractName: detail.contractName,
mode: 'edit',
certType: cert.certType,
certId: cert.certId,
certNo: cert.certNo
})
}
async function changeLink(
detail: ContractStatistics | undefined,
cert: ContractStatistics['certificates'][number],
action: 'delete' | 'inactive' | 'active'
) {
if (!detail?.id || linkSaving.value || !cert.bindingId) return
if (action === 'delete' && cert.referenced) return
if (action !== 'delete' && !cert.referenced) return
const message =
action === 'delete'
? `删除后,合同 ${detail.contractNo} 不能再使用 ${cert.certNo} 安排新的运输。只有从未被运输计划用过的关联才能删除。`
: action === 'inactive'
? `设为不可用后,合同 ${detail.contractNo} 不能再使用 ${cert.certNo} 安排新的运输。已经预占和核销的数量仍保留。`
: `恢复后,合同 ${detail.contractNo} 可以再使用 ${cert.certNo} 安排新的运输。历史用量不变。`
try {
await ElMessageBox.confirm(message, action === 'delete' ? '删除关联' : '调整关联', {
type: 'warning',
confirmButtonText: action === 'delete' ? '删除' : '确定',
cancelButtonText: '取消'
})
} catch {
return
}
linkSaving.value = true
try {
const existing = await quotaCertApi.bindings(detail.id)
const matched = existing.some(
(row) => row.certType === cert.certType && row.certId === cert.certId
)
if (!matched) {
ElMessage.warning('关联已变化,请刷新后再操作')
await load()
return
}
const next =
action === 'delete'
? existing.filter(
(row) => !(row.certType === cert.certType && row.certId === cert.certId)
)
: existing.map((row) =>
row.certType === cert.certType && row.certId === cert.certId
? { ...row, linkStatus: action }
: row
)
await quotaCertApi.saveBindings(detail.id, bindingPayload(next))
ElMessage.success(
action === 'delete' ? '关联已删除' : action === 'inactive' ? '已设为不可用' : '已恢复可安排'
)
await load()
} finally {
linkSaving.value = false
}
}
async function init() {
clear()
@@ -362,10 +572,34 @@
</script>
<style scoped>
.cert-list-toolbar-row,
.contract-quota-toolbar {
flex-wrap: nowrap;
align-items: center;
min-width: 0;
}
.cert-list-toolbar-row {
overflow: hidden;
}
.contract-quota-toolbar__tip {
margin-left: auto;
max-width: 62%;
color: var(--mint-text-muted, #64748b);
font-size: 13px;
line-height: 1.5;
text-align: right;
}
.statistics-expansion {
box-sizing: border-box;
max-width: 100%;
padding: 16px;
padding: 12px 16px 16px;
text-align: left;
> .el-button {
margin-bottom: 12px;
}
}
</style>
@@ -2,12 +2,18 @@
<el-table :data="products" stripe class="list-table" row-key="id" empty-text="暂无合同产品范围">
<el-table-column prop="productName" label="绑定合同产品" min-width="180" />
<el-table-column prop="model" label="规格" min-width="140" />
<el-table-column prop="unit" label="产品单位" min-width="90" />
<el-table-column label="产品单位" min-width="90"
><template #default="{ row }">{{ unitText(row.unit) }}</template></el-table-column
>
<el-table-column label="额度单位" min-width="90"
><template #default>{{ quantityUnit }}</template></el-table-column
>
<el-table-column prop="reservedQty" label="预占" min-width="120" />
<el-table-column prop="usedQty" label="已用" min-width="120" />
<el-table-column label="预占" min-width="120"
><template #default="{ row }">{{ formatCertQty(row.reservedQty) }}</template></el-table-column
>
<el-table-column label="已用" min-width="120"
><template #default="{ row }">{{ formatCertQty(row.usedQty) }}</template></el-table-column
>
<el-table-column label="范围状态" min-width="130"
><template #default="{ row }"
><el-tag size="small" :type="row.scopeStatus === 'active' ? 'success' : 'info'">{{
@@ -23,5 +29,12 @@
</template>
<script setup lang="ts">
import type { StatisticsProduct } from '@/api/pl/quota-cert'
import { formatCertQty } from '../quota-cert/model'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
defineProps<{ products: StatisticsProduct[]; quantityUnit: string }>()
function unitText(unit?: string | null) {
const label = getProductUnitLabel(useDictStore().getLabel, unit)
return !label || label === '—' ? '—' : label
}
</script>
@@ -3,6 +3,7 @@ export const statusLabel = (value: string) =>
draft: '草稿',
active: '有效',
suspended: '停用',
closed: '已核销',
void: '作废',
reserved: '预占',
settled: '已核销',
@@ -13,13 +14,13 @@ export const statusLabel = (value: string) =>
cancelled: '已取消'
})[value] || value
export const contractTypeOptions = [
{ value: 'sale', label: '销售合同' },
{ value: 'purchase', label: '采购合同' },
{ value: 'framework_sale', label: '框架销售合同' },
{ value: 'framework_purchase', label: '框架采购合同' },
{ value: 'framework', label: '框架合同' }
]
export const contractTypeLabel = (value?: string | null) =>
({
sale: '销售合同',
purchase: '采购合同',
framework_sale: '框架销售合同',
framework_purchase: '框架采购合同',
framework: '框架合同'
})[value || ''] ||
value ||
'—'
contractTypeOptions.find((item) => item.value === value)?.label || value || '—'
@@ -1,6 +1,37 @@
<!-- 自有车辆加油量、里程、月度/季度油耗,与 index(7).html 对齐 -->
<template>
<div v-loading="loading" class="fuel-plate-cards-wrap">
<div class="fuel-plate-cards-wrap">
<div class="fuel-month-bar">
<span class="fuel-month-label">统计月份</span>
<div class="fuel-month-control">
<el-button
class="fuel-month-step"
:disabled="month <= '1900-01'"
aria-label="上个月"
@click="shiftMonth(-1)"
>
<el-icon><ArrowLeft /></el-icon>
</el-button>
<el-date-picker
:model-value="month"
type="month"
value-format="YYYY-MM"
format="YYYY年MM月"
:clearable="false"
aria-label="统计月份"
@update:model-value="handleMonthChange"
/>
<el-button
class="fuel-month-step"
:disabled="month >= '2100-12'"
aria-label="下个月"
@click="shiftMonth(1)"
>
<el-icon><ArrowRight /></el-icon>
</el-button>
</div>
</div>
<div v-loading="loading" class="fuel-plate-body">
<div v-if="error" class="fuel-plate-error">{{ error }}</div>
<div v-else-if="!loading && !items.length" class="fuel-plate-empty">暂无自有车辆</div>
<div v-else class="fuel-plate-grid">
@@ -53,12 +84,14 @@
</div>
</article>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import type { VehicleFuelPlateMonthItem } from '@/api/pl'
import { formatPlVehiclePlateDisplay } from '@/utils/pl-display'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import {
fuelComparison,
formatFuelRate,
@@ -71,6 +104,7 @@
const props = withDefaults(
defineProps<{
items: VehicleFuelPlateMonthItem[]
month: string
loading?: boolean
error?: string
selectedPlate?: string
@@ -80,8 +114,24 @@
const emit = defineEmits<{
select: [plate: string | null]
'update:month': [month: string]
}>()
function handleMonthChange(value: string | null) {
if (!value || value === props.month) return
emit('update:month', value)
}
function shiftMonth(offset: number) {
const match = /^(\d{4})-(\d{2})$/.exec(props.month)
if (!match) return
const index = Number(match[1]) * 12 + (Number(match[2]) - 1) + offset
const year = Math.floor(index / 12)
const month = index - year * 12 + 1
if (year < 1900 || year > 2100) return
handleMonthChange(`${year}-${String(month).padStart(2, '0')}`)
}
const cards = computed(() =>
props.items.map((item) => ({
...item,
@@ -145,6 +195,41 @@
margin: 16px 16px 16px;
}
.fuel-month-bar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.fuel-month-label {
font-size: 14px;
line-height: 22px;
color: var(--el-text-color-regular);
}
.fuel-month-control {
display: inline-flex;
align-items: center;
gap: 6px;
}
.fuel-month-step {
width: 36px;
min-width: 36px;
height: 36px;
padding: 0;
margin: 0;
}
.fuel-month-bar :deep(.el-date-editor) {
width: 160px;
}
.fuel-plate-body {
min-height: 48px;
}
.fuel-plate-error,
.fuel-plate-empty {
padding: 8px 0;
@@ -4,10 +4,12 @@
<section class="panel">
<FuelPlateMonthCards
v-if="SHOW_FUEL_PLATE_MONTH_CARDS && !isMineMode"
:month="summaryMonth"
:items="plateSummaryItems"
:loading="plateSummaryLoading"
:error="plateSummaryError"
:selected-plate="selectedPlateFromFilter"
@update:month="handleSummaryMonthChange"
@select="handlePlateCardSelect"
/>
@@ -663,6 +665,18 @@ const plateSummaryItems = ref<VehicleFuelPlateMonthItem[]>([])
const plateSummaryLoading = ref(false)
const plateSummaryError = ref('')
function currentYearMonth() {
const now = new Date()
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
}
const summaryMonth = ref(currentYearMonth())
function handleSummaryMonthChange(month: string) {
summaryMonth.value = month || currentYearMonth()
fetchPlateSummary()
}
const selectedPlateFromFilter = computed(() => {
const s = filters.licensePlate as { text?: string } | undefined
return String(s?.text || '').trim()
@@ -673,7 +687,7 @@ async function fetchPlateSummary() {
plateSummaryLoading.value = true
plateSummaryError.value = ''
try {
const res = await vehicleFuelRegisterApi.plateMonthSummary()
const res = await vehicleFuelRegisterApi.plateMonthSummary(summaryMonth.value)
const data = (res as { data?: { items?: VehicleFuelPlateMonthItem[] } }).data ?? res
plateSummaryItems.value = (data as { items?: VehicleFuelPlateMonthItem[] }).items || []
} catch (e: unknown) {