This commit is contained in:
Your Name
2026-12-02 09:27:53 +08:00
parent 1e165a7894
commit 91e35cb905
21 changed files with 1780 additions and 421 deletions
+26 -3
View File
@@ -633,7 +633,7 @@ export function prescriptionOrderExport(params: any) {
}
/**
* 诊单下可关联的支付单(已支付 zyt_order;已占用且未撤回的会排除;编辑时传 prescription_order_id 保留当前单已选)。
* 诊单下可关联的支付单(已支付 zyt_order;已关联其他业务订单的会排除;编辑时传 prescription_order_id 保留当前单已选)。
* 服务端仅返回创建时间在 2026-04-20(含)之后的支付单;编辑时本单已关联的旧单仍会出现在列表中。
*/
export function prescriptionOrderPaidPayOrders(params: {
@@ -662,8 +662,27 @@ export function prescriptionOrderLogisticsJdUpdate(params: { id: number }) {
return request.post({ url: '/tcm.prescriptionOrder/logisticsJdUpdate', params })
}
export function prescriptionOrderDetail(params: { id: number }) {
return request.get({ url: '/tcm.prescriptionOrder/detail', params })
export function prescriptionOrderDetail(params: { id: number; prescription_id?: number }, signal?: AbortSignal) {
return request.get({ url: '/tcm.prescriptionOrder/detail', params, signal }, signal ? { ignoreCancelToken: true } : undefined)
}
export interface PrescriptionBindingOrder {
id: number
order_no: string
fulfillment_status: number
is_primary: boolean
is_linked: boolean
}
export function prescriptionOrdersForBinding(params: { prescription_id: number; order_no?: string }, signal: AbortSignal) {
return request.get<{ orders: PrescriptionBindingOrder[]; can_bind: boolean }>(
{ url: '/tcm.prescriptionOrder/prescriptionOrdersForBinding', params, signal },
{ ignoreCancelToken: true }
)
}
export function prescriptionOrderBindPrescription(params: { id: number; prescription_id: number }) {
return request.post({ url: '/tcm.prescriptionOrder/bindPrescription', params })
}
export function prescriptionOrderEdit(params: Record<string, unknown>) {
@@ -836,6 +855,10 @@ export function prescriptionOrderUnlinkPayOrder(params: { id: number; pay_order_
return request.post({ url: '/tcm.prescriptionOrder/unlinkPayOrder', params })
}
export function prescriptionOrderAttachReceipt(params: { id: number; pay_order_id: number }) {
return request.post({ url: '/tcm.prescriptionOrder/attachReceipt', params })
}
/** 修改订单金额 */
export function prescriptionOrderUpdateAmount(params: { id: number; amount: number }) {
return request.post({ url: '/tcm.prescriptionOrder/updateAmount', params })
@@ -0,0 +1,27 @@
<template>
<label v-if="options.length > 1 || (options.length === 1 && !options[0].is_primary)" class="flex flex-wrap items-center gap-2">
<span class="text-sm text-gray-600">订单处方</span>
<el-select
:model-value="modelValue || undefined"
:disabled="disabled"
aria-label="订单处方"
placeholder="请选择处方"
class="w-[270px] max-w-full"
@change="emit('change', $event)"
>
<el-option
v-for="entry in options"
:key="entry.id"
:value="entry.id"
:label="`${entry.is_primary ? '业务主处方' : '关联处方'} · ${entry.sn || '#' + entry.id}${Number(entry.void_status) === 1 ? '(已作废)' : ''}`"
/>
</el-select>
</label>
</template>
<script setup lang="ts">
import type { LinkedPrescription } from './useLinkedOrderPrescription'
defineProps<{ options: LinkedPrescription[]; modelValue: number; disabled?: boolean }>()
const emit = defineEmits<{ change: [id: number] }>()
</script>
@@ -0,0 +1,177 @@
<template>
<el-dialog
v-model="visible"
title="关联业务订单"
width="min(640px, calc(100vw - 24px))"
append-to-body
destroy-on-close
:close-on-click-modal="false"
:close-on-press-escape="!binding"
:show-close="!binding"
>
<p class="mb-4 text-sm text-gray-500">处方 {{ prescriptionNo }}</p>
<section v-loading="loading && !initialized" aria-label="已关联业务订单">
<h3 class="mb-2 text-sm font-medium">已关联订单</h3>
<p v-if="error && !initialized" class="text-sm text-red-600" role="alert">
加载关联订单失败。<el-button link type="primary" @click="loadOrders()">重试</el-button>
</p>
<el-table v-else :data="linkedOrders" size="small" max-height="280" empty-text="暂无关联订单">
<el-table-column label="业务订单号" prop="order_no" min-width="155" />
<el-table-column label="履约状态" min-width="90">
<template #default="{ row }">{{ fulfillmentText(row.fulfillment_status) }}</template>
</el-table-column>
<el-table-column label="处方关系" min-width="95">
<template #default="{ row }">{{ row.is_primary ? '业务主处方' : '关联处方' }}</template>
</el-table-column>
<el-table-column v-if="canViewDetails" label="操作" width="64" fixed="right">
<template #default="{ row }">
<el-button link type="primary" :disabled="binding" @click="viewOrder(row)">详情</el-button>
</template>
</el-table-column>
</el-table>
</section>
<section v-if="canBind" class="mt-5 border-t border-gray-100 pt-4" aria-label="绑定现有业务订单">
<h3 class="mb-2 text-sm font-medium">绑定现有业务订单</h3>
<p class="mb-3 text-sm text-gray-500">可绑定同一患者的订单,原处方须已作废或处方审核已驳回。</p>
<el-select
v-model="selectedOrderId"
class="w-full"
aria-label="选择要绑定的业务订单"
placeholder="搜索订单号或选择订单"
filterable
remote
clearable
:remote-method="searchOrders"
:loading="loading"
:disabled="binding"
:no-data-text="error ? '加载失败,请重新搜索' : '未找到原处方已作废或处方审核已驳回的订单'"
>
<el-option
v-for="order in candidates"
:key="order.id"
:value="order.id"
:label="`${order.order_no} · ${fulfillmentText(order.fulfillment_status)}`"
/>
</el-select>
</section>
<template #footer>
<el-button :disabled="binding" @click="visible = false">关闭</el-button>
<el-button
v-if="canBind"
type="primary"
:loading="binding"
:disabled="loading || !selectedOrderId"
@click="bindOrder"
>绑定订单</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { prescriptionOrderBindPrescription, prescriptionOrdersForBinding, type PrescriptionBindingOrder } from '@/api/tcm'
import feedback from '@/utils/feedback'
import { hasPermission } from '@/utils/perm'
import { fulfillmentText } from './prescription-order-utils'
const emit = defineEmits<{ bound: [] }>()
const router = useRouter()
const visible = ref(false)
const loading = ref(false)
const initialized = ref(false)
const error = ref(false)
const binding = ref(false)
const prescriptionId = ref(0)
const prescriptionNo = ref('')
const linkedOrders = ref<PrescriptionBindingOrder[]>([])
const candidates = ref<PrescriptionBindingOrder[]>([])
const selectedOrderId = ref<number>()
const bindingAllowed = ref(false)
const canBind = computed(() => bindingAllowed.value && hasPermission([
'tcm.prescriptionOrder/prescriptionOrdersForBinding', 'tcm.prescriptionOrder/bindPrescription'
]))
const orderListRoute = computed(() => router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists'))
const canViewDetails = computed(() => Boolean(orderListRoute.value) && hasPermission(['tcm.prescriptionOrder/detail']))
let activeRequest: AbortController | undefined
function open(row: { id: number; sn?: string }) {
const id = Number(row.id)
if (!Number.isSafeInteger(id) || id <= 0 || binding.value) return
prescriptionId.value = id
prescriptionNo.value = row.sn || `#${id}`
linkedOrders.value = []
candidates.value = []
selectedOrderId.value = undefined
bindingAllowed.value = false
initialized.value = false
visible.value = true
void loadOrders()
}
async function loadOrders(query = '') {
activeRequest?.abort()
const request = new AbortController()
activeRequest = request
loading.value = true
error.value = false
const orderNo = query.trim()
try {
const result = await prescriptionOrdersForBinding(
{ prescription_id: prescriptionId.value, ...(orderNo ? { order_no: orderNo } : {}) },
request.signal
)
if (request.signal.aborted) return
if (!orderNo) linkedOrders.value = result.orders.filter((order) => order.is_linked)
candidates.value = result.orders.filter((order) => !order.is_linked)
bindingAllowed.value = result.can_bind
if (!candidates.value.some((order) => order.id === selectedOrderId.value)) selectedOrderId.value = undefined
initialized.value = true
} catch {
if (request.signal.aborted) return
candidates.value = []
selectedOrderId.value = undefined
error.value = true
} finally {
if (!request.signal.aborted) loading.value = false
}
}
function searchOrders(query: string) {
if (canBind.value && !binding.value) void loadOrders(query)
}
async function bindOrder() {
const selected = candidates.value.find((order) => order.id === selectedOrderId.value)
if (!selected || !canBind.value || loading.value || binding.value) return
binding.value = true
try {
await prescriptionOrderBindPrescription({ id: selected.id, prescription_id: prescriptionId.value })
linkedOrders.value.unshift({ ...selected, is_linked: true })
feedback.msgSuccess('业务订单已绑定')
selectedOrderId.value = undefined
emit('bound')
await loadOrders()
} catch {
// 请求拦截器显示失败原因。
} finally {
binding.value = false
}
}
function viewOrder(order: PrescriptionBindingOrder) {
const path = orderListRoute.value?.path
if (!path || !canViewDetails.value) return
visible.value = false
void router.push({ path, query: { review_order: order.id, review_prescription: prescriptionId.value } })
}
watch(visible, (show) => {
if (!show) activeRequest?.abort()
}, { flush: 'sync' })
onScopeDispose(() => activeRequest?.abort())
defineExpose({ open })
</script>
@@ -42,7 +42,7 @@
</div>
<div v-if="detailData" class="flex items-center gap-2 mr-6">
<!-- 完整版:处方审核 / 支付审核 / 发货 / 退款等操作按钮 -->
<slot name="header-actions" :detail="detailData" />
<slot name="header-actions" :detail="detailData" :is-primary-prescription="isPrimaryPrescription" />
</div>
</div>
</template>
@@ -201,22 +201,22 @@
<!-- 左侧:处方单 -->
<el-card shadow="never" class="po-panel po-panel-rx border-gray-100 h-full relative overflow-hidden">
<!-- 处方审核印章 -->
<div v-if="detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
<div class="stamp-inner">审核通过</div>
</div>
<div v-if="detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
<div class="stamp-inner">已驳回</div>
</div>
<template #header>
<div class="flex items-center justify-between">
<div class="flex items-center gap-3">
<span class="font-medium text-[15px]">处方详情</span>
<span v-if="detailData.doctor_name" class="text-xs text-gray-500">
开方人:<span class="text-primary font-medium">{{ detailData.doctor_name }}</span>
<span v-if="detailPrescriptionDoctor" class="text-xs text-gray-500">
开方人:<span class="text-primary font-medium">{{ detailPrescriptionDoctor }}</span>
</span>
<el-button
v-if="
!readonly &&
!readonly && isPrimaryPrescription &&
detailData.prescription_id &&
detailPrescription &&
!String(detailData.prescription_detail_error || '').trim()
@@ -230,16 +230,17 @@
改患者信息
</el-button>
<el-button
v-if="!readonly && detailData.prescription_id && showPrescriptionAuditFilter"
v-if="!readonly && selectedPrescriptionId && showPrescriptionAuditFilter"
type="primary"
size="small"
link
@click="emit('view-prescription')"
:disabled="linkedPrescriptionLoading"
@click="emit('view-prescription', selectedPrescriptionId)"
>
详细
</el-button>
<el-button
v-if="!readonly && detailData.id && showPrescriptionAuditFilter"
v-if="!readonly && isPrimaryPrescription && detailData.id && showPrescriptionAuditFilter"
type="warning"
size="small"
link
@@ -250,17 +251,26 @@
测试价格
</el-button>
</div>
<span class="text-xs text-gray-400">ID: {{ detailData.prescription_id || '—' }}</span>
<span class="text-xs text-gray-400">ID: {{ selectedPrescriptionId || '—' }}</span>
</div>
</template>
<LinkedOrderPrescriptionSelect
:options="linkedPrescriptionOptions"
:model-value="selectedPrescriptionId"
class="mb-3"
@change="selectLinkedPrescription"
/>
<el-skeleton v-if="linkedPrescriptionLoading" :rows="5" animated />
<el-alert
v-if="!readonly && String(detailData.prescription_detail_error || '').trim()"
:title="detailData.prescription_detail_error"
v-else-if="(!readonly || !isPrimaryPrescription) && selectedPrescriptionError"
:title="selectedPrescriptionError"
type="warning"
:closable="false"
show-icon
class="mb-3"
/>
>
<el-button v-if="!isPrimaryPrescription" link type="primary" @click="selectLinkedPrescription(selectedPrescriptionId)">重试</el-button>
</el-alert>
<template v-else-if="detailPrescription">
<el-descriptions :column="2" border size="small" class="po-desc bg-white">
<el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
@@ -271,13 +281,13 @@
<el-descriptions-item label="手机">
<span
:class="
detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
isPrimaryPrescription && detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
"
>
{{ detailPrescription.phone || '—' }}
</span>
<el-tag
v-if="detailRecipientRxPhoneMismatch"
v-if="isPrimaryPrescription && detailRecipientRxPhoneMismatch"
type="danger"
size="small"
effect="dark"
@@ -293,7 +303,8 @@
{{ detailPrescription.clinical_diagnosis || '—' }}
</el-descriptions-item>
<el-descriptions-item label="剂数 / 用法" :span="2" v-if="showPrescriptionAuditFilter">
{{ detailData.dose_count ?? detailPrescription.dose_count ?? '—' }} {{ detailData.dose_unit || '剂' }} ·
{{ (isPrimaryPrescription ? detailData.dose_count ?? detailPrescription.dose_count : detailPrescription.dose_count) ?? '—' }}
{{ (isPrimaryPrescription ? detailData.dose_unit : detailPrescription.dose_unit) || '剂' }} ·
{{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
</el-descriptions-item>
<el-descriptions-item label="处方金额">
@@ -313,7 +324,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-if="!readonly && isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
@@ -337,7 +348,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-if="!readonly && isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
@@ -362,7 +373,7 @@
<span>服用方式</span>
<el-button
v-if="
!readonly &&
!readonly && isPrimaryPrescription &&
detailData.prescription_id &&
detailPrescription &&
!String(detailData.prescription_detail_error || '').trim()
@@ -416,7 +427,7 @@
}}
</div>
</template>
<div>
<div v-if="isPrimaryPrescription">
<span class="text-gray-500">订单设置:</span>
{{
detailData.medication_days != null &&
@@ -500,6 +511,17 @@
{{ formatOrderTime(row.create_time) }}
</template>
</el-table-column>
<el-table-column v-if="!readonly && canAttachReceipt" label="操作" width="86" fixed="right" align="center">
<template #default="{ row }">
<el-button
link
type="primary"
:loading="linkingReceiptId === Number(row.id)"
:disabled="changingReceipts"
@click="confirmAttachReceipt(row)"
>关联</el-button>
</template>
</el-table-column>
</el-table>
<el-empty v-else description="无未关联的收款单" :image-size="60" />
</el-card>
@@ -563,16 +585,15 @@
{{ formatOrderTime(row.create_time) }}
</template>
</el-table-column>
<el-table-column v-if="canUnlinkPayOrder" label="操作" width="80" fixed="right" align="center">
<el-table-column v-if="!readonly && canUnlinkReceipt" label="操作" width="80" fixed="right" align="center">
<template #default="{ row }">
<el-button
type="danger"
size="small"
link
:loading="unlinkPayOrderId === Number(row.id)"
:disabled="unlinkPayOrderId !== null || ![2, 4, 5].includes(Number(row.status))"
:title="Number(row.status) === 4 ? '解除已退款收款记录的关联,已付金额不变' : '解除关联并更新已付金额,总金额不变'"
@click="confirmUnlinkPayOrder(row)"
:loading="unlinkingReceiptId === Number(row.id)"
:disabled="changingReceipts || ![2, 4, 5].includes(Number(row.status))"
@click="confirmUnlinkReceipt(row)"
>移除</el-button>
</template>
</el-table-column>
@@ -1085,13 +1106,14 @@ import {
prescriptionOrderAddLog,
prescriptionOrderLogisticsTrace,
prescriptionOrderLogisticsJdUpdate,
prescriptionOrderPaidPayOrders,
prescriptionOrderUnlinkPayOrder,
prescriptionOrderPatchPrescriptionUsage
} from '@/api/tcm'
import { getDictData } from '@/api/app'
import feedback from '@/utils/feedback'
import useUserStore from '@/stores/modules/user'
import LinkedOrderPrescriptionSelect from './LinkedOrderPrescriptionSelect.vue'
import { useLinkedOrderPrescription } from './useLinkedOrderPrescription'
import { usePrescriptionOrderReceipts } from './usePrescriptionOrderReceipts'
import {
TCM_ASSISTANT_ROLE_ID,
PRESCRIPTION_AUDIT_ROLE_IDS,
@@ -1149,13 +1171,13 @@ defineSlots<{
/** 抽屉头部左侧扩展(完整版的发货类型切换等) */
'header-extra'?: (props: { detail: any }) => any
/** 抽屉头部右侧操作按钮(审核/发货/退款等) */
'header-actions'?: (props: { detail: any }) => any
'header-actions'?: (props: { detail: any; isPrimaryPrescription: boolean }) => any
}>()
const emit = defineEmits<{
(e: 'update-amount'): void
(e: 'patch-rx-patient'): void
(e: 'view-prescription'): void
(e: 'view-prescription', prescriptionId: number): void
(e: 'test-gancao-preview'): void
(e: 'view-patient'): void
(e: 'detail-changed'): void
@@ -1178,46 +1200,35 @@ const showPrescriptionAuditFilter = computed(() => {
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<Record<string, any> | null>(null)
const detailLogs = ref<any[]>([])
const detailUnlinkedPayOrders = ref<any[]>([])
const unlinkPayOrderId = ref<number | null>(null)
const canUnlinkPayOrder = computed(() =>
!props.readonly && canUpdateAmount(detailData.value) && hasPerm('tcm.prescriptionOrder/unlinkPayOrder')
const {
options: linkedPrescriptionOptions,
selectedId: selectedPrescriptionId,
isPrimary: isPrimaryPrescription,
prescription: detailPrescription,
loading: linkedPrescriptionLoading,
detailError: selectedPrescriptionError,
herbsVisible: detailHerbsVisible,
reset: resetLinkedPrescription,
select: selectLinkedPrescription
} = useLinkedOrderPrescription(detailData, detailVisible, computed(() => !props.detailLoader))
const detailPrescriptionDoctor = computed(() =>
isPrimaryPrescription.value ? detailData.value?.doctor_name : detailPrescription.value?.doctor_name
)
async function confirmUnlinkPayOrder(row: { id: number; order_no?: string; amount: number | string; status: number | string }) {
const orderId = Number(detailData.value?.id)
const payOrderId = Number(row.id)
if (!canUnlinkPayOrder.value || !orderId || !payOrderId || unlinkPayOrderId.value !== null) return
if (![2, 4, 5].includes(Number(row.status))) return
unlinkPayOrderId.value = payOrderId
try {
await feedback.confirm(
`确定移除收款记录「${row.order_no || '#' + payOrderId}」(¥${formatMoney(row.amount)})?` +
'仅解除关联,原收款记录保留;订单总金额不变,已付金额与需代收金额按剩余关联收款重新计算。'
)
if (!detailVisible.value || Number(detailData.value?.id) !== orderId) return
const res: any = await prescriptionOrderUnlinkPayOrder({ id: orderId, pay_order_id: payOrderId })
const updated = res?.data ?? res
if (Number(detailData.value?.id) === orderId && Number(updated?.id) === orderId) {
Object.assign(detailData.value!, updated)
}
feedback.msgSuccess('收款关联已移除,金额已同步更新')
emit('detail-changed')
await refreshIfCurrent(orderId)
} catch {
/* 取消不提交;接口错误由拦截器提示,保留当前收款记录 */
} finally {
unlinkPayOrderId.value = null
}
}
const detailPrescription = computed(() => {
const p = detailData.value?.prescription
return p && typeof p === 'object' ? p : null
const detailLogs = ref<any[]>([])
const {
unlinkedReceipts: detailUnlinkedPayOrders,
loadUnlinkedReceipts,
linkingReceiptId,
unlinkingReceiptId,
changingReceipts,
canAttachReceipt,
canUnlinkReceipt,
confirmAttachReceipt,
confirmUnlinkReceipt
} = usePrescriptionOrderReceipts(detailData, detailVisible, (orderId) => {
emit('detail-changed')
if (detailVisible.value && Number(detailData.value?.id) === orderId) void fetchLogs(orderId)
})
const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo))
const detailLinkedPayOrders = computed(() => {
@@ -1294,13 +1305,13 @@ const workflowFulfillStatus = computed(() => {
/** 详情抽屉:业务收货手机 vs 处方登记手机 */
const detailRecipientRxPhoneMismatch = computed(() => {
const rx = detailPrescription.value?.phone
const rx = detailData.value?.prescription?.phone
const biz = detailData.value?.recipient_phone
return recipientVsPrescriptionPhoneMismatch(biz, rx)
})
const detailPrescriptionPhoneDisplay = computed(() => {
const s = normalizeBizPhone(detailPrescription.value?.phone)
const s = normalizeBizPhone(detailData.value?.prescription?.phone)
return s || '—'
})
@@ -1377,7 +1388,7 @@ const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescri
const daysLocked = computed(() => detailData.value?.days_locked === true)
/** 处方已进入电子签署(内容冻结),服用参数改写为订单级覆盖值 */
const usageFrozenBySignature = computed(() => {
const esign = (detailPrescription.value as any)?.esign
const esign = detailData.value?.prescription?.esign
return esign?.required === true && esign?.status !== 'pending'
})
@@ -1390,9 +1401,6 @@ const detailAuxUsage = computed(() => {
return normalizeSlipAuxUsageForm(raw, rx.prescription_type || '浓缩水丸')
})
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
/** 内部成本(财务字段):仅完整版展示 */
const showInternalCost = computed(
() => !props.readonly && detailData.value?.internal_cost != null && detailData.value?.internal_cost !== ''
@@ -1466,6 +1474,7 @@ function canAddPrescriptionOrderLog() {
/** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */
const canSetRxAuditOnAddLog = computed(() => {
if (!isPrimaryPrescription.value) return false
if (Number(detailData.value?.prescription_audit_status) === 0
&& detailData.value?.can_review_prescription === false) return false
const u = userStore.userInfo
@@ -1534,6 +1543,7 @@ function openPatchUsageDialog() {
feedback.msgWarning('无处方数据')
return
}
if (rx.id && Number(rx.id) !== Number(ord.prescription_id)) return
const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day =
@@ -1668,28 +1678,6 @@ async function submitAddLog() {
}
}
// ─── 未关联支付单 ───
async function loadDetailUnlinkedPayOrders(diagnosisId: number, prescriptionOrderId: number, linkedIds: number[]) {
if (!diagnosisId) {
detailUnlinkedPayOrders.value = []
return
}
try {
const res: any = await prescriptionOrderPaidPayOrders({
diagnosis_id: diagnosisId,
prescription_order_id: prescriptionOrderId
})
const lists = res?.lists ?? res?.data?.lists ?? []
// 列表已由服务端限制;此处再过滤已关联项
const filtered = Array.isArray(lists)
? lists.filter((item: any) => !linkedIds.includes(item.id))
: []
detailUnlinkedPayOrders.value = filtered
} catch {
detailUnlinkedPayOrders.value = []
}
}
// ─── 物流轨迹 ───
const detailLogisticsExpress = ref<string>('auto')
const logisticsTraceLoading = ref(false)
@@ -1795,11 +1783,15 @@ function requestDetail(id: number) {
return props.detailLoader ? props.detailLoader({ id }) : prescriptionOrderDetail({ id })
}
async function open(id: number) {
let detailOpenRequest = 0
async function open(id: number, prescriptionId?: number) {
const request = ++detailOpenRequest
// 页面级同参数字典请求会取消抽屉挂载时的那次(axios 去重取消),打开时兜底重试
void loadServicePackageOptions()
// 显式彻底清空缓存,防止前一次弹窗的数据残留
detailData.value = null
resetLinkedPrescription()
detailUnlinkedPayOrders.value = []
bumpLogisticsTraceRequestToken()
detailLogisticsExpress.value = 'auto'
@@ -1810,6 +1802,7 @@ async function open(id: number) {
detailLoading.value = true
try {
const res: any = await requestDetail(id)
if (request !== detailOpenRequest || !detailVisible.value) return
const d = res?.data ?? res ?? null
detailData.value = d
if (d) {
@@ -1821,29 +1814,27 @@ async function open(id: number) {
}
if (props.loadRelatedData) fetchLogs(id)
// 加载未关联的支付单
const diagId = d.diagnosis_id
const linkedIds = d.pay_order_ids || []
if (props.loadRelatedData && diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, linkedIds)
}
if (props.loadRelatedData) void loadUnlinkedReceipts(d)
if (prescriptionId) void selectLinkedPrescription(prescriptionId)
}
} catch (e: any) {
if (request !== detailOpenRequest || !detailVisible.value) return
feedback.msgError(e?.message || '加载失败')
detailVisible.value = false
} finally {
detailLoading.value = false
if (request === detailOpenRequest) detailLoading.value = false
}
}
/** 静默刷新当前详情(含日志/未关联支付单;快递单号变化时重拉轨迹),供父页面操作成功后调用 */
async function refresh() {
const id = Number(detailData.value?.id)
const current = detailData.value
const id = Number(current?.id)
if (!id) return
try {
const res: any = await requestDetail(id)
const d = res?.data ?? res ?? null
if (!d) return
if (!d || detailData.value !== current) return
const prevTracking = String(detailData.value?.tracking_number || '').trim()
detailData.value = d
const nextTracking = String(d.tracking_number || '').trim()
@@ -1853,10 +1844,7 @@ async function refresh() {
void fetchLogisticsTrace()
}
if (props.loadRelatedData) await fetchLogs(id)
const diagId = d.diagnosis_id
if (props.loadRelatedData && diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
}
if (props.loadRelatedData) void loadUnlinkedReceipts(d)
} catch {
/* 静默失败,避免打断当前抽屉 */
}
@@ -168,6 +168,7 @@ export function logActionText(act: string) {
ship: '确认发货',
withdraw: '撤销',
link_pay_order: '关联支付单',
bind_prescription: '绑定关联处方',
unlink_pay_order: '移除收款关联',
completion_request: '完单申请',
auto_complete: '自动完成',
@@ -0,0 +1,89 @@
import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
import { prescriptionOrderDetail } from '@/api/tcm'
export interface LinkedPrescription {
id: number
sn: string
void_status: number
is_primary: boolean
}
export type OrderDetail = Record<string, any>
export function linkedPrescriptionOptions(order: OrderDetail | null): LinkedPrescription[] {
const entries: LinkedPrescription[] = Array.isArray(order?.linked_prescriptions) ? order.linked_prescriptions : []
return entries.map((entry) => ({
...entry,
id: Number(entry.id),
is_primary: Number(entry.id) === Number(order?.prescription_id)
}))
}
export async function loadLinkedOrderPrescription(orderId: number, prescriptionId: number, signal: AbortSignal) {
const response = await prescriptionOrderDetail({ id: orderId, prescription_id: prescriptionId }, signal)
const detail = response?.data ?? response
if (Number(detail?.id) !== orderId || Number(detail?.prescription?.id) !== prescriptionId) {
throw new Error(detail?.prescription_detail_error || '无法加载处方详情')
}
return detail as OrderDetail
}
export function useLinkedOrderPrescription(
order: Ref<OrderDetail | null>,
visible: Ref<boolean>,
enabled?: Ref<boolean>
) {
const options = computed(() => enabled?.value === false ? [] : linkedPrescriptionOptions(order.value))
const linkedId = ref(0)
const selectedId = computed(() => linkedId.value || Number(order.value?.prescription_id) || 0)
const isPrimary = computed(() => linkedId.value === 0)
const linkedDetail = ref<OrderDetail | null>(null)
const loading = ref(false)
const error = ref('')
const prescription = computed(() => isPrimary.value ? order.value?.prescription : linkedDetail.value?.prescription)
const detailError = computed(() => isPrimary.value ? String(order.value?.prescription_detail_error || '').trim() : error.value)
const herbsVisible = computed(() => (isPrimary.value ? order.value : linkedDetail.value)?.prescription_detail_herbs_visible !== false)
let activeRequest: AbortController | undefined
function reset() {
activeRequest?.abort()
linkedId.value = 0
linkedDetail.value = null
loading.value = false
error.value = ''
}
async function select(id: number) {
const orderId = Number(order.value?.id)
const option = options.value.find((entry) => entry.id === id)
if (!visible.value || !orderId || !option) return
reset()
if (option.is_primary) return
linkedId.value = id
const request = new AbortController()
activeRequest = request
loading.value = true
try {
const detail = await loadLinkedOrderPrescription(orderId, id, request.signal)
if (!request.signal.aborted) linkedDetail.value = detail
} catch (e) {
if (!request.signal.aborted) error.value = e instanceof Error ? e.message : '无法加载处方详情'
} finally {
if (!request.signal.aborted) loading.value = false
}
}
watch(visible, (show) => {
if (!show) reset()
}, { flush: 'sync' })
watch([() => order.value?.id, options], ([orderId, next], [previousOrderId]) => {
if (orderId !== previousOrderId || (linkedId.value && !next.some((entry) => entry.id === linkedId.value && !entry.is_primary))) {
reset()
}
}, { flush: 'sync' })
onScopeDispose(() => activeRequest?.abort())
return { options, selectedId, isPrimary, prescription, loading, detailError, herbsVisible, reset, select }
}
@@ -0,0 +1,105 @@
import { computed, onScopeDispose, ref, shallowRef, watch } from 'vue'
import { prescriptionDetail } from '@/api/tcm'
import { applyOrderUsageOverride } from '@/components/prescription-slip/utils'
import feedback from '@/utils/feedback'
import { linkedPrescriptionOptions, loadLinkedOrderPrescription, type OrderDetail } from './useLinkedOrderPrescription'
function mergePrimaryOrderContext(base: OrderDetail, order: OrderDetail) {
const prescription: OrderDetail = applyOrderUsageOverride({ ...base }, order.usage_override)
if (order.medication_days != null && String(order.medication_days).trim() !== '') {
prescription.medication_days = order.medication_days
}
for (const key of ['order_no', 'recipient_name', 'recipient_phone', 'shipping_address']) {
if (order[key] && !prescription[key]) prescription[key] = order[key]
}
if (order.amount != null && prescription.order_amount == null) prescription.order_amount = order.amount
if (Number(order.dose_count) > 0) prescription.dose_count = Number(order.dose_count)
if (order.dose_unit != null && String(order.dose_unit).trim() !== '') {
prescription.dose_unit = String(order.dose_unit)
}
if (!(Number(prescription.appointment_id) > 0) && Number(order.linked_appointment?.id) > 0) {
prescription.appointment_id = Number(order.linked_appointment.id)
}
return prescription
}
export function usePrescriptionOrderPreview(resolveAuxLibraryName?: (prescription: OrderDetail) => Promise<string>) {
const visible = ref(false)
const loading = ref(false)
const error = ref('')
const prescription = ref<OrderDetail | null>(null)
const auxLibraryName = ref('')
const tabType = ref<'internal' | 'user'>('internal')
const order = shallowRef<OrderDetail | null>(null)
const selectedId = ref(0)
const isPrimary = computed(() => selectedId.value === Number(order.value?.prescription_id))
const canExport = ref(false)
const options = computed(() => linkedPrescriptionOptions(order.value))
let activeRequest: AbortController | undefined
async function select(id: number) {
const context = order.value
if (!visible.value || !context || !id) return
const primary = id === Number(context.prescription_id)
if (!primary && !options.value.some((entry) => entry.id === id)) return
activeRequest?.abort()
const request = new AbortController()
activeRequest = request
selectedId.value = id
canExport.value = false
loading.value = true
prescription.value = null
auxLibraryName.value = ''
error.value = ''
try {
let data: OrderDetail
let exportAllowed = primary
if (primary) {
const response = await prescriptionDetail({ id }, request.signal)
const base = response?.data ?? response
if (Number(base?.id) !== id) throw new Error('无法加载处方详情')
data = mergePrimaryOrderContext(base, context)
} else {
const detail = await loadLinkedOrderPrescription(Number(context.id), id, request.signal)
data = detail.prescription
exportAllowed = detail.prescription_detail_herbs_visible === true
}
if (request.signal.aborted) return
const libraryName = resolveAuxLibraryName ? await resolveAuxLibraryName(data) : ''
if (request.signal.aborted) return
prescription.value = data
auxLibraryName.value = libraryName
canExport.value = exportAllowed
} catch {
if (!request.signal.aborted) error.value = '无法加载处方详情。'
} finally {
if (!request.signal.aborted) loading.value = false
}
}
function open(context: OrderDetail, initialId?: number) {
const entries = linkedPrescriptionOptions(context)
const id = entries.find((entry) => entry.id === initialId)?.id
|| entries.find((entry) => entry.is_primary)?.id
|| entries[0]?.id
|| Number(context.prescription_id)
if (!id) {
feedback.msgWarning('该订单未关联处方')
return
}
order.value = { ...context }
tabType.value = 'internal'
visible.value = true
void select(id)
}
watch(visible, (show) => {
if (!show) activeRequest?.abort()
}, { flush: 'sync' })
onScopeDispose(() => activeRequest?.abort())
return { visible, loading, error, prescription, auxLibraryName, tabType, selectedId, isPrimary, canExport, options, open, select }
}
@@ -0,0 +1,107 @@
import { computed, ref } from 'vue'
import type { Ref } from 'vue'
import { prescriptionOrderAttachReceipt, prescriptionOrderPaidPayOrders, prescriptionOrderUnlinkPayOrder } from '@/api/tcm'
import feedback from '@/utils/feedback'
import { hasPermission } from '@/utils/perm'
import { formatMoney } from './prescription-order-utils'
type Receipt = {
id: number | string
order_no?: string
amount: number | string
}
export function usePrescriptionOrderReceipts(
detail: Ref<Record<string, any> | null>,
visible: Ref<boolean>,
onChanged: (orderId: number) => void
) {
const unlinkedReceipts = ref<Receipt[]>([])
const linkingReceiptId = ref<number | null>(null)
const unlinkingReceiptId = ref<number | null>(null)
const changingReceipts = computed(() => linkingReceiptId.value !== null || unlinkingReceiptId.value !== null)
const canAttachReceipt = computed(() => Array.isArray(detail.value?.attachable_receipts))
const canUnlinkReceipt = computed(() =>
Number(detail.value?.id) > 0 && Number(detail.value?.fulfillment_status) !== 4
&& hasPermission(['tcm.prescriptionOrder/unlinkPayOrder'])
)
const isCurrentOrder = (id: number) => visible.value && Number(detail.value?.id) === id
async function loadUnlinkedReceipts(order: Record<string, any>) {
const id = Number(order.id)
const diagnosisId = Number(order.diagnosis_id)
if (!isCurrentOrder(id)) return
if (Array.isArray(order.attachable_receipts) || !diagnosisId) {
unlinkedReceipts.value = order.attachable_receipts ?? []
return
}
try {
const res = await prescriptionOrderPaidPayOrders({ diagnosis_id: diagnosisId, prescription_order_id: id })
const rows: Receipt[] = res?.lists ?? res?.data?.lists ?? []
const linkedIds = new Set((order.pay_order_ids ?? []).map(Number))
if (isCurrentOrder(id)) {
unlinkedReceipts.value = rows.filter((row) => !linkedIds.has(Number(row.id)))
}
} catch {
if (isCurrentOrder(id)) unlinkedReceipts.value = []
}
}
async function confirmAttachReceipt(receipt: Receipt) {
const orderId = Number(detail.value?.id)
const payId = Number(receipt.id)
if (!orderId || !payId || !canAttachReceipt.value || changingReceipts.value) return
linkingReceiptId.value = payId
try {
const orderComplete = Number(detail.value?.fulfillment_status) === 3
const message = `将收款「${receipt.order_no || '#' + payId}」(¥${formatMoney(receipt.amount)})关联到当前订单?`
await feedback.confirm(orderComplete ? message + '收款会先冲减需代收,超出部分计入总金额。' : message)
if (!isCurrentOrder(orderId)) return
const res = await prescriptionOrderAttachReceipt({ id: orderId, pay_order_id: payId })
const updated = res?.data ?? res
if (isCurrentOrder(orderId) && Number(updated?.id) === orderId) {
const remaining = unlinkedReceipts.value.filter((row) => Number(row.id) !== payId)
detail.value = { ...detail.value, ...updated, attachable_receipts: remaining }
unlinkedReceipts.value = remaining
}
feedback.msgSuccess('收款已关联')
onChanged(orderId)
} catch {
// 接口错误由请求拦截器提示。取消确认时保留当前列表。
} finally {
linkingReceiptId.value = null
}
}
async function confirmUnlinkReceipt(receipt: Receipt & { status: number | string }) {
const orderId = Number(detail.value?.id)
const payId = Number(receipt.id)
if (!payId || !canUnlinkReceipt.value || changingReceipts.value || ![2, 4, 5].includes(Number(receipt.status))) return
unlinkingReceiptId.value = payId
try {
await feedback.confirm(
`确定移除收款记录「${receipt.order_no || '#' + payId}」(¥${formatMoney(receipt.amount)})?` +
'移除后会保留原收款记录,并按订单总金额和剩余收款重算已付金额和需代收。'
)
if (!isCurrentOrder(orderId)) return
const response = await prescriptionOrderUnlinkPayOrder({ id: orderId, pay_order_id: payId })
const updated = response?.data ?? response
if (isCurrentOrder(orderId) && Number(updated?.id) === orderId) {
const order = { ...detail.value, ...updated, attachable_receipts: updated.attachable_receipts }
detail.value = order
await loadUnlinkedReceipts(order)
}
feedback.msgSuccess('收款关联已移除,金额已同步更新')
onChanged(orderId)
} catch {
// 请求拦截器负责显示接口报错。
} finally {
unlinkingReceiptId.value = null
}
}
return {
unlinkedReceipts, loadUnlinkedReceipts, linkingReceiptId, unlinkingReceiptId, changingReceipts,
canAttachReceipt, canUnlinkReceipt, confirmAttachReceipt, confirmUnlinkReceipt
}
}
@@ -221,11 +221,17 @@
{{ formatListCreateTime(row.create_time) }}
</template>
</el-table-column>
<el-table-column label="操作" width="340" fixed="right">
<el-table-column label="操作" width="390" fixed="right">
<template #default="{ row }">
<el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']">
查看
</el-button>
<el-button
v-if="canViewLinkedOrders"
type="primary"
link
@click="linkedOrdersDialog?.open(row)"
>关联订单</el-button>
<el-button
v-if="Number(row.void_status) !== 1"
type="primary"
@@ -1723,6 +1729,8 @@
</template>
</el-dialog>
<PrescriptionLinkedOrdersDialog v-if="canViewLinkedOrders" ref="linkedOrdersDialog" @bound="getLists()" />
<!-- 与 tcm/diagnosis/edit 同一套诊单界面(只读 + 全部分页签) -->
<TcmDiagnosisEditView ref="diagnosisViewRef" />
</div>
@@ -1758,6 +1766,7 @@ import DaterangePicker from '@/components/daterange-picker/index.vue'
import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import PrescriptionLinkedOrdersDialog from './components/PrescriptionLinkedOrdersDialog.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
import { canApprovePrescriptionEsign, downloadOriginalEsignPdf, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
@@ -1906,6 +1915,8 @@ const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const linkedOrdersDialog = ref<InstanceType<typeof PrescriptionLinkedOrdersDialog>>()
const canViewLinkedOrders = computed(() => hasPermission(['tcm.prescriptionOrder/prescriptionOrdersForBinding']))
function goBusinessOrderList() {
const hit = router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists')
@@ -626,7 +626,7 @@
:gancao-preview-loading="gancaoPreviewLoading"
@update-amount="openUpdateAmount"
@patch-rx-patient="openPatchRxPatientDialog"
@view-prescription="detailData && openPrescriptionView(detailData)"
@view-prescription="(id) => detailData && openPrescriptionView(detailData, id)"
@test-gancao-preview="testGancaoPreviewFromDetail"
@view-patient="openDiagnosisPatientDetailFromOrder"
@detail-changed="getLists"
@@ -655,18 +655,19 @@
>{{ shipModeLabel(detail.ship_mode) }}</el-tag>
</div>
</template>
<template #header-actions="{ detail }">
<template #header-actions="{ detail, isPrimaryPrescription }">
<el-button
v-perms="['tcm.prescriptionOrder/editTime']"
size="small"
@click="orderTimeDialogRef?.open(detail)"
>修改创建时间</el-button>
<gancao-submission-reconcile-button
v-if="isPrimaryPrescription"
:order="detail"
@resolved="handleGancaoSubmissionResolved"
/>
<el-button
v-if="canUploadPharmacyRow(detail)"
v-if="isPrimaryPrescription && canUploadPharmacyRow(detail)"
v-perms="['tcm.prescriptionOrder/uploadToPharmacy']"
type="warning"
size="small"
@@ -675,7 +676,7 @@
@click="confirmUploadToPharmacy(detail)"
>上传药房</el-button>
<el-button
v-if="canRxAudit(detail)"
v-if="isPrimaryPrescription && canRxAudit(detail)"
v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="warning"
size="small"
@@ -685,7 +686,7 @@
处方审核
</el-button>
<el-button
v-if="canRevokeRxAudit(detail)"
v-if="isPrimaryPrescription && canRevokeRxAudit(detail)"
v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="info"
size="small"
@@ -1637,7 +1638,7 @@
<el-radio-group v-model="addPayOrderForm.add_mode">
<el-radio value="create">付呗</el-radio>
<el-radio value="create_express">快递代收</el-radio>
<el-radio value="link">关联已有</el-radio>
<el-radio v-if="canLinkExistingReceipt" value="link">关联已有</el-radio>
<el-radio value="completion_only">直接完单申请</el-radio>
</el-radio-group>
</el-form-item>
@@ -1801,7 +1802,7 @@
<template #header>
<div class="flex items-center justify-between w-full pr-2 gap-3">
<span class="text-base font-medium text-gray-800">查看处方</span>
<div v-if="prescriptionViewData && !prescriptionViewLoading" class="flex items-center gap-2 shrink-0">
<div v-if="prescriptionViewData && !prescriptionViewLoading && previewCanExport" class="flex items-center gap-2 shrink-0">
<el-button
size="small"
:loading="prescriptionSlipExporting"
@@ -1831,7 +1832,18 @@
</div>
</div>
</template>
<div v-loading="prescriptionViewLoading" class="rx-wrap">
<LinkedOrderPrescriptionSelect
:options="previewPrescriptionOptions"
:model-value="previewPrescriptionId"
:disabled="prescriptionSlipExporting"
class="mx-4 mb-2"
@change="selectPreviewPrescription"
/>
<div class="rx-wrap">
<el-skeleton v-if="prescriptionViewLoading" :rows="6" animated class="p-4" />
<el-alert v-else-if="prescriptionViewError" type="warning" :closable="false" :title="prescriptionViewError" class="mb-3">
<el-button link type="primary" @click="selectPreviewPrescription(previewPrescriptionId)">重试</el-button>
</el-alert>
<!-- 药房联 / 处方联切换 -->
<el-tabs
v-if="prescriptionViewData"
@@ -1867,6 +1879,9 @@
size="small"
>待审核</el-tag>
<el-tag v-else type="danger" size="small">已驳回</el-tag>
<el-tag v-if="!previewIsPrimary && prescriptionViewData.esign?.status_label" type="info" size="small">
{{ prescriptionViewData.esign.status_label }}
</el-tag>
</div>
<div
@@ -1893,7 +1908,7 @@
</div>
<EsignPrescriptionPanel
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading && previewIsPrimary"
:key="prescriptionViewData.id"
:prescription-id="Number(prescriptionViewData.id)"
:initial-state="prescriptionViewData.esign"
@@ -1901,6 +1916,7 @@
/>
<PrescriptionSlip
v-if="prescriptionViewData"
:key="previewPrescriptionId"
ref="rxSlipRef"
:data="prescriptionViewData"
:variant="prescriptionTabType"
@@ -2097,11 +2113,14 @@
</template>
<script lang="ts" setup name="prescriptionOrderList">
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
import { computed, onActivated, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'
import { ArrowDown, InfoFilled, QuestionFilled, Search, Calendar, Document, Link as LinkIcon, Wallet } from '@element-plus/icons-vue'
import ListTimeFilter from '@/components/list-time-filter/index.vue'
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.vue'
import LinkedOrderPrescriptionSelect from './components/LinkedOrderPrescriptionSelect.vue'
import type { LinkedPrescription } from './components/useLinkedOrderPrescription'
import { usePrescriptionOrderPreview } from './components/usePrescriptionOrderPreview'
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
import {
@@ -2161,7 +2180,6 @@ import {
prescriptionOrderLinkPayOrder,
prescriptionOrderUploadToPharmacy,
prescriptionOrderPreviewGancaoRecipel,
prescriptionDetail,
prescriptionLibraryLists,
getDoctors,
getAssistants
@@ -2185,7 +2203,11 @@ import useUserStore from '@/stores/modules/user'
const TcmDiagnosisEditView = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
const userStore = useUserStore()
const canLinkExistingReceipt = computed(() =>
userStore.perms.includes('*') || userStore.perms.includes('tcm.prescriptionOrder/attachReceipt')
)
const route = useRoute()
const orderListPath = route.fullPath
const diagnosisViewRef = ref<{
openViewOnly: (id: number) => Promise<void>
@@ -3329,8 +3351,8 @@ async function submitUpdateAmount() {
}
}
async function openDetail(id: number) {
await detailDrawerRef.value?.open(id)
async function openDetail(id: number, prescriptionId?: number) {
await detailDrawerRef.value?.open(id, prescriptionId)
}
const editVisible = ref(false)
@@ -3368,6 +3390,7 @@ const editFormRef = ref<FormInstance>()
const editForm = reactive({
id: 0,
prescription_id: 0,
linked_prescriptions: [] as LinkedPrescription[],
diagnosis_id: 0,
recipient_name: '',
recipient_phone: '',
@@ -3527,6 +3550,7 @@ const editRules = computed<FormRules>(() => {
function resetEditOrderDialog() {
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editGancaoLogisticsOnlyMode.value = false
editGancaoDisplayNo.value = ''
editFormRef.value?.clearValidate()
@@ -3579,6 +3603,7 @@ async function openEdit(row: {
}
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editVisible.value = true
editDialogLoading.value = true
try {
@@ -3589,6 +3614,7 @@ async function openEdit(row: {
editVisible.value = false
return
}
editForm.linked_prescriptions = d.linked_prescriptions ?? []
const rx = d.prescription
if (rx && typeof rx === 'object') {
editOrderPrescription.value = rx as Record<string, any>
@@ -3979,6 +4005,17 @@ async function confirmUploadToPharmacy(row: { id: number; ship_mode?: string })
}
}
async function openOrderFromRoute() {
if (route.fullPath !== orderListPath) return
const id = Number(route.query.review_order)
if (Number.isSafeInteger(id) && id > 0) await openDetail(id, Number(route.query.review_prescription))
}
let orderListInitialized = false
onActivated(() => {
if (orderListInitialized) void openOrderFromRoute()
})
onMounted(async () => {
await loadRegionData()
await loadServicePackageOptions()
@@ -3986,8 +4023,8 @@ onMounted(async () => {
applyRouteQueryToPrescriptionOrderList()
await nextTick()
getLists()
const reviewOrderId = Number(route.query.review_order)
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId)
orderListInitialized = true
await openOrderFromRoute()
})
// ─── 快捷填写快递单号 ────────────────────────────────────────────
@@ -4481,7 +4518,7 @@ function openAddPayOrder(row: {
// 加载可用支付单列表,排除当前订单已关联的
const diagId = row.diagnosis_id || detailData.value?.diagnosis_id
const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || []
if (diagId) {
if (diagId && canLinkExistingReceipt.value) {
void loadAddPayOrderAvailable(diagId, currentLinkedIds)
}
}
@@ -4601,13 +4638,20 @@ const SLIP_TITLE = `${SLIP_HOSPITAL_NAME} 处方笺`
const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339'
const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号'
const prescriptionViewVisible = ref(false)
const prescriptionViewLoading = ref(false)
const prescriptionViewData = ref<any>(null)
/** 药房联辅方标题:处方库中该辅方模板的 prescription_name(导入或药材匹配解析) */
const slipAuxLibraryName = ref('')
/** 查看处方联次:药房联 / 处方联 */
const prescriptionTabType = ref<'internal' | 'user'>('internal')
const {
visible: prescriptionViewVisible,
loading: prescriptionViewLoading,
error: prescriptionViewError,
prescription: prescriptionViewData,
auxLibraryName: slipAuxLibraryName,
tabType: prescriptionTabType,
selectedId: previewPrescriptionId,
isPrimary: previewIsPrimary,
canExport: previewCanExport,
options: previewPrescriptionOptions,
open: openPrescriptionView,
select: selectPreviewPrescription
} = usePrescriptionOrderPreview(resolveSlipAuxLibraryName)
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
const prescriptionSlipExporting = ref(false)
@@ -4996,65 +5040,6 @@ async function resolveSlipAuxLibraryName(data: Record<string, unknown>): Promise
return ''
}
async function openPrescriptionView(row: any) {
if (!row.prescription_id) {
feedback.msgWarning('该订单未关联处方')
return
}
prescriptionViewVisible.value = true
prescriptionViewLoading.value = true
prescriptionViewData.value = null
slipAuxLibraryName.value = ''
prescriptionTabType.value = 'internal'
try {
const res: any = await prescriptionDetail({ id: row.prescription_id })
const base = res?.data ?? res ?? null
if (base) {
const md = row.medication_days
// 已签署处方在本订单修改过的服用参数(订单 usage_override),笺面按本订单生效值显示;CA 签署原件不变。
const merged: Record<string, unknown> = applyOrderUsageOverride({ ...base }, row.usage_override)
if (md != null && String(md).trim() !== '') {
merged.medication_days = md
}
/** 订单行带入:处方笺右上角"编号"、"收件信息"、底部"合计"用 */
if (row.order_no && !merged.order_no) merged.order_no = row.order_no
if (row.recipient_name && !merged.recipient_name) merged.recipient_name = row.recipient_name
if (row.recipient_phone && !merged.recipient_phone) merged.recipient_phone = row.recipient_phone
if (row.shipping_address && !merged.shipping_address) merged.shipping_address = row.shipping_address
if (row.amount != null && merged.order_amount == null) merged.order_amount = row.amount
/** 笺面剂数/单位与业务订单一致(甘草预览与订单详情同口径) */
if (row.dose_count != null && String(row.dose_count).trim() !== '' && Number(row.dose_count) > 0) {
merged.dose_count = Number(row.dose_count)
}
if (row.dose_unit != null && String(row.dose_unit).trim() !== '') {
merged.dose_unit = String(row.dose_unit)
}
const linkedAp = row.linked_appointment
if (
(!merged.appointment_id || Number(merged.appointment_id) <= 0) &&
linkedAp &&
typeof linkedAp === 'object' &&
Number(linkedAp.id) > 0
) {
merged.appointment_id = Number(linkedAp.id)
}
prescriptionViewData.value = merged
slipAuxLibraryName.value = await resolveSlipAuxLibraryName(merged)
} else {
prescriptionViewData.value = null
slipAuxLibraryName.value = ''
}
} catch (e: any) {
feedback.msgError(e?.message || '加载处方详情失败')
prescriptionViewVisible.value = false
slipAuxLibraryName.value = ''
} finally {
prescriptionViewLoading.value = false
}
}
async function preloadSlipImagesToDataUrl(el: HTMLElement): Promise<void> {
const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]')
const tasks = Array.from(imgs).map(async (img) => {
@@ -5170,7 +5155,7 @@ async function downloadPrescriptionSlipImage() {
/** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
if (!prescriptionViewData.value) return
if (!prescriptionViewData.value || !previewCanExport.value) return
prescriptionSlipExporting.value = true
try {
if (command === 'esign') {
@@ -554,11 +554,12 @@
</div>
<div v-if="detailData" class="po-detail-drawer-actions flex flex-wrap items-center gap-2">
<gancao-submission-reconcile-button
v-if="isPrimaryPrescription"
:order="detailData"
@resolved="handleGancaoSubmissionResolved"
/>
<el-button
v-if="canRxAudit(detailData)"
v-if="isPrimaryPrescription && canRxAudit(detailData)"
v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="warning"
size="small"
@@ -568,7 +569,7 @@
处方审核
</el-button>
<el-button
v-if="canRevokeRxAudit(detailData)"
v-if="isPrimaryPrescription && canRevokeRxAudit(detailData)"
v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="info"
size="small"
@@ -769,10 +770,10 @@
<!-- 左侧:处方单 -->
<el-card shadow="never" class="po-panel po-panel-rx border-gray-100 h-full relative overflow-hidden">
<!-- 处方审核印章 -->
<div v-if="detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
<div class="stamp-inner">审核通过</div>
</div>
<div v-if="detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
<div class="stamp-inner">已驳回</div>
</div>
<template #header>
@@ -780,15 +781,16 @@
<div class="flex w-full min-w-0 flex-wrap items-center justify-between gap-x-2 gap-y-1">
<span class="po-panel-rx-header__title font-medium text-[15px] leading-snug">处方详情</span>
<span class="shrink-0 text-xs text-gray-400 tabular-nums">
ID: {{ detailData.prescription_id || '—' }}
ID: {{ selectedPrescriptionId || '—' }}
</span>
</div>
<div v-if="detailData.doctor_name" class="min-w-0 text-xs leading-snug text-gray-500">
开方人:<span class="text-primary font-medium">{{ detailData.doctor_name }}</span>
<div v-if="detailPrescriptionDoctor" class="min-w-0 text-xs leading-snug text-gray-500">
开方人:<span class="text-primary font-medium">{{ detailPrescriptionDoctor }}</span>
</div>
<div class="flex w-full min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
<el-button
v-if="
isPrimaryPrescription &&
detailData.prescription_id &&
detailPrescription &&
!String(detailData.prescription_detail_error || '').trim()
@@ -802,16 +804,17 @@
改患者信息
</el-button>
<el-button
v-if="detailData.prescription_id && showPrescriptionAuditFilter"
v-if="selectedPrescriptionId && showPrescriptionAuditFilter"
type="primary"
size="small"
link
@click="openPrescriptionView(detailData)"
:disabled="linkedPrescriptionLoading"
@click="openPrescriptionView(detailData, selectedPrescriptionId)"
>
详细
</el-button>
<el-button
v-if="detailData.id && showPrescriptionAuditFilter"
v-if="isPrimaryPrescription && detailData.id && showPrescriptionAuditFilter"
type="warning"
size="small"
link
@@ -824,14 +827,23 @@
</div>
</div>
</template>
<LinkedOrderPrescriptionSelect
:options="detailPrescriptionOptions"
:model-value="selectedPrescriptionId"
class="mb-3"
@change="selectLinkedPrescription"
/>
<el-skeleton v-if="linkedPrescriptionLoading" :rows="5" animated />
<el-alert
v-if="String(detailData.prescription_detail_error || '').trim()"
:title="detailData.prescription_detail_error"
v-else-if="selectedPrescriptionError"
:title="selectedPrescriptionError"
type="warning"
:closable="false"
show-icon
class="mb-3"
/>
>
<el-button v-if="!isPrimaryPrescription" link type="primary" @click="selectLinkedPrescription(selectedPrescriptionId)">重试</el-button>
</el-alert>
<template v-else-if="detailPrescription">
<el-descriptions :column="1" border size="small" class="po-desc bg-white">
<el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
@@ -842,13 +854,13 @@
<el-descriptions-item label="手机">
<span
:class="
detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
isPrimaryPrescription && detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
"
>
{{ detailPrescription.phone || '—' }}
</span>
<el-tag
v-if="detailRecipientRxPhoneMismatch"
v-if="isPrimaryPrescription && detailRecipientRxPhoneMismatch"
type="danger"
size="small"
effect="dark"
@@ -864,7 +876,8 @@
{{ detailPrescription.clinical_diagnosis || '—' }}
</el-descriptions-item>
<el-descriptions-item label="剂数 / 用法" :span="2" v-if="showPrescriptionAuditFilter">
{{ detailData.dose_count ?? detailPrescription.dose_count ?? '—' }} {{ detailData.dose_unit || '剂' }} ·
{{ (isPrimaryPrescription ? detailData.dose_count ?? detailPrescription.dose_count : detailPrescription.dose_count) ?? '—' }}
{{ (isPrimaryPrescription ? detailData.dose_unit : detailPrescription.dose_unit) || '剂' }} ·
{{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
</el-descriptions-item>
<el-descriptions-item label="处方金额">
@@ -884,7 +897,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-if="isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
@@ -908,7 +921,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-if="isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
@@ -933,6 +946,7 @@
<span>服用方式</span>
<el-button
v-if="
isPrimaryPrescription &&
detailData.prescription_id &&
detailPrescription &&
!String(detailData.prescription_detail_error || '').trim()
@@ -986,7 +1000,7 @@
}}
</div>
</template>
<div>
<div v-if="isPrimaryPrescription">
<span class="text-gray-500">订单设置:</span>
{{
detailData.medication_days != null &&
@@ -1079,6 +1093,17 @@
{{ formatOrderTime(row.create_time) }}
</template>
</el-table-column>
<el-table-column v-if="canAttachReceipt" label="操作" width="86" fixed="right" align="center">
<template #default="{ row }">
<el-button
link
type="primary"
:loading="linkingReceiptId === Number(row.id)"
:disabled="changingReceipts"
@click="confirmAttachReceipt(row)"
>关联</el-button>
</template>
</el-table-column>
</el-table>
<el-empty v-else description="无未关联的收款单" :image-size="60" />
</el-card>
@@ -1142,6 +1167,17 @@
{{ formatOrderTime(row.create_time) }}
</template>
</el-table-column>
<el-table-column v-if="canUnlinkReceipt" label="操作" width="80" fixed="right" align="center">
<template #default="{ row }">
<el-button
link
type="danger"
:loading="unlinkingReceiptId === Number(row.id)"
:disabled="changingReceipts || ![2, 4, 5].includes(Number(row.status))"
@click="confirmUnlinkReceipt(row)"
>移除</el-button>
</template>
</el-table-column>
</el-table>
<el-empty v-else description="未关联收款单" :image-size="60" />
</el-card>
@@ -2135,7 +2171,7 @@
<el-radio-group v-model="addPayOrderForm.add_mode">
<el-radio value="create">付呗</el-radio>
<el-radio value="create_express">快递代收</el-radio>
<el-radio value="link">关联已有</el-radio>
<el-radio v-if="canLinkExistingReceipt" value="link">关联已有</el-radio>
<el-radio value="completion_only">直接完单申请</el-radio>
</el-radio-group>
</el-form-item>
@@ -2404,7 +2440,7 @@
<template #header>
<div class="flex items-center justify-between w-full pr-2 gap-3">
<span class="text-base font-medium text-gray-800">查看处方</span>
<div v-if="prescriptionViewData && !prescriptionViewLoading" class="flex items-center gap-2 shrink-0">
<div v-if="prescriptionViewData && !prescriptionViewLoading && previewCanExport" class="flex items-center gap-2 shrink-0">
<el-button
size="small"
:loading="prescriptionSlipExporting"
@@ -2434,7 +2470,18 @@
</div>
</div>
</template>
<div v-loading="prescriptionViewLoading" class="rx-wrap">
<LinkedOrderPrescriptionSelect
:options="previewPrescriptionOptions"
:model-value="previewPrescriptionId"
:disabled="prescriptionSlipExporting"
class="mx-4 mb-2"
@change="selectPreviewPrescription"
/>
<div class="rx-wrap">
<el-skeleton v-if="prescriptionViewLoading" :rows="6" animated class="p-4" />
<el-alert v-else-if="prescriptionViewError" type="warning" :closable="false" :title="prescriptionViewError" class="mb-3">
<el-button link type="primary" @click="selectPreviewPrescription(previewPrescriptionId)">重试</el-button>
</el-alert>
<!-- 药房联 / 处方联切换 -->
<el-tabs
v-if="prescriptionViewData"
@@ -2470,6 +2517,9 @@
size="small"
>待审核</el-tag>
<el-tag v-else type="danger" size="small">已驳回</el-tag>
<el-tag v-if="!previewIsPrimary && prescriptionViewData.esign?.status_label" type="info" size="small">
{{ prescriptionViewData.esign.status_label }}
</el-tag>
</div>
<div
@@ -2496,7 +2546,7 @@
</div>
<EsignPrescriptionPanel
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading && previewIsPrimary"
:key="prescriptionViewData.id"
:prescription-id="Number(prescriptionViewData.id)"
:initial-state="prescriptionViewData.esign"
@@ -2504,6 +2554,7 @@
/>
<PrescriptionSlip
v-if="prescriptionViewData"
:key="previewPrescriptionId"
ref="rxSlipRef"
:data="prescriptionViewData"
:variant="prescriptionTabType"
@@ -2674,7 +2725,7 @@
</template>
<script lang="ts" setup name="prescriptionOrderListH5">
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
import { computed, onActivated, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'
import {
Refresh,
@@ -2691,6 +2742,7 @@ import {
import ListTimeFilter from '@/components/list-time-filter/index.vue'
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
import { usePrescriptionOrderReceipts } from './components/usePrescriptionOrderReceipts'
import { useListTimeFilter } from '@/hooks/useListTimeFilter'
import {
prescriptionOrderAuditPayment,
@@ -2716,7 +2768,6 @@ import {
prescriptionOrderRequestCompletion,
prescriptionOrderUploadToPharmacy,
prescriptionOrderPreviewGancaoRecipel,
prescriptionDetail,
getDoctors,
getAssistants
} from '@/api/tcm'
@@ -2734,6 +2785,9 @@ import {
supplyModeTagType
} from './components/prescription-order-utils'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import LinkedOrderPrescriptionSelect from './components/LinkedOrderPrescriptionSelect.vue'
import { useLinkedOrderPrescription, type LinkedPrescription } from './components/useLinkedOrderPrescription'
import { usePrescriptionOrderPreview } from './components/usePrescriptionOrderPreview'
import { applyOrderUsageOverride } from '@/components/prescription-slip/utils'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
@@ -2752,6 +2806,9 @@ import useUserStore from '@/stores/modules/user'
const TcmDiagnosisEditView = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
const userStore = useUserStore()
const canLinkExistingReceipt = computed(() =>
userStore.perms.includes('*') || userStore.perms.includes('tcm.prescriptionOrder/attachReceipt')
)
const diagnosisViewRef = ref<{
openViewOnly: (id: number) => Promise<void>
@@ -3630,6 +3687,20 @@ function canUpdateAmount(row: { id?: number; fulfillment_status?: number } | nul
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<Record<string, any> | null>(null)
const {
options: detailPrescriptionOptions,
selectedId: selectedPrescriptionId,
isPrimary: isPrimaryPrescription,
prescription: detailPrescription,
loading: linkedPrescriptionLoading,
detailError: selectedPrescriptionError,
herbsVisible: detailHerbsVisible,
reset: resetLinkedPrescription,
select: selectLinkedPrescription
} = useLinkedOrderPrescription(detailData, detailVisible)
const detailPrescriptionDoctor = computed(() =>
isPrimaryPrescription.value ? detailData.value?.doctor_name : detailPrescription.value?.doctor_name
)
const orderTimeDialogRef = ref<InstanceType<typeof PrescriptionOrderTimeDialog>>()
async function onOrderTimeSaved(id: number) {
@@ -3715,28 +3786,20 @@ const detailAgencyToCollect = computed(() => {
return Math.round((total - paid) * 100) / 100
})
const detailUnlinkedPayOrders = ref<any[]>([])
async function loadDetailUnlinkedPayOrders(diagnosisId: number, prescriptionOrderId: number, linkedIds: number[]) {
if (!diagnosisId) {
detailUnlinkedPayOrders.value = []
return
}
try {
const res: any = await prescriptionOrderPaidPayOrders({
diagnosis_id: diagnosisId,
prescription_order_id: prescriptionOrderId
})
const lists = res?.lists ?? res?.data?.lists ?? []
// 列表已由服务端限制为 2026-04-20 及之后创建的支付单(本单已关联除外);此处再过滤已关联项
const filtered = Array.isArray(lists)
? lists.filter((item: any) => !linkedIds.includes(item.id))
: []
detailUnlinkedPayOrders.value = filtered
} catch {
detailUnlinkedPayOrders.value = []
}
}
const {
unlinkedReceipts: detailUnlinkedPayOrders,
loadUnlinkedReceipts,
linkingReceiptId,
unlinkingReceiptId,
changingReceipts,
canAttachReceipt,
canUnlinkReceipt,
confirmAttachReceipt,
confirmUnlinkReceipt
} = usePrescriptionOrderReceipts(detailData, detailVisible, (orderId) => {
void getLists()
if (detailVisible.value && Number(detailData.value?.id) === orderId) void fetchLogs(orderId)
})
function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number }> {
if (!raw) return []
@@ -3749,11 +3812,6 @@ function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number
return []
}
const detailPrescription = computed(() => {
const p = detailData.value?.prescription
return p && typeof p === 'object' ? p : null
})
const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo))
function normalizeBizPhone(v: unknown): string {
@@ -3770,13 +3828,13 @@ function recipientVsPrescriptionPhoneMismatch(recipient: unknown, rxPhone: unkno
/** 详情抽屉:业务收货手机 vs 处方登记手机 */
const detailRecipientRxPhoneMismatch = computed(() => {
const rx = detailPrescription.value?.phone
const rx = detailData.value?.prescription?.phone
const biz = detailData.value?.recipient_phone
return recipientVsPrescriptionPhoneMismatch(biz, rx)
})
const detailPrescriptionPhoneDisplay = computed(() => {
const s = normalizeBizPhone(detailPrescription.value?.phone)
const s = normalizeBizPhone(detailData.value?.prescription?.phone)
return s || '—'
})
@@ -3812,7 +3870,6 @@ const detailAuxUsage = computed(() => {
})
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
// 完整收货地址(省市区 + 详细地址)
const detailFullAddress = computed(() => {
@@ -3956,6 +4013,7 @@ function logActionText(act: string) {
ship: '确认发货',
withdraw: '撤销',
link_pay_order: '关联支付单',
bind_prescription: '绑定关联处方',
revoke_rx_audit: '撤回处方审核',
revoke_pay_audit: '撤回支付审核',
gancao_submit: '甘草下单',
@@ -4078,6 +4136,7 @@ function openPatchUsageDialog() {
feedback.msgWarning('无处方数据')
return
}
if (rx.id && Number(rx.id) !== Number(ord.prescription_id)) return
const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day =
@@ -4157,6 +4216,7 @@ async function submitPatchUsage() {
}
function openPatchRxPatientDialog() {
if (!isPrimaryPrescription.value) return
const rx = detailPrescription.value
const ord = detailData.value
if (!rx || !ord?.id || !ord.prescription_id) {
@@ -4194,12 +4254,13 @@ function openUpdateAmount() {
}
async function refreshCurrentPrescriptionOrderDetail() {
const id = detailData.value?.id
const current = detailData.value
const id = current?.id
if (!id) return
try {
const res: any = await prescriptionOrderDetail({ id })
const d = res?.data ?? res ?? null
if (d) detailData.value = d
if (d && detailData.value === current) detailData.value = d
} catch {
/* 静默失败,避免打断当前抽屉 */
}
@@ -4263,9 +4324,13 @@ async function submitUpdateAmount() {
}
}
async function openDetail(id: number) {
let detailOpenRequest = 0
async function openDetail(id: number, prescriptionId?: number) {
const request = ++detailOpenRequest
// 修复 Bug:显式彻底清空缓存,防止前一次弹窗的数据残留
detailData.value = null
resetLinkedPrescription()
detailUnlinkedPayOrders.value = []
bumpLogisticsTraceRequestToken()
detailLogisticsExpress.value = 'auto'
@@ -4276,6 +4341,7 @@ async function openDetail(id: number) {
detailLoading.value = true
try {
const res: any = await prescriptionOrderDetail({ id })
if (request !== detailOpenRequest || !detailVisible.value) return
const d = res?.data ?? res ?? null
detailData.value = d
if (d) {
@@ -4287,18 +4353,15 @@ async function openDetail(id: number) {
}
fetchLogs(id)
// 加载未关联的支付单
const diagId = d.diagnosis_id
const linkedIds = d.pay_order_ids || []
if (diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, linkedIds)
}
void loadUnlinkedReceipts(d)
if (prescriptionId) void selectLinkedPrescription(prescriptionId)
}
} catch (e: any) {
if (request !== detailOpenRequest || !detailVisible.value) return
feedback.msgError(e?.message || '加载失败')
detailVisible.value = false
} finally {
detailLoading.value = false
if (request === detailOpenRequest) detailLoading.value = false
}
}
@@ -4333,6 +4396,7 @@ const editFormRef = ref<FormInstance>()
const editForm = reactive({
id: 0,
prescription_id: 0,
linked_prescriptions: [] as LinkedPrescription[],
diagnosis_id: 0,
recipient_name: '',
recipient_phone: '',
@@ -4511,6 +4575,7 @@ const editRules = computed<FormRules>(() => {
function resetEditOrderDialog() {
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editFormRef.value?.clearValidate()
}
@@ -4561,6 +4626,7 @@ async function openEdit(row: {
}
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editVisible.value = true
editDialogLoading.value = true
try {
@@ -4571,6 +4637,7 @@ async function openEdit(row: {
editVisible.value = false
return
}
editForm.linked_prescriptions = d.linked_prescriptions ?? []
const rx = d.prescription
if (rx && typeof rx === 'object') {
editOrderPrescription.value = rx as Record<string, any>
@@ -4709,6 +4776,7 @@ async function submitEdit() {
const auditVisible = ref(false)
const route = useRoute()
const orderListPath = route.fullPath
const auditKind = ref<'prescription' | 'payment'>('prescription')
const auditTargetId = ref(0)
const auditRowData = ref<any>(null)
@@ -4913,13 +4981,24 @@ async function confirmUploadToPharmacy(row: { id: number; ship_mode?: string })
}
}
async function openOrderFromRoute() {
if (route.fullPath !== orderListPath) return
const id = Number(route.query.review_order)
if (Number.isSafeInteger(id) && id > 0) await openDetail(id, Number(route.query.review_prescription))
}
let orderListInitialized = false
onActivated(() => {
if (orderListInitialized) void openOrderFromRoute()
})
onMounted(async () => {
await loadRegionData()
await loadServicePackageOptions()
await loadDoctorAssistantOptions()
getLists()
const reviewOrderId = Number(route.query.review_order)
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId)
orderListInitialized = true
await openOrderFromRoute()
})
// ─── 快捷填写快递单号 ────────────────────────────────────────────
@@ -5364,7 +5443,7 @@ function openAddPayOrder(row: { id: number; diagnosis_id?: number; pay_order_ids
// 加载可用支付单列表,排除当前订单已关联的
const diagId = row.diagnosis_id || detailData.value?.diagnosis_id
const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || []
if (diagId) {
if (diagId && canLinkExistingReceipt.value) {
void loadAddPayOrderAvailable(diagId, currentLinkedIds)
}
}
@@ -5492,11 +5571,19 @@ const SLIP_TITLE = `${SLIP_HOSPITAL_NAME} 处方笺`
const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339'
const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号'
const prescriptionViewVisible = ref(false)
const prescriptionViewLoading = ref(false)
const prescriptionViewData = ref<any>(null)
/** 查看处方联次:药房联 / 处方联 */
const prescriptionTabType = ref<'internal' | 'user'>('internal')
const {
visible: prescriptionViewVisible,
loading: prescriptionViewLoading,
error: prescriptionViewError,
prescription: prescriptionViewData,
tabType: prescriptionTabType,
selectedId: previewPrescriptionId,
isPrimary: previewIsPrimary,
canExport: previewCanExport,
options: previewPrescriptionOptions,
open: openPrescriptionView,
select: selectPreviewPrescription
} = usePrescriptionOrderPreview()
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
const prescriptionSlipExporting = ref(false)
@@ -5755,61 +5842,6 @@ function openPrescriptionViewFromEdit() {
openPrescriptionView(editForm)
}
async function openPrescriptionView(row: any) {
if (!row.prescription_id) {
feedback.msgWarning('该订单未关联处方')
return
}
prescriptionViewVisible.value = true
prescriptionViewLoading.value = true
prescriptionViewData.value = null
prescriptionTabType.value = 'internal'
try {
const res: any = await prescriptionDetail({ id: row.prescription_id })
const base = res?.data ?? res ?? null
if (base) {
const md = row.medication_days
// 已签署处方在本订单修改过的服用参数(订单 usage_override),笺面按本订单生效值显示;CA 签署原件不变。
const merged: Record<string, unknown> = applyOrderUsageOverride({ ...base }, row.usage_override)
if (md != null && String(md).trim() !== '') {
merged.medication_days = md
}
/** 订单行带入:处方笺右上角"编号"、"收件信息"、底部"合计"用 */
if (row.order_no && !merged.order_no) merged.order_no = row.order_no
if (row.recipient_name && !merged.recipient_name) merged.recipient_name = row.recipient_name
if (row.recipient_phone && !merged.recipient_phone) merged.recipient_phone = row.recipient_phone
if (row.shipping_address && !merged.shipping_address) merged.shipping_address = row.shipping_address
if (row.amount != null && merged.order_amount == null) merged.order_amount = row.amount
/** 笺面剂数/单位与业务订单一致(甘草预览与订单详情同口径) */
if (row.dose_count != null && String(row.dose_count).trim() !== '' && Number(row.dose_count) > 0) {
merged.dose_count = Number(row.dose_count)
}
if (row.dose_unit != null && String(row.dose_unit).trim() !== '') {
merged.dose_unit = String(row.dose_unit)
}
const linkedAp = row.linked_appointment
if (
(!merged.appointment_id || Number(merged.appointment_id) <= 0) &&
linkedAp &&
typeof linkedAp === 'object' &&
Number(linkedAp.id) > 0
) {
merged.appointment_id = Number(linkedAp.id)
}
prescriptionViewData.value = merged
} else {
prescriptionViewData.value = null
}
} catch (e: any) {
feedback.msgError(e?.message || '加载处方详情失败')
prescriptionViewVisible.value = false
} finally {
prescriptionViewLoading.value = false
}
}
async function preloadSlipImagesToDataUrl(el: HTMLElement): Promise<void> {
const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]')
const tasks = Array.from(imgs).map(async (img) => {
@@ -5925,7 +5957,7 @@ async function downloadPrescriptionSlipImage() {
/** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
if (!prescriptionViewData.value) return
if (!prescriptionViewData.value || !previewCanExport.value) return
prescriptionSlipExporting.value = true
try {
if (command === 'esign') {
@@ -72,7 +72,9 @@ class PrescriptionOrderController extends BaseAdminController
public function detail()
{
$params = (new PrescriptionOrderValidate())->get()->goCheck('detail');
$detail = PrescriptionOrderLogic::detail((int) $params['id'], $this->adminId, $this->adminInfo);
$detail = PrescriptionOrderLogic::detail(
(int) $params['id'], $this->adminId, $this->adminInfo, (int) ($params['prescription_id'] ?? 0)
);
if ($detail === null) {
return $this->fail(PrescriptionOrderLogic::getError());
}
@@ -80,6 +82,29 @@ class PrescriptionOrderController extends BaseAdminController
return $this->data($detail);
}
public function prescriptionOrdersForBinding()
{
$params = (new PrescriptionOrderValidate())->get()->goCheck('prescriptionOrdersForBinding');
try {
return $this->data(PrescriptionOrderLogic::prescriptionOrdersForBinding(
(int) $params['prescription_id'], trim((string) ($params['order_no'] ?? '')), $this->adminId, $this->adminInfo
));
} catch (\DomainException $exception) {
return $this->fail($exception->getMessage());
}
}
public function bindPrescription()
{
$params = (new PrescriptionOrderValidate())->post()->goCheck('bindPrescription');
try {
PrescriptionOrderLogic::bindPrescription((int) $params['id'], (int) $params['prescription_id'], $this->adminId, $this->adminInfo);
} catch (\DomainException $exception) {
return $this->fail($exception->getMessage());
}
return $this->success('业务订单已绑定');
}
/**
* 快递轨迹查询(对接快递100;未配置时仍可跳转顺丰/京东官网)
*/
@@ -437,6 +462,18 @@ class PrescriptionOrderController extends BaseAdminController
return $this->success('关联支付单成功', $result);
}
/** 在业务订单详情关联一笔已有收款。 */
public function attachReceipt()
{
$params = (new PrescriptionOrderValidate())->post()->goCheck('attachReceipt');
$result = PrescriptionOrderLogic::attachReceipt($params, $this->adminId, $this->adminInfo);
if ($result === false) {
return $this->fail(PrescriptionOrderLogic::getError());
}
return $this->success('收款已关联', $result);
}
/** 解除单笔收款关联,总金额不变,同步更新已付金额和需代收。 */
public function unlinkPayOrder()
{
+14 -13
View File
@@ -10,7 +10,6 @@ use app\common\model\OrderDetail;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\tcm\Diagnosis;
use app\common\model\tcm\PrescriptionOrder;
use app\common\model\tcm\PrescriptionOrderPayOrder;
use app\common\service\wechat\WechatWorkExternalPayService;
use think\facade\Db;
@@ -1300,7 +1299,7 @@ class OrderLogic
/**
* 某诊单下可关联的支付单(待支付/已支付),供关联业务订单多选(主管/诊单医助看该诊单全部;否则仅本人创建)
* 已占用(关联到未撤回/未取消的业务订单)的支付单会排除;编辑某业务订单时传 $exceptPrescriptionOrderId 以保留当前单已选中的项
* 已关联到未删除业务订单的支付单会排除;编辑时保留当前单已选中的项
* 列表仅含 2026-04-20 及之后创建的支付单(已关联到当前编辑业务订单的除外)
*
* @return array<int, array<string, mixed>>
@@ -1332,15 +1331,8 @@ class OrderLogic
->select()
->toArray();
$activePoIds = PrescriptionOrder::whereNull('delete_time')
->where('fulfillment_status', '<>', 4)
->column('id');
$busyPayIds = [];
if ($activePoIds !== []) {
$busyPayIds = PrescriptionOrderPayOrder::whereIn('prescription_order_id', $activePoIds)
->column('pay_order_id');
$busyPayIds = array_unique(array_map('intval', $busyPayIds));
}
$busyPayIds = $rows === [] ? [] : array_map('intval', self::prescriptionOrderReceiptLinks(array_column($rows, 'id'))
->column('link.pay_order_id'));
$whiteList = [];
if ($exceptPrescriptionOrderId !== null && $exceptPrescriptionOrderId > 0) {
$whiteList = array_map(
@@ -1372,8 +1364,17 @@ class OrderLogic
return $out;
}
/** @param int[] $payOrderIds */
public static function prescriptionOrderReceiptLinks(array $payOrderIds): \think\db\Query
{
return Db::name('tcm_prescription_order_pay_order')->alias('link')
->join('tcm_prescription_order po', 'po.id = link.prescription_order_id')
->whereIn('link.pay_order_id', $payOrderIds)
->whereNull('po.delete_time');
}
/**
* 校验支付单均可关联到指定诊单(已支付、归属与权限)
* 校验支付单均可关联到指定诊单(已支付、归属与权限),调用方须持有事务
* 默认仅允许关联 2026-04-20 及之后创建的支付单;编辑业务订单时传入 $prescriptionOrderIdForDateGrace,已关联到该业务订单的旧单除外
*
* @param int[] $ids zyt_order.id
@@ -1402,7 +1403,7 @@ class OrderLogic
$assistantId = (int) Diagnosis::where('id', $diagnosisId)->value('assistant_id');
$isDiagAssistant = $assistantId === $adminId;
$orders = Order::whereIn('id', $ids)->whereNull('delete_time')->select();
$orders = Order::whereIn('id', $ids)->whereNull('delete_time')->order('id', 'asc')->lock(true)->select();
if (count($orders) !== count($ids)) {
return '部分支付单不存在或已删除';
}
@@ -41,6 +41,7 @@ use app\common\service\storage\Driver as StorageDriver;
use app\common\service\tcm\RevisitDueHook;
use app\common\service\tcm\RevisitDueService;
use app\common\service\tcm\RevisitVisitSlotService;
use think\db\Query;
use think\facade\Db;
/**
* 中医辨房病因诊单逻辑
@@ -4356,7 +4357,18 @@ class DiagnosisLogic extends BaseLogic
return false;
}
$query = Diagnosis::where('id', $diagnosisId)->whereNull('delete_time');
if (!self::readonlyDiagnosisQuery($adminId, $adminInfo)->where('id', $diagnosisId)->find()) {
self::setError('诊单不存在或无权访问');
return false;
}
return true;
}
public static function readonlyDiagnosisQuery(int $adminId, array $adminInfo): Query
{
$query = Diagnosis::whereNull('delete_time');
// 纯医助只看本人归属诊单;兼有团队角色时交给下方数据范围按部门过滤
$selfRoles = DataScopeService::selfOnlyRoleIds($adminId, $adminInfo);
if (in_array(2, $selfRoles, true)) {
@@ -4366,22 +4378,13 @@ class DiagnosisLogic extends BaseLogic
if (DataScopeService::isEnabled()) {
$visibleIds = DataScopeService::getVisibleAdminIds($adminId, $adminInfo);
if ($visibleIds === []) {
self::setError('诊单不存在或无权访问');
return false;
}
if (is_array($visibleIds)) {
$query->whereRaw('1 = 0');
} elseif (is_array($visibleIds)) {
$query->whereIn('assistant_id', $visibleIds);
}
}
if (!$query->find()) {
self::setError('诊单不存在或无权访问');
return false;
}
return true;
return $query;
}
/**
@@ -989,6 +989,19 @@ class PrescriptionLogic
}
}
/** 关联处方预览使用处方原始内容和只读签署状态。 */
public static function orderReferenceDetail(int $id, int $diagnosisId, int $adminId, array $adminInfo): ?array
{
$row = Prescription::where('id', $id)->where('diagnosis_id', $diagnosisId)->whereNull('delete_time')->find();
if (!$row || !self::canViewPrescription($row, $adminId, $adminInfo)) {
return null;
}
$data = self::withSigningStatus($row->toArray(), 0, false, true);
$data['can_review_prescription'] = false;
$data['esign']['can_review_prescription'] = false;
return $data;
}
/**
* 处方详情(带查看权限校验,供后台管理端)
*/
@@ -50,6 +50,10 @@ class PrescriptionOrderLogic
private static string $error = '';
private const TRACKING_AUDIT_REQUIRED = '处方审核和支付单审核均通过后,才可填写或修改快递单号';
private const ATTACH_RECEIPT_PERMISSION = 'tcm.prescriptionOrder/attachReceipt';
private const VIEW_RX_LINKS_PERMISSION = 'tcm.prescriptionOrder/prescriptionOrdersForBinding';
private const BIND_RX_PERMISSION = 'tcm.prescriptionOrder/bindPrescription';
private const RX_LINK_TABLE = 'tcm_prescription_order_prescription';
public static function setError(string $msg): void
{
@@ -380,7 +384,8 @@ class PrescriptionOrderLogic
}
$perms = AuthLogic::getAuthByAdminId((int) ($adminInfo['admin_id'] ?? 0));
foreach ($perms as $p) {
if (is_string($p) && str_starts_with($p, 'tcm.prescriptionOrder/')) {
if (is_string($p) && str_starts_with($p, 'tcm.prescriptionOrder/')
&& !in_array($p, [self::VIEW_RX_LINKS_PERMISSION, self::BIND_RX_PERMISSION], true)) {
return true;
}
}
@@ -897,7 +902,7 @@ class PrescriptionOrderLogic
}
/**
* 支付单不可同时关联多条「有效」业务订单(未删除且未撤回/取消);$exceptPrescriptionOrderId 为当前编辑单 ID 时跳过自检
* 收款须由调用方在同一事务中锁定。撤回会清除原关联,取消单事后补录的关联仍占用该收款。
*
* @param int[] $payOrderIds
*/
@@ -907,27 +912,13 @@ class PrescriptionOrderLogic
if ($ids === []) {
return null;
}
$activePoIds = PrescriptionOrder::whereNull('delete_time')
->where('fulfillment_status', '<>', 4)
->column('id');
if ($activePoIds === []) {
return null;
$links = OrderLogic::prescriptionOrderReceiptLinks($ids);
if ($exceptPrescriptionOrderId !== null) {
$links->where('link.prescription_order_id', '<>', $exceptPrescriptionOrderId);
}
$activeSet = array_fill_keys(array_map('intval', $activePoIds), true);
$links = PrescriptionOrderPayOrder::whereIn('pay_order_id', $ids)->select();
foreach ($links as $link) {
$poId = (int) $link->prescription_order_id;
if ($exceptPrescriptionOrderId !== null && $poId === $exceptPrescriptionOrderId) {
continue;
}
if (!isset($activeSet[$poId])) {
continue;
}
return '支付单 #' . (int) $link->pay_order_id . ' 已关联其他有效业务订单,不可重复关联';
}
return null;
// 等待收款行锁后,用当前读检查其他事务是否已经占用收款。
$link = $links->field('link.pay_order_id')->lock(true)->find();
return $link ? '支付单 #' . $link['pay_order_id'] . ' 已关联业务订单,不可重复关联' : null;
}
/** 收款关联增删共用订单行锁,失败时连同金额和日志一起回滚。 */
@@ -1073,22 +1064,22 @@ class PrescriptionOrderLogic
if (!$order) {
return;
}
$amount = round((float) $order->amount, 2);
$paid = 0.0;
$ids = self::linkedPayOrderIdList($id);
if ($ids !== []) {
$payOrders = Order::whereIn('id', $ids)->whereNull('delete_time')->field(['amount', 'status'])->select();
foreach ($payOrders as $po) {
$st = (int) $po->status;
if ($st === 2 || $st === 5) {
$paid += (float) $po->amount;
}
}
}
$order->agency_collect_amount = round($amount - $paid, 2);
$amount = (int) round((float) $order->amount * 100);
$paid = self::linkedPayPaidCents(self::linkedPayOrderIdList($id));
$order->agency_collect_amount = ($amount - $paid) / 100;
$order->save();
}
/** @param int[] $ids */
private static function linkedPayPaidCents(array $ids): int
{
if ($ids === []) {
return 0;
}
return (int) round((float) Order::whereIn('id', $ids)->whereNull('delete_time')
->whereIn('status', [2, 5])->sum('amount') * 100);
}
/**
* @param array<string,mixed> $params
* @return array<string,mixed>|false
@@ -1329,7 +1320,199 @@ class PrescriptionOrderLogic
return $edited;
}
public static function detail(int $id, int $adminId, array $adminInfo): ?array
private static function prescriptionLinkPermissions(int $adminId, array $adminInfo): array
{
if ($adminId <= 0) {
return [];
}
if ((int) ($adminInfo['root'] ?? 0) === 1) {
return [self::VIEW_RX_LINKS_PERMISSION, self::BIND_RX_PERMISSION];
}
return AuthLogic::getAuthByAdminId($adminId);
}
/** @return int[] 有权访问的同患者诊单。没有患者编号的旧诊单仅匹配自身。 */
private static function prescriptionLinkDiagnosisIds(int $diagnosisId, int $adminId, array $adminInfo): array
{
if ($diagnosisId <= 0) {
return [];
}
$scope = DiagnosisLogic::readonlyDiagnosisQuery($adminId, $adminInfo);
$diagnosis = (clone $scope)->where('id', $diagnosisId)->field('id,patient_id')->find();
if (!$diagnosis) {
return [];
}
$patientId = (int) $diagnosis->patient_id;
return $patientId > 0
? array_map('intval', $scope->where('patient_id', $patientId)->column('id'))
: [$diagnosisId];
}
private static function scopedOrdersForPrescriptionLink(array $diagnosisIds, int $adminId, array $adminInfo): Query
{
$query = Db::name('tcm_prescription_order')->alias('o')
->whereIn('o.diagnosis_id', $diagnosisIds)->whereNull('o.delete_time');
self::applyPrescriptionOrderListAccessForCommissionQuery($query, 'o', $adminId, $adminInfo);
return $query;
}
private static function ordersWithReplaceablePrescription(Query $orders): Query
{
return $orders->leftJoin([Db::name('tcm_prescription')->getTable() => 'original_rx'],
'original_rx.id = o.prescription_id AND original_rx.diagnosis_id = o.diagnosis_id'
. ' AND original_rx.delete_time IS NULL')
->where(static function (Query $query): void {
$query->where('original_rx.void_status', 1)->whereOr('original_rx.audit_status', 2)
->whereOr('o.prescription_audit_status', 2);
});
}
/** @return array{orders: array, can_bind: bool} */
public static function prescriptionOrdersForBinding(int $rxId, string $orderNo, int $adminId, array $adminInfo): array
{
$permissions = self::prescriptionLinkPermissions($adminId, $adminInfo);
if (!in_array(self::VIEW_RX_LINKS_PERMISSION, $permissions, true)) {
throw new \DomainException('无权限查看关联业务订单');
}
$rx = Prescription::where('id', $rxId)->whereNull('delete_time')->find();
if (!$rx || !PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
throw new \DomainException('处方不存在或无权查看');
}
$diagnosisId = (int) $rx->diagnosis_id;
if ($diagnosisId <= 0) {
return ['orders' => [], 'can_bind' => false];
}
$diagnosisIds = self::prescriptionLinkDiagnosisIds($diagnosisId, $adminId, $adminInfo);
if ($diagnosisIds === []) {
throw new \DomainException('诊单不存在或无权访问');
}
$canBind = (int) $rx->void_status === 0 && (int) $rx->audit_status !== 2
&& in_array(self::BIND_RX_PERMISSION, $permissions, true);
$ids = Db::name(self::RX_LINK_TABLE)->where('prescription_id', $rxId)->column('prescription_order_id');
$base = self::scopedOrdersForPrescriptionLink($diagnosisIds, $adminId, $adminInfo)
->field('o.id,o.order_no,o.fulfillment_status,o.prescription_id')->order('o.id', 'desc');
$linked = (clone $base)->where(static function (Query $query) use ($rxId, $ids): void {
$query->where('o.prescription_id', $rxId);
if ($ids !== []) {
$query->whereOr('o.id', 'in', $ids);
}
})->select()->toArray();
foreach ($linked as &$order) {
$order['id'] = (int) $order['id'];
$order['fulfillment_status'] = (int) $order['fulfillment_status'];
$order['is_primary'] = (int) $order['prescription_id'] === $rxId;
$order['is_linked'] = true;
unset($order['prescription_id']);
}
unset($order);
if ($canBind) {
$candidates = self::ordersWithReplaceablePrescription($base)
->where(static function (Query $query) use ($rxId): void {
$query->whereNull('o.prescription_id')->whereOr('o.prescription_id', '<>', $rxId);
});
if ($ids !== []) {
$candidates->whereNotIn('o.id', $ids);
}
if ($orderNo !== '') {
$candidates->whereLike('o.order_no', '%' . $orderNo . '%');
}
foreach ($candidates->limit(30)->select() as $order) {
$linked[] = [
'id' => (int) $order['id'], 'order_no' => $order['order_no'],
'fulfillment_status' => (int) $order['fulfillment_status'],
'is_linked' => false, 'is_primary' => false,
];
}
}
return ['orders' => $linked, 'can_bind' => $canBind];
}
/** 原处方作废或驳回后可补关联同患者的新处方,供订单详情和处方笺查阅。 */
public static function bindPrescription(int $orderId, int $rxId, int $adminId, array $adminInfo): void
{
$permissions = self::prescriptionLinkPermissions($adminId, $adminInfo);
if (array_diff([self::VIEW_RX_LINKS_PERMISSION, self::BIND_RX_PERMISSION], $permissions) !== []) {
throw new \DomainException('无权限绑定业务订单');
}
Db::transaction(static function () use ($orderId, $rxId, $adminId, $adminInfo): void {
// 与处方作废和业务订单审核保持相同的加锁顺序。
$order = Db::name('tcm_prescription_order')->where('id', $orderId)->whereNull('delete_time')->lock(true)->find();
if (!$order || !self::scopedOrdersForPrescriptionLink([(int) $order['diagnosis_id']], $adminId, $adminInfo)
->where('o.id', $orderId)->find()) {
throw new \DomainException('业务订单不存在或无权访问');
}
$rx = Prescription::where('id', $rxId)->whereNull('delete_time')->lock(true)->find();
if (!$rx || !PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
throw new \DomainException('处方不存在或无权查看');
}
$diagnosisIds = self::prescriptionLinkDiagnosisIds((int) $rx->diagnosis_id, $adminId, $adminInfo);
if (!in_array((int) $order['diagnosis_id'], $diagnosisIds, true)) {
throw new \DomainException('仅可绑定同一患者且有权访问的业务订单');
}
$keys = ['prescription_order_id' => $orderId, 'prescription_id' => $rxId];
if ((int) $order['prescription_id'] === $rxId || Db::name(self::RX_LINK_TABLE)->where($keys)->find()) {
return;
}
if ((int) $rx->void_status !== 0 || (int) $rx->audit_status === 2) {
throw new \DomainException('已作废或已驳回的处方不能作为新处方绑定');
}
$original = self::ordersWithReplaceablePrescription(
Db::name('tcm_prescription_order')->alias('o')->where('o.id', $orderId)
)->field('original_rx.sn,original_rx.void_status')->lock(true)->find();
if (!$original) {
throw new \DomainException('原处方已作废或处方审核已驳回的业务订单才可绑定新处方');
}
Db::name(self::RX_LINK_TABLE)->insert($keys + ['create_by' => $adminId, 'create_time' => time()]);
$reason = (int) $original['void_status'] === 1 ? '已作废' : '审核已驳回';
$subject = $original['sn'] !== null ? '原处方 ' . $original['sn'] . ' ' : '业务订单处方';
self::writeLog($orderId, $adminId, $adminInfo, 'bind_prescription',
$subject . $reason . ',绑定关联处方 ' . (string) $rx->sn, true);
});
}
/** @return ?array 已授权时返回可见范围内的处方摘要 */
private static function linkedPrescriptionsForDetail(array $order, int $adminId, array $adminInfo): ?array
{
if (!in_array(self::VIEW_RX_LINKS_PERMISSION, self::prescriptionLinkPermissions($adminId, $adminInfo), true)) {
return null;
}
$diagnosisId = (int) ($order['diagnosis_id'] ?? 0);
$diagnosisIds = self::prescriptionLinkDiagnosisIds($diagnosisId, $adminId, $adminInfo);
if ($diagnosisIds === [] || !self::scopedOrdersForPrescriptionLink([$diagnosisId], $adminId, $adminInfo)
->where('o.id', (int) $order['id'])->find()) {
return null;
}
$primaryId = (int) $order['prescription_id'];
$ids = Db::name(self::RX_LINK_TABLE)->where('prescription_order_id', (int) $order['id'])->column('prescription_id');
$ids[] = $primaryId;
$visible = [];
$rows = Db::name('tcm_prescription')->whereIn('id', $ids)->whereIn('diagnosis_id', $diagnosisIds)
->whereNull('delete_time')->field('id,sn,diagnosis_id,void_status,creator_id,assistant_id,is_shared,visible_role_ids')
->order('id', 'desc')->select();
foreach ($rows as $rx) {
if (PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
$id = (int) $rx['id'];
$visible[$id] = [
'id' => $id, 'sn' => $rx['sn'], 'diagnosis_id' => (int) $rx['diagnosis_id'],
'void_status' => (int) $rx['void_status'], 'is_primary' => $id === $primaryId,
];
}
}
if (isset($visible[$primaryId])) {
$visible = [$primaryId => $visible[$primaryId]] + $visible;
}
return array_values($visible);
}
public static function detail(int $id, int $adminId, array $adminInfo, ?int $viewedRxId = null): ?array
{
self::$error = '';
$row = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find();
@@ -1344,6 +1527,16 @@ class PrescriptionOrderLogic
return null;
}
$arr = $row->toArray();
$linked = $viewedRxId === null ? null : self::linkedPrescriptionsForDetail($arr, $adminId, $adminInfo);
$viewReference = $viewedRxId > 0 && $viewedRxId !== (int) $row->prescription_id;
$referenceDiagnosisId = $viewReference ? (array_column($linked ?? [], 'diagnosis_id', 'id')[$viewedRxId] ?? 0) : 0;
if ($viewReference && !$referenceDiagnosisId) {
self::$error = '关联处方不存在或无权查看';
return null;
}
if ($linked !== null) {
$arr['linked_prescriptions'] = $linked;
}
self::maskInternalCostIfNeeded($arr, $adminInfo);
self::maskRemarkExtraIfNeeded($arr, $adminInfo);
self::attachLinkedPayOrders($arr);
@@ -1387,21 +1580,16 @@ class PrescriptionOrderLogic
}
$arr = self::withReviewAvailability($arr, $arr['prescription'] ?? []);
if (self::canAttachReceipt($adminId, $adminInfo)) {
$arr['attachable_receipts'] = OrderLogic::listPaidOrdersForDiagnosis(
(int) $arr['diagnosis_id'], $adminId, $adminInfo
);
}
$canHerbs = self::canViewPrescriptionHerbsInOrderDetail($adminInfo);
$arr['prescription_detail_herbs_visible'] = $canHerbs;
if (! $canHerbs && isset($arr['prescription']) && is_array($arr['prescription'])) {
$rx = &$arr['prescription'];
$herbs = is_array($rx['herbs'] ?? null) ? $rx['herbs'] : [];
$hasAux = false;
foreach ($herbs as $h) {
if (is_array($h) && (string) ($h['formula_type'] ?? '') === '辅方') {
$hasAux = true;
break;
}
}
$rx['has_aux_formula'] = $hasAux ? 1 : 0;
unset($rx['herbs']);
if (!$canHerbs && is_array($arr['prescription'])) {
self::maskPrescriptionHerbs($arr['prescription']);
}
// 诊单医助 / 诊单创建人姓名(tcm_diagnosis.admin_id);部门见下方:优先业务订单 creator_id
@@ -1487,9 +1675,28 @@ class PrescriptionOrderLogic
// 已发货后服用天数锁定(前端据此禁用天数输入,服务端同样拦截)。
$arr['days_locked'] = self::isOrderShipped($row->toArray());
if ($viewReference) {
$rx = PrescriptionLogic::orderReferenceDetail($viewedRxId, $referenceDiagnosisId, $adminId, $adminInfo);
if (!$rx) {
self::$error = '关联处方不存在或无权查看';
return null;
}
if (!$canHerbs) {
self::maskPrescriptionHerbs($rx);
$rx['esign']['can_download'] = false;
}
$arr['prescription'] = $rx;
}
return $arr;
}
private static function maskPrescriptionHerbs(array &$rx): void
{
$herbs = is_array($rx['herbs'] ?? null) ? $rx['herbs'] : [];
$rx['has_aux_formula'] = in_array('辅方', array_column($herbs, 'formula_type'), true) ? 1 : 0;
unset($rx['herbs']);
}
/**
* 业务订单详情场景:仅更新关联处方的患者姓名与手机号(不重置消费者处方审核、不改变其它处方字段)
*/
@@ -3165,6 +3372,11 @@ class PrescriptionOrderLogic
*/
public static function linkPayOrder(array $params, int $adminId, array $adminInfo)
{
self::$error = '';
if (!self::canAttachReceipt($adminId, $adminInfo)) {
self::$error = '无权限关联收款';
return false;
}
return self::mutatePayOrderLinks(
(int) ($params['id'] ?? 0),
static fn () => self::linkPayOrderLocked($params, $adminId, $adminInfo)
@@ -3277,6 +3489,90 @@ class PrescriptionOrderLogic
return $out;
}
private static function canAttachReceipt(int $adminId, array $adminInfo): bool
{
return (int) ($adminInfo['root'] ?? 0) === 1
|| in_array(self::ATTACH_RECEIPT_PERMISSION, AuthLogic::getAuthByAdminId($adminId), true);
}
/** 补录已支付收款的关联,适用于任意订单状态。 */
public static function attachReceipt(array $params, int $adminId, array $adminInfo): array|false
{
self::$error = '';
if (!self::canAttachReceipt($adminId, $adminInfo)) {
self::$error = '无权限关联收款';
return false;
}
$id = (int) ($params['id'] ?? 0);
$payOrderId = (int) ($params['pay_order_id'] ?? 0);
if ($payOrderId <= 0) {
self::$error = '请选择要关联的收款记录';
return false;
}
return self::mutatePayOrderLinks($id, static function () use ($id, $payOrderId, $adminId, $adminInfo): array|false {
$order = PrescriptionOrder::find($id);
if (!self::canAccessOrder($order, $adminId, $adminInfo)) {
self::$error = '无权限操作此订单';
return false;
}
$error = OrderLogic::assertPayOrdersLinkable([$payOrderId], (int) $order->diagnosis_id, $adminId, $adminInfo);
$error ??= self::assertPayOrdersExclusive([$payOrderId], null);
if ($error !== null) {
self::$error = $error;
return false;
}
$payOrder = Order::where('id', $payOrderId)->whereNull('delete_time')->lock(true)->find();
$receiptCents = (int) round((float) ($payOrder->amount ?? 0) * 100);
if (!$payOrder || $receiptCents < 0) {
self::$error = '收款金额异常,请先核对金额';
return false;
}
$previousIds = self::linkedPayOrderIdList($id);
$previousLinkedCents = self::linkedPayPaidCents($previousIds);
$linkedCents = $previousLinkedCents + $receiptCents;
$amountCents = (int) round((float) $order->amount * 100);
$previousDueCents = max(0, $amountCents - $previousLinkedCents);
$completed = (int) $order->fulfillment_status === 3;
$increaseCents = 0;
if ($completed) {
// 补录的款项先抵销已有欠款。超出欠款的部分属于结案后的追加收款。
$increaseCents = max(0, $receiptCents - $previousDueCents);
$amountCents += $increaseCents;
$order->amount = $amountCents / 100;
// 部分退款时 paid 可能低于关联收款原额,增量入账可保留已扣退款。
$order->paid = (float) ($order->refund_amount ?? 0) > 0
? min($linkedCents, (int) round((float) $order->paid * 100) + $receiptCents) / 100
: $linkedCents / 100;
}
$dueCents = $completed ? max(0, $amountCents - $linkedCents) : $amountCents - $linkedCents;
$link = new PrescriptionOrderPayOrder();
if (!$link->save(['prescription_order_id' => $id, 'pay_order_id' => $payOrderId, 'create_time' => time()])) {
throw new \RuntimeException('收款关联未保存');
}
$order->linked_pay_order_id = $previousIds[0] ?? $payOrderId;
$order->agency_collect_amount = $dueCents / 100;
if (!$order->save()) {
throw new \RuntimeException('订单收款关联未保存');
}
$summary = sprintf('关联已支付收款 #%d(¥%.2f)', $payOrderId, $receiptCents / 100);
if ($completed) {
$summary .= sprintf(',订单总金额 ¥%.2f → ¥%.2f,需代收 ¥%.2f → ¥%.2f',
($amountCents - $increaseCents) / 100, $amountCents / 100, $previousDueCents / 100, $dueCents / 100);
}
self::writeLog($id, $adminId, $adminInfo, 'link_pay_order', $summary, true);
$out = PrescriptionOrder::find($id)->toArray();
self::maskInternalCostIfNeeded($out, $adminInfo);
self::maskRemarkExtraIfNeeded($out, $adminInfo);
self::attachLinkedPayOrders($out);
return $out;
});
}
/**
* 移除单笔收款关联:保留原支付单、总金额与履约/审核状态,同步已付及代收金额。
* 普通订单 paid 按剩余有效收款重算;退款订单的 paid 保留退款后的余额口径。
@@ -3306,8 +3602,8 @@ class PrescriptionOrderLogic
self::$error = '无权限操作此订单';
return false;
}
if (in_array((int) $order->fulfillment_status, [3, 4], true)) {
self::$error = '已完成或已取消的订单不允许移除收款关联';
if ((int) $order->fulfillment_status === 4) {
self::$error = '已取消的订单不允许移除收款关联';
return false;
}
if (!in_array($payOrderId, self::linkedPayOrderIdList($id), true)) {
@@ -3334,8 +3630,7 @@ class PrescriptionOrderLogic
throw new \RuntimeException('收款关联已变化,请刷新后重试');
}
$remainingIds = self::linkedPayOrderIdList($id);
$remainingPaidCents = $remainingIds === [] ? 0 : (int) round((float) Order::whereIn('id', $remainingIds)
->whereNull('delete_time')->whereIn('status', [2, 5])->sum('amount') * 100);
$remainingPaidCents = self::linkedPayPaidCents($remainingIds);
$order->linked_pay_order_id = $remainingIds[0] ?? null;
// 部分退款可能未拆分收款单金额,不能用剩余收款原额覆盖退款后的 paid 余额。
$hasRefund = (float) ($order->refund_amount ?? 0) > 0 || (int) $order->fulfillment_status === 10;
@@ -3344,8 +3639,11 @@ class PrescriptionOrderLogic
: $remainingPaidCents;
$order->paid = $newPaidCents / 100;
// 与详情的关联已付总额口径一致;订单 amount 不变。
$order->agency_collect_amount = round((float) $order->amount - $remainingPaidCents / 100, 2);
$order->save();
$dueCents = (int) round((float) $order->amount * 100) - $remainingPaidCents;
$order->agency_collect_amount = ((int) $order->fulfillment_status === 3 ? max(0, $dueCents) : $dueCents) / 100;
if (!$order->save()) {
throw new \RuntimeException('订单收款关联未保存');
}
self::writeLog($id, $adminId, $adminInfo, 'unlink_pay_order', sprintf(
'移除%s收款关联 #%d(%s,¥%.2f),订单总金额 ¥%.2f 不变;已付金额(paid)¥%.2f → ¥%.2f;原收款记录保留',
@@ -3357,6 +3655,11 @@ class PrescriptionOrderLogic
self::maskInternalCostIfNeeded($out, $adminInfo);
self::maskRemarkExtraIfNeeded($out, $adminInfo);
self::attachLinkedPayOrders($out);
if (self::canAttachReceipt($adminId, $adminInfo)) {
$out['attachable_receipts'] = OrderLogic::listPaidOrdersForDiagnosis(
(int) $order->diagnosis_id, $adminId, $adminInfo
);
}
return $out;
}
@@ -47,6 +47,7 @@ class PrescriptionOrderValidate extends BaseValidate
'patient_name' => 'require|max:50',
'phone' => 'require|max:20',
'phone_tail' => 'max:20|regex:/^\\d*$/',
'order_no' => 'alphaDash|max:50',
];
protected $message = [
@@ -73,7 +74,6 @@ class PrescriptionOrderValidate extends BaseValidate
'is_follow_up', 'prev_staff', 'service_channel', 'service_package',
'tracking_number', 'express_company', 'ship_mode', 'fee_type', 'amount', 'remark_extra', 'remark_assistant', 'pay_order_ids',
],
'detail' => ['id'],
'editTime' => ['id', 'create_time'],
'edit' => [
'id', 'recipient_name', 'recipient_phone', 'shipping_address',
@@ -106,6 +106,30 @@ class PrescriptionOrderValidate extends BaseValidate
'confirmGancaoSubmission' => ['id', 'resolution', 'remote_order_no', 'note'],
];
public function sceneAttachReceipt(): PrescriptionOrderValidate
{
return $this->only(['id', 'pay_order_id'])
->append('id', 'require|integer|gt:0')
->append('pay_order_id', 'require|integer|gt:0');
}
public function sceneDetail(): PrescriptionOrderValidate
{
return $this->only(['id', 'prescription_id'])
->remove('prescription_id', 'require')
->append('prescription_id', 'gt:0');
}
public function scenePrescriptionOrdersForBinding(): PrescriptionOrderValidate
{
return $this->only(['prescription_id', 'order_no'])->append('prescription_id', 'gt:0');
}
public function sceneBindPrescription(): PrescriptionOrderValidate
{
return $this->only(['id', 'prescription_id'])->append('id', 'gt:0')->append('prescription_id', 'gt:0');
}
public function sceneUnlinkPayOrder(): PrescriptionOrderValidate
{
return $this->only(['id', 'pay_order_id'])
@@ -0,0 +1,14 @@
-- 执行后在角色权限「处方业务订单」下按需勾选「关联收款」。
SET @po_menu_id := (
SELECT id FROM zyt_system_menu WHERE perms = 'tcm.prescriptionOrder/lists' LIMIT 1
);
INSERT INTO zyt_system_menu (
pid, type, name, icon, sort, perms, paths, component,
selected, params, is_cache, is_show, is_disable, create_time, update_time
)
SELECT @po_menu_id, 'A', '关联收款', '', 33, 'tcm.prescriptionOrder/attachReceipt', '', '',
'', '', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
FROM DUAL
WHERE @po_menu_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms = 'tcm.prescriptionOrder/attachReceipt');
@@ -0,0 +1,30 @@
-- 主处方仍由 tcm_prescription_order.prescription_id 管理。关联表用于附加处方查阅。
CREATE TABLE IF NOT EXISTS zyt_tcm_prescription_order_prescription (
prescription_order_id int unsigned NOT NULL,
prescription_id int unsigned NOT NULL,
create_by int unsigned NOT NULL,
create_time int unsigned NOT NULL,
PRIMARY KEY (prescription_order_id, prescription_id),
KEY idx_prescription (prescription_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='业务订单关联处方';
SET @rx_menu_id = (
SELECT id FROM zyt_system_menu WHERE type = 'C' AND perms = 'tcm.prescription/lists'
AND component = 'consumer/prescription/index' ORDER BY id LIMIT 1
);
INSERT INTO zyt_system_menu
(pid, type, name, icon, sort, perms, paths, component, selected, params, is_cache, is_show, is_disable, create_time, update_time)
SELECT @rx_menu_id, 'A', '查看关联业务订单与处方', '', 0,
'tcm.prescriptionOrder/prescriptionOrdersForBinding', '', '', '', '', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
FROM DUAL
WHERE @rx_menu_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms = 'tcm.prescriptionOrder/prescriptionOrdersForBinding');
INSERT INTO zyt_system_menu
(pid, type, name, icon, sort, perms, paths, component, selected, params, is_cache, is_show, is_disable, create_time, update_time)
SELECT @rx_menu_id, 'A', '绑定业务订单', '', 0,
'tcm.prescriptionOrder/bindPrescription', '', '', '', '', 0, 1, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
FROM DUAL
WHERE @rx_menu_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms = 'tcm.prescriptionOrder/bindPrescription');
@@ -0,0 +1,275 @@
<?php
declare(strict_types=1);
/** Runs against a disposable local MySQL database. Never loads the site's database configuration. */
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\adminapi\validate\tcm\PrescriptionOrderValidate;
use think\Container;
use think\DbManager;
use think\facade\Db;
$port = (int) getenv('ZYT_RX_LINK_TEST_MYSQL_PORT');
if ($port <= 0) {
fwrite(STDERR, "Set ZYT_RX_LINK_TEST_MYSQL_PORT to an isolated local MySQL instance.\n");
exit(1);
}
$database = 'rx_links_test_' . bin2hex(random_bytes(6));
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec("CREATE DATABASE {$database} CHARACTER SET utf8mb4");
$pdo->exec("USE {$database}");
$app = new think\App();
$manager = new DbManager();
$manager->setConfig([
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
'connections' => ['mysql' => [
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port, 'database' => $database,
'username' => 'root', 'password' => '', 'charset' => 'utf8mb4', 'prefix' => 'zyt_', 'fields_strict' => true,
]],
]);
Container::getInstance()->instance('think\DbManager', $manager);
$config = new think\Config();
$config->set(['data_scope' => ['enabled' => false]], 'project');
Container::getInstance()->instance('config', $config);
think\Validate::maker(static fn (think\Validate $validator) => $validator->setLang(new think\Lang($app)));
$checks = 0;
$expect = static function (bool $condition, string $message) use (&$checks): void {
if (!$condition) {
throw new RuntimeException($message . ' | ' . PrescriptionOrderLogic::getError());
}
$checks++;
};
$denied = static function (callable $call, string $message) use ($expect): void {
try {
$call();
} catch (DomainException) {
$expect(true, $message);
return;
}
$expect(false, $message);
};
$migration = dirname(__DIR__) . '/database/migrations/';
try {
foreach (['2026_04_07_create_tcm_prescription_order.sql', '2026_04_09_prescription_order_pay_links.sql'] as $file) {
$pdo->exec(file_get_contents($migration . $file));
}
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
id INT PRIMARY KEY, sn VARCHAR(32), diagnosis_id INT, creator_id INT, assistant_id INT,
is_shared INT DEFAULT 0, visible_role_ids VARCHAR(80) DEFAULT "", void_status INT DEFAULT 0,
audit_status INT DEFAULT 1, gender INT DEFAULT 1, dose_count INT DEFAULT 1,
usage_days INT DEFAULT 7, esign_required INT DEFAULT 0, herbs TEXT,
delete_time INT NULL
)');
$pdo->exec('CREATE TABLE zyt_tcm_diagnosis (
id INT PRIMARY KEY, patient_id INT DEFAULT 0, assistant_id INT DEFAULT 0,
status INT DEFAULT 1, id_card VARCHAR(32), delete_time INT NULL
)');
$pdo->exec('CREATE TABLE zyt_system_menu (
id INT PRIMARY KEY AUTO_INCREMENT, pid INT, type VARCHAR(5), name VARCHAR(100), icon VARCHAR(50),
sort INT, perms VARCHAR(100), paths VARCHAR(100), component VARCHAR(100), selected VARCHAR(100),
params VARCHAR(100), is_cache INT, is_show INT, is_disable INT DEFAULT 0, create_time INT, update_time INT
)');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_log (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, admin_id INT, admin_name VARCHAR(64),
action VARCHAR(32), summary VARCHAR(500), create_time INT
)');
$pdo->exec('CREATE TABLE zyt_order (id INT PRIMARY KEY, patient_id INT, status INT, delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY, type VARCHAR(32), name VARCHAR(32), value TEXT)');
$pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY, name VARCHAR(64), account VARCHAR(64), delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_admin_dept (admin_id INT, dept_id INT)');
$pdo->exec('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
$pdo->exec('CREATE TABLE zyt_system_role (id INT PRIMARY KEY, name VARCHAR(64), data_scope INT, delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_system_role_menu (role_id INT, menu_id INT)');
$pdo->exec('CREATE TABLE zyt_doctor_appointment (id INT PRIMARY KEY, patient_id INT, doctor_id INT, status INT, delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY, prescription_order_id INT, source_revision INT)');
Db::name('system_menu')->insert(['type' => 'C', 'perms' => 'tcm.prescription/lists', 'component' => 'consumer/prescription/index']);
Db::name('tcm_diagnosis')->insertAll([
['id' => 1, 'patient_id' => 100, 'id_card' => 'TEST-PRIVATE'],
['id' => 2, 'patient_id' => 200, 'id_card' => 'OTHER'],
['id' => 3, 'patient_id' => 100, 'id_card' => 'TEST-PRIVATE'],
['id' => 4, 'patient_id' => 0, 'id_card' => 'LEGACY'],
['id' => 5, 'patient_id' => 0, 'id_card' => 'LEGACY'],
]);
foreach ([
[101, 1, 2, 1], [102, 1, 2, 0], [103, 2, 2, 1], [104, 1, 3, 1], [105, 1, 2, 0],
[106, 3, 2, 0], [107, 4, 2, 1], [108, 5, 2, 0], [109, 4, 2, 0], [110, 3, 2, 1],
[111, 1, 2, 0], [112, 1, 2, 0], [113, 1, 2, 1],
] as [$id, $diagnosisId, $owner, $void]) {
Db::name('tcm_prescription')->insert([
'id' => $id, 'sn' => 'RX-' . $id, 'diagnosis_id' => $diagnosisId, 'creator_id' => $owner,
'void_status' => $void, 'dose_count' => $id === 102 ? 2 : 1,
'herbs' => '[{"name":"fixture","formula_type":"辅方"}]',
]);
}
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order MODIFY prescription_id INT UNSIGNED NULL DEFAULT 0');
foreach ([
[201, 1, 101, 2, 1], [202, 1, 102, 2, 3], [203, 1, 104, 3, 6], [204, 2, 103, 2, 1],
[205, 4, 107, 2, 1], [206, 1, 101, 2, 3],
[207, 1, 105, 2, 1], [208, 1, 111, 2, 1], [209, 1, 112, 2, 1],
[210, 1, 0, 2, 1], [211, 1, 999, 2, 1], [212, 1, 113, 2, 1], [213, 1, 0, 2, 1],
[214, 1, null, 2, 1], [215, 1, 113, 2, 1],
] as [$id, $diagnosisId, $primary, $owner, $status]) {
Db::name('tcm_prescription_order')->insert([
'id' => $id, 'order_no' => 'PO-' . $id, 'diagnosis_id' => $diagnosisId, 'prescription_id' => $primary,
'creator_id' => $owner, 'fulfillment_status' => $status, 'prescription_audit_status' => 1,
'payment_slip_audit_status' => 1, 'recipient_name' => 'recipient-' . $id,
]);
}
Db::name('tcm_prescription')->where('id', 111)->update(['audit_status' => 2]);
Db::name('tcm_prescription')->where('id', 113)->update(['delete_time' => time()]);
Db::name('tcm_prescription_order')->whereIn('id', [207, 210, 211, 212, 214])->update(['prescription_audit_status' => 2]);
Db::name('tcm_prescription_order')->where('id', 209)->update(['payment_slip_audit_status' => 2]);
Db::name('system_role')->insert(['id' => 11, 'name' => '隔离测试角色', 'data_scope' => 4]);
Db::name('admin_role')->insert(['admin_id' => 2, 'role_id' => 11]);
$operator = ['root' => 0, 'admin_id' => 2, 'role_id' => [11], 'name' => '隔离测试员'];
$root = ['root' => 1, 'admin_id' => 1, 'name' => '隔离管理员'];
$list = static fn (int $id, string $sn = '') => PrescriptionOrderLogic::prescriptionOrdersForBinding($id, $sn, 2, $operator);
$bind = static fn (int $order, int $rx) => PrescriptionOrderLogic::bindPrescription($order, $rx, 2, $operator);
$denied(fn () => $list(102), 'Viewing or owning a prescription does not grant viewing its order links');
$sql = file_get_contents($migration . '2026_12_01_prescription_order_prescription_links.sql');
$pdo->exec($sql);
$pdo->exec($sql);
$path = 'tcm.prescriptionOrder/';
$menuIds = Db::name('system_menu')->whereIn('perms', [$path . 'prescriptionOrdersForBinding', $path . 'bindPrescription'])
->column('id', 'perms');
$expect(count($menuIds) === 2 && Db::name('system_role_menu')->count() === 0,
'Migration is repeatable and grants no roles');
Db::name('system_role_menu')->insert(['role_id' => 11, 'menu_id' => $menuIds[$path . 'prescriptionOrdersForBinding']]);
$result = $list(102);
$expect(!$result['can_bind'] && count($result['orders']) === 1 && $result['orders'][0]['is_primary'],
'View permission returns established links without exposing candidates');
$denied(fn () => $bind(201, 102), 'Viewing permission does not permit binding');
Db::name('system_role_menu')->insert(['role_id' => 11, 'menu_id' => $menuIds[$path . 'bindPrescription']]);
$expect(!PrescriptionOrderLogic::hasPrescriptionOrderMenuAccess($operator), 'Binding permission does not unlock unrelated order actions');
$result = $list(102, 'PO-201');
$expect($result['can_bind'] && array_map('intval', array_column($result['orders'], 'id')) === [202, 201],
'Search returns existing links and voided-primary candidates in scope');
$expect($list(106, 'PO-202')['orders'] === [], 'An order with an active original prescription is not offered');
$expect($list(106, 'PO-203')['orders'] === [], 'An inaccessible order with a voided original is not offered');
$expect($list(106, 'PO-204')['orders'] === [], 'An order for a different patient is not offered');
$expect(array_column($list(106, 'PO-206')['orders'], 'id') === [206],
'Order search finds a completed order from a different diagnosis of the same patient');
$expect(!$list(101)['can_bind'], 'A voided prescription can show its orders but cannot be bound again');
$expect(array_column($list(109, 'PO-205')['orders'], 'id') === [205] && $list(108, 'PO-205')['orders'] === [],
'Legacy patients without a patient ID can only bind within their own diagnosis');
$denied(fn () => $bind(203, 102), 'An order outside the data scope cannot be bound');
$denied(fn () => $bind(204, 102), 'Cross-patient binding cannot be done');
$denied(fn () => $bind(201, 104), 'An unreadable prescription cannot be bound');
$denied(fn () => $bind(202, 106), 'The API rejects an order with a live original');
$denied(fn () => $bind(201, 110), 'The API rejects a voided replacement');
$denied(fn () => $bind(205, 108), 'Legacy patient identities cannot match by card or placeholder ID');
Db::name('tcm_prescription')->where('id', 101)->update(['void_status' => 0]);
$denied(fn () => $bind(206, 106), 'The API rechecks the original current status after candidates are loaded');
Db::name('tcm_prescription')->where('id', 101)->update(['void_status' => 1]);
$before = Db::name('tcm_prescription_order')->where('id', 201)->find();
$bind(201, 102);
$bind(201, 102);
$bind(201, 101);
$expect(Db::name('tcm_prescription_order_prescription')->count() === 1
&& Db::name('tcm_prescription_order_log')->where('action', 'bind_prescription')->count() === 1
&& $before === Db::name('tcm_prescription_order')->where('id', 201)->find(),
'Duplicate and primary binds are idempotent and preserve operational order fields');
$result = $list(102);
$linkedOrders = array_values(array_filter($result['orders'], static fn (array $order) => $order['is_linked']));
$expect(array_column($linkedOrders, 'id') === [202, 201] && !$linkedOrders[1]['is_primary'],
'A supplemental prescription is visible from the reverse lookup');
$pdo->exec("CREATE TRIGGER reject_bind_log BEFORE INSERT ON zyt_tcm_prescription_order_log
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced bind log failure'");
try {
$bind(201, 105);
} catch (RuntimeException $exception) {
$expect(str_contains($exception->getMessage(), '日志写入失败'), 'Failed log invalidates the binding');
}
$expect(Db::name('tcm_prescription_order_prescription')->where('prescription_id', 105)->count() === 0,
'A log exception rolls back the binding');
$pdo->exec('DROP TRIGGER reject_bind_log');
$detail = PrescriptionOrderLogic::detail(201, 2, $operator, 0);
$expect(array_column($detail['linked_prescriptions'], 'id') === [101, 102]
&& (int) $detail['prescription']['id'] === 101, 'Order detail defaults to the primary prescription');
$ref = PrescriptionOrderLogic::detail(201, 2, $operator, 102);
$expect((int) $ref['prescription_id'] === 101 && (int) $ref['prescription']['id'] === 102
&& (int) $ref['prescription']['dose_count'] === 2 && !$ref['prescription']['can_review_prescription']
&& !isset($ref['prescription']['recipient_name'])
&& !isset($ref['prescription']['herbs']) && (int) $ref['prescription']['has_aux_formula'] === 1,
'Switching shows the selected original prescription, honoring herb masking and avoiding another order snapshot');
$expect(PrescriptionOrderLogic::detail(201, 1, $root, 105) === null, 'Even root cannot load a prescription unrelated to this order');
$bind(206, 106);
$linkedOrders = array_filter($list(106)['orders'], static fn (array $order) => $order['is_linked']);
$expect(array_column($linkedOrders, 'id') === [206],
'The reverse lookup shows the linked order across diagnoses');
$crossDiagnosis = PrescriptionOrderLogic::detail(206, 2, $operator, 106);
$expect(array_column($crossDiagnosis['linked_prescriptions'], 'id') === [101, 106]
&& (int) $crossDiagnosis['prescription']['id'] === 106 && (int) $crossDiagnosis['fulfillment_status'] === 3,
'The same order retains its archived original and can preview the new prescription without changing fulfillment');
$candidateIds = static fn (array $result): array => array_column(
array_filter($result['orders'], static fn (array $order) => !$order['is_linked']), 'id'
);
$expect($candidateIds($list(106, 'PO-207')) === [207],
'An order-side prescription rejection is eligible even though its primary prescription was not voided');
$expect($candidateIds($list(106, 'PO-208')) === [208],
'A historically rejected primary prescription without a void flag is eligible');
$expect($candidateIds($list(106, 'PO-209')) === [], 'A payment rejection alone does not make an order eligible');
$denied(fn () => $bind(209, 106), 'Submitting directly cannot bypass the prescription eligibility check');
$expect(!$list(111)['can_bind'], 'An already rejected prescription can show existing orders but is not an eligible replacement');
$denied(fn () => $bind(201, 111), 'Submitting directly cannot bind a rejected replacement');
Db::name('tcm_prescription_order')->where('id', 207)->update(['prescription_audit_status' => 0]);
$denied(fn () => $bind(207, 106), 'The API rechecks the order-side prescription review after search');
Db::name('tcm_prescription_order')->where('id', 207)->update(['prescription_audit_status' => 2]);
foreach ([207, 208] as $orderId) {
$archivedOrder = Db::name('tcm_prescription_order')->where('id', $orderId)->find();
$bind($orderId, 106);
$expect(Db::name('tcm_prescription_order_prescription')->where('prescription_order_id', $orderId)
->where('prescription_id', 106)->count() === 1
&& $archivedOrder === Db::name('tcm_prescription_order')->where('id', $orderId)->find()
&& str_contains((string) Db::name('tcm_prescription_order_log')->where('prescription_order_id', $orderId)
->where('action', 'bind_prescription')->value('summary'), '审核已驳回'),
'Binding adds a supplemental link and logs the rejection without changing the original order');
}
foreach ([210, 211, 212, 214] as $orderId) {
$expect($candidateIds($list(106, 'PO-' . $orderId)) === [$orderId],
'Rejected order remains selectable when its original is unset, dangling, deleted or null');
$archivedOrder = Db::name('tcm_prescription_order')->where('id', $orderId)->find();
$bind($orderId, 106);
$bind($orderId, 106);
$visibleOrder = PrescriptionOrderLogic::detail($orderId, 2, $operator, 106);
$expect((int) $visibleOrder['prescription']['id'] === 106
&& array_column($visibleOrder['linked_prescriptions'], 'id') === [106]
&& $archivedOrder === Db::name('tcm_prescription_order')->where('id', $orderId)->find()
&& Db::name('tcm_prescription_order_log')->where('prescription_order_id', $orderId)
->where('action', 'bind_prescription')->count() === 1,
'Binding and preview use the new association without changing the rejected original or recording a duplicate');
}
foreach ([213, 215] as $orderId) {
$expect($candidateIds($list(106, 'PO-' . $orderId)) === [],
'A non-rejected order is ineligible when the original is unset or only a deleted voided row remains');
$denied(fn () => $bind($orderId, 106), 'Direct binding also requires rejection if no current original exists');
}
Db::name('system_role_menu')->where('menu_id', $menuIds[$path . 'prescriptionOrdersForBinding'])->delete();
$expect(PrescriptionOrderLogic::detail(201, 2, $operator, 102) === null
&& !isset(PrescriptionOrderLogic::detail(201, 2, $operator, 0)['linked_prescriptions']),
'Orders without link-view permission keep their original details and omit supplemental relations');
$expect((new PrescriptionOrderValidate())->scene('detail')->check(['id' => 201])
&& (new PrescriptionOrderValidate())->scene('detail')->check(['id' => 201, 'prescription_id' => 102])
&& !(new PrescriptionOrderValidate())->scene('detail')->check(['id' => 201, 'prescription_id' => -1])
&& !(new PrescriptionOrderValidate())->scene('bindPrescription')->check(['id' => 201, 'prescription_id' => 0]),
'Detail preserves the existing request shape while mutations and explicit selections validate positive ids');
echo "PrescriptionOrderPrescriptionLinksTest: {$checks} assertions passed\n";
} finally {
$manager->connect()->close();
$pdo->exec("DROP DATABASE {$database}");
}
@@ -8,8 +8,10 @@ declare(strict_types=1);
* Never loads the application's database configuration or touches business data.
*/
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\lists\tcm\PrescriptionOrderLists;
use app\adminapi\logic\order\OrderLogic;
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\adminapi\validate\tcm\PrescriptionOrderValidate;
use think\Container;
@@ -89,7 +91,7 @@ try {
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_pay_order (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, pay_order_id INT,
create_time INT, UNIQUE KEY uk_po_pay (prescription_order_id,pay_order_id)
create_time INT, UNIQUE KEY uk_po_pay (prescription_order_id,pay_order_id), KEY idx_pay_order (pay_order_id)
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_log (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, admin_id INT,
@@ -135,9 +137,9 @@ try {
Db::name('tcm_prescription_order_log')->where('prescription_order_id', $id)->order('id')->select()->toArray(),
];
$amounts = static function (array $result, float $total, float $paid, float $collect, bool $checkStoredPaid = true) use ($expect): void {
$expect((float) $result['amount'] === $total, 'Unlink must leave the business total unchanged');
$expect((float) $result['amount'] === $total, 'Business total must use the expected settlement amount');
$expect((float) $result['linked_pay_paid_total'] === $paid, 'Paid total must use remaining active payments');
$expect((float) $result['agency_collect_amount'] === $collect, 'Collection snapshot must equal unchanged total minus remaining payments');
$expect((float) $result['agency_collect_amount'] === $collect, 'Collection snapshot must use the updated order and receipt amounts');
if ($checkStoredPaid) {
$expect((float) $result['paid'] === $paid, 'Response paid must match remaining effective receipts');
$expect((float) Db::name('tcm_prescription_order')->where('id', $result['id'])->value('paid') === $paid,
@@ -182,11 +184,9 @@ try {
$expect($remove($id, $otherPayIds[0]) === false && $snapshot($id) === $before, 'Foreign payment ID must not affect either order');
$expect(count($snapshot($otherId)[1]) === 1, 'Foreign order must retain its payment');
foreach ([3, 4] as $status) {
[$id, $payIds] = $fixture('100.00', [['amount' => '100.00']], ['fulfillment_status' => $status, 'paid' => '100.00']);
$before = $snapshot($id);
$expect($remove($id, $payIds[0]) === false && $snapshot($id) === $before, 'Completed/cancelled orders must retain amount and paid snapshot');
}
[$id, $payIds] = $fixture('100.00', [['amount' => '100.00']], ['fulfillment_status' => 4, 'paid' => '100.00']);
$before = $snapshot($id);
$expect($remove($id, $payIds[0]) === false && $snapshot($id) === $before, 'Cancelled orders must retain amount and paid snapshot');
foreach ([['amount' => '100.00', 'status' => 1],
['amount' => '100.00', 'delete_time' => time()], ['amount' => '-1.00']] as $payment) {
[$id, $payIds] = $fixture('100.00', [$payment]);
@@ -279,16 +279,115 @@ try {
$expect(is_array($out), 'Existing link payment flow must still succeed');
$amounts($out, 1000.0, 250.0, 750.0, false);
// Separate PHP/DB connections race against a held parent row lock. Both are ready
// before release, so this tests the database lock rather than sequential double-clicks.
$race = static function (int $id, array $operations) use ($database): array {
$attach = static fn (int $id, int $payId) => PrescriptionOrderLogic::attachReceipt([
'id' => $id, 'pay_order_id' => $payId,
], 1, $admin);
$newReceipt = static fn (array $fields = []): int => (int) Db::name('order')->insertGetId($fields + [
'order_no' => 'PAID-' . bin2hex(random_bytes(4)), 'patient_id' => 1, 'status' => 2,
'amount' => 80, 'create_time' => time(),
]);
[$id] = $fixture('1000.00', [], ['creator_id' => 2]);
$receipt = $newReceipt(['creator_id' => 2]);
$operator = ['root' => 0, 'admin_id' => 2, 'role_id' => [2], 'name' => '获授权测试员'];
$attachAsOperator = static fn () => PrescriptionOrderLogic::attachReceipt(['id' => $id, 'pay_order_id' => $receipt], 2, $operator);
$before = $snapshot($id);
$expect($attachAsOperator() === false
&& PrescriptionOrderLogic::linkPayOrder(['id' => $id, 'pay_order_id' => $receipt], 2, $operator) === false
&& $snapshot($id) === $before, 'Order access and unlink permission do not grant attachment through either workflow');
$migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_12_01_prescription_order_attach_receipt_menu.sql');
$pdo->exec($migration);
$pdo->exec($migration);
$menu = Db::name('system_menu')->where('perms', 'tcm.prescriptionOrder/attachReceipt');
$expect($menu->count() === 1 && $attachAsOperator() === false, 'Idempotent migration must not grant any role by default');
$attachMenuId = (int) $menu->value('id');
$expect($attachMenuId > 0, 'Attachment menu id must exist');
Db::name('system_role_menu')->insert(['role_id' => 2, 'menu_id' => $attachMenuId]);
$expect(is_array($attachAsOperator()), 'An authorized role can attach a receipt within its scope');
foreach (range(1, 12) as $status) {
$auditStatus = $status % 3;
[$id] = $fixture('1000.00', [], [
'fulfillment_status' => $status, 'prescription_audit_status' => $auditStatus,
'payment_slip_audit_status' => $auditStatus,
'payment_slip_audit_remark' => '保留原审核意见', 'completion_request' => 1,
'paid' => 35, 'refund_amount' => 100,
]);
$receipt = $newReceipt();
$out = $attach($id, $receipt);
$expect(is_array($out) && (int) $out['fulfillment_status'] === $status
&& (int) $out['prescription_audit_status'] === $auditStatus && (int) $out['payment_slip_audit_status'] === $auditStatus
&& $out['payment_slip_audit_remark'] === '保留原审核意见' && (int) $out['completion_request'] === 1
&& (float) $out['paid'] === ($status === 3 ? 80.0 : 35.0) && (float) $out['refund_amount'] === 100.0,
"Status {$status} must allow linking while preserving audit and refund history");
$amounts($out, 1000.0, 80.0, 920.0, false);
$expect((int) $out['linked_pay_order_id'] === $receipt
&& !in_array($receipt, array_map('intval', array_column(OrderLogic::listPaidOrdersForDiagnosis(1, 1, $admin), 'id')), true),
'A linked receipt must leave the candidates even for a cancelled order');
[$other] = $fixture('1000.00', []);
$expect($attach($id, $receipt) === false && $attach($other, $receipt) === false,
'A linked receipt cannot be counted twice');
}
[$id] = $fixture('100.00', [['amount' => 100]], ['fulfillment_status' => 3, 'paid' => 100]);
$before = $snapshot($id);
foreach ([['patient_id' => 2], ['status' => 1], ['status' => 4], ['amount' => -1], ['delete_time' => time()]] as $invalidReceipt) {
$expect($attach($id, $newReceipt($invalidReceipt)) === false && $snapshot($id) === $before,
'Out-of-scope or non-paid receipt must not change the order');
}
$receipt = $newReceipt();
$pdo->exec("CREATE TRIGGER reject_attach_log BEFORE INSERT ON zyt_tcm_prescription_order_log
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced attachment audit log failure'");
$expect($attach($id, $receipt) === false && $snapshot($id) === $before, 'Attaching must roll back when its audit log fails');
$pdo->exec('DROP TRIGGER reject_attach_log');
$out = $attach($id, $receipt);
$expect(is_array($out) && count($out['linked_pay_orders']) === 2 && (int) $out['linked_pay_order_id'] !== $receipt,
'Attaching another receipt must preserve the original link and primary receipt');
$amounts($out, 180.0, 180.0, 0.0);
[$id] = $fixture('9936.00', [['amount' => '9936.00']], [
'fulfillment_status' => 3, 'paid' => 9936, 'agency_collect_amount' => 0,
]);
$receipt = $newReceipt(['amount' => '100.01']);
$amounts($attach($id, $receipt), 10036.01, 10036.01, 0.0);
$out = $remove($id, $receipt);
$amounts($out, 10036.01, 9936.0, 100.01);
$expect((int) $out['fulfillment_status'] === 3
&& (int) Db::name('order')->where('id', $receipt)->value('status') === 2
&& in_array($receipt, array_map('intval', array_column($out['attachable_receipts'], 'id')), true),
'Completed unlink keeps the order complete and releases the original receipt back to the chooser');
$amounts($attach($id, $receipt), 10036.01, 10036.01, 0.0);
[$id, $payIds] = $fixture('1200.00', [['amount' => 800], ['amount' => 200, 'status' => 4]], [
'fulfillment_status' => 3, 'paid' => 700, 'refund_amount' => 300, 'agency_collect_amount' => 0,
]);
$out = $attach($id, $newReceipt(['amount' => '300.26']));
$amounts($out, 1200.0, 1100.26, 99.74, false);
$expect((float) $out['paid'] === 1000.26 && (float) $out['refund_amount'] === 300.0,
'New receipts first fill the current unpaid balance and preserve net paid after partial refund');
$tail = $newReceipt(['amount' => '100.00']);
$out = $attach($id, $tail);
$amounts($out, 1200.26, 1200.26, 0.0, false);
$expect((float) $out['paid'] === 1100.26 && str_contains($snapshot($id)[2][1]['summary'], '¥1200.00 → ¥1200.26'),
'Only the excess goes into the total and is recorded in the log');
$out = $remove($id, $payIds[1]);
$amounts($out, 1200.26, 1200.26, 0.0, false);
$expect((float) $out['paid'] === 1100.26, 'Removing an already refunded receipt leaves net payment and COD unchanged');
// Launch separate connections while the shared order or receipt row is locked.
$race = static function (int $id, array $operations, ?int $receiptId = null) use ($database): array {
putenv('ZYT_UNLINK_TEST_DATABASE=' . $database);
Db::startTrans();
Db::name('tcm_prescription_order')->where('id', $id)->lock(true)->find();
if ($receiptId !== null) {
Db::name('order')->where('id', $receiptId)->lock(true)->find();
} else {
Db::name('tcm_prescription_order')->where('id', $id)->lock(true)->find();
}
$workers = [];
try {
foreach ($operations as [$operation, $payId]) {
$process = proc_open([PHP_BINARY, __FILE__, '--worker', $operation, (string) $id, (string) $payId],
foreach ($operations as $operationParams) {
[$operation, $payId] = $operationParams;
$targetId = $operationParams[2] ?? $id;
$process = proc_open([PHP_BINARY, __FILE__, '--worker', $operation, (string) $targetId, (string) $payId],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
if (!is_resource($process)) throw new RuntimeException('Unable to start concurrency worker');
fclose($pipes[0]);
@@ -327,9 +426,24 @@ try {
$expect(count($remaining) === 1 && !in_array($payIds[0], array_map('intval', $remaining), true), 'Concurrent link replacement must not resurrect a removed payment');
}
[$cancelledId] = $fixture('1000.00', [], ['fulfillment_status' => 4]);
[$shippedId] = $fixture('1000.00', []);
$receipt = $newReceipt();
$results = $race($cancelledId, [['attachReceipt', $receipt], ['linkPayOrder', $receipt, $shippedId]], $receipt);
$expect(count(array_filter($results, static fn (array $r): bool => $r['success'])) === 1
&& Db::name('tcm_prescription_order_pay_order')->where('pay_order_id', $receipt)->count() === 1,
'Concurrent legacy and direct links to separate orders must reserve a receipt exactly once');
[$completedId] = $fixture('100.00', [['amount' => 100]], ['fulfillment_status' => 3, 'paid' => 100]);
$results = $race($completedId, [['attachReceipt', $newReceipt(['amount' => 20])], ['attachReceipt', $newReceipt(['amount' => 30])]]);
$completed = $snapshot($completedId)[0];
$expect($results[0]['success'] && $results[1]['success'] && (float) $completed['amount'] === 150.0
&& (float) $completed['paid'] === 150.0 && (float) $completed['agency_collect_amount'] === 0.0,
'Concurrent completed attachments must both be included in the settlement');
foreach ([[], ['id' => 1], ['id' => 0, 'pay_order_id' => 1], ['id' => 1, 'pay_order_id' => -1],
['id' => 1, 'pay_order_id' => 1.5], ['id' => 1, 'pay_order_id' => [1]]] as $params) {
$expect(!(new PrescriptionOrderValidate())->scene('unlinkPayOrder')->check($params), 'Request must require two positive integer IDs');
$expect(!(new PrescriptionOrderValidate())->scene('attachReceipt')->check($params), 'Attach requires two positive integer IDs');
}
$expect((new PrescriptionOrderValidate())->scene('unlinkPayOrder')->check(['id' => 1, 'pay_order_id' => 2]), 'Valid IDs must pass validation');
echo "PrescriptionOrderUnlinkPayOrderTest: {$checks} assertions passed\n";