Compare commits

...
18 Commits
Author SHA1 Message Date
Your NameandClaude Opus 5 14936cb28a 已开处方列表提速;处方 AI 拒答带全部候选键时按拒答处理
- 置顶风险处方改为从订单表出发计算并缓存 60 秒,分页只查 ID,不再整表扫描与排序
- 列表行不再返回 doctor_signature,查看/编辑仍另取详情
- 模型拒绝开方时把候选键置空返回,不再判为 INVALID_REPORT_OUTPUT,可进入追问

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-04 15:01:39 +08:00
Your Name 63e52f6273 更新 2026-12-04 10:01:42 +08:00
Your Name 91e35cb905 更新 2026-12-02 09:27:53 +08:00
Your Name 1e165a7894 Merge branch 'master' into CA-11-17 2026-11-30 15:12:37 +08:00
Your Name 887ab3e839 更新 2026-11-30 15:11:48 +08:00
Your NameandClaude Opus 5 4ae38b45ed 业务订单中已退款的收款记录也可移除关联
- 移除收款关联放开「已退款」(status 4):只解除关联、保留原收款记录;已退款记录本不计入已付金额,移除后已付金额与需代收不变,日志注明「已退款」
- 已支付/待审核规则不变;已完成/已取消订单仍不可移除
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 15:08:58 +08:00
Your Name fdca55853a 更新 2026-11-30 14:56:23 +08:00
Your NameandClaude Opus 5 9dde9a34b5 已签署处方在业务订单中可修改服用参数(只改订单页面与药房下单,不改 CA 签署原件);查看处方可下载 CA 原件或当前样式的药房联/处方联
- 处方已电子签署(内容冻结)时,「修改服用参数」改写为订单级覆盖值 usage_override(次数/天数/袋数,含辅方),
  签署原文、快照哈希与 CA PDF 不变;订单详情、处方笺、甘草/洛阳下单按本订单生效值;未签署处方仍直接修改处方
- 已发货锁定天数按生效值比较;重新开方改关联时清除旧覆盖值
- 迁移 2026_11_30_prescription_order_usage_override.sql
- 业务订单「查看处方」下载改为下拉:CA 签署处方 PDF、药房联 PDF、处方联 PDF(当前页面样式,A4);PC 与 H5 一致
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 14:49:53 +08:00
Your NameandClaude Opus 5 dc18098566 已签署处方在业务订单中可修改服用参数(只改订单页面与药房下单,不改 CA 签署原件);查看处方可下载 CA 原件或当前样式的药房联/处方联
- 处方已电子签署(内容冻结)时,「修改服用参数」改写为订单级覆盖值 usage_override(次数/天数/袋数,含辅方),
  签署原文、快照哈希与 CA PDF 不变;订单详情、处方笺、甘草/洛阳下单按本订单生效值;未签署处方仍直接修改处方
- 已发货锁定天数按生效值比较;重新开方改关联时清除旧覆盖值
- 迁移 2026_11_30_prescription_order_usage_override.sql
- 业务订单「查看处方」下载改为下拉:CA 签署处方 PDF、药房联 PDF、处方联 PDF(当前页面样式,A4);PC 与 H5 一致
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 14:49:34 +08:00
Your Name 562f8d6ce4 更新 2026-11-30 14:14:03 +08:00
Your Name 5374f05c80 更新 2026-11-30 14:12:56 +08:00
Your NameandClaude Opus 5 18a0989c00 业务订单已发货后不能再修改服用天数
- 已发货判定:履约状态已发货/已签收/已完成,或已填快递单号,或药房回传已发货(洛阳 SHIPPED/COMPLETED、甘草 20/30)
- 已发货后「修改服用参数」与订单编辑中的主方/辅方开立天数、订单服用天数不可修改(服务端拦截);次数、袋数仍可改;
  订单未单独设置天数时以处方开立天数为准,不会误判为修改
- 订单详情返回 days_locked,详情抽屉、订单列表(含 H5)编辑时禁用天数输入并提示
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 14:04:17 +08:00
Your NameandClaude Opus 5 b675822377 处方手机号/身份证号输入校验;已作废处方任何有开方权限的账号可重新开方
- 手机号:11 位手机号或带区号座机(0571-88888888),桌面端输入只允许数字与「-」、身份证号只允许数字与 X;
  保存时桌面端与服务端(开方/编辑、改姓名手机)统一校验,未改动的历史号码不受影响;管理后台改姓名手机同规则
- 重新开方:原方子作废后(含他人所开、他人作废),有开方权限的账号即可重新开方,新处方以当前账号为开方医生(管理后台与桌面端)
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 12:19:36 +08:00
Your NameandClaude Opus 5 c6df345138 桌面端编辑处方可修改手机号、身份证号
- 桌面端开方/编辑处方表单新增「手机号」「身份证号」,已开处方编辑时可修改(姓名仍只读);身份证号本地先校验格式
- 服务端 add/edit 接收 phone(写入处方笺)与 id_card(写回关联诊单,校验格式与重复,按出生日期更新年龄,与处方保存同一事务);
  编辑时须可管理该诊单;处方详情仅对可管理诊单的账号返回 patient_id_card

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 12:04:39 +08:00
Your NameandClaude Opus 5 365b16c14d 已提交药房的处方也可作废:先远端撤单再作废
- 洛阳药房:作废时先调用 POST /api/openapi/v1/prescription-orders/{订单号}/cancel 撤单,确认 CANCELLED 后再作废并挂起订单;
  远端拒绝(已发货/已扣库存,409)或未确认时不作废并提示原因;撤单写订单日志。撤单后的订单重新审核通过后以新版本提交药房
- 甘草:暂无撤单接口,须先在甘草撤单;甘草回传撤单/驳回(91/92)后可作废
- 远端已确认取消且无在途新版本提交时,订单不再被药房快照锁定
- 列表与详情的 can_void 按「能否自动撤单」判断
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 11:47:14 +08:00
Your NameandClaude Opus 5 b55f30753c 处方作废不再受签署/审核/订单状态限制,作废后订单随重新开方自动关联;签署原文去掉辅方方名;出丸显示辅方克数;查看处方可下载 CA 原件或药房联/处方联
- 作废:药师签署、审核通过、已有业务订单后均可作废(仍需「作废」权限;已提交药房的订单须先远端取消)。
  作废时关联的待审核/履约中订单处方审核重置为待审核(履约中退回待审核,支付审核保留),
  同诊单重新开方后自动改关联到新处方并写订单日志;已发货/已完成订单按原处方留档。
  迁移 2026_11_30_prescription_order_reissue.sql 新增 reissue_from_prescription_id
- 签署 PDF 不再写入「辅方方名」
- 出丸:有辅方药材时显示「主方 X克,辅方 Y克」(管理后台与桌面端)
- 已开处方「查看处方」下载改为下拉:CA 签署处方 PDF、药房联 PDF、处方联 PDF(A4,按当前笺面样式)
- 重新构建管理后台

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-11-30 10:45:08 +08:00
long 0eeb572f0f Update .gitignore 2026-11-28 10:38:10 +08:00
long fce7c78de3 feat(miniapp): 从识糖小课堂打开智慧科技小程序 2026-11-28 10:33:07 +08:00
577 changed files with 3324 additions and 1021 deletions
+1
View File
@@ -38,3 +38,4 @@ app/.test-tmp-stream/
TUICallKit-Vue3/.env
/.codegraph
app/artifacts/
/artifacts
+15 -6
View File
@@ -1595,17 +1595,26 @@ async function goMorePage() {
uni.navigateTo({ url: buildMorePageUrl() })
}
function openGamePage(url) {
function goEndlessGamePage() {
// #ifdef MP-WEIXIN
wx.navigateToMiniProgram({
appId: 'wx0c2a9d5ebad26a3f',
path: 'tongji/endless-game/index',
envVersion: 'release',
fail(err) {
if (err?.errMsg?.includes('cancel')) return
uni.showToast({ title: '暂时无法打开课堂', icon: 'none' })
}
})
// #endif
// #ifndef MP-WEIXIN
uni.navigateTo({
url,
url: '/tongji/endless-game/index',
fail() {
uni.showToast({ title: '暂时无法打开游戏', icon: 'none' })
}
})
}
function goEndlessGamePage() {
openGamePage('/tongji/endless-game/index')
// #endif
}
function navToUser() {
+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 })
Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

@@ -182,6 +182,14 @@
/>
<span v-else class="rx-bot-reviewer-name">{{ reviewerName }}</span>
</div>
<div
v-else-if="showPharmacistSample"
class="rx-bot-cell rx-bot-reviewer rx-pharmacist-sample"
data-html2canvas-ignore="true"
>
<span class="rx-bot-label rx-bot-label--inline">药师</span>
<img :src="pharmacistImage" alt="签名预览" class="rx-bot-sign-img" />
</div>
<div v-if="isInternal" class="rx-bot-cell rx-bot-meta">
<span class="rx-bot-meta-key">类型:</span>
<span class="rx-bot-meta-val">{{ typeText }}</span>
@@ -206,9 +214,12 @@
<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { PrescriptionEsignStatus } from '@/api/tcm'
// 来源:https://gz-1349751149.cos.ap-guangzhou.myqcloud.com/uploads/images/20261203/2026120314015402c2e8093.png
import pharmacistImage from '@/assets/images/pharmacist-signature-20261203.png'
import {
getAuxHerbs,
getMainHerbs,
getSlipHerbs,
rxAdviceText,
rxAppointmentFlowText,
rxAuxUsageText,
@@ -241,6 +252,7 @@ const props = withDefaults(
/** 抬头(处方联) */
title?: string
compact?: boolean
showPharmacistSignatureSample?: boolean
}>(),
{
variant: 'internal',
@@ -279,6 +291,18 @@ const reviewerSignature = computed(() => {
const signature = props.data?.esign?.review_signature
return reviewerName.value && isVerifiedSignaturePng(signature) && signature !== failedReviewerSignature.value ? signature : ''
})
const showPharmacistSample = computed(() => {
const data = props.data
const signing: PrescriptionEsignStatus | undefined = data?.esign
if (!props.showPharmacistSignatureSample || !data || signing?.status !== 'legacy'
|| signing.required !== false || signing.can_download !== false || !getSlipHerbs(data).length
|| Number(data.is_system_auto) === 1 || Number(data.void_status) === 1 || Number(data.audit_status) === 2) return false
if (signing.review_state === 'signed' || Number(signing.review_signature_time) > 0
|| signing.review_signature || signing.review_signer_name) return false
return Number(data.audit_status) === 1
|| (Number(signing.review_submitted_at ?? data.review_submitted_at) > 0
&& typeof data.doctor_signature === 'string' && data.doctor_signature.trim() !== '')
})
function isVerifiedSignaturePng(signature: unknown): signature is string {
return typeof signature === 'string' && /^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/.test(signature)
@@ -654,6 +678,7 @@ defineExpose({
}
.rx-bot-row-1 {
--rx-reviewed-columns: minmax(164px, 1.15fr) minmax(188px, 1.3fr) 1.4fr 0.75fr 0.85fr;
/* 类型/剂数/单剂量 三个 meta 列适当加宽,
* 避免"浓缩丸-浓缩水丸"被强制折行后把整行挤错位 */
grid-template-columns: 1.6fr 0.6fr 0.6fr 0.6fr 0.6fr 1.7fr 0.95fr 1.25fr;
@@ -661,15 +686,18 @@ defineExpose({
}
.rx-bot-row-1--user {
--rx-reviewed-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr;
grid-template-columns: 1.6fr 0.6fr;
}
.rx-bot-row-1--reviewed {
grid-template-columns: minmax(164px, 1.15fr) minmax(188px, 1.3fr) 1.4fr 0.75fr 0.85fr;
grid-template-columns: var(--rx-reviewed-columns);
}
.rx-bot-row-1--user.rx-bot-row-1--reviewed {
grid-template-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr;
@media screen {
.rx-bot-row-1:has(> .rx-pharmacist-sample) {
grid-template-columns: var(--rx-reviewed-columns);
}
}
.rx-hospital-row {
@@ -769,6 +797,12 @@ defineExpose({
object-fit: contain;
}
@media print {
.rx-pharmacist-sample {
display: none;
}
}
.rx-bot-meta {
flex-wrap: nowrap;
@@ -308,8 +308,63 @@ function computeOutPellet(data: Record<string, any>): string {
return formatNum(perDose * getDoseCount(data))
}
/** 辅方出丸 = 辅方服用天数 × 每日次数 × 每袋用量 × 每次袋数;仅浓缩水丸且确有辅方药材时计算。 */
function computeAuxOutPellet(data: Record<string, any>): string {
if ((data.prescription_type || '浓缩水丸') !== '浓缩水丸' || !getAuxHerbs(data).length) return ''
let raw = data.aux_usage
if (typeof raw === 'string') {
try {
raw = JSON.parse(raw)
} catch {
raw = null
}
}
const aux = normalizeAuxUsageForm(raw, '浓缩水丸')
const days = Number(aux.usage_days)
const times = Number(aux.times_per_day)
const doseG = Number(aux.dosage_amount)
const bags = Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
return days > 0 && times > 0 && doseG > 0 ? formatNum(days * times * doseG * bags) : ''
}
/**
* 合并业务订单的服用参数覆盖:已签署(CA 冻结)处方在订单中修改的次数/天数/袋数记在订单 usage_override,
* 只作用于该订单的页面与药房下单,签署原文不变。与服务端 PrescriptionOrderLogic::applyUsageOverride 一致。
*/
export function applyOrderUsageOverride<T extends Record<string, any>>(rx: T, rawOverride: unknown): T {
let override: unknown = rawOverride
if (typeof override === 'string') {
try {
override = JSON.parse(override)
} catch {
override = null
}
}
if (!override || typeof override !== 'object' || Array.isArray(override)) return rx
const o = override as Record<string, any>
const out: Record<string, any> = { ...rx }
for (const key of ['times_per_day', 'usage_days', 'dosage_bag_count']) {
if (o[key] != null && Number.isFinite(Number(o[key]))) out[key] = Number(o[key])
}
if (o.aux_usage && typeof o.aux_usage === 'object') {
let aux = out.aux_usage
if (typeof aux === 'string') {
try {
aux = JSON.parse(aux)
} catch {
aux = null
}
}
out.aux_usage = { ...(aux && typeof aux === 'object' ? aux : {}), ...o.aux_usage }
}
out.usage_overridden = 1
return out as T
}
export function rxOutPelletText(data: Record<string, any> | null | undefined): string {
if (!data) return ''
const out = computeOutPellet(data)
const aux = computeAuxOutPellet(data)
if (out && aux) return `主方 ${out}克,辅方 ${aux}克`
return out ? `${out}克` : ''
}
@@ -701,16 +701,16 @@
{{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }}
</el-button>
<el-tooltip
v-if="savedPrescription.void_status !== 1 && !approvedPreviewOnly"
:disabled="!hasPrescriptionOrderBlockVoid"
content="该处方已存在业务订单,无法作废,请前往已开处方里修改"
v-if="savedPrescription.void_status !== 1 && savedPrescription.can_void !== false"
:disabled="!hasLinkedPrescriptionOrder"
content="作废后,关联的业务订单会在同诊单重新开方时自动关联到新处方"
placement="top"
>
<span class="inline-block">
<el-button
v-perms="['tcm.prescription/void']"
type="danger"
plain
:disabled="hasPrescriptionOrderBlockVoid"
:loading="voiding"
@click="handleVoid"
>
@@ -1080,8 +1080,8 @@ const approvedPreviewOnly = computed(() => {
return Number(s.audit_status) === 1 && Number(s.void_status) !== 1
})
/** 已有关联业务订单(与列表 has_prescription_order 一致)则禁止作废 */
const hasPrescriptionOrderBlockVoid = computed(() => {
/** 已有关联业务订单(与列表 has_prescription_order 一致):作废时提示订单将随重新开方迁移 */
const hasLinkedPrescriptionOrder = computed(() => {
const s = savedPrescription.value
if (!s) return false
return Number(s.has_prescription_order) === 1
@@ -2165,12 +2165,10 @@ const formatVoidTime = (ts: number | null | undefined) => {
const handleVoid = async () => {
const id = savedPrescription.value?.id
if (!id) return
if (Number(savedPrescription.value?.has_prescription_order) === 1) {
feedback.msgWarning('该处方已存在业务订单,无法作废')
return
}
try {
await feedback.confirm('确定要作废该处方吗?作废后不可恢复。')
await feedback.confirm(Number(savedPrescription.value?.has_prescription_order) === 1
? '确定要作废该处方吗?作废后不可恢复;已提交洛阳药房的订单会先撤销药房订单,关联的业务订单将退回待审核,同诊单重新开方后自动关联到新处方。'
: '确定要作废该处方吗?作废后不可恢复。')
voiding.value = true
await prescriptionVoid({ id })
feedback.msgSuccess('作废成功')
@@ -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, 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>
@@ -964,6 +985,22 @@
:rules="patchUsageRules"
label-width="108px"
>
<el-alert
v-if="usageFrozenBySignature"
type="warning"
:closable="false"
show-icon
class="mb-3"
title="处方已电子签署:此处修改只作用于本订单的页面与药房下单,CA 签署的处方原件不变。"
/>
<el-alert
v-if="daysLocked"
type="info"
:closable="false"
show-icon
class="mb-3"
title="订单已发货,服用天数不可修改;次数、袋数仍可修改。"
/>
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
@@ -988,6 +1025,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="patchUsageForm.usage_days"
:disabled="daysLocked"
:min="1"
:max="999"
:step="1"
@@ -1022,6 +1060,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="patchUsageForm.aux_usage_days"
:disabled="daysLocked"
:min="1"
:max="999"
:step="1"
@@ -1037,6 +1076,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="patchUsageForm.medication_days"
:disabled="daysLocked"
:min="1"
:max="999"
:step="1"
@@ -1066,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,
@@ -1130,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
@@ -1159,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, 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(() => {
@@ -1275,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 || '—'
})
@@ -1353,7 +1383,14 @@ const detailLinkedAppointmentChannelText = computed(() => {
const detailRxHerbs = computed(() => normalizeSlipHerbs(detailPrescription.value?.herbs))
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
/** 已发货的订单服用天数锁定(服务端 days_locked,同样拦截保存) */
const daysLocked = computed(() => detailData.value?.days_locked === true)
/** 处方已进入电子签署(内容冻结),服用参数改写为订单级覆盖值 */
const usageFrozenBySignature = computed(() => {
const esign = detailData.value?.prescription?.esign
return esign?.required === true && esign?.status !== 'pending'
})
/** 详情:辅方用法(aux_usage JSON 经规范化后的对象,与处方类型一致) */
const detailAuxUsage = computed(() => {
@@ -1364,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 !== ''
@@ -1440,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
@@ -1508,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 =
@@ -1642,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)
@@ -1769,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'
@@ -1784,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) {
@@ -1795,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()
@@ -1827,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
}
}
+81 -35
View File
@@ -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"
@@ -283,7 +289,7 @@
审核
</el-button>
<el-button
v-if="canVoidPendingPrescription(row)"
v-if="canVoidPrescription(row)"
v-perms="['tcm.prescription/void']"
type="danger"
link
@@ -440,16 +446,26 @@
@click="handleReissue(slipView)"
>重新开方</el-button>
<el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
<el-button
type="primary"
:icon="Download"
size="small"
:loading="downloadingSlip"
:disabled="viewDetailLoading || (requiresOriginalEsignPdf(slipView?.esign) && !slipView?.esign?.can_download)"
@click="handleDownloadSlip"
<el-dropdown
trigger="click"
:disabled="viewDetailLoading || downloadingSlip"
@command="handleDownloadSlip"
>
{{ requiresOriginalEsignPdf(slipView?.esign) ? '下载已签原始 PDF' : '下载 PDF (A4)' }}
</el-button>
<el-button type="primary" :icon="Download" size="small" :loading="downloadingSlip">
下载 PDF (A4)
</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
v-if="requiresOriginalEsignPdf(slipView?.esign)"
command="esign"
:disabled="!slipView?.esign?.can_download"
>CA 签署处方 PDF</el-dropdown-item>
<el-dropdown-item command="internal">药房联 PDF</el-dropdown-item>
<el-dropdown-item command="user">处方联 PDF</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
<!-- 状态提示(不进入打印区) -->
@@ -480,10 +496,21 @@
:before-leave="() => !downloadingSlip"
>
<el-tab-pane label="药房联" name="internal">
<PrescriptionSlip v-if="prescriptionTabType === 'internal'" ref="rxSlipRef" :data="slipView" />
<PrescriptionSlip
v-if="prescriptionTabType === 'internal'"
ref="rxSlipRef"
:data="slipView"
:show-pharmacist-signature-sample="!viewDetailLoading && !viewDetailError"
/>
</el-tab-pane>
<el-tab-pane label="处方联" name="user">
<PrescriptionSlip v-if="prescriptionTabType === 'user'" ref="rxSlipRef" :data="slipView" variant="user" />
<PrescriptionSlip
v-if="prescriptionTabType === 'user'"
ref="rxSlipRef"
:data="slipView"
variant="user"
:show-pharmacist-signature-sample="!viewDetailLoading && !viewDetailError"
/>
</el-tab-pane>
</el-tabs>
@@ -1713,6 +1740,8 @@
</template>
</el-dialog>
<PrescriptionLinkedOrdersDialog v-if="canViewLinkedOrders" ref="linkedOrdersDialog" @bound="getLists()" />
<!-- 与 tcm/diagnosis/edit 同一套诊单界面(只读 + 全部分页签) -->
<TcmDiagnosisEditView ref="diagnosisViewRef" />
</div>
@@ -1748,9 +1777,10 @@ 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, downloadPrescriptionPdfIfRequired, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import { canApprovePrescriptionEsign, downloadOriginalEsignPdf, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import type { PrescriptionEsignStatus } from '@/api/tcm'
import { prescriptionListSigningStatus } from './components/prescription-list-signing-status'
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
@@ -1896,6 +1926,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')
@@ -2028,7 +2060,10 @@ const patchPatientForm = reactive({
const patchPatientRules: FormRules = {
patient_name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^(?:1[3-9]\d{9}|0\d{2,3}-?\d{7,8})$/, message: '请输入 11 位手机号或带区号的座机号', trigger: 'blur' }
]
}
function openPatchPatientDialog(row: Record<string, unknown>) {
@@ -2859,18 +2894,25 @@ function handlePrintSlip() {
})
}
/* === 下载 PDF(A4) === */
async function handleDownloadSlip() {
if (downloadingSlip.value) return
downloadingSlip.value = true
try {
if (await downloadPrescriptionPdfIfRequired(Number(slipView.value?.id))) return
} catch (e: any) {
feedback.msgError(e?.message || '下载签署文件失败')
return
} finally {
downloadingSlip.value = false
}
/* === 下载 PDF(A4):CA 签署原件,或按当前笺面样式导出药房联 / 处方联 === */
async function handleDownloadSlip(command: 'esign' | 'internal' | 'user') {
if (downloadingSlip.value || !slipView.value) return
if (command === 'esign') {
downloadingSlip.value = true
try {
await downloadOriginalEsignPdf(Number(slipView.value.id))
} catch (e: any) {
feedback.msgError(e?.message || '下载签署文件失败')
} finally {
downloadingSlip.value = false
}
return
}
// 切到对应联次再截图,导出与页面一致的样式(含医师 / 药师签章)。
if (prescriptionTabType.value !== command) {
prescriptionTabType.value = command
await nextTick()
}
const node = getRxPaperEl()
if (!node) {
feedback.msgWarning('处方笺尚未渲染完成')
@@ -2957,7 +2999,8 @@ async function handleDownloadSlip() {
const name = (slipView.value as any)?.patient_name || '处方'
const id = (slipView.value as any)?.id || ''
const date = (slipView.value as any)?.prescription_date || ''
pdf.save(`处方-${name}${date ? '-' + date : ''}${id ? '-' + id : ''}.pdf`)
const copy = command === 'internal' ? '药房联' : '处方联'
pdf.save(`${copy}-${name}${date ? '-' + date : ''}${id ? '-' + id : ''}.pdf`)
} catch (e: any) {
console.error('下载处方 PDF 失败:', e)
feedback.msgError(e?.message || '下载失败,请重试')
@@ -3338,17 +3381,20 @@ type VoidablePrescriptionRow = Parameters<typeof isPendingPrescriptionAudit>[0]
can_review_prescription?: boolean
}
function canVoidPendingPrescription(row: VoidablePrescriptionRow) {
return isPendingPrescriptionAudit(row) && row.can_void === true
/** 作废不再限于待审核:签署、审核通过或已有业务订单后也可作废(以服务端 can_void 为准) */
function canVoidPrescription(row: VoidablePrescriptionRow) {
return Number(row.void_status) !== 1 && row.can_void === true
}
async function voidPendingPrescription(row: VoidablePrescriptionRow) {
const id = Number(row.id)
if (!Number.isSafeInteger(id) || id <= 0 || voidingPrescriptionId.value || !canVoidPendingPrescription(row)) return
if (!Number.isSafeInteger(id) || id <= 0 || voidingPrescriptionId.value || !canVoidPrescription(row)) return
voidingPrescriptionId.value = id
try {
await feedback.confirm('确定作废这张处方吗?作废后可重新开方。')
await prescriptionVoid({ id, pending_only: true })
await feedback.confirm(Number((row as { has_prescription_order?: number }).has_prescription_order) === 1
? '确定作废这张处方吗?已提交洛阳药房的订单会先撤销药房订单;关联的业务订单将退回待审核,同诊单重新开方后自动关联到新处方。'
: '确定作废这张处方吗?作废后可重新开方。')
await prescriptionVoid({ id })
row.void_status = 1
row.can_void = false
row.can_submit_for_review = false
@@ -4083,10 +4129,10 @@ function openNewPrescription(source?: Record<string, any>) {
})
}
/** 已作废处方(含他人所开、他人作废)均可由有开方权限的账号重新开方;新处方以当前账号为开方医生 */
function canReissuePrescription(row: { creator_id?: number | string; void_status?: number | string }) {
const doctorId = Number(userStore.userInfo?.id)
return Number(row.void_status) === 1 && doctorId > 0 && Number(row.creator_id) === doctorId
&& hasPermission(['cf.prescription/add'])
return Number(row.void_status) === 1 && doctorId > 0 && hasPermission(['cf.prescription/add'])
}
async function handleReissue(row: { id?: number | string; creator_id?: number | string; void_status?: number | string }) {
@@ -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"
@@ -990,6 +991,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="editForm.medication_days"
:disabled="editDaysLocked"
:min="1"
:max="999"
:step="1"
@@ -1636,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>
@@ -1800,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"
@@ -1809,18 +1811,39 @@
>
下载图片
</el-button>
<el-button
size="small"
:loading="prescriptionSlipExporting"
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download"
@click="downloadPrescriptionSlipPdf"
<el-dropdown
trigger="click"
:disabled="prescriptionSlipExporting"
@command="downloadPrescriptionSlipPdf"
>
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
</el-button>
<el-button size="small" type="primary" :loading="prescriptionSlipExporting">下载 PDF (A4)</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
v-if="requiresOriginalEsignPdf(prescriptionViewData.esign)"
command="esign"
:disabled="!prescriptionViewData.esign?.can_download"
>CA 签署处方 PDF</el-dropdown-item>
<el-dropdown-item command="internal">药房联 PDF(当前页面样式)</el-dropdown-item>
<el-dropdown-item command="user">处方联 PDF(当前页面样式)</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</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"
@@ -1856,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
@@ -1882,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"
@@ -1890,11 +1916,13 @@
/>
<PrescriptionSlip
v-if="prescriptionViewData"
:key="previewPrescriptionId"
ref="rxSlipRef"
:data="prescriptionViewData"
:variant="prescriptionTabType"
:aux-library-name="slipAuxLibraryName"
:title="SLIP_TITLE"
show-pharmacist-signature-sample
/>
<!-- 审核痕迹(不进入导出) -->
@@ -2086,11 +2114,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 {
@@ -2150,16 +2181,16 @@ import {
prescriptionOrderLinkPayOrder,
prescriptionOrderUploadToPharmacy,
prescriptionOrderPreviewGancaoRecipel,
prescriptionDetail,
prescriptionLibraryLists,
getDoctors,
getAssistants
} from '@/api/tcm'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import { applyOrderUsageOverride } from '@/components/prescription-slip/utils'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import type { PrescriptionEsignStatus } from '@/api/tcm'
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import { canApprovePrescriptionEsign, downloadOriginalEsignPdf, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app'
@@ -2173,7 +2204,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>
@@ -3317,8 +3352,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)
@@ -3356,6 +3391,7 @@ const editFormRef = ref<FormInstance>()
const editForm = reactive({
id: 0,
prescription_id: 0,
linked_prescriptions: [] as LinkedPrescription[],
diagnosis_id: 0,
recipient_name: '',
recipient_phone: '',
@@ -3515,6 +3551,7 @@ const editRules = computed<FormRules>(() => {
function resetEditOrderDialog() {
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editGancaoLogisticsOnlyMode.value = false
editGancaoDisplayNo.value = ''
editFormRef.value?.clearValidate()
@@ -3543,6 +3580,9 @@ async function goEditOrderNextStep() {
}
}
/** 已发货订单服用天数锁定(来自订单详情 days_locked,服务端同样拦截) */
const editDaysLocked = ref(false)
async function openEdit(row: {
id: number
creator_id?: number
@@ -3564,6 +3604,7 @@ async function openEdit(row: {
}
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editVisible.value = true
editDialogLoading.value = true
try {
@@ -3574,6 +3615,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>
@@ -3616,7 +3658,8 @@ async function openEdit(row: {
editForm.shipping_address = d.shipping_address || ''
editForm.is_follow_up = d.is_follow_up ? 1 : 0
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
editDaysLocked.value = d.days_locked === true
editForm.dose_count = d.dose_count > 0 ? d.dose_count : 1
editForm.dose_unit = d.dose_unit || '剂'
editForm.prev_staff = d.prev_staff || ''
@@ -3963,6 +4006,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()
@@ -3970,8 +4024,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()
})
// ─── 快捷填写快递单号 ────────────────────────────────────────────
@@ -4465,7 +4519,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)
}
}
@@ -4585,13 +4639,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)
@@ -4980,64 +5041,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
const merged: Record<string, unknown> = { ...base }
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) => {
@@ -5130,7 +5133,8 @@ async function capturePrescriptionSlipCanvas(): Promise<HTMLCanvasElement> {
function slipDownloadBaseName() {
const name = prescriptionViewData.value?.patient_name
const safe = typeof name === 'string' && name.trim() ? name.trim().replace(/[\\/:*?"<>|]/g, '_') : '未命名'
return `处方_${safe}_${Date.now()}`
const copy = prescriptionTabType.value === 'internal' ? '药房联' : '处方联'
return `${copy}_${safe}_${Date.now()}`
}
async function downloadPrescriptionSlipImage() {
@@ -5150,11 +5154,19 @@ async function downloadPrescriptionSlipImage() {
}
}
async function downloadPrescriptionSlipPdf() {
if (!prescriptionViewData.value) return
/** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
if (!prescriptionViewData.value || !previewCanExport.value) return
prescriptionSlipExporting.value = true
try {
if (await downloadPrescriptionPdfIfRequired(Number(prescriptionViewData.value.id))) return
if (command === 'esign') {
await downloadOriginalEsignPdf(Number(prescriptionViewData.value.id))
return
}
if (prescriptionTabType.value !== command) {
prescriptionTabType.value = command
await nextTick()
}
const canvas = await capturePrescriptionSlipCanvas()
const imgData = canvas.toDataURL('image/jpeg', 0.95)
/**
@@ -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>
@@ -1570,6 +1606,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="editForm.medication_days"
:disabled="editDaysLocked"
:min="1"
:max="999"
:step="1"
@@ -2134,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>
@@ -2323,6 +2360,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="patchUsageForm.usage_days"
:disabled="patchUsageDaysLocked"
:min="1"
:max="999"
:step="1"
@@ -2357,6 +2395,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="patchUsageForm.aux_usage_days"
:disabled="patchUsageDaysLocked"
:min="1"
:max="999"
:step="1"
@@ -2372,6 +2411,7 @@
<div class="flex items-center gap-1 w-full">
<el-input-number
v-model="patchUsageForm.medication_days"
:disabled="patchUsageDaysLocked"
:min="1"
:max="999"
:step="1"
@@ -2400,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"
@@ -2409,18 +2449,39 @@
>
下载图片
</el-button>
<el-button
size="small"
:loading="prescriptionSlipExporting"
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download"
@click="downloadPrescriptionSlipPdf"
<el-dropdown
trigger="click"
:disabled="prescriptionSlipExporting"
@command="downloadPrescriptionSlipPdf"
>
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
</el-button>
<el-button size="small" type="primary" :loading="prescriptionSlipExporting">下载 PDF (A4)</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item
v-if="requiresOriginalEsignPdf(prescriptionViewData.esign)"
command="esign"
:disabled="!prescriptionViewData.esign?.can_download"
>CA 签署处方 PDF</el-dropdown-item>
<el-dropdown-item command="internal">药房联 PDF(当前页面样式)</el-dropdown-item>
<el-dropdown-item command="user">处方联 PDF(当前页面样式)</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</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"
@@ -2456,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
@@ -2482,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"
@@ -2490,10 +2554,12 @@
/>
<PrescriptionSlip
v-if="prescriptionViewData"
:key="previewPrescriptionId"
ref="rxSlipRef"
:data="prescriptionViewData"
:variant="prescriptionTabType"
:title="SLIP_TITLE"
show-pharmacist-signature-sample
/>
<!-- 审核痕迹(不进入导出) -->
@@ -2660,7 +2726,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,
@@ -2677,6 +2743,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,
@@ -2702,7 +2769,6 @@ import {
prescriptionOrderRequestCompletion,
prescriptionOrderUploadToPharmacy,
prescriptionOrderPreviewGancaoRecipel,
prescriptionDetail,
getDoctors,
getAssistants
} from '@/api/tcm'
@@ -2719,11 +2785,15 @@ import {
supplyModeLabel,
supplyModeTagType
} from './components/prescription-order-utils'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
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'
import type { PrescriptionEsignStatus } from '@/api/tcm'
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import { canApprovePrescriptionEsign, downloadOriginalEsignPdf, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app'
@@ -2737,6 +2807,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>
@@ -3615,6 +3688,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) {
@@ -3700,28 +3787,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 []
@@ -3734,11 +3813,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 {
@@ -3755,13 +3829,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 || '—'
})
@@ -3784,7 +3858,9 @@ const detailLinkedAppointmentResolvedFromTag = computed(() => {
const detailRxHerbs = computed(() => normalizeSlipHerbs(detailPrescription.value?.herbs))
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
/** 已发货订单服用天数锁定(服务端 days_locked,同样拦截保存) */
const patchUsageDaysLocked = computed(() => detailData.value?.days_locked === true)
const detailAuxUsage = computed(() => {
const rx = detailPrescription.value as any
@@ -3795,7 +3871,6 @@ const detailAuxUsage = computed(() => {
})
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
// 完整收货地址(省市区 + 详细地址)
const detailFullAddress = computed(() => {
@@ -3939,6 +4014,7 @@ function logActionText(act: string) {
ship: '确认发货',
withdraw: '撤销',
link_pay_order: '关联支付单',
bind_prescription: '绑定关联处方',
revoke_rx_audit: '撤回处方审核',
revoke_pay_audit: '撤回支付审核',
gancao_submit: '甘草下单',
@@ -4061,6 +4137,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 =
@@ -4140,6 +4217,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) {
@@ -4177,12 +4255,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 {
/* 静默失败,避免打断当前抽屉 */
}
@@ -4246,9 +4325,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'
@@ -4259,6 +4342,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) {
@@ -4270,18 +4354,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
}
}
@@ -4316,6 +4397,7 @@ const editFormRef = ref<FormInstance>()
const editForm = reactive({
id: 0,
prescription_id: 0,
linked_prescriptions: [] as LinkedPrescription[],
diagnosis_id: 0,
recipient_name: '',
recipient_phone: '',
@@ -4494,6 +4576,7 @@ const editRules = computed<FormRules>(() => {
function resetEditOrderDialog() {
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editFormRef.value?.clearValidate()
}
@@ -4520,6 +4603,9 @@ async function goEditOrderNextStep() {
}
}
/** 已发货订单服用天数锁定(来自订单详情 days_locked,服务端同样拦截) */
const editDaysLocked = ref(false)
async function openEdit(row: {
id: number
creator_id?: number
@@ -4541,6 +4627,7 @@ async function openEdit(row: {
}
editOrderStep.value = 0
editOrderPrescription.value = null
editForm.linked_prescriptions = []
editVisible.value = true
editDialogLoading.value = true
try {
@@ -4551,6 +4638,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>
@@ -4593,7 +4681,8 @@ async function openEdit(row: {
editForm.shipping_address = d.shipping_address || ''
editForm.is_follow_up = d.is_follow_up ? 1 : 0
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
editDaysLocked.value = d.days_locked === true
editForm.dose_count = d.dose_count > 0 ? d.dose_count : 1
editForm.dose_unit = d.dose_unit || '剂'
editForm.prev_staff = d.prev_staff || ''
@@ -4688,6 +4777,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)
@@ -4892,13 +4982,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()
})
// ─── 快捷填写快递单号 ────────────────────────────────────────────
@@ -5343,7 +5444,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)
}
}
@@ -5471,11 +5572,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)
@@ -5734,60 +5843,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
const merged: Record<string, unknown> = { ...base }
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) => {
@@ -5880,7 +5935,8 @@ async function capturePrescriptionSlipCanvas(): Promise<HTMLCanvasElement> {
function slipDownloadBaseName() {
const name = prescriptionViewData.value?.patient_name
const safe = typeof name === 'string' && name.trim() ? name.trim().replace(/[\\/:*?"<>|]/g, '_') : '未命名'
return `处方_${safe}_${Date.now()}`
const copy = prescriptionTabType.value === 'internal' ? '药房联' : '处方联'
return `${copy}_${safe}_${Date.now()}`
}
async function downloadPrescriptionSlipImage() {
@@ -5900,11 +5956,19 @@ async function downloadPrescriptionSlipImage() {
}
}
async function downloadPrescriptionSlipPdf() {
if (!prescriptionViewData.value) return
/** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
if (!prescriptionViewData.value || !previewCanExport.value) return
prescriptionSlipExporting.value = true
try {
if (await downloadPrescriptionPdfIfRequired(Number(prescriptionViewData.value.id))) return
if (command === 'esign') {
await downloadOriginalEsignPdf(Number(prescriptionViewData.value.id))
return
}
if (prescriptionTabType.value !== command) {
prescriptionTabType.value = command
await nextTick()
}
const canvas = await capturePrescriptionSlipCanvas()
const imgData = canvas.toDataURL('image/jpeg', 0.95)
/**
+54 -9
View File
@@ -1305,6 +1305,48 @@ test('both slips use verified physician and pharmacist PNGs and fall back to the
assert.equal(reviewerName.value, '测试药师')
})
test('only issued prescriptions without physician CA or a pharmacist signature display the sample', () => {
const legacy = status({ status: 'legacy', required: false })
const signed = status({ status: 'signed', can_download: true, review_required: true, review_state: 'pending' })
const base = { audit_status: 1, void_status: 0, is_system_auto: 0, herbs: [{ name: '测试药材', dosage: 1 }], esign: legacy }
const props = vue.reactive({ data: base, showPharmacistSignatureSample: true })
const { getSlipHerbs } = loadModule('components/prescription-slip/utils.ts', {})
const { showPharmacistSample } = pageDeclarations('components/prescription-slip/index.vue', ['showPharmacistSample'],
{ computed: vue.computed, props, getSlipHerbs })
assert.equal(showPharmacistSample.value, true)
props.showPharmacistSignatureSample = false
assert.equal(showPharmacistSample.value, false)
props.showPharmacistSignatureSample = true
props.data = { ...base, audit_status: 0, esign: signed }
assert.equal(showPharmacistSample.value, false)
props.data = { ...base, audit_status: 0, doctor_signature: 'signature.png', review_submitted_at: 123 }
assert.equal(showPharmacistSample.value, true)
for (const update of [
{ audit_status: 0 }, { void_status: 1 }, { audit_status: 2 }, { herbs: [] }, { is_system_auto: 1 },
{ esign: status({ awaiting_upload: true }) }, { esign: signed },
{ esign: { ...signed, review_required: false, review_state: undefined } },
{ esign: { ...legacy, required: true } }, { esign: { ...legacy, can_download: true } },
{ esign: { ...legacy, review_state: 'signed' } }, { esign: { ...legacy, review_signature_time: 123 } },
{ esign: { ...legacy, review_signer_name: '已签署药师' } }, { esign: { ...legacy, review_signature: 'seal' } }
]) {
props.data = { ...base, ...update }
assert.equal(showPharmacistSample.value, false, JSON.stringify(update))
}
})
test('issued and order previews opt into the sample and the slip excludes it from exports', () => {
const source = (file) => fs.readFileSync(path.join(__dirname, '../src', file), 'utf8')
const paths = ['index.vue', 'order_list.vue', 'order_list_h5.vue']
for (const filename of paths) {
assert.match(source(`views/consumer/prescription/${filename}`), /<PrescriptionSlip[^>]+show-pharmacist-signature-sample/)
}
const slip = source('components/prescription-slip/index.vue')
assert.match(slip, /rx-bot-doctor[\s\S]*v-else-if="showPharmacistSample"[^>]*data-html2canvas-ignore="true"[\s\S]*rx-bot-meta/)
assert.match(slip, /@media print\s*\{\s*\.rx-pharmacist-sample\s*\{\s*display: none;/)
})
test('the slip reloads a newly verified physician seal once from prescription detail', async () => {
const requests = []
const { updatePrescriptionSlipEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': {
@@ -1425,7 +1467,7 @@ test('list upload can retry and opens signing without exposing audit to the phar
assert.match(messages[0], /请完成医师签署/)
})
test('issued prescriptions can void pending drafts with permission and keep the record', async () => {
test('issued prescriptions can be voided in any review state when the server allows it', async () => {
const calls = []
const messages = []
let cancel = true
@@ -1443,24 +1485,26 @@ test('issued prescriptions can void pending drafts with permission and keep the
msgSuccess: (message) => messages.push(message)
}
}
const { canVoidPendingPrescription, voidPendingPrescription } = pageDeclarations(
const { canVoidPrescription, voidPendingPrescription } = pageDeclarations(
'views/consumer/prescription/index.vue',
['isPendingPrescriptionAudit', 'canVoidPendingPrescription', 'voidPendingPrescription'], globals
['canVoidPrescription', 'voidPendingPrescription'], globals
)
assert.equal(canVoidPendingPrescription(row), true)
for (const other of [{ audit_status: 1 }, { audit_status: 2 }, { void_status: 1 }, { can_void: false }]) {
assert.equal(canVoidPrescription(row), true)
// 审核通过(药师已签署)后仍可作废;以服务端 can_void 为准。
assert.equal(canVoidPrescription({ ...row, audit_status: 1 }), true)
for (const other of [{ void_status: 1 }, { can_void: false }]) {
await voidPendingPrescription({ ...row, ...other })
}
await voidPendingPrescription(row)
assert.deepEqual(calls, [])
cancel = false
await voidPendingPrescription(row)
assert.equal(canVoidPendingPrescription(row), true)
assert.equal(canVoidPrescription(row), true)
await Promise.all([voidPendingPrescription(row), voidPendingPrescription(row)])
assert.deepEqual(calls, [{ id: 17, pending_only: true }, { id: 17, pending_only: true }])
assert.deepEqual(calls, [{ id: 17 }, { id: 17 }])
assert.equal(row.void_status, 1)
assert.equal(row.can_submit_for_review, false)
assert.equal(canVoidPendingPrescription(row), false)
assert.equal(canVoidPrescription(row), false)
assert.equal(refreshes, 1)
assert.deepEqual(messages, ['处方已作废'])
})
@@ -1504,8 +1548,9 @@ test('issued prescriptions reopen a voided record as a new prescription with fre
['resetForm', 'fillPrescriptionContents', 'openNewPrescription', 'handleAdd', 'canReissuePrescription', 'handleReissue', 'handleSubmit'], globals
)
assert.equal(canReissuePrescription(source), true)
// 他人所开、已作废的处方也可由有开方权限的账号重新开方。
assert.equal(canReissuePrescription({ ...source, creator_id: 9 }), true)
await handleReissue({ ...source, void_status: 0 })
await handleReissue({ ...source, creator_id: 9 })
permitted = false
await handleReissue(source)
assert.deepEqual(reads, [])
+1 -1
View File
@@ -3,7 +3,7 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.5.5"
__version__ = "1.5.6"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
@@ -454,10 +454,9 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
def can_void_prescription(record: Any) -> bool:
# 已有业务订单、已审核签署的处方也可作废:订单随同诊单重新开方自动关联新处方;权限与药房锁由服务端判定。
_, mode = prescription_action(record)
return mode in {"edit", "view"} and not _as_bool(
first_value(record, "has_prescription_order", default=False)
)
return mode in {"edit", "view"}
def _prescription_action_label(record: Any, *, force_open: bool = False) -> str:
@@ -33,6 +33,7 @@ from PySide6.QtCore import (
QObject,
QPoint,
QRectF,
QRegularExpression,
QSize,
Qt,
QTimer,
@@ -52,6 +53,7 @@ from PySide6.QtGui import (
QPainter,
QPdfWriter,
QPen,
QRegularExpressionValidator,
QStandardItem,
QStandardItemModel,
QTextDocument,
@@ -98,7 +100,7 @@ from PySide6.QtWidgets import (
)
from shiboken6 import isValid
from ...core.esign import esign_config, esign_status
from ...core.esign import certificate_identity_number, esign_config, esign_status
from .. import icons
from ..design_system import clinical_stylesheet
from ..diagnosis_terms import shared_terms
@@ -993,6 +995,7 @@ _REISSUE_FIELDS = (
"herbs", "dose_count", "dose_unit", "dosage_amount", "dosage_unit", "dosage_bag_count",
"need_decoction", "bags_per_dose", "usage_days", "times_per_day", "usage_instruction",
"usage_time", "usage_way", "dietary_taboo", "usage_notes", "aux_usage", "ai_assisted",
"patient_id_card",
)
@@ -1004,10 +1007,21 @@ def can_void_issued_prescription(prescription: Any) -> bool:
return not prescription_is_voided(prescription) and _bool(get_value(prescription, "can_void"))
_PRESCRIPTION_PHONE = re.compile(r"1[3-9][0-9]{9}|0[0-9]{2,3}-?[0-9]{7,8}")
def prescription_phone_error(value: Any) -> str:
"""处方笺手机号:11 位手机号或带区号座机;为空表示沿用原号码。与服务端规则一致。"""
phone = str(value or "").strip()
if not phone or _PRESCRIPTION_PHONE.fullmatch(phone):
return ""
return "手机号格式不正确,请输入 11 位手机号或带区号的座机号(如 0571-88888888)"
def can_reissue_prescription(prescription: Any, current_user: Any, permissions: Any) -> bool:
# 已作废处方(含他人作废、他人所开)均可由有开方权限的账号重新开方;新处方以当前账号为开方医生并由其签署。
actor_id = _int(first_value(current_user, "id", "user_id", "admin_id"))
creator_id = _int(first_value(prescription, "creator_id", "doctor_id"))
return (prescription_is_voided(prescription) and actor_id > 0 and actor_id == creator_id
return (prescription_is_voided(prescription) and actor_id > 0
and has_permission(permissions, PRESCRIBE_PERMISSIONS))
@@ -3451,12 +3465,24 @@ class PrescriptionEditorDialog(QDialog):
self.age.setRange(0, 150)
self.visit_no = QLineEdit()
self.visit_no.setPlaceholderText("自动生成或手动输入")
# 手机号写入处方笺;身份证号写回关联诊单(服务端校验格式与重复,并按出生日期更新年龄)。
self.phone = QLineEdit()
self.phone.setPlaceholderText("11 位手机号或带区号座机,如 0571-88888888")
self.phone.setMaxLength(20)
# 输入时只允许数字与连字符;格式在保存时按 prescription_phone_error 校验。
self.phone.setValidator(QRegularExpressionValidator(QRegularExpression(r"[0-9-]{0,20}"), self.phone))
self.id_card = QLineEdit()
self.id_card.setPlaceholderText("15 或 18 位身份证号,保存后同步到诊单")
self.id_card.setMaxLength(18)
self.id_card.setValidator(QRegularExpressionValidator(QRegularExpression(r"[0-9]{0,17}[0-9Xx]?"), self.id_card))
self.date_edit = PrescriptionDateEdit(QDate.currentDate())
name_grid = QGridLayout()
self._prepare_grid(name_grid, 2)
self._place_field(name_grid, 0, 0, "患者姓名", self.patient_name, required=True)
self._place_field(name_grid, 0, 1, "门诊号", self.visit_no)
self._place_field(name_grid, 1, 0, "手机号", self.phone)
self._place_field(name_grid, 1, 1, "身份证号", self.id_card)
layout.addLayout(name_grid)
self._register_responsive_grid(name_grid, 2)
@@ -3855,6 +3881,8 @@ class PrescriptionEditorDialog(QDialog):
appointment_id=_int(source.get("appointment_id"), 0),
)
self.visit_no.setText(visit_no)
self.phone.setText(str(source.get("phone") or "").strip())
self.id_card.setText(str(source.get("patient_id_card") or source.get("id_card") or "").strip())
self._set_gender(source.get("gender", 1))
self.age.setValue(_int(source.get("age"), 0))
date_value = QDate.fromString(
@@ -4301,6 +4329,8 @@ class PrescriptionEditorDialog(QDialog):
"need_decoction": int(self.need_decoction.isChecked()),
"bags_per_dose": self.bags_per_dose.value(),
"patient_name": self.patient_name.text().strip(),
"phone": self.phone.text().strip(),
"id_card": self.id_card.text().strip().upper(),
"gender": self._gender_value(),
"age": self.age.value(),
"visit_no": self.visit_no.text().strip(),
@@ -4398,6 +4428,21 @@ class PrescriptionEditorDialog(QDialog):
self.validation.show_message(message, "warning")
widget.setFocus()
return
original_phone = str(self._source.get("phone") or "").strip()
phone_error = "" if payload.get("phone") == original_phone else prescription_phone_error(payload.get("phone"))
if phone_error:
self.tabs.setCurrentIndex(0)
self.validation.show_message(phone_error, "warning")
self.phone.setFocus()
return
if payload.get("id_card"):
try:
payload["id_card"] = certificate_identity_number(payload["id_card"])
except ValueError as error:
self.tabs.setCurrentIndex(0)
self.validation.show_message(str(error), "warning")
self.id_card.setFocus()
return
length_checks = (
(
payload["clinical_diagnosis"],
@@ -5061,6 +5106,14 @@ def render_prescription_html(
bags = positive_number(source.get("dosage_bag_count"), 1)
if prescription_type == "浓缩水丸" and days and times and amount:
out_pellet = f"{number_text(days * times * amount * bags)}克"
# 有辅方药材时同时给出辅方出丸(辅方服用天数 × 每日次数 × 每袋用量 × 每次袋数),与管理后台一致。
aux_days = positive_number(aux_usage.get("usage_days"), 0)
aux_times = positive_number(aux_usage.get("times_per_day"), 0)
aux_amount = positive_number(aux_usage.get("dosage_amount"), 0)
aux_bags = positive_number(aux_usage.get("dosage_bag_count"), 1)
if aux and aux_days and aux_times and aux_amount:
aux_pellet = number_text(aux_days * aux_times * aux_amount * aux_bags)
out_pellet = f"主方 {out_pellet},辅方 {aux_pellet}克"
elif herbs:
total_weight = sum(_float(row.get("dosage")) for row in herbs) * dose_count
out_pellet = f"{number_text(total_weight)}克"
+21
View File
@@ -143,3 +143,24 @@ def test_ai_report_columns_keep_headings_at_the_same_text_baseline(
assert abs(centers[0] - centers[1]) <= 1
finally:
dialog.close()
def test_prescription_form_edits_phone_and_id_card(application: QApplication) -> None:
editor = PrescriptionEditorDialog(
SimpleNamespace(list_medicines=lambda **kwargs: {"lists": [], "count": 0}),
{"id": 77, "diagnosis_id": 501, "patient_name": "林晓岚", "phone": "13800000000",
"patient_id_card": "11010119800101123X", "prescription_type": "浓缩水丸"},
)
try:
# 已开处方编辑时手机号、身份证号可见可改(姓名仍只读),保存时随处方提交。
assert editor.phone.text() == "13800000000" and editor.id_card.text() == "11010119800101123X"
assert not editor.phone.isReadOnly() and not editor.id_card.isReadOnly()
editor.phone.setText(" 13900000001 ")
editor.id_card.setText("110101200001011234")
payload = editor.payload()
assert payload["phone"] == "13900000001" and payload["id_card"] == "110101200001011234"
editor.id_card.setText("12345")
assert editor.payload()["id_card"] == "12345"
finally:
editor.close()
editor.deleteLater()
+19 -1
View File
@@ -1085,7 +1085,8 @@ def test_editor_matches_admin_four_observation_fields_and_edit_context(
assert editor.windowTitle() == "编辑处方"
assert editor.patient_name.isReadOnly()
assert editor.visit_no.isReadOnly()
assert not hasattr(editor, "phone")
# 已开处方编辑可修改手机号与身份证号(姓名、门诊号仍只读)。
assert not editor.phone.isReadOnly() and not editor.id_card.isReadOnly()
assert editor.gender_male.isChecked()
assert editor.payload()["gender"] == 1
assert editor.tongue.text() == "面象哨兵"
@@ -1640,3 +1641,20 @@ def test_demo_repository_pages_render_offscreen(
library.close()
issued.close()
application.processEvents()
def test_voided_prescriptions_can_be_reissued_by_any_prescriber() -> None:
from doctor_workstation.ui.dialogs.prescription import can_reissue_prescription, prescription_phone_error
voided_by_admin = {"id": 14011, "creator_id": 117, "void_status": 1}
prescriber = {"tcm.diagnosis/kaifang"}
# 原方子作废后(含他人所开、他人作废)有开方权限即可重新开方;未作废或无开方权限不行。
assert can_reissue_prescription(voided_by_admin, SimpleNamespace(id=1), prescriber)
assert can_reissue_prescription(voided_by_admin, SimpleNamespace(id=117), prescriber)
assert not can_reissue_prescription({**voided_by_admin, "void_status": 0}, SimpleNamespace(id=117), prescriber)
assert not can_reissue_prescription(voided_by_admin, SimpleNamespace(id=1), {"cf.prescription/read"})
for valid in ("", "13800138000", "0571-88888888", "01088888888"):
assert prescription_phone_error(valid) == ""
for invalid in ("c", "1380013800", "23800138000", "138001380001", "0571-888"):
assert "手机号格式不正确" in prescription_phone_error(invalid)
+3 -4
View File
@@ -19,7 +19,7 @@ endobj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents 7 0 R >>
endobj
7 0 obj
<< /Length 1969>>
<< /Length 1889>>
stream
BT /F1 20 Tf 1 0 0 1 235 795 Tm <4e2d533b590465b97b3a> Tj ET
BT /F1 12 Tf 1 0 0 1 170 770 Tm <6c997bb16d4b8bd565874ef6002000b700204e0d75284e8e6b635f0f53d1836f> Tj ET
@@ -33,8 +33,7 @@ BT /F1 11 Tf 1 0 0 1 45 630 Tm <836f54c100200032ff1a752891cf002000360020002f0020
BT /F1 11 Tf 1 0 0 1 45 612 Tm <53556b21888b6570ff1a0033> Tj ET
BT /F1 11 Tf 1 0 0 1 45 594 Tm <4ee3714eff1a5426> Tj ET
BT /F1 11 Tf 1 0 0 1 45 576 Tm <8f8565b953556b21888b6570ff1a0034> Tj ET
BT /F1 11 Tf 1 0 0 1 45 558 Tm <8f8565b965b9540dff1a8f8552a965b96a21677f> Tj ET
BT /F1 11 Tf 1 0 0 1 45 540 Tm <8f8565b9670d752859296570ff1a0038> Tj ET
BT /F1 11 Tf 1 0 0 1 45 558 Tm <8f8565b9670d752859296570ff1a0038> Tj ET
0.7 w 45 133 m 550 133 l S
BT /F1 12 Tf 1 0 0 1 45 110 Tm <5f0065b9533b5e08ff1a6d4b8bd5533b5e08> Tj ET
BT /F1 11 Tf 1 0 0 1 420 104 Tm <533b5e0875355b507b7e7ae0> Tj ET
@@ -55,5 +54,5 @@ xref
0000000735 00000 n
trailer << /Size 8 /Root 1 0 R >>
startxref
2754
2674
%%EOF
@@ -45,7 +45,7 @@ class PrescriptionController extends BaseAdminController
public function edit()
{
$params = (new PrescriptionValidate())->post()->goCheck('edit');
$result = PrescriptionLogic::edit($params, $this->adminId);
$result = PrescriptionLogic::edit($params, $this->adminId, $this->adminInfo);
if (!$result) {
return $this->fail(PrescriptionLogic::getError());
}
@@ -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()
{
@@ -13,6 +13,7 @@ use app\common\model\tcm\Prescription;
use app\common\model\tcm\PrescriptionOrder;
use app\common\service\esign\PrescriptionEsignService;
use think\db\Query;
use think\facade\Cache;
/**
* 处方列表
@@ -21,51 +22,92 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
{
use HasDataScopeFilter;
/** 置顶风险处方 ID 的缓存键与有效期(秒);只影响置顶顺序,行内警示仍按当前数据实时计算 */
private const RISK_IDS_CACHE_KEY = 'tcm_prescription_lists_risk_ids';
private const RISK_IDS_CACHE_TTL = 60;
/** 列表行不返回的大字段:签名图 base64 动辄数十 KB,查看/编辑都会另取详情 */
private const LIST_OMIT_FIELDS = ['doctor_signature'];
/**
* 识别「有业务订单且处方药材为空白/重复」的处方 ID(用于全局置顶排序)
*
* @param array<int,int|string> $candidateIds
* 风险是处方自身的属性,与筛选条件无关:这里在全库范围计算一次并短时缓存,
* 筛选范围的交集由 pinnedIds() 在当前查询里取。以前每次请求都先把筛选结果的
* 全部 ID 拉出来,再逐个读药材,处方表行很宽(病历快照、签名图),整表扫描
* 是列表慢的主因。
*
* @return array<int,int>
*/
private function collectRiskPrescriptionIds(array $candidateIds): array
private function collectRiskPrescriptionIds(): array
{
$candidateIds = array_values(array_unique(array_filter(array_map('intval', $candidateIds), static function (int $id): bool {
return $id > 0;
})));
if ($candidateIds === []) {
return [];
$cached = Cache::get(self::RISK_IDS_CACHE_KEY);
if (is_array($cached)) {
return $cached;
}
// 仅在「存在有效业务订单」的处方里做风险判定
$orderRxIds = PrescriptionOrder::whereIn('prescription_id', $candidateIds)
->whereNull('delete_time')
// 仅在「存在有效业务订单」的处方里做风险判定;订单表很小,从订单侧出发
$orderRxIds = PrescriptionOrder::whereNull('delete_time')
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
->column('prescription_id');
$orderRxIds = array_values(array_unique(array_filter(array_map('intval', $orderRxIds), static function (int $id): bool {
return $id > 0;
})));
if ($orderRxIds === []) {
$riskIds = [];
foreach (array_chunk($orderRxIds, 1000) as $chunk) {
$herbsById = Prescription::whereIn('id', $chunk)
->whereNull('delete_time')
->column('herbs', 'id');
foreach ($herbsById as $rid => $herbs) {
$rid = (int) $rid;
if ($rid > 0 && $this->isRiskHerbs($herbs)) {
$riskIds[] = $rid;
}
}
}
$riskIds = array_values(array_unique($riskIds));
Cache::set(self::RISK_IDS_CACHE_KEY, $riskIds, self::RISK_IDS_CACHE_TTL);
return $riskIds;
}
/**
* 当前页的处方 ID:先排当前筛选范围内的风险处方,再按 ID 倒序排其余处方。
*
* 拆成两段只查 ID,避免对整表做 ORDER BY CASE 的文件排序;第二段可直接沿主键倒序扫描,
* 取够一页即停止。
*
* @return array<int,int>
*/
private function pageIds(Query $query): array
{
$offset = max(0, (int) $this->limitOffset);
$length = max(0, (int) $this->limitLength);
if ($length === 0) {
return [];
}
$rows = Prescription::whereIn('id', $orderRxIds)
->whereNull('delete_time')
->field(['id', 'herbs'])
->select()
->toArray();
$riskIds = [];
foreach ($rows as $row) {
$rid = (int) ($row['id'] ?? 0);
if ($rid <= 0) {
continue;
}
if ($this->isRiskHerbs($row['herbs'] ?? null)) {
$riskIds[] = $rid;
}
$riskIds = $this->collectRiskPrescriptionIds();
$pinned = [];
if ($riskIds !== []) {
$pinned = array_map('intval', (clone $query)->whereIn('id', $riskIds)->order('id', 'desc')->column('id'));
}
return array_values(array_unique($riskIds));
$ids = array_slice($pinned, $offset, $length);
$remaining = $length - count($ids);
if ($remaining > 0) {
$rest = clone $query;
if ($pinned !== []) {
$rest->whereNotIn('id', $pinned);
}
$restIds = $rest->order('id', 'desc')
->limit(max(0, $offset - count($pinned)), $remaining)
->column('id');
$ids = array_merge($ids, array_map('intval', $restIds));
}
return $ids;
}
/**
@@ -253,22 +295,25 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
*/
public function lists(): array
{
$query = $this->buildFilteredQuery();
// 全局置顶:有业务订单且处方药材为空白/重复
$candidateIds = (clone $query)->column('id');
$riskIds = $this->collectRiskPrescriptionIds(is_array($candidateIds) ? $candidateIds : []);
$listQuery = $query;
if ($riskIds !== []) {
$riskIdStr = implode(',', array_map('intval', $riskIds));
$listQuery->orderRaw("CASE WHEN id IN ({$riskIdStr}) THEN 0 ELSE 1 END ASC");
$pageIds = $this->pageIds($this->buildFilteredQuery());
if ($pageIds === []) {
return [];
}
$lists = $listQuery
->order('id', 'desc')
->limit($this->limitOffset, $this->limitLength)
$rowsById = [];
$rows = Prescription::whereIn('id', $pageIds)
->withoutField(self::LIST_OMIT_FIELDS)
->select()
->toArray();
foreach ($rows as $row) {
$rowsById[(int) $row['id']] = $row;
}
$lists = [];
foreach ($pageIds as $pageId) {
if (isset($rowsById[$pageId])) {
$lists[] = $rowsById[$pageId];
}
}
$rxIds = array_column($lists, 'id');
$rxIds = array_map('intval', $rxIds);
@@ -325,8 +370,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
$rid = (int) $item['id'];
$item['can_void'] = empty($item['void_status'])
&& PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess)
&& !PrescriptionLogic::hasBlockingVoidOrder($item, $ordersByPrescription[$rid] ?? [])
&& (empty($ordersByPrescription[$rid]) || PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($rid) === null);
&& (empty($ordersByPrescription[$rid]) || PrescriptionOrderLogic::voidBlockerForPrescription($rid) === null);
$item['can_restore_rejected'] = PrescriptionLogic::canRestoreRejected($item);
$item = PrescriptionLogic::withSigningStatus($item, $this->adminId, $maySubmit);
// 设置默认值
@@ -885,8 +885,8 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
'export_supply_mode' => '供货方式',
'export_gancao_prescription_cost' => '处方成本',
'export_first_visit_assistant' => '初诊医助',
'export_rx_audit_time' => '审核时间',
'export_rx_auditor' => '审核人',
'export_payment_audit_time' => '审核时间',
'export_payment_auditor' => '审核人',
];
}
+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;
}
/**
@@ -248,36 +248,20 @@ class PrescriptionLogic
!in_array((int) $order['fulfillment_status'], PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) !== [];
$row['has_prescription_order'] = $hasBizOrder ? 1 : 0;
$row['can_restore_rejected'] = self::canRestoreRejected($row);
$row['can_void'] = empty($row['void_status']) && !self::hasBlockingVoidOrder($row, $orders)
// 作废不再受审核、签署或订单状态限制;仅已提交药房的订单(须先远端取消)会阻止作废。
$row['can_void'] = empty($row['void_status'])
&& self::hasVoidAccess(
$row,
$viewerAdminId,
$viewerAdminInfo,
self::getVoidAccess($viewerAdminId, $viewerAdminInfo)
)
&& PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($id) === null;
// 已提交洛阳药房的订单在作废时自动撤单;甘草等无法自动撤单的才阻止作废。
&& PrescriptionOrderLogic::voidBlockerForPrescription($id) === null;
return $row;
}
/** Pending prescriptions can be voided while any active order is still waiting for both reviews. */
public static function hasBlockingVoidOrder(array $prescription, array $orders): bool
{
foreach ($orders as $order) {
$fulfillmentStatus = (int) ($order['fulfillment_status'] ?? -1);
if (in_array($fulfillmentStatus, PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) {
continue;
}
if ($fulfillmentStatus !== 1
|| !in_array($order['prescription_audit_status'] ?? null, [0, '0'], true)
|| !in_array($order['payment_slip_audit_status'] ?? null, [0, '0'], true)
|| !PrescriptionEsignPolicy::isPendingReview($prescription)) {
return true;
}
}
return false;
}
private static function generateSn(): string
{
return 'RX' . date('Ymd') . str_pad((string)mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
@@ -539,7 +523,8 @@ class PrescriptionLogic
$data['esign_status'] = 'pending';
}
try {
return Db::transaction(static function () use ($data, $params, $adminId, $adminInfo, $diagnosisIdRule, $dateYmd): int {
$relinkedOrderIds = [];
$newId = Db::transaction(static function () use ($data, $params, $adminId, $adminInfo, $diagnosisIdRule, $dateYmd, &$relinkedOrderIds): int {
$replayed = PrescriptionAiRequest::replay($params, $adminId, true);
if ($replayed !== null) {
return $replayed;
@@ -549,10 +534,18 @@ class PrescriptionLogic
if (!self::assertUniquePrescriptionPerDiagnosisDay($diagnosisIdRule, $adminId, $dateYmd, null)) {
throw new \DomainException(self::getError());
}
// 开方入口已校验诊单管理权限;身份证号写回诊单并按出生日期更新年龄。
$age = self::applyPatientIdCard($diagnosisIdRule, (string) ($params['id_card'] ?? ''));
if ($age !== null) {
$data['age'] = $age;
}
}
$data['phone'] = self::phoneParam($params, (string) $data['phone']);
$prescription = new Prescription();
$prescription->save($data);
$id = (int) $prescription->id;
// 原处方作废后挂起的业务订单,随本次重新开方自动关联到新处方。
$relinkedOrderIds = PrescriptionOrderLogic::relinkOrdersToReissue($diagnosisIdRule, $id, $data['sn'], $adminId, $adminInfo);
// Read database defaults and JSON exactly as workers will fingerprint them.
$saved = Db::name('tcm_prescription')->where('id', $id)->find();
self::scheduleAiSaved($saved, $adminId, $adminInfo,
@@ -560,6 +553,10 @@ class PrescriptionLogic
PrescriptionAiRequest::complete($params, $adminId, $id);
return $id;
});
foreach ($relinkedOrderIds as $orderId) {
\app\common\service\tcm\RevisitDueHook::onOrderChanged($diagnosisIdRule, $orderId, 'reissue');
}
return $newId;
} catch (\Throwable $e) {
self::setError($e instanceof \DomainException ? $e->getMessage() : '处方保存失败,请稍后重试');
return null;
@@ -569,14 +566,14 @@ class PrescriptionLogic
/**
* 编辑处方
*/
public static function edit(array $params, int $adminId): bool
public static function edit(array $params, int $adminId, array $adminInfo = []): bool
{
$prescriptionId = (int) ($params['id'] ?? 0);
self::setError('');
try {
return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
$prescriptionId,
static fn (): bool => self::editLocked($params, $adminId)
static fn (): bool => self::editLocked($params, $adminId, $adminInfo)
);
} catch (\Throwable $exception) {
if (self::getError() === '') {
@@ -586,7 +583,7 @@ class PrescriptionLogic
}
}
private static function editLocked(array $params, int $adminId): bool
private static function editLocked(array $params, int $adminId, array $adminInfo = []): bool
{
try {
$prescription = Prescription::where('id', $params['id'])->lock(true)->find();
@@ -732,6 +729,17 @@ class PrescriptionLogic
$data['void_by'] = null;
$data['void_by_name'] = '';
}
$data['phone'] = self::phoneParam($params, (string) ($prescription->phone ?? ''));
if (trim((string) ($params['id_card'] ?? '')) !== '') {
if ($newDiagnosisId <= 0 || $adminInfo === []
|| !DiagnosisLogic::canManageDiagnosis($newDiagnosisId, $adminId, $adminInfo)) {
throw new \DomainException('无权修改该患者身份证号');
}
$age = self::applyPatientIdCard($newDiagnosisId, (string) $params['id_card']);
if ($age !== null) {
$data['age'] = $age;
}
}
$prescription->save($data);
PrescriptionOrderLogic::onConsumerPrescriptionSaved((int) $params['id']);
@@ -748,6 +756,49 @@ class PrescriptionLogic
}
}
public const PHONE_FORMAT_ERROR = '手机号格式不正确,请输入 11 位手机号或带区号的座机号(如 0571-88888888)';
/** 处方笺手机号:11 位手机号或带区号座机(与桌面端、管理后台一致)。 */
public static function isValidPhone(string $phone): bool
{
return preg_match('/^(?:1[3-9]\d{9}|0\d{2,3}-?\d{7,8})$/D', $phone) === 1;
}
/** 处方笺手机号:传入非空值时须符合格式,否则保留原值。 */
private static function phoneParam(array $params, string $fallback): string
{
$phone = trim((string) ($params['phone'] ?? ''));
if ($phone === '' || $phone === $fallback) {
return $fallback;
}
if (!self::isValidPhone($phone)) {
throw new \DomainException(self::PHONE_FORMAT_ERROR);
}
return $phone;
}
/**
* 补全/修改患者身份证号:写入诊单并按出生日期更新年龄,返回新年龄;为空或未变更返回 null。
* 调用方须已确认当前账号可管理该诊单,并在同一事务内调用。
*/
private static function applyPatientIdCard(int $diagnosisId, string $idCard): ?int
{
$idCard = strtoupper(trim($idCard));
if ($diagnosisId <= 0 || $idCard === '') {
return null;
}
if (strtoupper(trim((string) Diagnosis::where('id', $diagnosisId)->value('id_card'))) === $idCard) {
return null;
}
if (!empty(DiagnosisLogic::checkIdCard(['id' => $diagnosisId, 'id_card' => $idCard])['exists'])) {
throw new \DomainException('该身份证号已登记在其他诊单');
}
if (!DiagnosisLogic::fillIdCard(['id' => $diagnosisId, 'id_card' => $idCard])) {
throw new \DomainException(DiagnosisLogic::getError() ?: '身份证号保存失败');
}
return (int) Diagnosis::where('id', $diagnosisId)->value('age');
}
private static function scheduleAiSaved(array $saved, int $actor, ?array $info, array $options): void
{
try {
@@ -826,6 +877,11 @@ class PrescriptionLogic
return false;
}
if ($phone !== trim((string) ($prescription->phone ?? '')) && !self::isValidPhone($phone)) {
self::setError(self::PHONE_FORMAT_ERROR);
return false;
}
if (!in_array($gender, [0, 1], true)) {
self::setError('性别无效');
@@ -933,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;
}
/**
* 处方详情(带查看权限校验,供后台管理端)
*/
@@ -964,6 +1033,11 @@ class PrescriptionLogic
$arr = self::withActionAvailability($arr, $viewerAdminId, $viewerAdminInfo);
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
// 患者身份证号存于诊单,仅对可管理该诊单的账号返回,供编辑处方时修改。
$diagnosisId = (int) ($arr['diagnosis_id'] ?? 0);
if ($diagnosisId > 0 && DiagnosisLogic::canManageDiagnosis($diagnosisId, $viewerAdminId, $viewerAdminInfo)) {
$arr['patient_id_card'] = (string) Diagnosis::where('id', $diagnosisId)->value('id_card');
}
/**
* 处方笺展示所需的"收件信息/订单号/合计"等字段,
@@ -1428,6 +1502,12 @@ class PrescriptionLogic
self::setError('处方不存在或无权作废');
return false;
}
if ((int) ($row->void_status ?? 0) === 1) {
self::setError('该处方已作废');
return false;
}
// 已提交药房的订单先远端撤单,确认撤销后再在同一锁内作废。
PrescriptionOrderLogic::cancelRemoteOrdersForVoid($id, (string) $row->sn, $adminId, $adminInfo);
return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
$id,
@@ -1456,17 +1536,14 @@ class PrescriptionLogic
self::setError('处方审核状态已变化,请刷新列表后查看');
return false;
}
if (self::hasBlockingVoidOrder($row->toArray(), $orders)) {
self::setError('关联业务订单的审核或履约状态不允许作废此处方');
return false;
}
$row->void_status = 1;
$row->void_time = time();
$row->void_by = $adminId;
$row->void_by_name = (string) ($adminInfo['name'] ?? '');
$saved = (bool) $row->save();
if ($saved) {
// 关联订单挂起,待同诊单重新开方后自动关联新处方。
PrescriptionOrderLogic::holdOrdersForReissue($row->toArray(), $orders, $adminId, $adminInfo);
PrescriptionAiStore::invalidate($id, 'voided');
}
return $saved;
@@ -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);
@@ -1370,7 +1563,7 @@ class PrescriptionOrderLogic
if ($rxId > 0) {
$rxDetail = PrescriptionLogic::detail($rxId, $adminId, $adminInfo);
if ($rxDetail !== null) {
$arr['prescription'] = $rxDetail;
$arr['prescription'] = self::applyUsageOverride($rxDetail, $arr);
// 添加开方人姓名(优先使用处方的 doctor_name,否则从 creator_id 获取)
$doctorName = (string) ($rxDetail['doctor_name'] ?? '');
if ($doctorName === '') {
@@ -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
@@ -1484,10 +1672,31 @@ class PrescriptionOrderLogic
$adminInfo,
$diagIdForMeta > 0 ? [$diagIdForMeta => (int) ($arr['assistant_id'] ?? 0)] : []
);
// 已发货后服用天数锁定(前端据此禁用天数输入,服务端同样拦截)。
$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']);
}
/**
* 业务订单详情场景:仅更新关联处方的患者姓名与手机号(不重置消费者处方审核、不改变其它处方字段)
*/
@@ -2035,6 +2244,12 @@ class PrescriptionOrderLogic
$medDays = $params['medication_days'] ?? null;
$medDays = $medDays === '' || $medDays === null ? null : (int) $medDays;
if (self::isOrderShipped($order->toArray())
&& (int) ($medDays ?? 0) !== (int) ($order->medication_days ?? 0)) {
self::$error = self::SHIPPED_DAYS_LOCKED;
return false;
}
$order->recipient_name = (string) $params['recipient_name'];
$order->recipient_phone = (string) $params['recipient_phone'];
@@ -3015,7 +3230,8 @@ class PrescriptionOrderLogic
$logSummary = $summary;
if ($changeParts !== []) {
$logSummary .= '(' . implode(';', $changeParts) . ')';
$changeSummary = '(' . implode(';', $changeParts) . ')';
$logSummary = mb_substr($summary, 0, 500 - mb_strlen($changeSummary)) . $changeSummary;
}
self::writeLog($id, $adminId, $adminInfo, 'manual_log', $logSummary);
@@ -3157,6 +3373,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)
@@ -3269,6 +3490,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 保留退款后的余额口径。
@@ -3298,8 +3603,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)) {
@@ -3307,13 +3612,15 @@ class PrescriptionOrderLogic
return false;
}
$payOrder = Order::where('id', $payOrderId)->whereNull('delete_time')->lock(true)->find();
if (!$payOrder || !in_array((int) $payOrder->status, [2, 5], true)) {
self::$error = '仅已支付或待审核的收款记录可移除,已退款记录不可移除';
// 已支付(2)、待审核(5)、已退款(4) 均可移除;已退款记录不计入已付金额,移除后已付金额不变。
if (!$payOrder || !in_array((int) $payOrder->status, [2, 4, 5], true)) {
self::$error = '仅已支付、待审核或已退款的收款记录可移除';
return false;
}
$refunded = (int) $payOrder->status === 4;
$oldPaidCents = (int) round((float) $order->paid * 100);
$removedCents = (int) round((float) $payOrder->amount * 100);
$removedCents = $refunded ? 0 : (int) round((float) $payOrder->amount * 100);
if ($removedCents < 0) {
self::$error = '收款金额异常,请先核对金额';
return false;
@@ -3324,8 +3631,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;
@@ -3334,12 +3640,15 @@ 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(
'移除收款关联 #%d(%s,¥%.2f),订单总金额 ¥%.2f 不变;已付金额(paid)¥%.2f → ¥%.2f;原收款记录保留',
$payOrderId, (string) $payOrder->order_no, $removedCents / 100,
'移除%s收款关联 #%d(%s,¥%.2f),订单总金额 ¥%.2f 不变;已付金额(paid)¥%.2f → ¥%.2f;原收款记录保留',
$refunded ? '已退款' : '', $payOrderId, (string) $payOrder->order_no, (float) $payOrder->amount,
(float) $order->amount, $oldPaidCents / 100, $newPaidCents / 100
), true);
@@ -3347,6 +3656,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;
}
@@ -4482,26 +4796,35 @@ class PrescriptionOrderLogic
}
}
$paymentAuditActions = ['audit_pay_approve', 'audit_pay_reject'];
$paymentAuditResetActions = [
'revoke_pay_audit', 'audit_rx_reject', 'revoke_rx_audit', 'add_pay_order', 'link_pay_order', 'completion_request',
];
$logRows = PrescriptionOrderLog::whereIn('prescription_order_id', $poIds)
->whereIn('action', ['audit_rx_approve', 'audit_rx_reject', 'revoke_rx_audit'])
->field(['prescription_order_id', 'id', 'action', 'admin_name', 'create_time'])
->whereIn('action', [...$paymentAuditActions, ...$paymentAuditResetActions, 'manual_log'])
->field(['prescription_order_id', 'action', 'admin_name', 'create_time', 'summary'])
->order('id', 'asc')
->select()
->toArray();
$auditEffectiveByPo = [];
$paymentAuditByPo = [];
foreach ($logRows as $lg) {
$pid = (int) ($lg['prescription_order_id'] ?? 0);
if ($pid <= 0) {
$pid = (int) $lg['prescription_order_id'];
$action = $lg['action'];
if (in_array($action, $paymentAuditActions, true)) {
$paymentAuditByPo[$pid] = $lg;
continue;
}
$act = (string) ($lg['action'] ?? '');
if ($act === 'revoke_rx_audit') {
$auditEffectiveByPo[$pid] = null;
$summary = (string) $lg['summary'];
// 补录已支付收款也记为 link_pay_order,但只有发起新审核的关联操作会重置状态。
if ($action === 'link_pay_order' && !str_starts_with($summary, '关联支付单 ')) {
continue;
}
if ($act === 'audit_rx_approve' || $act === 'audit_rx_reject') {
$auditEffectiveByPo[$pid] = $lg;
// 手工调整支付审核状态会追加固定格式的变更说明,普通备注不影响已有审核记录。
if ($action === 'manual_log'
&& !preg_match('/[(;]支付单审核:(待审核|已通过|已驳回) → (待审核|已通过|已驳回))$/u', $summary)) {
continue;
}
unset($paymentAuditByPo[$pid]);
}
// 服务套餐字典:与前端 formatServicePackage 同口径(dict_data type_value=server_order;只取启用项做兜底取原值)
@@ -4703,16 +5026,18 @@ class PrescriptionOrderLogic
$item['export_center_label'] = '一中心';
}
$paSt = (int) ($item['prescription_audit_status'] ?? 0);
$aud = $auditEffectiveByPo[$poId] ?? null;
if (($paSt === 1 || $paSt === 2) && \is_array($aud)) {
$at = (int) ($aud['create_time'] ?? 0);
$item['export_rx_audit_time'] = $at > 0 ? date('Y-m-d H:i:s', $at) : '';
$item['export_rx_auditor'] = (string) ($aud['admin_name'] ?? '');
} else {
$item['export_rx_audit_time'] = '';
$item['export_rx_auditor'] = '';
$paymentAudit = $paymentAuditByPo[$poId] ?? [];
$expectedAction = match ((int) ($item['payment_slip_audit_status'] ?? 0)) {
1 => 'audit_pay_approve',
2 => 'audit_pay_reject',
default => null,
};
if ($expectedAction === null || ($paymentAudit['action'] ?? null) !== $expectedAction) {
$paymentAudit = [];
}
$auditTime = (int) ($paymentAudit['create_time'] ?? 0);
$item['export_payment_audit_time'] = $auditTime > 0 ? date('Y-m-d H:i:s', $auditTime) : '';
$item['export_payment_auditor'] = (string) ($paymentAudit['admin_name'] ?? '');
}
unset($item);
}
@@ -5246,6 +5571,7 @@ class PrescriptionOrderLogic
if ($prescription === null) {
throw new \DomainException(PrescriptionLogic::getError() ?: '处方不存在');
}
$prescription = self::applyUsageOverride($prescription, $order->toArray());
$herbs = PharmacyHerbIdentityResolver::resolve(
is_array($prescription['herbs'] ?? null) ? $prescription['herbs'] : [],
@@ -5387,6 +5713,7 @@ class PrescriptionOrderLogic
return false;
}
$rx = self::applyUsageOverride($rx, $order->toArray());
$c = Config::get('gancao_scm', []);
$nameMap = is_array($c['herb_id_map'] ?? null) ? $c['herb_id_map'] : [];
$herbs = is_array($rx['herbs'] ?? null) ? $rx['herbs'] : [];
@@ -5542,6 +5869,7 @@ class PrescriptionOrderLogic
self::$error = PrescriptionLogic::getError() !== '' ? PrescriptionLogic::getError() : '处方不存在';
return false;
}
$rx = self::applyUsageOverride($rx, $order->toArray());
$c = Config::get('gancao_scm', []);
$nameMap = is_array($c['herb_id_map'] ?? null) ? $c['herb_id_map'] : [];
@@ -5886,6 +6214,187 @@ class PrescriptionOrderLogic
];
}
/**
* 处方作废前必须先撤销仍在药房的订单。返回 null 表示可作废(含需由系统自动撤单的洛阳药房订单),否则返回原因。
* 仅判断不调用远端,供列表/详情的 can_void 使用。
*/
public static function voidBlockerForPrescription(int $prescriptionId): ?string
{
foreach (self::lockedPharmacyOrders($prescriptionId) as [$order, $claim]) {
$reason = self::remoteCancelBlocker($order, $claim);
if ($reason !== null) {
return $reason;
}
}
return null;
}
/**
* 作废处方前先远端撤单:洛阳药房订单调用撤单接口,确认已撤销后记录状态与订单日志;
* 甘草订单暂无撤单接口,须先在甘草撤单,回传撤单(91/92)后即可作废。失败抛 DomainException。
*/
public static function cancelRemoteOrdersForVoid(int $prescriptionId, string $prescriptionSn, int $adminId, array $adminInfo): void
{
foreach (self::lockedPharmacyOrders($prescriptionId) as [$order, $claim]) {
$reason = self::remoteCancelBlocker($order, $claim);
if ($reason !== null) {
throw new \DomainException($reason);
}
$remoteNo = (string) $order['ej_pharmacy_order_no'];
try {
$response = app(EjPharmacyClient::class)->cancelPrescriptionOrder((string) $order['order_no'],
max((int) ($claim['source_revision'] ?? 1), 1), "处方 {$prescriptionSn} 作废,撤销药房订单");
} catch (\Throwable) {
throw new \DomainException("洛阳药房订单 {$remoteNo} 撤单请求失败,处方未作废,请稍后重试");
}
$httpStatus = (int) ($response['http_status'] ?? 0);
$body = is_array($response['body'] ?? null) ? $response['body'] : [];
$status = strtoupper(trim((string) (($body['data'] ?? [])['status'] ?? '')));
if ($httpStatus === 409) {
throw new \DomainException("洛阳药房订单 {$remoteNo} 已发货或已扣减库存,无法自动撤单,请联系药房处理后再作废");
}
if ($httpStatus !== 200 || (int) ($body['code'] ?? -1) !== 0 || $status !== 'CANCELLED') {
throw new \DomainException("洛阳药房订单 {$remoteNo} 撤单未确认,处方未作废,请稍后重试");
}
Db::name('tcm_prescription_order')->where('id', (int) $order['id'])
->update(['ej_pharmacy_status' => 'CANCELLED', 'update_time' => time()]);
self::writeLog((int) $order['id'], $adminId, $adminInfo, 'ej_cancel',
"作废处方 {$prescriptionSn} 前已撤销洛阳药房订单 {$remoteNo}", true);
}
}
/** @return list<array{0: array<string,mixed>, 1: ?array<string,mixed>}> 该处方下仍被药房快照锁定的订单 */
private static function lockedPharmacyOrders(int $prescriptionId): array
{
$locked = [];
$orders = Db::name('tcm_prescription_order')->where('prescription_id', $prescriptionId)
->whereNull('delete_time')->order('id')->select()->toArray();
foreach ($orders as $order) {
$claim = PharmacySubmissionClaimService::claimForOrder((int) $order['id']);
if (PharmacyRemoteSnapshotPolicy::isLocked($order, $claim)) {
$locked[] = [$order, $claim];
}
}
return $locked;
}
/** 已锁定订单不能自动撤单的原因;可由系统撤销的洛阳药房订单返回 null。 */
private static function remoteCancelBlocker(array $order, ?array $claim): ?string
{
if (PharmacyRemoteSnapshotPolicy::isClaimInFlight($claim)) {
return '订单正在提交药房,提交结果确认后再作废';
}
$ejNo = trim((string) ($order['ej_pharmacy_order_no'] ?? ''));
if ($ejNo === '') {
return '订单已提交甘草药房,系统暂不支持自动撤单:请先在甘草撤单,甘草回传撤单后即可作废';
}
if (in_array(strtoupper(trim((string) ($order['ej_pharmacy_status'] ?? ''))), ['SHIPPED', 'COMPLETED'], true)) {
return "洛阳药房订单 {$ejNo} 已发货,无法撤单作废";
}
if (!EjPharmacyClient::isConfigured()) {
return '洛阳药房接口未启用,无法自动撤单';
}
return null;
}
public const SHIPPED_DAYS_LOCKED = '订单已发货,不能再修改服用天数';
/**
* 合并订单级服用参数覆盖(已签署处方的修改写在订单 usage_override),返回本订单生效的处方数组。
* 签署原文、处方表与 CA PDF 均不变;无覆盖时原样返回。
*/
public static function applyUsageOverride(array $rx, array $order): array
{
$override = $order['usage_override'] ?? null;
if (is_string($override)) {
$override = json_decode($override, true);
}
if (!is_array($override) || $override === []) {
return $rx;
}
foreach (['times_per_day', 'usage_days', 'dosage_bag_count'] as $key) {
if (isset($override[$key])) {
$rx[$key] = (int) $override[$key];
}
}
if (isset($override['aux_usage']) && is_array($override['aux_usage'])) {
$aux = $rx['aux_usage'] ?? null;
$aux = is_string($aux) ? (json_decode($aux, true) ?: []) : (is_array($aux) ? $aux : []);
$rx['aux_usage'] = $override['aux_usage'] + $aux;
}
$rx['usage_overridden'] = 1;
return $rx;
}
/** 已发货:履约已完成/已发货/已签收,或已填快递单号,或药房回传已发货(洛阳 SHIPPED/COMPLETED,甘草 20/30)。 */
public static function isOrderShipped(array $order): bool
{
return in_array((int) ($order['fulfillment_status'] ?? 0), [3, 5, 6], true)
|| trim((string) ($order['tracking_number'] ?? '')) !== ''
|| in_array(strtoupper(trim((string) ($order['ej_pharmacy_status'] ?? ''))), ['SHIPPED', 'COMPLETED'], true)
|| in_array((int) ($order['gancao_order_state'] ?? 0), [20, 30], true);
}
/** 处方作废时可随重新开方迁移的订单状态:待审核(1)、履约中(2);已发货/已完成的订单按原处方留档。 */
private const REISSUE_FOLLOW_STATUSES = [1, 2];
/**
* 处方作废后挂起关联的业务订单:处方审核退回待审核、履约中退回待审核,等待同诊单重新开方后自动关联新处方。
* 由 PrescriptionLogic::void 在处方与订单的同一锁内调用。
*
* @param array<int, array<string, mixed>> $orders 已加锁的订单行
*/
public static function holdOrdersForReissue(array $voided, array $orders, int $adminId, array $adminInfo): void
{
$sn = (string) ($voided['sn'] ?? '');
foreach ($orders as $order) {
if (!in_array((int) ($order['fulfillment_status'] ?? 0), self::REISSUE_FOLLOW_STATUSES, true)) {
continue;
}
$updates = ['reissue_from_prescription_id' => (int) $voided['id'],
'prescription_audit_status' => 0, 'prescription_audit_remark' => '', 'update_time' => time()];
if ((int) $order['fulfillment_status'] === 2) {
$updates['fulfillment_status'] = 1;
}
Db::name('tcm_prescription_order')->where('id', (int) $order['id'])->update($updates);
self::writeLog((int) $order['id'], $adminId, $adminInfo, 'rx_void_hold',
"处方 {$sn} 已作废,订单处方审核重置为待审核;同诊单重新开方后将自动关联新处方", true);
}
}
/**
* 新处方保存后,把同诊单中因处方作废而挂起的订单关联到新处方。在开方事务内调用。
*
* @return int[] 已改关联的订单 ID
*/
public static function relinkOrdersToReissue(int $diagnosisId, int $prescriptionId, string $sn, int $adminId, array $adminInfo): array
{
if ($diagnosisId <= 0) {
return [];
}
$orders = Db::name('tcm_prescription_order')->alias('o')
->join([Db::name('tcm_prescription')->getTable() => 'p'], 'p.id = o.prescription_id')
->where('o.diagnosis_id', $diagnosisId)->where('o.reissue_from_prescription_id', '>', 0)
->whereColumn('o.reissue_from_prescription_id', '=', 'o.prescription_id')
->where('p.void_status', 1)->whereNull('o.delete_time')
->whereNotIn('o.fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
->field('o.*,p.sn AS voided_sn')->order('o.id')->lock(true)->select()->toArray();
$relinked = [];
foreach ($orders as $order) {
if (PharmacyRemoteSnapshotPolicy::isLocked($order, PharmacySubmissionClaimService::claimForOrder((int) $order['id']))) {
continue; // 已提交药房的订单不改处方,须先完成远端取消。
}
Db::name('tcm_prescription_order')->where('id', (int) $order['id'])->update([
'prescription_id' => $prescriptionId, 'reissue_from_prescription_id' => 0, 'usage_override' => null,
'prescription_audit_status' => 0, 'prescription_audit_remark' => '', 'update_time' => time(),
]);
self::writeLog((int) $order['id'], $adminId, $adminInfo, 'rx_reissue_link',
"重新开方 {$sn},自动关联新处方(原处方 {$order['voided_sn']} 已作废)", true);
$relinked[] = (int) $order['id'];
}
return $relinked;
}
private static function writeLog(
int $orderId,
int $adminId,
@@ -5981,7 +6490,9 @@ class PrescriptionOrderLogic
return false;
}
PrescriptionEsignPolicy::assertMutable($rx->toArray());
// CA 签名覆盖服用参数:已签署(冻结)的处方不改签署原文,修改写入订单级覆盖值,仅作用于本订单页面与药房下单。
$frozen = !empty($rx->esign_required) && (string) ($rx->esign_status ?? 'pending') !== 'pending';
$current = self::applyUsageOverride($rx->toArray(), $order->toArray());
if (!PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
self::setError('无权限修改此处方');
@@ -6050,11 +6561,25 @@ class PrescriptionOrderLogic
}
}
$oldTimes = (int) ($rx->times_per_day ?? 0);
$oldUsageDays = (int) ($rx->usage_days ?? 0);
$oldDosageBagCount = max(1, (int) ($rx->dosage_bag_count ?? 1));
// 已发货后天数随药品已定,不可再改;次数、袋数等仍可修正。
if (self::isOrderShipped($order->toArray())) {
$oldUsage = is_array($current['aux_usage'] ?? null) ? $current['aux_usage']
: (json_decode((string) ($current['aux_usage'] ?? ''), true) ?: []);
// 订单未单独设置天数时,以处方开立天数为准(弹窗会用它预填)。
$effectiveMedDays = (int) ($order->medication_days ?? 0) ?: (int) ($current['usage_days'] ?? 0);
if ($usageDays !== (int) ($current['usage_days'] ?? 0) || $medDays !== $effectiveMedDays
|| ($hasAux && $auxUsageDays !== (int) ($oldUsage['usage_days'] ?? 0))) {
self::setError(self::SHIPPED_DAYS_LOCKED);
return false;
}
}
$oldTimes = (int) ($current['times_per_day'] ?? 0);
$oldUsageDays = (int) ($current['usage_days'] ?? 0);
$oldDosageBagCount = max(1, (int) ($current['dosage_bag_count'] ?? 1));
$oldMedDays = (int) ($order->medication_days ?? 0);
$oldAuxUsage = $rx->aux_usage;
$oldAuxUsage = $current['aux_usage'] ?? null;
if (is_string($oldAuxUsage)) {
$decoded = json_decode($oldAuxUsage, true);
$oldAuxUsage = is_array($decoded) ? $decoded : [];
@@ -6111,15 +6636,22 @@ class PrescriptionOrderLogic
}
$rxUpdates['aux_usage'] = $auxUsage;
}
if ($prescriptionChanged && PrescriptionEsignPolicy::isPendingReview($rx->toArray())) {
$rxUpdates['review_submitted_at'] = 0;
if ($frozen) {
// 签署原文不变;订单记录覆盖值(含未修改项,便于完整还原当前生效参数)。
$override = $rxUpdates + ['dosage_bag_count' => max(1, (int) ($current['dosage_bag_count'] ?? 1))];
$order->usage_override = json_encode($override, JSON_UNESCAPED_UNICODE);
} else {
if ($prescriptionChanged && PrescriptionEsignPolicy::isPendingReview($rx->toArray())) {
$rxUpdates['review_submitted_at'] = 0;
}
$rx->save($rxUpdates);
}
$rx->save($rxUpdates);
$order->medication_days = $medDays;
$order->save();
$summary = '服用参数:' . implode(';', $parts);
$summary = ($frozen && $prescriptionChanged ? '服用参数(仅本订单生效,CA 签署处方不变):' : '服用参数:')
. implode(';', $parts);
self::writeLog($prescriptionOrderId, $adminId, $adminInfo, 'patch_rx_usage', $summary, true);
return true;
@@ -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'])
@@ -79,6 +79,9 @@ final class PrescriptionPdf
$label = ['dosage_amount' => '单次用量', 'dosage_bag_count' => '单次袋数', 'need_decoction' => '代煎',
'times_per_day' => '每日次数', 'usage_days' => '服用天数',
'prescription_name' => '方名'][$key] ?? $key;
if ($key === 'prescription_name') {
continue; // 辅方方名仅内部使用,不提交签署原文。
}
if ($key === 'need_decoction') {
// 辅方不代煎(0)时不写;代煎时与主方一样显示「是」。
if ((int) $value === 0) {
@@ -76,6 +76,25 @@ final class EjPharmacyClient
);
}
/**
* 撤销已提交的处方订单。远端对已发货/已扣库存的订单返回 409,已撤销的重复请求幂等返回订单。
*
* @return array{http_status:int,body:array<string,mixed>,request_id:string}
*/
public function cancelPrescriptionOrder(string $sourceOrderNo, int $sourceRevision, string $reason): array
{
$query = ['source_system' => 'zyt'];
if ($sourceRevision > 0) {
$query['source_revision'] = $sourceRevision;
}
return $this->request(
'POST',
'/api/openapi/v1/prescription-orders/' . rawurlencode($sourceOrderNo) . '/cancel',
['reason' => mb_substr($reason, 0, 500)],
$query
);
}
/** @param array<string,mixed>|null $payload @param array<string,int|string> $query @return array{http_status:int,body:array<string,mixed>,request_id:string} */
private function request(string $method, string $path, ?array $payload = null, array $query = []): array
{
@@ -14,6 +14,10 @@ final class PharmacyRemoteSnapshotPolicy
*/
public static function isLocked(array $order, ?array $claim): bool
{
// 远端已确认取消(洛阳药房撤单、甘草撤单/驳回)且没有在途的新版本提交:快照不再被药房使用。
if (self::isRemoteCancelled($order) && !self::isClaimInFlight($claim)) {
return false;
}
if (trim((string) ($order['gancao_reciperl_order_no'] ?? '')) !== '') {
return true;
}
@@ -31,6 +35,23 @@ final class PharmacyRemoteSnapshotPolicy
);
}
/** @param array<string,mixed> $order */
public static function isRemoteCancelled(array $order): bool
{
return strtoupper(trim((string) ($order['ej_pharmacy_status'] ?? ''))) === 'CANCELLED'
|| in_array((int) ($order['gancao_order_state'] ?? 0), [91, 92], true);
}
/** @param array<string,mixed>|null $claim */
public static function isClaimInFlight(?array $claim): bool
{
return is_array($claim) && in_array(
strtoupper((string) ($claim['status'] ?? '')),
['PENDING', 'UNKNOWN', 'PENDING_RECONCILE'],
true
);
}
/**
* @param array<string,mixed> $order
* @param array<string,mixed>|null $claim
@@ -400,7 +400,8 @@ final class PharmacySubmissionClaimService
if ($target !== 'direct') {
return false;
}
return strtoupper(trim((string) ($order['ej_pharmacy_status'] ?? ''))) === 'REJECTED'
// 驳回或已撤单(作废处方前远端撤销)的洛阳药房订单,都以新版本重新提交。
return in_array(strtoupper(trim((string) ($order['ej_pharmacy_status'] ?? ''))), ['REJECTED', 'CANCELLED'], true)
|| strtoupper(trim((string) ($order['ej_pharmacy_review_status'] ?? ''))) === 'REJECTED';
}
@@ -14,6 +14,8 @@ final class PrescriptionAiGenerator
{
public const PROMPT_VERSION = 'manual-prescription-tcm-four-diagnoses-v7';
private const REPORT_KEYS = ['summary', 'diagnosis', 'risk_assessment', 'treatment_advice', 'evidence_references', 'missing_information'];
private const CANDIDATE_KEYS = ['status', 'reason', 'prescription_name', 'prescription_type', 'dose_basis', 'herbs', 'usage_instruction',
'times_per_day', 'usage_days', 'rationale', 'risk_warnings', 'evidence_references'];
private const RETRYABLE = ['UPSTREAM_TIMEOUT', 'UPSTREAM_BUSY', 'UPSTREAM_UNAVAILABLE', 'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE',
'CANDIDATE_WITHHELD_BY_MODEL', 'INVALID_EVIDENCE_OUTPUT', 'INVALID_REPORT_OUTPUT'];
/** Reserved prompt budget for one refusal re-ask plus one format repair. */
@@ -742,10 +744,16 @@ final class PrescriptionAiGenerator
return self::reject('candidate_shape', strlen($content));
}
if ($candidate['status'] !== 'available_for_review') {
return self::keys($candidate, ['status', 'reason', 'herbs']) && $candidate['herbs'] === []
? $value : self::reject('candidate_shape', strlen($content));
// 模型拒绝开方时常把完整候选键一并带上(置空或附说明)。拒绝回答只认 status、reason
// 与空 herbs,其余已知候选键不含药味,直接剥离;否则整份报告会被当成格式错误,
// 连「携带拒绝理由追问」的环节都走不到。
if ($candidate['herbs'] !== [] || !self::keys($candidate, self::CANDIDATE_KEYS)) {
return self::reject('candidate_shape', strlen($content));
}
$value['candidate'] = ['status' => $candidate['status'], 'reason' => $candidate['reason'], 'herbs' => []];
return $value;
}
if (!self::keys($candidate, ['status', 'reason', 'prescription_name', 'prescription_type', 'dose_basis', 'herbs', 'usage_instruction', 'times_per_day', 'usage_days', 'rationale', 'risk_warnings', 'evidence_references'])
if (!self::keys($candidate, self::CANDIDATE_KEYS)
|| !in_array($candidate['dose_basis'] ?? '', ['per_dose', 'per_day'], true) || $candidate['herbs'] === [] || count($candidate['herbs']) > 100
|| !self::positiveNumber($candidate['times_per_day'] ?? null) || !self::positiveNumber($candidate['usage_days'] ?? null)
|| !self::strings($candidate['risk_warnings'] ?? null) || !self::references($candidate['evidence_references'] ?? null, $knownIds) || $candidate['evidence_references'] === []) {
@@ -0,0 +1,11 @@
-- 处方作废后,关联的业务订单挂起并记录原处方 ID;同诊单重新开方时自动改关联到新处方(PrescriptionOrderLogic::relinkOrdersToReissue)。
SET @has_reissue_from = (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'zyt_tcm_prescription_order' AND COLUMN_NAME = 'reissue_from_prescription_id'
);
SET @ddl = IF(@has_reissue_from = 0, 'ALTER TABLE `zyt_tcm_prescription_order`
ADD COLUMN `reissue_from_prescription_id` int unsigned NOT NULL DEFAULT 0 COMMENT ''处方作废后待重新开方关联:原处方 ID,0 表示无'',
ADD KEY `idx_order_reissue` (`diagnosis_id`, `reissue_from_prescription_id`)', 'SELECT 1');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,11 @@
-- 已签署(CA 冻结)处方在业务订单中修改服用参数时,改写到订单级覆盖值,签署原文与 CA PDF 不变。
-- 内容:{"times_per_day":3,"usage_days":30,"dosage_bag_count":2,"aux_usage":{...}};NULL 表示沿用处方。
SET @has_usage_override = (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'zyt_tcm_prescription_order' AND COLUMN_NAME = 'usage_override'
);
SET @ddl = IF(@has_usage_override = 0, 'ALTER TABLE `zyt_tcm_prescription_order`
ADD COLUMN `usage_override` text NULL COMMENT ''订单级服用参数覆盖(已签署处方的修改),JSON;NULL 沿用处方''', 'SELECT 1');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -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');
View File

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

@@ -1 +1 @@
import t from"./error--OD9Gfho.js";import{o,q as r,r as a,v as n,D as c,s}from"./.pnpm-DnXobOVo.js";import"./index-B5yNocKV.js";const p="/admin/assets/no_perms-jDxcYpYC.png",i={class:"error404"},x=o({__name:"403",setup(m){return(_,e)=>(r(),a("div",i,[n(t,{code:"403",title:"您的账号权限不足,请联系管理员添加权限!","show-btn":!1},{content:c(()=>[...e[0]||(e[0]=[s("div",{class:"flex justify-center"},[s("img",{class:"w-[150px] h-[150px]",src:p,alt:""})],-1)])]),_:1})]))}});export{x as default};
import t from"./error-D1ZjmW1A.js";import{o,q as r,r as a,v as n,D as c,s}from"./.pnpm-DnXobOVo.js";import"./index-CcDX_qzp.js";const p="/admin/assets/no_perms-jDxcYpYC.png",i={class:"error404"},x=o({__name:"403",setup(m){return(_,e)=>(r(),a("div",i,[n(t,{code:"403",title:"您的账号权限不足,请联系管理员添加权限!","show-btn":!1},{content:c(()=>[...e[0]||(e[0]=[s("div",{class:"flex justify-center"},[s("img",{class:"w-[150px] h-[150px]",src:p,alt:""})],-1)])]),_:1})]))}});export{x as default};
@@ -1 +1 @@
import e from"./error--OD9Gfho.js";import{o,q as r,r as t,v as s}from"./.pnpm-DnXobOVo.js";import"./index-B5yNocKV.js";const a={class:"error404"},d=o({__name:"404",setup(c){return(n,_)=>(r(),t("div",a,[s(e,{code:"404",title:"哎呀,出错了!您访问的页面不存在…"})]))}});export{d as default};
import e from"./error-D1ZjmW1A.js";import{o,q as r,r as t,v as s}from"./.pnpm-DnXobOVo.js";import"./index-CcDX_qzp.js";const a={class:"error404"},d=o({__name:"404",setup(c){return(n,_)=>(r(),t("div",a,[s(e,{code:"404",title:"哎呀,出错了!您访问的页面不存在…"})]))}});export{d as default};
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
import{o as C,R as D,q as d,r as I,ag as N,O as u,bn as B,D as o,v as l,bo as E,bp as L,L as i,T as r,s as p,bq as R,M as w}from"./.pnpm-DnXobOVo.js";import{a as V}from"./doctor-B7efth9T.js";import{s as q,_ as A}from"./index-B5yNocKV.js";const M={class:"appointment-record-panel"},P={class:"cell-stack"},$={class:"font-medium"},O={class:"text-gray-500 text-sm"},j={class:"cell-stack"},F={class:"text-gray-500 text-sm"},G=C({__name:"AppointmentRecordPanel",props:{diagnosisId:{}},setup(v,{expose:y}){const f=v,m=w(!1),g=w([]),h=w({});function x(t){return t?String(t).length>=8?String(t).slice(0,5):t:""}function k(t){return t==="morning"?"上午":t==="afternoon"?"下午":t==="all"?"全天":t||"—"}function S(t){const n=t.channel_source??t.channels??"";if(n===""||n===null||n===void 0)return"—";const a=String(n),s=h.value[a]||a,c=String(t.channel_source_detail??"").trim();return c!==""?`${s}(${c})`:s}function T(t){return[...t].sort((n,a)=>{const s=String(n.appointment_date||""),c=String(a.appointment_date||"");if(s!==c)return c.localeCompare(s);const _=String(n.appointment_time||""),e=String(a.appointment_time||"");return _!==e?e.localeCompare(_):Number(a.id||0)-Number(n.id||0)})}const z=async()=>{try{const t=await q({type:"channels"}),n=((t==null?void 0:t.channels)||[]).filter(s=>s.status!==0),a={};for(const s of n)s.value!=null&&(a[String(s.value)]=s.name||String(s.value));h.value=a}catch{h.value={}}},b=async()=>{if(f.diagnosisId){m.value=!0;try{await z();const t=await V({patient_id:f.diagnosisId,diag_scope_relax:1,page_no:1,page_size:500}),n=(t==null?void 0:t.lists)||[];g.value=T(n)}catch(t){console.error(t),g.value=[]}finally{m.value=!1}}};return D(()=>f.diagnosisId,()=>{b()},{immediate:!0}),y({refresh:b}),(t,n)=>{const a=E,s=L,c=B,_=R;return d(),I("div",M,[N((d(),u(c,{data:g.value,border:"",stripe:"","empty-text":"暂无挂号记录"},{default:o(()=>[l(a,{label:"ID",prop:"id",width:"72",align:"center"}),l(a,{label:"状态",width:"100",align:"center"},{default:o(({row:e})=>[l(s,{type:e.status===1?"success":e.status===2?"info":e.status===3?"primary":"danger",size:"small",effect:"light"},{default:o(()=>[i(r(e.status_desc||"—"),1)]),_:2},1032,["type"])]),_:1}),l(a,{label:"患者(挂号人)","min-width":"150"},{default:o(({row:e})=>[p("div",P,[p("span",$,r(e.patient_name||"—"),1),p("span",O,r(e.patient_phone||""),1)])]),_:1}),l(a,{label:"挂号医生",prop:"doctor_name",width:"110","show-overflow-tooltip":""}),l(a,{label:"挂号助理",width:"110","show-overflow-tooltip":""},{default:o(({row:e})=>[i(r(e.assistant_name||"—"),1)]),_:1}),l(a,{label:"预约时间","min-width":"130"},{default:o(({row:e})=>[p("div",j,[p("span",null,r(e.appointment_date||"—"),1),p("span",F,r(x(e.appointment_time)),1)])]),_:1}),l(a,{label:"时段",width:"80",align:"center"},{default:o(({row:e})=>[i(r(k(e.period)),1)]),_:1}),l(a,{label:"类型",width:"100","show-overflow-tooltip":""},{default:o(({row:e})=>[i(r(e.appointment_type_desc||"—"),1)]),_:1}),l(a,{label:"渠道",width:"110","show-overflow-tooltip":""},{default:o(({row:e})=>[i(r(S(e)),1)]),_:1}),l(a,{label:"确认诊单",width:"92",align:"center"},{default:o(({row:e})=>[e.diagnosis_confirmed?(d(),u(s,{key:0,type:"success",size:"small",effect:"plain"},{default:o(()=>[...n[0]||(n[0]=[i("已确认",-1)])]),_:1})):(d(),u(s,{key:1,type:"warning",size:"small",effect:"plain"},{default:o(()=>[...n[1]||(n[1]=[i("未确认",-1)])]),_:1}))]),_:1}),l(a,{label:"开方",width:"80",align:"center"},{default:o(({row:e})=>[e.has_prescription?(d(),u(s,{key:0,type:"success",size:"small",effect:"plain"},{default:o(()=>[...n[2]||(n[2]=[i("已开方",-1)])]),_:1})):(d(),u(s,{key:1,type:"info",size:"small",effect:"plain"},{default:o(()=>[...n[3]||(n[3]=[i("未开方",-1)])]),_:1}))]),_:1}),l(a,{label:"备注",prop:"remark","min-width":"100","show-overflow-tooltip":""}),l(a,{label:"创建时间",width:"165",prop:"create_time"})]),_:1},8,["data"])),[[_,m.value]])])}}}),Q=A(G,[["__scopeId","data-v-4de87dfa"]]);export{Q as default};
import{o as C,R as D,q as d,r as I,ag as N,O as u,bn as B,D as o,v as l,bo as E,bp as L,L as i,T as r,s as p,bq as R,M as w}from"./.pnpm-DnXobOVo.js";import{a as V}from"./doctor-Dy9Wew03.js";import{s as q,_ as A}from"./index-CcDX_qzp.js";const M={class:"appointment-record-panel"},P={class:"cell-stack"},$={class:"font-medium"},O={class:"text-gray-500 text-sm"},j={class:"cell-stack"},F={class:"text-gray-500 text-sm"},G=C({__name:"AppointmentRecordPanel",props:{diagnosisId:{}},setup(v,{expose:y}){const f=v,m=w(!1),g=w([]),h=w({});function x(t){return t?String(t).length>=8?String(t).slice(0,5):t:""}function k(t){return t==="morning"?"上午":t==="afternoon"?"下午":t==="all"?"全天":t||"—"}function S(t){const n=t.channel_source??t.channels??"";if(n===""||n===null||n===void 0)return"—";const a=String(n),s=h.value[a]||a,c=String(t.channel_source_detail??"").trim();return c!==""?`${s}(${c})`:s}function T(t){return[...t].sort((n,a)=>{const s=String(n.appointment_date||""),c=String(a.appointment_date||"");if(s!==c)return c.localeCompare(s);const _=String(n.appointment_time||""),e=String(a.appointment_time||"");return _!==e?e.localeCompare(_):Number(a.id||0)-Number(n.id||0)})}const z=async()=>{try{const t=await q({type:"channels"}),n=((t==null?void 0:t.channels)||[]).filter(s=>s.status!==0),a={};for(const s of n)s.value!=null&&(a[String(s.value)]=s.name||String(s.value));h.value=a}catch{h.value={}}},b=async()=>{if(f.diagnosisId){m.value=!0;try{await z();const t=await V({patient_id:f.diagnosisId,diag_scope_relax:1,page_no:1,page_size:500}),n=(t==null?void 0:t.lists)||[];g.value=T(n)}catch(t){console.error(t),g.value=[]}finally{m.value=!1}}};return D(()=>f.diagnosisId,()=>{b()},{immediate:!0}),y({refresh:b}),(t,n)=>{const a=E,s=L,c=B,_=R;return d(),I("div",M,[N((d(),u(c,{data:g.value,border:"",stripe:"","empty-text":"暂无挂号记录"},{default:o(()=>[l(a,{label:"ID",prop:"id",width:"72",align:"center"}),l(a,{label:"状态",width:"100",align:"center"},{default:o(({row:e})=>[l(s,{type:e.status===1?"success":e.status===2?"info":e.status===3?"primary":"danger",size:"small",effect:"light"},{default:o(()=>[i(r(e.status_desc||"—"),1)]),_:2},1032,["type"])]),_:1}),l(a,{label:"患者(挂号人)","min-width":"150"},{default:o(({row:e})=>[p("div",P,[p("span",$,r(e.patient_name||"—"),1),p("span",O,r(e.patient_phone||""),1)])]),_:1}),l(a,{label:"挂号医生",prop:"doctor_name",width:"110","show-overflow-tooltip":""}),l(a,{label:"挂号助理",width:"110","show-overflow-tooltip":""},{default:o(({row:e})=>[i(r(e.assistant_name||"—"),1)]),_:1}),l(a,{label:"预约时间","min-width":"130"},{default:o(({row:e})=>[p("div",j,[p("span",null,r(e.appointment_date||"—"),1),p("span",F,r(x(e.appointment_time)),1)])]),_:1}),l(a,{label:"时段",width:"80",align:"center"},{default:o(({row:e})=>[i(r(k(e.period)),1)]),_:1}),l(a,{label:"类型",width:"100","show-overflow-tooltip":""},{default:o(({row:e})=>[i(r(e.appointment_type_desc||"—"),1)]),_:1}),l(a,{label:"渠道",width:"110","show-overflow-tooltip":""},{default:o(({row:e})=>[i(r(S(e)),1)]),_:1}),l(a,{label:"确认诊单",width:"92",align:"center"},{default:o(({row:e})=>[e.diagnosis_confirmed?(d(),u(s,{key:0,type:"success",size:"small",effect:"plain"},{default:o(()=>[...n[0]||(n[0]=[i("已确认",-1)])]),_:1})):(d(),u(s,{key:1,type:"warning",size:"small",effect:"plain"},{default:o(()=>[...n[1]||(n[1]=[i("未确认",-1)])]),_:1}))]),_:1}),l(a,{label:"开方",width:"80",align:"center"},{default:o(({row:e})=>[e.has_prescription?(d(),u(s,{key:0,type:"success",size:"small",effect:"plain"},{default:o(()=>[...n[2]||(n[2]=[i("已开方",-1)])]),_:1})):(d(),u(s,{key:1,type:"info",size:"small",effect:"plain"},{default:o(()=>[...n[3]||(n[3]=[i("未开方",-1)])]),_:1}))]),_:1}),l(a,{label:"备注",prop:"remark","min-width":"100","show-overflow-tooltip":""}),l(a,{label:"创建时间",width:"165",prop:"create_time"})]),_:1},8,["data"])),[[_,m.value]])])}}}),Q=A(G,[["__scopeId","data-v-4de87dfa"]]);export{Q as default};
View File
@@ -1 +1 @@
import{o as $,R as D,q as c,r as u,ag as F,O as L,bn as E,D as o,v as s,bo as P,L as _,T as d,F as A,bp as B,P as V,s as v,a5 as q,w as M,u as N,cl as w,bq as z,M as x}from"./.pnpm-DnXobOVo.js";import{bz as K,_ as H}from"./index-B5yNocKV.js";const O={class:"assign-log-panel"},R={key:0,class:"assign-log-inherit-slot"},Y={key:1,class:"text-gray-400"},j=$({__name:"AssignLogPanel",props:{diagnosisId:{}},setup(y,{expose:S}){const m=y,p=x(!1),f=x([]);function T(n){const t=n.related_po_creator_name;if(t!=null&&String(t).trim()!=="")return String(t);const e=Number(n.related_po_creator_id);return Number.isFinite(e)&&e>0?`ID:${e}`:"—"}function k(n){const t=n.related_po_create_time_text;if(t!=null&&String(t).trim()!=="")return String(t);const e=Number(n.related_po_create_time);if(!Number.isFinite(e)||e<=0)return"—";const a=new Date(e*1e3);if(Number.isNaN(a.getTime()))return"—";const i=l=>String(l).padStart(2,"0");return`${a.getFullYear()}-${i(a.getMonth()+1)}-${i(a.getDate())} ${i(a.getHours())}:${i(a.getMinutes())}:${i(a.getSeconds())}`}function g(n){const t=n.inherit_visit_slot_text;if(t!=null&&String(t).trim()!=="")return String(t);const e=Number(n.inherit_visit_slot_calc_time);if(!Number.isFinite(e)||e<=0)return"";const a=Number(n.inherit_visit_slot);return Number.isFinite(a)&&a>0?`继承时第 ${a} 诊`:"继承时未成交"}function b(n,t){const e=t==="from"?"from_assistant_name":"to_assistant_name",a=t==="from"?"from_assistant_id":"to_assistant_id",i=n[e];if(i!=null&&String(i).trim()!==""&&String(i)!=="—")return String(i);const l=Number(n[a]);return Number.isFinite(l)&&l>0?`ID:${l}`:"—"}const h=async()=>{if(m.diagnosisId){p.value=!0;try{const n=await K({id:m.diagnosisId}),t=Array.isArray(n)?n:[];f.value=t}catch(n){console.error(n),f.value=[]}finally{p.value=!1}}};return D(()=>m.diagnosisId,()=>{h()},{immediate:!0}),S({refresh:h}),(n,t)=>{const e=P,a=M,i=q,l=B,C=E,I=z;return c(),u("div",O,[F((c(),L(C,{data:f.value,border:"",stripe:"","empty-text":"暂无指派记录"},{default:o(()=>[s(e,{label:"操作时间",width:"175",prop:"create_time_text"}),s(e,{label:"原医助","min-width":"120"},{default:o(({row:r})=>[_(d(b(r,"from")),1)]),_:1}),s(e,{label:"新医助","min-width":"120"},{default:o(({row:r})=>[_(d(b(r,"to")),1)]),_:1}),s(e,{label:"继承",width:"118",align:"center"},{header:o(()=>[t[0]||(t[0]=v("span",null,"继承",-1)),s(i,{placement:"top",content:"继承时第 k 诊:继承时刻之前患者已完成的诊次(有效实单数 + 偏移),复诊接诊率从第 k+1 诊起计入新医助分母;2026-10 前的继承记录无此快照"},{default:o(()=>[s(a,{class:"assign-log-col-hint"},{default:o(()=>[s(N(w))]),_:1})]),_:1})]),default:o(({row:r})=>[Number(r.is_inherit)===1?(c(),u(A,{key:0},[s(l,{type:"success",size:"small"},{default:o(()=>[...t[1]||(t[1]=[_("是",-1)])]),_:1}),g(r)?(c(),u("div",R,d(g(r)),1)):V("",!0)],64)):(c(),u("span",Y,"否"))]),_:1}),s(e,{label:"快照·业务单创建人","min-width":"130","show-overflow-tooltip":""},{default:o(({row:r})=>[_(d(T(r)),1)]),_:1}),s(e,{label:"快照·业务单创建时间",width:"190"},{header:o(()=>[t[2]||(t[2]=v("span",null,"快照·业务单创建时间",-1)),s(i,{placement:"top",content:"related_po_create_time:触发本次操作的处方业务订单 create_time;与原文助一致时表示医助创建订单时间"},{default:o(()=>[s(a,{class:"assign-log-col-hint"},{default:o(()=>[s(N(w))]),_:1})]),_:1})]),default:o(({row:r})=>[_(d(k(r)),1)]),_:1}),s(e,{label:"操作人",width:"110",prop:"operator_name"}),s(e,{label:"操作账号",width:"120",prop:"operator_account","show-overflow-tooltip":""}),s(e,{label:"IP",width:"130",prop:"ip","show-overflow-tooltip":""})]),_:1},8,["data"])),[[I,p.value]])])}}}),Q=H(j,[["__scopeId","data-v-078f6683"]]);export{Q as default};
import{o as $,R as D,q as c,r as u,ag as F,O as L,bn as E,D as o,v as s,bo as P,L as _,T as d,F as A,bp as B,P as V,s as v,a5 as q,w as M,u as N,cl as w,bq as K,M as y}from"./.pnpm-DnXobOVo.js";import{by as z,_ as H}from"./index-CcDX_qzp.js";const O={class:"assign-log-panel"},R={key:0,class:"assign-log-inherit-slot"},Y={key:1,class:"text-gray-400"},j=$({__name:"AssignLogPanel",props:{diagnosisId:{}},setup(x,{expose:S}){const m=x,p=y(!1),f=y([]);function T(n){const t=n.related_po_creator_name;if(t!=null&&String(t).trim()!=="")return String(t);const e=Number(n.related_po_creator_id);return Number.isFinite(e)&&e>0?`ID:${e}`:"—"}function k(n){const t=n.related_po_create_time_text;if(t!=null&&String(t).trim()!=="")return String(t);const e=Number(n.related_po_create_time);if(!Number.isFinite(e)||e<=0)return"—";const a=new Date(e*1e3);if(Number.isNaN(a.getTime()))return"—";const i=l=>String(l).padStart(2,"0");return`${a.getFullYear()}-${i(a.getMonth()+1)}-${i(a.getDate())} ${i(a.getHours())}:${i(a.getMinutes())}:${i(a.getSeconds())}`}function g(n){const t=n.inherit_visit_slot_text;if(t!=null&&String(t).trim()!=="")return String(t);const e=Number(n.inherit_visit_slot_calc_time);if(!Number.isFinite(e)||e<=0)return"";const a=Number(n.inherit_visit_slot);return Number.isFinite(a)&&a>0?`继承时第 ${a} 诊`:"继承时未成交"}function b(n,t){const e=t==="from"?"from_assistant_name":"to_assistant_name",a=t==="from"?"from_assistant_id":"to_assistant_id",i=n[e];if(i!=null&&String(i).trim()!==""&&String(i)!=="—")return String(i);const l=Number(n[a]);return Number.isFinite(l)&&l>0?`ID:${l}`:"—"}const h=async()=>{if(m.diagnosisId){p.value=!0;try{const n=await z({id:m.diagnosisId}),t=Array.isArray(n)?n:[];f.value=t}catch(n){console.error(n),f.value=[]}finally{p.value=!1}}};return D(()=>m.diagnosisId,()=>{h()},{immediate:!0}),S({refresh:h}),(n,t)=>{const e=P,a=M,i=q,l=B,C=E,I=K;return c(),u("div",O,[F((c(),L(C,{data:f.value,border:"",stripe:"","empty-text":"暂无指派记录"},{default:o(()=>[s(e,{label:"操作时间",width:"175",prop:"create_time_text"}),s(e,{label:"原医助","min-width":"120"},{default:o(({row:r})=>[_(d(b(r,"from")),1)]),_:1}),s(e,{label:"新医助","min-width":"120"},{default:o(({row:r})=>[_(d(b(r,"to")),1)]),_:1}),s(e,{label:"继承",width:"118",align:"center"},{header:o(()=>[t[0]||(t[0]=v("span",null,"继承",-1)),s(i,{placement:"top",content:"继承时第 k 诊:继承时刻之前患者已完成的诊次(有效实单数 + 偏移),复诊接诊率从第 k+1 诊起计入新医助分母;2026-10 前的继承记录无此快照"},{default:o(()=>[s(a,{class:"assign-log-col-hint"},{default:o(()=>[s(N(w))]),_:1})]),_:1})]),default:o(({row:r})=>[Number(r.is_inherit)===1?(c(),u(A,{key:0},[s(l,{type:"success",size:"small"},{default:o(()=>[...t[1]||(t[1]=[_("是",-1)])]),_:1}),g(r)?(c(),u("div",R,d(g(r)),1)):V("",!0)],64)):(c(),u("span",Y,"否"))]),_:1}),s(e,{label:"快照·业务单创建人","min-width":"130","show-overflow-tooltip":""},{default:o(({row:r})=>[_(d(T(r)),1)]),_:1}),s(e,{label:"快照·业务单创建时间",width:"190"},{header:o(()=>[t[2]||(t[2]=v("span",null,"快照·业务单创建时间",-1)),s(i,{placement:"top",content:"related_po_create_time:触发本次操作的处方业务订单 create_time;与原文助一致时表示医助创建订单时间"},{default:o(()=>[s(a,{class:"assign-log-col-hint"},{default:o(()=>[s(N(w))]),_:1})]),_:1})]),default:o(({row:r})=>[_(d(k(r)),1)]),_:1}),s(e,{label:"操作人",width:"110",prop:"operator_name"}),s(e,{label:"操作账号",width:"120",prop:"operator_account","show-overflow-tooltip":""}),s(e,{label:"IP",width:"130",prop:"ip","show-overflow-tooltip":""})]),_:1},8,["data"])),[[I,p.value]])])}}}),Q=H(j,[["__scopeId","data-v-078f6683"]]);export{Q as default};
View File
View File
@@ -1 +1 @@
import{o as B,R as D,q as E,O,D as I,r as _,T as S,P as x,ag as W,s as h,ah as j,v as P,K as U,L as $,a2 as H,p as K,M as v,dj as c}from"./.pnpm-DnXobOVo.js";import{bA as Y,_ as q}from"./index-B5yNocKV.js";const z={key:0,class:"watch-state"},F={key:1,class:"watch-state watch-error"},G=B({__name:"AssistantWatchCallDialog",props:{modelValue:{type:Boolean},diagnosisId:{}},emits:["update:modelValue","closed"],setup(A,{emit:R}){const u=A,g=R,y=K({get:()=>u.modelValue,set:t=>g("update:modelValue",t)}),r=v(null),l=v(!1),i=v(""),p=v("旁观视频通话"),n=new Map;let a=null,f=0;function w(t,e){return`${t}\0${String(e)}`}function N(t){return t.startsWith("patient_")?"患者":t.startsWith("doctor_")?"医护":t}async function T(t){if(!a||!r.value||t.streamType!==c.TYPE.STREAM_TYPE_MAIN)return;const e=w(t.userId,t.streamType);if(n.has(e))return;const o=document.createElement("div");o.className="watch-tile";const s=document.createElement("div");s.className="watch-tile-cap",s.textContent=N(t.userId);const d=document.createElement("div");d.className="watch-tile-view",o.appendChild(s),o.appendChild(d),r.value.appendChild(o),n.set(e,{wrap:o,userId:t.userId,streamType:t.streamType});try{await a.startRemoteVideo({userId:t.userId,streamType:t.streamType,view:d})}catch(b){console.warn("[AssistantWatchCall] startRemoteVideo",b)}}async function V(t){if(!a)return;const e=w(t.userId,t.streamType),o=n.get(e);if(o){try{await a.stopRemoteVideo({userId:t.userId,streamType:t.streamType})}catch{}o.wrap.remove(),n.delete(e)}}function C(){a&&(a.on(c.EVENT.REMOTE_VIDEO_AVAILABLE,T),a.on(c.EVENT.REMOTE_VIDEO_UNAVAILABLE,V))}function k(){a&&(a.off(c.EVENT.REMOTE_VIDEO_AVAILABLE,T),a.off(c.EVENT.REMOTE_VIDEO_UNAVAILABLE,V))}async function m(){if(k(),a){for(const[,t]of n){try{await a.stopRemoteVideo({userId:t.userId,streamType:t.streamType})}catch{}t.wrap.remove()}n.clear(),r.value&&(r.value.innerHTML="");try{await a.exitRoom()}catch{}try{a.destroy()}catch{}a=null}else n.clear(),r.value&&(r.value.innerHTML="")}async function L(){const t=++f;if(await m(),!u.diagnosisId){i.value="诊单无效";return}l.value=!0,i.value="",p.value="旁观视频通话";try{const e=await Y({diagnosis_id:u.diagnosisId});if(t!==f)return;e.patientName&&(p.value=`旁观视频通话 · ${e.patientName}`),a=c.create(),C();const o={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,autoReceiveAudio:!0,autoReceiveVideo:!0,...e.roomId!=null&&e.roomId>0?{roomId:e.roomId}:{strRoomId:e.strRoomId}};if(!(e.roomId!=null&&e.roomId>0)&&!e.strRoomId)throw new Error("缺少房间号");if(await a.enterRoom(o),t!==f){await m();return}l.value=!1}catch(e){l.value=!1;let o="进入房间失败";if(typeof e=="string")o=e;else if(e&&typeof e=="object"){const s=e;s.msg?o=String(s.msg):s.message&&(o=String(s.message))}i.value=o,await m()}}function M(){m(),l.value=!1,i.value="",p.value="旁观视频通话",g("closed")}return D(()=>[u.modelValue,u.diagnosisId],([t,e])=>{if(!t){f++,m();return}e>0&&L()}),(t,e)=>{const o=U,s=H;return E(),O(s,{modelValue:y.value,"onUpdate:modelValue":e[1]||(e[1]=d=>y.value=d),title:p.value,width:"760px","destroy-on-close":"","append-to-body":"","close-on-click-modal":!1,class:"assistant-watch-call-dialog",onClosed:M},{footer:I(()=>[e[3]||(e[3]=h("span",{class:"watch-hint"},"仅观看,不会开启摄像头与麦克风",-1)),P(o,{type:"primary",onClick:e[0]||(e[0]=d=>y.value=!1)},{default:I(()=>[...e[2]||(e[2]=[$("离开",-1)])]),_:1})]),default:I(()=>[l.value?(E(),_("div",z,"正在连接房间…")):i.value?(E(),_("div",F,S(i.value),1)):x("",!0),W(h("div",{ref_key:"gridRef",ref:r,class:"watch-grid"},null,512),[[j,!l.value&&!i.value]])]),_:1},8,["modelValue","title"])}}}),X=q(G,[["__scopeId","data-v-8c719418"]]);export{X as default};
import{o as B,R as D,q as E,O,D as I,r as _,T as S,P as x,ag as W,s as h,ah as j,v as P,K as U,L as $,a2 as H,p as K,M as v,dj as c}from"./.pnpm-DnXobOVo.js";import{bz as Y,_ as q}from"./index-CcDX_qzp.js";const z={key:0,class:"watch-state"},F={key:1,class:"watch-state watch-error"},G=B({__name:"AssistantWatchCallDialog",props:{modelValue:{type:Boolean},diagnosisId:{}},emits:["update:modelValue","closed"],setup(R,{emit:A}){const u=R,g=A,y=K({get:()=>u.modelValue,set:t=>g("update:modelValue",t)}),r=v(null),l=v(!1),i=v(""),p=v("旁观视频通话"),n=new Map;let a=null,f=0;function w(t,e){return`${t}\0${String(e)}`}function N(t){return t.startsWith("patient_")?"患者":t.startsWith("doctor_")?"医护":t}async function T(t){if(!a||!r.value||t.streamType!==c.TYPE.STREAM_TYPE_MAIN)return;const e=w(t.userId,t.streamType);if(n.has(e))return;const o=document.createElement("div");o.className="watch-tile";const s=document.createElement("div");s.className="watch-tile-cap",s.textContent=N(t.userId);const d=document.createElement("div");d.className="watch-tile-view",o.appendChild(s),o.appendChild(d),r.value.appendChild(o),n.set(e,{wrap:o,userId:t.userId,streamType:t.streamType});try{await a.startRemoteVideo({userId:t.userId,streamType:t.streamType,view:d})}catch(b){console.warn("[AssistantWatchCall] startRemoteVideo",b)}}async function V(t){if(!a)return;const e=w(t.userId,t.streamType),o=n.get(e);if(o){try{await a.stopRemoteVideo({userId:t.userId,streamType:t.streamType})}catch{}o.wrap.remove(),n.delete(e)}}function C(){a&&(a.on(c.EVENT.REMOTE_VIDEO_AVAILABLE,T),a.on(c.EVENT.REMOTE_VIDEO_UNAVAILABLE,V))}function k(){a&&(a.off(c.EVENT.REMOTE_VIDEO_AVAILABLE,T),a.off(c.EVENT.REMOTE_VIDEO_UNAVAILABLE,V))}async function m(){if(k(),a){for(const[,t]of n){try{await a.stopRemoteVideo({userId:t.userId,streamType:t.streamType})}catch{}t.wrap.remove()}n.clear(),r.value&&(r.value.innerHTML="");try{await a.exitRoom()}catch{}try{a.destroy()}catch{}a=null}else n.clear(),r.value&&(r.value.innerHTML="")}async function L(){const t=++f;if(await m(),!u.diagnosisId){i.value="诊单无效";return}l.value=!0,i.value="",p.value="旁观视频通话";try{const e=await Y({diagnosis_id:u.diagnosisId});if(t!==f)return;e.patientName&&(p.value=`旁观视频通话 · ${e.patientName}`),a=c.create(),C();const o={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,autoReceiveAudio:!0,autoReceiveVideo:!0,...e.roomId!=null&&e.roomId>0?{roomId:e.roomId}:{strRoomId:e.strRoomId}};if(!(e.roomId!=null&&e.roomId>0)&&!e.strRoomId)throw new Error("缺少房间号");if(await a.enterRoom(o),t!==f){await m();return}l.value=!1}catch(e){l.value=!1;let o="进入房间失败";if(typeof e=="string")o=e;else if(e&&typeof e=="object"){const s=e;s.msg?o=String(s.msg):s.message&&(o=String(s.message))}i.value=o,await m()}}function M(){m(),l.value=!1,i.value="",p.value="旁观视频通话",g("closed")}return D(()=>[u.modelValue,u.diagnosisId],([t,e])=>{if(!t){f++,m();return}e>0&&L()}),(t,e)=>{const o=U,s=H;return E(),O(s,{modelValue:y.value,"onUpdate:modelValue":e[1]||(e[1]=d=>y.value=d),title:p.value,width:"760px","destroy-on-close":"","append-to-body":"","close-on-click-modal":!1,class:"assistant-watch-call-dialog",onClosed:M},{footer:I(()=>[e[3]||(e[3]=h("span",{class:"watch-hint"},"仅观看,不会开启摄像头与麦克风",-1)),P(o,{type:"primary",onClick:e[0]||(e[0]=d=>y.value=!1)},{default:I(()=>[...e[2]||(e[2]=[$("离开",-1)])]),_:1})]),default:I(()=>[l.value?(E(),_("div",z,"正在连接房间…")):i.value?(E(),_("div",F,S(i.value),1)):x("",!0),W(h("div",{ref_key:"gridRef",ref:r,class:"watch-grid"},null,512),[[j,!l.value&&!i.value]])]),_:1},8,["modelValue","title"])}}}),X=q(G,[["__scopeId","data-v-8c719418"]]);export{X as default};
View File
@@ -1 +1 @@
import{o as N,dl as O,R as P,q as r,r as f,v as o,D as i,K as V,L as n,P as h,ag as D,O as w,bn as L,bo as q,T as u,s as y,bq as z,M as v}from"./.pnpm-DnXobOVo.js";import M from"./RecordingPlaybackBlock-2brEtpcH.js";import{U as x}from"./index-BwIr9qiy.js";import{bE as F,f as c,bF as R,bG as G,_ as K}from"./index-B5yNocKV.js";import"./RecordingVideoPlayer-D3EW1shD.js";import"./file-CN5TlpMj.js";const j={class:"call-record-panel"},A={key:0,class:"call-record-toolbar"},H={class:"call-record-empty"},J={class:"call-record-empty__desc"},Q={key:0,class:"text-primary"},W={key:1,class:"text-gray-400"},X=N({__name:"CallRecordPanel",props:{diagnosisId:{},readOnly:{type:Boolean,default:!1}},setup(_,{expose:k}){const d=_,p=v(!1),g=v([]),U=O("toolbarUploadRef"),m=async()=>{if(d.diagnosisId){p.value=!0;try{g.value=await F({diagnosis_id:d.diagnosisId})||[]}catch(e){console.error(e),g.value=[]}finally{p.value=!1}}};P(()=>d.diagnosisId,()=>{m()},{immediate:!0}),k({refresh:m});function C(e){return{1:"进行中",2:"已结束",3:"未接听",4:"已取消"}[e]??"—"}async function E(e){const t=b(e);if(!t){c.msgError("上传成功但未返回视频地址");return}try{const a=await G({diagnosis_id:d.diagnosisId});await R({diagnosis_id:d.diagnosisId,call_record_id:Number((a==null?void 0:a.id)||0),file_url:t}),c.msgSuccess("视频回放上传成功"),await m()}catch(a){c.msgError((a==null?void 0:a.message)||"写入回放失败")}}async function S(e,t){const a=b(t);if(!a){c.msgError("上传成功但未返回视频地址");return}try{await R({diagnosis_id:d.diagnosisId,call_record_id:Number(e.id||0),file_url:a}),c.msgSuccess("视频回放上传成功"),await m()}catch(l){c.msgError((l==null?void 0:l.message)||"写入回放失败")}}function b(e){var t,a;return String(((t=e==null?void 0:e.data)==null?void 0:t.uri)||((a=e==null?void 0:e.data)==null?void 0:a.url)||"").trim()}return(e,t)=>{const a=V,l=q,I=L,B=z;return r(),f("div",j,[_.readOnly?h("",!0):(r(),f("div",A,[o(x,{ref_key:"toolbarUploadRef",ref:U,type:"video",direct:"",multiple:!1,limit:1,"show-progress":!0,onSuccess:E},{default:i(()=>[o(a,{type:"primary"},{default:i(()=>[...t[0]||(t[0]=[n("上传视频",-1)])]),_:1})]),_:1},512)])),D((r(),w(I,{data:g.value,border:"",stripe:""},{empty:i(()=>[y("div",H,[t[1]||(t[1]=y("div",{class:"call-record-empty__title"},"暂无通话记录",-1)),y("div",J,u(_.readOnly?"暂无录制回放数据。":"现在可以直接点击上方“上传视频”。系统会自动生成一条默认通话记录来承载回放。"),1)])]),default:i(()=>[o(l,{label:"录制回放","min-width":"320"},{default:i(({row:s})=>[o(M,{"record-id":s.id,urls:s.recording_urls_list},null,8,["record-id","urls"])]),_:1}),o(l,{label:"开始时间",width:"170",prop:"start_time_text"}),o(l,{label:"结束时间",width:"170",prop:"end_time_text"}),o(l,{label:"通话类型",width:"100"},{default:i(({row:s})=>[n(u(s.call_type===1?"语音":"视频"),1)]),_:1}),o(l,{label:"房间号",width:"180"},{default:i(({row:s})=>[s.room_id?(r(),f("span",Q,u(s.room_id),1)):(r(),f("span",W,"—"))]),_:1}),o(l,{label:"时长",width:"110",prop:"duration_text"}),o(l,{label:"状态",width:"90"},{default:i(({row:s})=>[n(u(C(s.status)),1)]),_:1}),o(l,{label:"录制",width:"100"},{default:i(({row:s})=>[n(u(s.recording_status_text||"—"),1)]),_:1}),_.readOnly?h("",!0):(r(),w(l,{key:0,label:"上传回放",width:"180"},{default:i(({row:s})=>[o(x,{type:"video",direct:"",multiple:!1,limit:1,"show-progress":!0,onSuccess:T=>S(s,T)},{default:i(()=>[o(a,{type:"primary",plain:"",size:"small"},{default:i(()=>[...t[2]||(t[2]=[n("上传视频",-1)])]),_:1})]),_:1},8,["onSuccess"])]),_:1}))]),_:1},8,["data"])),[[B,p.value]])])}}}),la=K(X,[["__scopeId","data-v-78d5c9e4"]]);export{la as default};
import{o as N,dl as O,R as D,q as r,r as f,v as o,D as i,K as P,L as n,P as h,ag as V,O as w,bn as L,bo as q,T as u,s as y,bq as z,M as v}from"./.pnpm-DnXobOVo.js";import M from"./RecordingPlaybackBlock-CCGZyrFu.js";import{U as x}from"./index-BWMgSEq-.js";import{bD as F,f as c,bE as R,bF as K,_ as j}from"./index-CcDX_qzp.js";import"./RecordingVideoPlayer-CT5H3XKE.js";import"./file-CwKsS4EB.js";const A={class:"call-record-panel"},G={key:0,class:"call-record-toolbar"},H={class:"call-record-empty"},J={class:"call-record-empty__desc"},Q={key:0,class:"text-primary"},W={key:1,class:"text-gray-400"},X=N({__name:"CallRecordPanel",props:{diagnosisId:{},readOnly:{type:Boolean,default:!1}},setup(_,{expose:k}){const d=_,p=v(!1),g=v([]),U=O("toolbarUploadRef"),m=async()=>{if(d.diagnosisId){p.value=!0;try{g.value=await F({diagnosis_id:d.diagnosisId})||[]}catch(e){console.error(e),g.value=[]}finally{p.value=!1}}};D(()=>d.diagnosisId,()=>{m()},{immediate:!0}),k({refresh:m});function C(e){return{1:"进行中",2:"已结束",3:"未接听",4:"已取消"}[e]??"—"}async function E(e){const t=b(e);if(!t){c.msgError("上传成功但未返回视频地址");return}try{const a=await K({diagnosis_id:d.diagnosisId});await R({diagnosis_id:d.diagnosisId,call_record_id:Number((a==null?void 0:a.id)||0),file_url:t}),c.msgSuccess("视频回放上传成功"),await m()}catch(a){c.msgError((a==null?void 0:a.message)||"写入回放失败")}}async function S(e,t){const a=b(t);if(!a){c.msgError("上传成功但未返回视频地址");return}try{await R({diagnosis_id:d.diagnosisId,call_record_id:Number(e.id||0),file_url:a}),c.msgSuccess("视频回放上传成功"),await m()}catch(l){c.msgError((l==null?void 0:l.message)||"写入回放失败")}}function b(e){var t,a;return String(((t=e==null?void 0:e.data)==null?void 0:t.uri)||((a=e==null?void 0:e.data)==null?void 0:a.url)||"").trim()}return(e,t)=>{const a=P,l=q,I=L,B=z;return r(),f("div",A,[_.readOnly?h("",!0):(r(),f("div",G,[o(x,{ref_key:"toolbarUploadRef",ref:U,type:"video",direct:"",multiple:!1,limit:1,"show-progress":!0,onSuccess:E},{default:i(()=>[o(a,{type:"primary"},{default:i(()=>[...t[0]||(t[0]=[n("上传视频",-1)])]),_:1})]),_:1},512)])),V((r(),w(I,{data:g.value,border:"",stripe:""},{empty:i(()=>[y("div",H,[t[1]||(t[1]=y("div",{class:"call-record-empty__title"},"暂无通话记录",-1)),y("div",J,u(_.readOnly?"暂无录制回放数据。":"现在可以直接点击上方“上传视频”。系统会自动生成一条默认通话记录来承载回放。"),1)])]),default:i(()=>[o(l,{label:"录制回放","min-width":"320"},{default:i(({row:s})=>[o(M,{"record-id":s.id,urls:s.recording_urls_list},null,8,["record-id","urls"])]),_:1}),o(l,{label:"开始时间",width:"170",prop:"start_time_text"}),o(l,{label:"结束时间",width:"170",prop:"end_time_text"}),o(l,{label:"通话类型",width:"100"},{default:i(({row:s})=>[n(u(s.call_type===1?"语音":"视频"),1)]),_:1}),o(l,{label:"房间号",width:"180"},{default:i(({row:s})=>[s.room_id?(r(),f("span",Q,u(s.room_id),1)):(r(),f("span",W,"—"))]),_:1}),o(l,{label:"时长",width:"110",prop:"duration_text"}),o(l,{label:"状态",width:"90"},{default:i(({row:s})=>[n(u(C(s.status)),1)]),_:1}),o(l,{label:"录制",width:"100"},{default:i(({row:s})=>[n(u(s.recording_status_text||"—"),1)]),_:1}),_.readOnly?h("",!0):(r(),w(l,{key:0,label:"上传回放",width:"180"},{default:i(({row:s})=>[o(x,{type:"video",direct:"",multiple:!1,limit:1,"show-progress":!0,onSuccess:T=>S(s,T)},{default:i(()=>[o(a,{type:"primary",plain:"",size:"small"},{default:i(()=>[...t[2]||(t[2]=[n("上传视频",-1)])]),_:1})]),_:1},8,["onSuccess"])]),_:1}))]),_:1},8,["data"])),[[B,p.value]])])}}}),la=j(X,[["__scopeId","data-v-78d5c9e4"]]);export{la as default};
View File
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
import{o as T,a0 as V,R as I,q as o,r as l,v as a,K as N,D as n,L as c,P as w,ag as z,bq as M,u as p,O as f,bo as O,T as _,F as P,bp as F,s as R,bn as j,by as q,M as k}from"./.pnpm-DnXobOVo.js";import{bH as A,_ as H}from"./index-B5yNocKV.js";const K={class:"case-record-list"},Y={key:0,class:"mb-3 flex justify-end"},G={key:0},J={key:1,class:"text-gray-400"},Q={class:"void-detail text-xs text-gray-500 mt-1"},U=T({__name:"CaseRecordList",props:{diagnosisId:{type:Number,default:0},readOnly:{type:Boolean,default:!1}},emits:["view","openPrescription"],setup(y,{expose:x,emit:C}){const m=y,b=C,r=k([]),d=k(!1),u=async()=>{if(m.diagnosisId){d.value=!0;try{const t=await A({diagnosis_id:m.diagnosisId});r.value=Array.isArray(t)?t:[]}catch(t){console.error("获取病历记录失败:",t),r.value=[]}finally{d.value=!1}}},S=t=>{if(!t)return"";const e=new Date(t*1e3);return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},$=t=>{b("view",t)},B=()=>{b("openPrescription")};return V(()=>{u()}),I(()=>m.diagnosisId,()=>{u()}),x({refresh:u}),(t,e)=>{const h=N,i=O,v=F,E=j,D=q,L=M;return o(),l("div",K,[y.readOnly?w("",!0):(o(),l("div",Y,[a(h,{type:"primary",size:"small",onClick:B},{default:n(()=>[...e[0]||(e[0]=[c("开方",-1)])]),_:1})])),z((o(),f(E,{data:p(r),border:""},{default:n(()=>[a(i,{prop:"prescription_date",label:"就诊日期",width:"120"}),a(i,{prop:"visit_no",label:"门诊号",width:"120"}),a(i,{prop:"clinical_diagnosis",label:"临床诊断","min-width":"160","show-overflow-tooltip":""}),a(i,{label:"处方摘要","min-width":"180"},{default:n(({row:s})=>[s.herbs&&s.herbs.length?(o(),l("span",G,_(s.herbs.slice(0,3).map(g=>`${g.name}${g.dosage}克`).join("、"))+_(s.herbs.length>3?"...":""),1)):(o(),l("span",J,"—"))]),_:1}),a(i,{prop:"doctor_name",label:"医师",width:"90","show-overflow-tooltip":""}),a(i,{label:"状态",width:"140",align:"center"},{default:n(({row:s})=>[s.void_status===1?(o(),l(P,{key:0},[a(v,{type:"danger",size:"small"},{default:n(()=>[...e[1]||(e[1]=[c("已作废",-1)])]),_:1}),R("div",Q,_(s.void_by_name||"—")+" "+_(S(s.void_time)),1)],64)):(o(),f(v,{key:1,type:"success",size:"small"},{default:n(()=>[...e[2]||(e[2]=[c("正常",-1)])]),_:1}))]),_:1}),a(i,{label:"操作",width:"120",fixed:"right"},{default:n(({row:s})=>[a(h,{link:"",type:"primary",size:"small",onClick:g=>$(s)},{default:n(()=>[...e[3]||(e[3]=[c(" 查看 ",-1)])]),_:1},8,["onClick"])]),_:1})]),_:1},8,["data"])),[[L,p(d)]]),!p(d)&&p(r).length===0?(o(),f(D,{key:1,description:"暂无病历记录,开方后会自动显示",class:"mt-4"})):w("",!0)])}}}),Z=H(U,[["__scopeId","data-v-043d2738"]]);export{Z as default};
import{o as T,a0 as V,R as I,q as o,r as l,v as a,K as N,D as n,L as c,P as w,ag as z,bq as M,u as p,O as f,bo as O,T as _,F as P,bp as F,s as R,bn as j,by as q,M as k}from"./.pnpm-DnXobOVo.js";import{bG as A,_ as G}from"./index-CcDX_qzp.js";const H={class:"case-record-list"},K={key:0,class:"mb-3 flex justify-end"},Y={key:0},J={key:1,class:"text-gray-400"},Q={class:"void-detail text-xs text-gray-500 mt-1"},U=T({__name:"CaseRecordList",props:{diagnosisId:{type:Number,default:0},readOnly:{type:Boolean,default:!1}},emits:["view","openPrescription"],setup(y,{expose:x,emit:C}){const m=y,b=C,r=k([]),d=k(!1),u=async()=>{if(m.diagnosisId){d.value=!0;try{const t=await A({diagnosis_id:m.diagnosisId});r.value=Array.isArray(t)?t:[]}catch(t){console.error("获取病历记录失败:",t),r.value=[]}finally{d.value=!1}}},S=t=>{if(!t)return"";const e=new Date(t*1e3);return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},$=t=>{b("view",t)},B=()=>{b("openPrescription")};return V(()=>{u()}),I(()=>m.diagnosisId,()=>{u()}),x({refresh:u}),(t,e)=>{const h=N,i=O,v=F,E=j,D=q,L=M;return o(),l("div",H,[y.readOnly?w("",!0):(o(),l("div",K,[a(h,{type:"primary",size:"small",onClick:B},{default:n(()=>[...e[0]||(e[0]=[c("开方",-1)])]),_:1})])),z((o(),f(E,{data:p(r),border:""},{default:n(()=>[a(i,{prop:"prescription_date",label:"就诊日期",width:"120"}),a(i,{prop:"visit_no",label:"门诊号",width:"120"}),a(i,{prop:"clinical_diagnosis",label:"临床诊断","min-width":"160","show-overflow-tooltip":""}),a(i,{label:"处方摘要","min-width":"180"},{default:n(({row:s})=>[s.herbs&&s.herbs.length?(o(),l("span",Y,_(s.herbs.slice(0,3).map(g=>`${g.name}${g.dosage}克`).join("、"))+_(s.herbs.length>3?"...":""),1)):(o(),l("span",J,"—"))]),_:1}),a(i,{prop:"doctor_name",label:"医师",width:"90","show-overflow-tooltip":""}),a(i,{label:"状态",width:"140",align:"center"},{default:n(({row:s})=>[s.void_status===1?(o(),l(P,{key:0},[a(v,{type:"danger",size:"small"},{default:n(()=>[...e[1]||(e[1]=[c("已作废",-1)])]),_:1}),R("div",Q,_(s.void_by_name||"—")+" "+_(S(s.void_time)),1)],64)):(o(),f(v,{key:1,type:"success",size:"small"},{default:n(()=>[...e[2]||(e[2]=[c("正常",-1)])]),_:1}))]),_:1}),a(i,{label:"操作",width:"120",fixed:"right"},{default:n(({row:s})=>[a(h,{link:"",type:"primary",size:"small",onClick:g=>$(s)},{default:n(()=>[...e[3]||(e[3]=[c(" 查看 ",-1)])]),_:1},8,["onClick"])]),_:1})]),_:1},8,["data"])),[[L,p(d)]]),!p(d)&&p(r).length===0?(o(),f(D,{key:1,description:"暂无病历记录,开方后会自动显示",class:"mt-4"})):w("",!0)])}}}),Z=G(U,[["__scopeId","data-v-043d2738"]]);export{Z as default};
View File
File diff suppressed because one or more lines are too long
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
View File
View File
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
View File
View File
View File
View File
@@ -0,0 +1 @@
import{_ as o}from"./GancaoSubmissionReconcileButton.vue_vue_type_script_setup_true_lang-DIYnv8Ue.js";import"./.pnpm-DnXobOVo.js";import"./index-CcDX_qzp.js";export{o as default};
@@ -1 +0,0 @@
import{_ as o}from"./GancaoSubmissionReconcileButton.vue_vue_type_script_setup_true_lang-DLsU5t1Y.js";import"./.pnpm-DnXobOVo.js";import"./index-B5yNocKV.js";export{o as default};
@@ -1 +1 @@
import{o as U,br as F,q as f,r as k,F as D,ag as M,O as E,D as t,L as u,K as G,v as r,a2 as B,bf as q,be as P,az as A,bc as L,bi as T,bs as z,a3 as K,P as g,p as W,M as v,aD as $}from"./.pnpm-DnXobOVo.js";import{f as C,x as j}from"./index-B5yNocKV.js";const Q=U({__name:"GancaoSubmissionReconcileButton",props:{order:{}},emits:["resolved"],setup(N,{emit:y}){const d=N,V=y,w=W(()=>{var m,_,a;const i=String(((m=d.order)==null?void 0:m.pharmacy_claim_target)||"").trim().toLowerCase(),e=String(((_=d.order)==null?void 0:_.pharmacy_claim_status)||"").trim().toUpperCase(),n=Number(((a=d.order)==null?void 0:a.pharmacy_claim_lease_expires_at)||0),c=e==="PENDING"&&n>0&&n<=Math.floor(Date.now()/1e3);return i==="gancao"&&(c||["UNKNOWN","PENDING_RECONCILE"].includes(e))}),s=v(!1),p=v(!1),o=$({resolution:"CONFIRM_SUCCESS",remote_order_no:"",note:""});function x(){o.resolution="CONFIRM_SUCCESS",o.remote_order_no="",o.note="",s.value=!0}async function b(){var e;const i=Number((e=d.order)==null?void 0:e.id);if(i){if(o.resolution==="CONFIRM_SUCCESS"&&!o.remote_order_no.trim()){C.msgError("请填写甘草药方单号");return}if(!o.note.trim()){C.msgError("请填写甘草后台核对依据");return}p.value=!0;try{await j({id:i,resolution:o.resolution,remote_order_no:o.resolution==="CONFIRM_SUCCESS"?o.remote_order_no.trim():"",note:o.note.trim()}),C.msgSuccess("甘草提交核对已记录"),s.value=!1,V("resolved")}catch{}finally{p.value=!1}}}return(i,e)=>{const n=G,c=q,m=z,_=T,a=L,S=K,O=P,R=B,I=F("perms");return w.value?(f(),k(D,{key:0},[M((f(),E(n,{type:"danger",size:"small",plain:"",onClick:x},{default:t(()=>[...e[5]||(e[5]=[u("核对甘草提交",-1)])]),_:1})),[[I,["tcm.prescriptionOrder/confirmGancaoSubmission"]]]),r(R,{modelValue:s.value,"onUpdate:modelValue":e[4]||(e[4]=l=>s.value=l),title:"人工核对甘草提交",width:"min(92vw, 520px)","append-to-body":"","destroy-on-close":"","close-on-click-modal":!1},{footer:t(()=>[r(n,{onClick:e[3]||(e[3]=l=>s.value=!1)},{default:t(()=>[...e[8]||(e[8]=[u("取消",-1)])]),_:1}),r(n,{type:"primary",loading:p.value,onClick:b},{default:t(()=>[...e[9]||(e[9]=[u("确认并记录",-1)])]),_:1},8,["loading"])]),default:t(()=>[r(c,{title:"请先在甘草后台核对。本操作会写入不可变更的审计记录。",type:"warning",closable:!1,"show-icon":"",class:"mb-4"}),r(O,{"label-width":"100px",onSubmit:A(b,["prevent"])},{default:t(()=>[r(a,{label:"核对结果",required:""},{default:t(()=>[r(_,{modelValue:o.resolution,"onUpdate:modelValue":e[0]||(e[0]=l=>o.resolution=l)},{default:t(()=>[r(m,{label:"CONFIRM_SUCCESS"},{default:t(()=>[...e[6]||(e[6]=[u("确认已创建",-1)])]),_:1}),r(m,{label:"CONFIRM_NOT_CREATED"},{default:t(()=>[...e[7]||(e[7]=[u("确认未创建",-1)])]),_:1})]),_:1},8,["modelValue"])]),_:1}),o.resolution==="CONFIRM_SUCCESS"?(f(),E(a,{key:0,label:"甘草单号",required:""},{default:t(()=>[r(S,{modelValue:o.remote_order_no,"onUpdate:modelValue":e[1]||(e[1]=l=>o.remote_order_no=l),maxlength:"64",clearable:""},null,8,["modelValue"])]),_:1})):g("",!0),r(a,{label:"核对依据",required:""},{default:t(()=>[r(S,{modelValue:o.note,"onUpdate:modelValue":e[2]||(e[2]=l=>o.note=l),type:"textarea",rows:3,maxlength:"1000","show-word-limit":"",placeholder:"例如:核对时间、甘草后台查询条件及结果"},null,8,["modelValue"])]),_:1})]),_:1})]),_:1},8,["modelValue"])],64)):g("",!0)}}});export{Q as _};
import{o as U,br as F,q as f,r as k,F as D,ag as M,O as E,D as t,L as u,K as G,v as r,a2 as B,bf as q,be as P,az as A,bc as L,bi as T,bs as z,a3 as K,P as g,p as W,M as v,aD as $}from"./.pnpm-DnXobOVo.js";import{f as C,x as j}from"./index-CcDX_qzp.js";const Q=U({__name:"GancaoSubmissionReconcileButton",props:{order:{}},emits:["resolved"],setup(N,{emit:y}){const d=N,V=y,w=W(()=>{var m,_,a;const i=String(((m=d.order)==null?void 0:m.pharmacy_claim_target)||"").trim().toLowerCase(),e=String(((_=d.order)==null?void 0:_.pharmacy_claim_status)||"").trim().toUpperCase(),n=Number(((a=d.order)==null?void 0:a.pharmacy_claim_lease_expires_at)||0),c=e==="PENDING"&&n>0&&n<=Math.floor(Date.now()/1e3);return i==="gancao"&&(c||["UNKNOWN","PENDING_RECONCILE"].includes(e))}),s=v(!1),p=v(!1),o=$({resolution:"CONFIRM_SUCCESS",remote_order_no:"",note:""});function x(){o.resolution="CONFIRM_SUCCESS",o.remote_order_no="",o.note="",s.value=!0}async function b(){var e;const i=Number((e=d.order)==null?void 0:e.id);if(i){if(o.resolution==="CONFIRM_SUCCESS"&&!o.remote_order_no.trim()){C.msgError("请填写甘草药方单号");return}if(!o.note.trim()){C.msgError("请填写甘草后台核对依据");return}p.value=!0;try{await j({id:i,resolution:o.resolution,remote_order_no:o.resolution==="CONFIRM_SUCCESS"?o.remote_order_no.trim():"",note:o.note.trim()}),C.msgSuccess("甘草提交核对已记录"),s.value=!1,V("resolved")}catch{}finally{p.value=!1}}}return(i,e)=>{const n=G,c=q,m=z,_=T,a=L,S=K,O=P,R=B,I=F("perms");return w.value?(f(),k(D,{key:0},[M((f(),E(n,{type:"danger",size:"small",plain:"",onClick:x},{default:t(()=>[...e[5]||(e[5]=[u("核对甘草提交",-1)])]),_:1})),[[I,["tcm.prescriptionOrder/confirmGancaoSubmission"]]]),r(R,{modelValue:s.value,"onUpdate:modelValue":e[4]||(e[4]=l=>s.value=l),title:"人工核对甘草提交",width:"min(92vw, 520px)","append-to-body":"","destroy-on-close":"","close-on-click-modal":!1},{footer:t(()=>[r(n,{onClick:e[3]||(e[3]=l=>s.value=!1)},{default:t(()=>[...e[8]||(e[8]=[u("取消",-1)])]),_:1}),r(n,{type:"primary",loading:p.value,onClick:b},{default:t(()=>[...e[9]||(e[9]=[u("确认并记录",-1)])]),_:1},8,["loading"])]),default:t(()=>[r(c,{title:"请先在甘草后台核对。本操作会写入不可变更的审计记录。",type:"warning",closable:!1,"show-icon":"",class:"mb-4"}),r(O,{"label-width":"100px",onSubmit:A(b,["prevent"])},{default:t(()=>[r(a,{label:"核对结果",required:""},{default:t(()=>[r(_,{modelValue:o.resolution,"onUpdate:modelValue":e[0]||(e[0]=l=>o.resolution=l)},{default:t(()=>[r(m,{label:"CONFIRM_SUCCESS"},{default:t(()=>[...e[6]||(e[6]=[u("确认已创建",-1)])]),_:1}),r(m,{label:"CONFIRM_NOT_CREATED"},{default:t(()=>[...e[7]||(e[7]=[u("确认未创建",-1)])]),_:1})]),_:1},8,["modelValue"])]),_:1}),o.resolution==="CONFIRM_SUCCESS"?(f(),E(a,{key:0,label:"甘草单号",required:""},{default:t(()=>[r(S,{modelValue:o.remote_order_no,"onUpdate:modelValue":e[1]||(e[1]=l=>o.remote_order_no=l),maxlength:"64",clearable:""},null,8,["modelValue"])]),_:1})):g("",!0),r(a,{label:"核对依据",required:""},{default:t(()=>[r(S,{modelValue:o.note,"onUpdate:modelValue":e[2]||(e[2]=l=>o.note=l),type:"textarea",rows:3,maxlength:"1000","show-word-limit":"",placeholder:"例如:核对时间、甘草后台查询条件及结果"},null,8,["modelValue"])]),_:1})]),_:1})]),_:1},8,["modelValue"])],64)):g("",!0)}}});export{Q as _};
View File
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
import{o as I,q as a,r as l,ai as x,v as r,D as m,L as d,T as i,a4 as D,s as n,O as g,bp as K,P as B,ae as L,u as v,bS as U,w as q,bT as A,bU as G,bV as O,F as P,K as j,p as u}from"./.pnpm-DnXobOVo.js";import{t as H,_ as J}from"./index-B5yNocKV.js";const Q={class:"msg-body"},R={class:"msg-meta"},W={class:"msg-sender"},X={class:"msg-time"},Y={key:0,class:"content-text"},Z={key:2,class:"content-pending"},ee=["src"],se={key:4,class:"content-pending"},te=["src"],ae={key:6,class:"content-pending"},ne={key:7,class:"content-file"},le={class:"file-meta"},ie=["title"],oe={class:"file-info"},ce={key:8,class:"content-fallback"},re={class:"fallback-title"},me={class:"fallback-desc"},ue=I({__name:"MessageBubble",props:{message:{}},setup(s){const o=s,w=u(()=>o.message.from_is_staff),c=u(()=>(o.message.media||[]).find(t=>t.status===1)??null),_=u(()=>{const e=o.message.from_profile;return e&&e.name||o.message.from_user}),z=u(()=>{const e=o.message.from_profile;return(e==null?void 0:e.avatar)||""}),F=u(()=>(_.value||"").slice(-2)||"?"),C=u(()=>{const e=o.message.msgtype;return e==="image"||e==="video"||e==="voice"?"bubble-media":e==="file"?"bubble-file":"bubble-text"}),E=u(()=>{switch(o.message.msgtype){case"link":return"[链接]";case"weapp":return"[小程序]";case"chatrecord":return"[聊天记录]";case"location":return"[位置]";case"card":return"[名片]";case"meeting":return"[会议]";case"docmsg":return"[文档]";case"mixed":return"[混合消息]";case"emotion":return"[表情]";default:return`[${o.message.msgtype}]`}});function M(e){return e?H(e*1e3,"mm-dd hh:MM"):""}function N(e){return e?e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(2)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`:""}function $(e){window.open(e,"_blank","noopener")}return(e,t)=>{var b,y,p,h;const T=D,k=K,V=L,f=q,S=j;return a(),l("div",{class:x(["msg-bubble",{"is-staff":w.value}])},[r(T,{class:"msg-avatar",size:36,src:z.value},{default:m(()=>[d(i(F.value),1)]),_:1},8,["src"]),n("div",Q,[n("div",R,[n("span",W,i(_.value),1),n("span",X,i(M(s.message.send_time)),1),s.message.action==="recall"?(a(),g(k,{key:0,size:"small",type:"info"},{default:m(()=>[...t[1]||(t[1]=[d(" 已撤回 ",-1)])]),_:1})):B("",!0)]),n("div",{class:x(["msg-content",C.value])},[s.message.msgtype==="text"||s.message.msgtype==="markdown"?(a(),l("div",Y,i(s.message.content),1)):s.message.msgtype==="image"&&((b=c.value)!=null&&b.file_url)?(a(),g(V,{key:1,src:c.value.file_url,"preview-src-list":[c.value.file_url],fit:"contain",class:"content-image","hide-on-click-modal":""},null,8,["src","preview-src-list"])):s.message.msgtype==="image"?(a(),l("div",Z,[r(f,null,{default:m(()=>[r(v(U))]),_:1}),t[2]||(t[2]=n("span",null,"图片下载中…",-1))])):s.message.msgtype==="video"&&((y=c.value)!=null&&y.file_url)?(a(),l("video",{key:3,src:c.value.file_url,controls:"",class:"content-video"},null,8,ee)):s.message.msgtype==="video"?(a(),l("div",se,[r(f,null,{default:m(()=>[r(v(A))]),_:1}),t[3]||(t[3]=n("span",null,"视频下载中…",-1))])):s.message.msgtype==="voice"&&((p=c.value)!=null&&p.file_url)?(a(),l("audio",{key:5,src:c.value.file_url,controls:"",class:"content-audio"},null,8,te)):s.message.msgtype==="voice"?(a(),l("div",ae,[r(f,null,{default:m(()=>[r(v(G))]),_:1}),n("span",null,"语音下载中…("+i(s.message.play_length)+"s)",1)])):s.message.msgtype==="file"?(a(),l("div",ne,[r(f,{size:24},{default:m(()=>[r(v(O))]),_:1}),n("div",le,[n("div",{class:"file-name",title:s.message.file_name},i(s.message.file_name||"未命名文件"),9,ie),n("div",oe,[d(i(N(s.message.file_size))+" ",1),s.message.file_ext?(a(),l(P,{key:0},[d("· "+i(s.message.file_ext),1)],64)):B("",!0)])]),(h=c.value)!=null&&h.file_url?(a(),g(S,{key:0,size:"small",type:"primary",link:"",onClick:t[0]||(t[0]=de=>$(c.value.file_url))},{default:m(()=>[...t[4]||(t[4]=[d(" 下载 ",-1)])]),_:1})):(a(),g(k,{key:1,size:"small",type:"info"},{default:m(()=>[...t[5]||(t[5]=[d("下载中…",-1)])]),_:1}))])):(a(),l("div",ce,[n("div",re,i(E.value),1),n("div",me,i(s.message.content),1)]))],2)])],2)}}}),ve=J(ue,[["__scopeId","data-v-80799394"]]);export{ve as default};
import{o as I,q as a,r as l,ai as x,v as r,D as m,L as d,T as i,a4 as D,s as n,O as g,bp as K,P as B,ae as L,u as v,bS as U,w as q,bT as A,bU as G,bV as O,F as P,K as j,p as u}from"./.pnpm-DnXobOVo.js";import{t as H,_ as J}from"./index-CcDX_qzp.js";const Q={class:"msg-body"},R={class:"msg-meta"},W={class:"msg-sender"},X={class:"msg-time"},Y={key:0,class:"content-text"},Z={key:2,class:"content-pending"},ee=["src"],se={key:4,class:"content-pending"},te=["src"],ae={key:6,class:"content-pending"},ne={key:7,class:"content-file"},le={class:"file-meta"},ie=["title"],oe={class:"file-info"},ce={key:8,class:"content-fallback"},re={class:"fallback-title"},me={class:"fallback-desc"},ue=I({__name:"MessageBubble",props:{message:{}},setup(s){const o=s,w=u(()=>o.message.from_is_staff),c=u(()=>(o.message.media||[]).find(t=>t.status===1)??null),_=u(()=>{const e=o.message.from_profile;return e&&e.name||o.message.from_user}),z=u(()=>{const e=o.message.from_profile;return(e==null?void 0:e.avatar)||""}),F=u(()=>(_.value||"").slice(-2)||"?"),C=u(()=>{const e=o.message.msgtype;return e==="image"||e==="video"||e==="voice"?"bubble-media":e==="file"?"bubble-file":"bubble-text"}),E=u(()=>{switch(o.message.msgtype){case"link":return"[链接]";case"weapp":return"[小程序]";case"chatrecord":return"[聊天记录]";case"location":return"[位置]";case"card":return"[名片]";case"meeting":return"[会议]";case"docmsg":return"[文档]";case"mixed":return"[混合消息]";case"emotion":return"[表情]";default:return`[${o.message.msgtype}]`}});function M(e){return e?H(e*1e3,"mm-dd hh:MM"):""}function N(e){return e?e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/1024/1024).toFixed(2)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`:""}function $(e){window.open(e,"_blank","noopener")}return(e,t)=>{var b,y,p,h;const T=D,k=K,V=L,f=q,S=j;return a(),l("div",{class:x(["msg-bubble",{"is-staff":w.value}])},[r(T,{class:"msg-avatar",size:36,src:z.value},{default:m(()=>[d(i(F.value),1)]),_:1},8,["src"]),n("div",Q,[n("div",R,[n("span",W,i(_.value),1),n("span",X,i(M(s.message.send_time)),1),s.message.action==="recall"?(a(),g(k,{key:0,size:"small",type:"info"},{default:m(()=>[...t[1]||(t[1]=[d(" 已撤回 ",-1)])]),_:1})):B("",!0)]),n("div",{class:x(["msg-content",C.value])},[s.message.msgtype==="text"||s.message.msgtype==="markdown"?(a(),l("div",Y,i(s.message.content),1)):s.message.msgtype==="image"&&((b=c.value)!=null&&b.file_url)?(a(),g(V,{key:1,src:c.value.file_url,"preview-src-list":[c.value.file_url],fit:"contain",class:"content-image","hide-on-click-modal":""},null,8,["src","preview-src-list"])):s.message.msgtype==="image"?(a(),l("div",Z,[r(f,null,{default:m(()=>[r(v(U))]),_:1}),t[2]||(t[2]=n("span",null,"图片下载中…",-1))])):s.message.msgtype==="video"&&((y=c.value)!=null&&y.file_url)?(a(),l("video",{key:3,src:c.value.file_url,controls:"",class:"content-video"},null,8,ee)):s.message.msgtype==="video"?(a(),l("div",se,[r(f,null,{default:m(()=>[r(v(A))]),_:1}),t[3]||(t[3]=n("span",null,"视频下载中…",-1))])):s.message.msgtype==="voice"&&((p=c.value)!=null&&p.file_url)?(a(),l("audio",{key:5,src:c.value.file_url,controls:"",class:"content-audio"},null,8,te)):s.message.msgtype==="voice"?(a(),l("div",ae,[r(f,null,{default:m(()=>[r(v(G))]),_:1}),n("span",null,"语音下载中…("+i(s.message.play_length)+"s)",1)])):s.message.msgtype==="file"?(a(),l("div",ne,[r(f,{size:24},{default:m(()=>[r(v(O))]),_:1}),n("div",le,[n("div",{class:"file-name",title:s.message.file_name},i(s.message.file_name||"未命名文件"),9,ie),n("div",oe,[d(i(N(s.message.file_size))+" ",1),s.message.file_ext?(a(),l(P,{key:0},[d("· "+i(s.message.file_ext),1)],64)):B("",!0)])]),(h=c.value)!=null&&h.file_url?(a(),g(S,{key:0,size:"small",type:"primary",link:"",onClick:t[0]||(t[0]=de=>$(c.value.file_url))},{default:m(()=>[...t[4]||(t[4]=[d(" 下载 ",-1)])]),_:1})):(a(),g(k,{key:1,size:"small",type:"info"},{default:m(()=>[...t[5]||(t[5]=[d("下载中…",-1)])]),_:1}))])):(a(),l("div",ce,[n("div",re,i(E.value),1),n("div",me,i(s.message.content),1)]))],2)])],2)}}}),ve=J(ue,[["__scopeId","data-v-80799394"]]);export{ve as default};
View File
@@ -1,2 +1,2 @@
import{o as ie,R as oe,q as n,r as o,O as k,K as le,D as r,L as B,P as m,v as l,s as d,F as w,G as V,by as ae,a3 as re,a2 as de,p as ue,M as g,T as P,ae as me,u as E,db as U,az as M,w as ce,bV as pe,e as ge}from"./.pnpm-DnXobOVo.js";import{_ as fe}from"./picker-BeXyJvkw.js";import{h as ve,c as _e,f,O as ye,_ as he}from"./index-B5yNocKV.js";import{a as T,d as ke}from"./patient-CqiBEV1n.js";import"./index-DR8bxDFy.js";import"./index-Iz1Kn8Vz.js";import"./index.vue_vue_type_script_setup_true_lang-GSVwwezT.js";import"./index-D413krku.js";import"./index-BwIr9qiy.js";import"./file-CN5TlpMj.js";import"./index.vue_vue_type_script_setup_true_lang-Bxg_mWlx.js";import"./usePaging-DdtNlhkl.js";const we={class:"note-timeline-wrap"},Ie={key:0,class:"timeline-actions"},Ce={class:"upload-trigger"},xe={class:"upload-trigger"},be={key:1,class:"note-timeline"},Ve={class:"timeline-date"},Ee={class:"timeline-body"},Ne={key:0,class:"timeline-content"},Se={key:1,class:"timeline-images"},De={key:2,class:"timeline-images"},ze={key:0,class:"thumb-wrap"},Ae={key:1,class:"file-wrap"},Be=["href","title"],Pe={class:"file-name"},W=8e3,Ue=ie({__name:"NoteTimeline",props:{notes:{},diagnosisId:{},readonly:{type:Boolean}},emits:["refresh"],setup(u,{emit:j}){const c=u,I=j,X=ue(()=>ye(["doctor.appointment/addDoctorNote"])),v=g(!1),C=g(""),N=g(!1),q=ve(),_=t=>q.getImageUrl(t),S=g([]),D=g([]),y=g(0),h=g(0),K=["jpg","jpeg","png","gif","bmp","webp","svg"],z=t=>{var i;const e=((i=t.split(".").pop())==null?void 0:i.toLowerCase().split("?")[0])||"";return K.includes(e)},$=t=>{var i;const e=t.split("/");return decodeURIComponent(((i=e[e.length-1])==null?void 0:i.split("?")[0])||"文件")},Z=t=>t.filter(z).map(_),H=(t,e)=>{const i=t.filter(z),x=t[e];return i.indexOf(x)},J=t=>t?t.split(`
import{o as ie,R as oe,q as n,r as o,O as k,K as le,D as r,L as B,P as m,v as l,s as d,F as w,G as V,by as ae,a3 as re,a2 as de,p as ue,M as g,T as P,ae as me,u as E,db as U,az as M,w as ce,bV as pe,e as ge}from"./.pnpm-DnXobOVo.js";import{_ as fe}from"./picker-f_1nIK_X.js";import{h as ve,c as _e,f,O as ye,_ as he}from"./index-CcDX_qzp.js";import{a as T,d as ke}from"./patient-57s-3C15.js";import"./index-D5laSpve.js";import"./index-B-JgdpqF.js";import"./index.vue_vue_type_script_setup_true_lang-GSVwwezT.js";import"./index-BtjzKsa0.js";import"./index-BWMgSEq-.js";import"./file-CwKsS4EB.js";import"./index.vue_vue_type_script_setup_true_lang-Bxg_mWlx.js";import"./usePaging-DdtNlhkl.js";const we={class:"note-timeline-wrap"},Ie={key:0,class:"timeline-actions"},Ce={class:"upload-trigger"},xe={class:"upload-trigger"},be={key:1,class:"note-timeline"},Ve={class:"timeline-date"},Ee={class:"timeline-body"},Ne={key:0,class:"timeline-content"},Se={key:1,class:"timeline-images"},De={key:2,class:"timeline-images"},ze={key:0,class:"thumb-wrap"},Ae={key:1,class:"file-wrap"},Be=["href","title"],Pe={class:"file-name"},W=8e3,Ue=ie({__name:"NoteTimeline",props:{notes:{},diagnosisId:{},readonly:{type:Boolean}},emits:["refresh"],setup(u,{emit:j}){const c=u,I=j,X=ue(()=>ye(["doctor.appointment/addDoctorNote"])),v=g(!1),C=g(""),N=g(!1),q=ve(),_=t=>q.getImageUrl(t),S=g([]),D=g([]),y=g(0),h=g(0),K=["jpg","jpeg","png","gif","bmp","webp","svg"],z=t=>{var i;const e=((i=t.split(".").pop())==null?void 0:i.toLowerCase().split("?")[0])||"";return K.includes(e)},$=t=>{var i;const e=t.split("/");return decodeURIComponent(((i=e[e.length-1])==null?void 0:i.split("?")[0])||"文件")},Z=t=>t.filter(z).map(_),H=(t,e)=>{const i=t.filter(z),x=t[e];return i.indexOf(x)},J=t=>t?t.split(`
`).filter(Boolean):[],Q=t=>{if(!c.diagnosisId)return;const e=Array.isArray(t)?t:[t];if(e.length<=y.value){y.value=e.length;return}const i=e.slice(y.value);y.value=e.length,i.length>0&&T({diagnosis_id:c.diagnosisId,tongue_images:i}).then(()=>{f.msgSuccess("舌苔照片已添加"),I("refresh")})},Y=t=>{if(!c.diagnosisId)return;const e=Array.isArray(t)?t:[t];if(e.length<=h.value){h.value=e.length;return}const i=e.slice(h.value);h.value=e.length,i.length>0&&T({diagnosis_id:c.diagnosisId,report_files:i}).then(()=>{f.msgSuccess("检查报告已添加"),I("refresh")})};oe(()=>c.notes,()=>{S.value=[],D.value=[],y.value=0,h.value=0});const ee=async()=>{if(!c.diagnosisId){f.msgWarning("当前无诊单,无法添加备注");return}const t=C.value.trim();if(!t){f.msgWarning("请输入备注内容");return}N.value=!0;try{await T({diagnosis_id:c.diagnosisId,content:t}),f.msgSuccess("备注保存成功"),C.value="",v.value=!1,I("refresh")}catch(e){f.msgError((e==null?void 0:e.message)||"保存失败")}finally{N.value=!1}},A=async(t,e,i)=>{try{await ge.confirm("确认删除?","提示",{type:"warning"})}catch{return}await ke({note_id:t,image_type:e,image_path:i}),f.msgSuccess("已删除"),I("refresh")};return(t,e)=>{const i=le,x=_e,F=fe,L=me,b=ce,te=ae,se=re,ne=de;return n(),o("div",we,[!u.readonly&&u.diagnosisId?(n(),o("div",Ie,[X.value?(n(),k(i,{key:0,type:"primary",plain:"",size:"small",onClick:e[0]||(e[0]=s=>v.value=!0)},{default:r(()=>[...e[6]||(e[6]=[B(" 添加备注 ",-1)])]),_:1})):m("",!0),l(F,{modelValue:S.value,"onUpdate:modelValue":e[1]||(e[1]=s=>S.value=s),limit:99,type:"image","exclude-domain":!0,onChange:Q},{upload:r(()=>[d("div",Ce,[l(x,{size:20,name:"el-icon-Plus"}),e[7]||(e[7]=d("span",null,"舌苔照片",-1))])]),_:1},8,["modelValue"]),l(F,{modelValue:D.value,"onUpdate:modelValue":e[2]||(e[2]=s=>D.value=s),limit:99,type:"file","exclude-domain":!0,onChange:Y},{upload:r(()=>[d("div",xe,[l(x,{size:20,name:"el-icon-Plus"}),e[8]||(e[8]=d("span",null,"检查报告",-1))])]),_:1},8,["modelValue"])])):m("",!0),u.notes.length?(n(),o("div",be,[(n(!0),o(w,null,V(u.notes,s=>{var R,O;return n(),o("div",{key:s.id,class:"timeline-node"},[e[11]||(e[11]=d("div",{class:"timeline-dot"},null,-1)),d("div",Ve,P(s.note_date),1),d("div",Ee,[s.content?(n(),o("div",Ne,[(n(!0),o(w,null,V(J(s.content),(a,p)=>(n(),o("div",{key:p,class:"content-line"},P(a),1))),128))])):m("",!0),(R=s.tongue_images)!=null&&R.length?(n(),o("div",Se,[e[9]||(e[9]=d("span",{class:"images-label"},"舌苔照片",-1)),(n(!0),o(w,null,V(s.tongue_images,(a,p)=>(n(),o("div",{key:p,class:"thumb-wrap"},[l(L,{src:_(a),"preview-src-list":s.tongue_images.map(_),"initial-index":p,"z-index":W,fit:"cover",class:"timeline-thumb","preview-teleported":""},null,8,["src","preview-src-list","initial-index"]),u.readonly?m("",!0):(n(),k(b,{key:0,class:"thumb-delete",onClick:M(G=>A(s.id,"tongue_images",a),["stop"])},{default:r(()=>[l(E(U))]),_:1},8,["onClick"]))]))),128))])):m("",!0),(O=s.report_files)!=null&&O.length?(n(),o("div",De,[e[10]||(e[10]=d("span",{class:"images-label"},"检查报告",-1)),(n(!0),o(w,null,V(s.report_files,(a,p)=>(n(),o(w,{key:p},[z(a)?(n(),o("div",ze,[l(L,{src:_(a),"preview-src-list":Z(s.report_files),"initial-index":H(s.report_files,p),"z-index":W,fit:"cover",class:"timeline-thumb","preview-teleported":""},null,8,["src","preview-src-list","initial-index"]),u.readonly?m("",!0):(n(),k(b,{key:0,class:"thumb-delete",onClick:M(G=>A(s.id,"report_files",a),["stop"])},{default:r(()=>[l(E(U))]),_:1},8,["onClick"]))])):(n(),o("div",Ae,[d("a",{href:_(a),target:"_blank",class:"file-link",title:$(a)},[l(b,{size:20},{default:r(()=>[l(E(pe))]),_:1}),d("span",Pe,P($(a)),1)],8,Be),u.readonly?m("",!0):(n(),k(b,{key:0,class:"file-delete",onClick:M(G=>A(s.id,"report_files",a),["stop"])},{default:r(()=>[l(E(U))]),_:1},8,["onClick"]))]))],64))),128))])):m("",!0)])])}),128))])):m("",!0),!u.notes.length&&u.readonly?(n(),k(te,{key:2,description:"暂无备注","image-size":48})):m("",!0),l(ne,{modelValue:v.value,"onUpdate:modelValue":e[5]||(e[5]=s=>v.value=s),title:"添加备注",width:"480px","append-to-body":""},{footer:r(()=>[l(i,{onClick:e[4]||(e[4]=s=>v.value=!1)},{default:r(()=>[...e[12]||(e[12]=[B("取消",-1)])]),_:1}),l(i,{type:"primary",loading:N.value,onClick:ee},{default:r(()=>[...e[13]||(e[13]=[B("保存",-1)])]),_:1},8,["loading"])]),default:r(()=>[l(se,{modelValue:C.value,"onUpdate:modelValue":e[3]||(e[3]=s=>C.value=s),type:"textarea",rows:4,placeholder:"输入今日备注...",maxlength:"500","show-word-limit":""},null,8,["modelValue"])]),_:1},8,["modelValue"])])}}}),Ke=he(Ue,[["__scopeId","data-v-e548427d"]]);export{Ke as default};
View File
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
View File
View File
View File
@@ -1 +1 @@
import{m as I,f as p,a as w}from"./diag-display-DCz_VAqj.js";import{o as y,q as x,r as B,s as e,T as a,u as i,P as N}from"./.pnpm-DnXobOVo.js";import{_ as V}from"./index-B5yNocKV.js";const b={class:"card patient-card"},q={class:"patient-hero"},D={class:"patient-name"},E={class:"patient-meta"},G={key:0},S=y({__name:"PatientInfoCard",props:{apt:{default:()=>({})},diag:{default:()=>({})}},setup(t){return(T,n)=>{var d,s,o,c,m,l,r,g,u,f,h,v,k,P,C;return x(),B("div",b,[n[0]||(n[0]=e("div",{class:"card-title"},"患者信息",-1)),e("div",q,[e("div",D,a(((d=t.apt)==null?void 0:d.patient_name)||"—"),1),e("div",E,[e("div",null,a(i(I)((s=t.apt)==null?void 0:s.patient_phone))+" · "+a(i(p)((o=t.diag)==null?void 0:o.gender))+" · "+a(((c=t.diag)==null?void 0:c.age)!=null?t.diag.age+"岁":"—"),1),e("div",null,a((m=t.diag)!=null&&m.height?t.diag.height+"cm":"—")+" / "+a((l=t.diag)!=null&&l.weight?t.diag.weight+"kg":"—")+" · "+a(((r=t.diag)==null?void 0:r.region)||"—"),1),e("div",null," 预约:"+a((g=t.apt)==null?void 0:g.appointment_date)+" "+a((u=t.apt)==null?void 0:u.appointment_time)+" · "+a(i(w)((f=t.apt)==null?void 0:f.period)),1),e("div",null,"医生:"+a(((h=t.apt)==null?void 0:h.doctor_name)||"—")+" 客服:"+a(((v=t.apt)==null?void 0:v.assistant_name)||"—"),1),e("div",null," 状态:"+a(((k=t.apt)==null?void 0:k.status_desc)||"—")+" · "+a((P=t.apt)!=null&&P.has_prescription?"已开方":"未开方"),1),(C=t.apt)!=null&&C.remark?(x(),B("div",G,"备注:"+a(t.apt.remark),1)):N("",!0)])])])}}}),F=V(S,[["__scopeId","data-v-37de0c0b"]]);export{F as default};
import{m as I,f as p,a as w}from"./diag-display-DCz_VAqj.js";import{o as y,q as x,r as B,s as e,T as a,u as i,P as N}from"./.pnpm-DnXobOVo.js";import{_ as V}from"./index-CcDX_qzp.js";const b={class:"card patient-card"},q={class:"patient-hero"},D={class:"patient-name"},E={class:"patient-meta"},G={key:0},S=y({__name:"PatientInfoCard",props:{apt:{default:()=>({})},diag:{default:()=>({})}},setup(t){return(T,n)=>{var d,s,o,c,m,l,r,g,u,f,h,v,k,P,C;return x(),B("div",b,[n[0]||(n[0]=e("div",{class:"card-title"},"患者信息",-1)),e("div",q,[e("div",D,a(((d=t.apt)==null?void 0:d.patient_name)||"—"),1),e("div",E,[e("div",null,a(i(I)((s=t.apt)==null?void 0:s.patient_phone))+" · "+a(i(p)((o=t.diag)==null?void 0:o.gender))+" · "+a(((c=t.diag)==null?void 0:c.age)!=null?t.diag.age+"岁":"—"),1),e("div",null,a((m=t.diag)!=null&&m.height?t.diag.height+"cm":"—")+" / "+a((l=t.diag)!=null&&l.weight?t.diag.weight+"kg":"—")+" · "+a(((r=t.diag)==null?void 0:r.region)||"—"),1),e("div",null," 预约:"+a((g=t.apt)==null?void 0:g.appointment_date)+" "+a((u=t.apt)==null?void 0:u.appointment_time)+" · "+a(i(w)((f=t.apt)==null?void 0:f.period)),1),e("div",null,"医生:"+a(((h=t.apt)==null?void 0:h.doctor_name)||"—")+" 客服:"+a(((v=t.apt)==null?void 0:v.assistant_name)||"—"),1),e("div",null," 状态:"+a(((k=t.apt)==null?void 0:k.status_desc)||"—")+" · "+a((P=t.apt)!=null&&P.has_prescription?"已开方":"未开方"),1),(C=t.apt)!=null&&C.remark?(x(),B("div",G,"备注:"+a(t.apt.remark),1)):N("",!0)])])])}}}),F=V(S,[["__scopeId","data-v-37de0c0b"]]);export{F as default};

Some files were not shown because too many files have changed in this diff Show More