Compare commits

..
28 Commits
Author SHA1 Message Date
Your NameandClaude Opus 5 537c52c1b9 构建 admin:处方列表重新开方按开方权限显示
Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 13:52:34 +08:00
Your NameandClaude Opus 5 4d1a8683e5 处方列表:「重新开方」按钮改按开方权限显示,与后端口径一致
原先只认 cf.prescription/add,诊单开方(tcm.diagnosis/kaifang、chufang)或 tcm.prescription/add 授权的医生能开方却看不到按钮。
改为与后端 PrescriptionLogic::PRESCRIBE_PERMISSIONS 一致,任一开方权限即显示;保存仍走 /tcm.prescription/add 由后端校验。

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 13:50:30 +08:00
Your NameandClaude Opus 5 7458ff03a7 构建 admin:复诊到期跟进预计复诊列排序
Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 12:11:41 +08:00
Your NameandClaude Opus 5 19159668fb 复诊到期跟进:预计复诊列支持正序/倒序排序,默认按最新在前
- 后端 RevisitDueLists 新增 sort_field / sort_order 参数(白名单 due_date),默认 due_date 倒序,无预计复诊日的行始终置后,同日按 id 同向排序保证分页稳定
- 前端表头「预计复诊」改为可排序,仅在倒序/正序间切换,切换后回到第 1 页;导出沿用当前排序

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 12:03:41 +08:00
Your NameandClaude Opus 5 d199d66f8c 处方 AI:Dify 包装的模型网关故障改为可重试,不再按 UPSTREAM_REJECTED 直接失败
OpenAI 分支的 Dify 应用经 gpt.zhenyangtang.cn 网关调用模型,网关间歇返回
503 no_available_provider(无可用账号)。Dify 把工作流内模型节点失败统一包成
400 invalid_param「Run failed: ...」,与真正的参数错误同码,于是任务被判为
UPSTREAM_REJECTED 且不重试。12-05 09:41–10:30 该网关整段不可用,期间任务全部失败。

- upstreamErrorMetadata:带模型插件调用痕迹且属网关无可用账号、5xx/408/429、
  过载、超时的「Run failed」归为 unavailable → UPSTREAM_BUSY(可重试);
  404、鉴权、参数错误不受影响。
- 重试策略:UPSTREAM_BUSY / UPSTREAM_UNAVAILABLE 改为 2 分钟、10 分钟后重试,
  其余错误仍为 30 秒、2 分钟;总次数仍受 max_attempts 限制。
- 新增离线测试 DifyGatewayOutageClassificationTest,补充策略测试。

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 10:57:16 +08:00
Your NameandClaude Opus 5 5ea3417e4c 同步线上直接修改的代码:处方 AI 队列派发与重试额度、角色 13 处方权限
以下改动此前只在生产服务器上直接修改,未进仓库,现按线上文件原样收回:
- 处方 AI:新增 prescription-ai:dispatch 每分钟派发单轮队列(PrescriptionAiDispatch、
  PrescriptionAiLaneGuard 队列锁),work 命令支持 --scheduled;重试接口返回与轮询一致的
  任务状态,额度用尽时提示最早可重试时间;每日模型任务默认额度 200 → 5000
- 定时任务 SQL:database/migrations/2026_12_02_prescription_ai_crontab.sql(线上已执行)
- project.php:prescription_library_manage_all_roles / prescription_audit_roles 加入角色 13

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 10:27:47 +08:00
Your NameandClaude Opus 5 580444731b 构建 admin:复诊到期跟进诊次筛选与筛选栏宽度修复
Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 09:52:14 +08:00
Your NameandClaude Opus 5 e1a3638b35 复诊到期跟进:筛选栏宽度改用 !w-[...],避免被 Element Plus 默认 100% 宽度覆盖
Element Plus 按需注入的 .el-select / .el-input 样式与 Tailwind 宽度类同优先级,
加载顺序靠后时会把下拉框压成只剩箭头。

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 09:47:01 +08:00
Your NameandClaude Opus 5 1bd1224af7 处方 AI:教材方提问要求兼证时取最贴近主证的一首
线上实测证名带兼证(如气阴两虚兼血瘀)时,模型以「没有单一对应方」为由返回空药味;
明确要求取最贴近主证的汤剂或散剂方后,同类证名均能给出组成与剂量。

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 09:37:31 +08:00
Your NameandClaude Opus 5 63152179bd 复诊到期跟进:新增诊次筛选
按当前已完成诊次(current_slot)筛选:未成交 / 第 1~5 诊 / 第 6 诊及以上,
列表、计数与导出同口径;后端 slot 参数支持 N 精确与 N+ 下限。

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 09:29:12 +08:00
Your NameandClaude Opus 5 b8f3c049be 处方 AI:模型追问后仍拒绝开方时,先辨证再取教材代表方作候选
OpenAI 分支对带病例的请求坚持不给剂量,但会单独给出证名与治法,
也会回答不含病例的方剂学问题。追问仍拒绝时改走 final:syndrome →
final:textbook 两步,候选方标注【教材代表方】,服次疗程不给则留空。
提示词版本升至 v8。

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-05 08:59:18 +08:00
Your NameandClaude Opus 5 7189f33812 新增处方 AI 任务诊断脚本(只读,输出调用阶段与格式拒绝规则)
Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-04 17:58:35 +08:00
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
655 changed files with 4230 additions and 1225 deletions
+6
View File
@@ -159,8 +159,14 @@ export interface RevisitDueListsParams {
dept_id?: number | '' dept_id?: number | ''
state?: string state?: string
days_bucket?: string days_bucket?: string
/** 诊次(current_slot):'1'~'5' 精确,'6+' = 第 6 诊及以上 */
slot?: string
min_snooze?: number | '' min_snooze?: number | ''
keyword?: string keyword?: string
/** 排序列(白名单:due_date = 预计复诊),缺省 due_date */
sort_field?: 'due_date'
/** 排序方向,缺省 desc(最新在前);无预计复诊日的行始终置后 */
sort_order?: 'asc' | 'desc'
page_no?: number page_no?: number
page_size?: number page_size?: number
/** 1 = 导出(export-data 组件追加) */ /** 1 = 导出(export-data 组件追加) */
+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(含)之后的支付单;编辑时本单已关联的旧单仍会出现在列表中。 * 服务端仅返回创建时间在 2026-04-20(含)之后的支付单;编辑时本单已关联的旧单仍会出现在列表中。
*/ */
export function prescriptionOrderPaidPayOrders(params: { export function prescriptionOrderPaidPayOrders(params: {
@@ -662,8 +662,27 @@ export function prescriptionOrderLogisticsJdUpdate(params: { id: number }) {
return request.post({ url: '/tcm.prescriptionOrder/logisticsJdUpdate', params }) return request.post({ url: '/tcm.prescriptionOrder/logisticsJdUpdate', params })
} }
export function prescriptionOrderDetail(params: { id: number }) { export function prescriptionOrderDetail(params: { id: number; prescription_id?: number }, signal?: AbortSignal) {
return request.get({ url: '/tcm.prescriptionOrder/detail', params }) 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>) { 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 }) 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 }) { export function prescriptionOrderUpdateAmount(params: { id: number; amount: number }) {
return request.post({ url: '/tcm.prescriptionOrder/updateAmount', params }) 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> <span v-else class="rx-bot-reviewer-name">{{ reviewerName }}</span>
</div> </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"> <div v-if="isInternal" class="rx-bot-cell rx-bot-meta">
<span class="rx-bot-meta-key">类型:</span> <span class="rx-bot-meta-key">类型:</span>
<span class="rx-bot-meta-val">{{ typeText }}</span> <span class="rx-bot-meta-val">{{ typeText }}</span>
@@ -206,9 +214,12 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import type { PrescriptionEsignStatus } from '@/api/tcm' 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 { import {
getAuxHerbs, getAuxHerbs,
getMainHerbs, getMainHerbs,
getSlipHerbs,
rxAdviceText, rxAdviceText,
rxAppointmentFlowText, rxAppointmentFlowText,
rxAuxUsageText, rxAuxUsageText,
@@ -241,6 +252,7 @@ const props = withDefaults(
/** 抬头(处方联) */ /** 抬头(处方联) */
title?: string title?: string
compact?: boolean compact?: boolean
showPharmacistSignatureSample?: boolean
}>(), }>(),
{ {
variant: 'internal', variant: 'internal',
@@ -279,6 +291,18 @@ const reviewerSignature = computed(() => {
const signature = props.data?.esign?.review_signature const signature = props.data?.esign?.review_signature
return reviewerName.value && isVerifiedSignaturePng(signature) && signature !== failedReviewerSignature.value ? 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 { function isVerifiedSignaturePng(signature: unknown): signature is string {
return typeof signature === 'string' && /^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/.test(signature) 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-bot-row-1 {
--rx-reviewed-columns: minmax(164px, 1.15fr) minmax(188px, 1.3fr) 1.4fr 0.75fr 0.85fr;
/* 类型/剂数/单剂量 三个 meta 列适当加宽, /* 类型/剂数/单剂量 三个 meta 列适当加宽,
* 避免"浓缩丸-浓缩水丸"被强制折行后把整行挤错位 */ * 避免"浓缩丸-浓缩水丸"被强制折行后把整行挤错位 */
grid-template-columns: 1.6fr 0.6fr 0.6fr 0.6fr 0.6fr 1.7fr 0.95fr 1.25fr; 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-bot-row-1--user {
--rx-reviewed-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr;
grid-template-columns: 1.6fr 0.6fr; grid-template-columns: 1.6fr 0.6fr;
} }
.rx-bot-row-1--reviewed { .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 { @media screen {
grid-template-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr; .rx-bot-row-1:has(> .rx-pharmacist-sample) {
grid-template-columns: var(--rx-reviewed-columns);
}
} }
.rx-hospital-row { .rx-hospital-row {
@@ -769,6 +797,12 @@ defineExpose({
object-fit: contain; object-fit: contain;
} }
@media print {
.rx-pharmacist-sample {
display: none;
}
}
.rx-bot-meta { .rx-bot-meta {
flex-wrap: nowrap; flex-wrap: nowrap;
@@ -308,8 +308,63 @@ function computeOutPellet(data: Record<string, any>): string {
return formatNum(perDose * getDoseCount(data)) 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 { export function rxOutPelletText(data: Record<string, any> | null | undefined): string {
if (!data) return '' if (!data) return ''
const out = computeOutPellet(data) const out = computeOutPellet(data)
const aux = computeAuxOutPellet(data)
if (out && aux) return `主方 ${out}克,辅方 ${aux}克`
return out ? `${out}克` : '' return out ? `${out}克` : ''
} }
@@ -701,16 +701,16 @@
{{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }} {{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }}
</el-button> </el-button>
<el-tooltip <el-tooltip
v-if="savedPrescription.void_status !== 1 && !approvedPreviewOnly" v-if="savedPrescription.void_status !== 1 && savedPrescription.can_void !== false"
:disabled="!hasPrescriptionOrderBlockVoid" :disabled="!hasLinkedPrescriptionOrder"
content="该处方已存在业务订单,无法作废,请前往已开处方里修改" content="作废后,关联的业务订单会在同诊单重新开方时自动关联到新处方"
placement="top" placement="top"
> >
<span class="inline-block"> <span class="inline-block">
<el-button <el-button
v-perms="['tcm.prescription/void']"
type="danger" type="danger"
plain plain
:disabled="hasPrescriptionOrderBlockVoid"
:loading="voiding" :loading="voiding"
@click="handleVoid" @click="handleVoid"
> >
@@ -1080,8 +1080,8 @@ const approvedPreviewOnly = computed(() => {
return Number(s.audit_status) === 1 && Number(s.void_status) !== 1 return Number(s.audit_status) === 1 && Number(s.void_status) !== 1
}) })
/** 已有关联业务订单(与列表 has_prescription_order 一致)则禁止作废 */ /** 已有关联业务订单(与列表 has_prescription_order 一致):作废时提示订单将随重新开方迁移 */
const hasPrescriptionOrderBlockVoid = computed(() => { const hasLinkedPrescriptionOrder = computed(() => {
const s = savedPrescription.value const s = savedPrescription.value
if (!s) return false if (!s) return false
return Number(s.has_prescription_order) === 1 return Number(s.has_prescription_order) === 1
@@ -2165,12 +2165,10 @@ const formatVoidTime = (ts: number | null | undefined) => {
const handleVoid = async () => { const handleVoid = async () => {
const id = savedPrescription.value?.id const id = savedPrescription.value?.id
if (!id) return if (!id) return
if (Number(savedPrescription.value?.has_prescription_order) === 1) {
feedback.msgWarning('该处方已存在业务订单,无法作废')
return
}
try { try {
await feedback.confirm('确定要作废该处方吗?作废后不可恢复。') await feedback.confirm(Number(savedPrescription.value?.has_prescription_order) === 1
? '确定要作废该处方吗?作废后不可恢复;已提交洛阳药房的订单会先撤销药房订单,关联的业务订单将退回待审核,同诊单重新开方后自动关联到新处方。'
: '确定要作废该处方吗?作废后不可恢复。')
voiding.value = true voiding.value = true
await prescriptionVoid({ id }) await prescriptionVoid({ id })
feedback.msgSuccess('作废成功') 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>
<div v-if="detailData" class="flex items-center gap-2 mr-6"> <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>
</div> </div>
</template> </template>
@@ -201,22 +201,22 @@
<!-- 左侧:处方单 --> <!-- 左侧:处方单 -->
<el-card shadow="never" class="po-panel po-panel-rx border-gray-100 h-full relative overflow-hidden"> <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 class="stamp-inner">审核通过</div>
</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 class="stamp-inner">已驳回</div>
</div> </div>
<template #header> <template #header>
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<span class="font-medium text-[15px]">处方详情</span> <span class="font-medium text-[15px]">处方详情</span>
<span v-if="detailData.doctor_name" class="text-xs text-gray-500"> <span v-if="detailPrescriptionDoctor" class="text-xs text-gray-500">
开方人:<span class="text-primary font-medium">{{ detailData.doctor_name }}</span> 开方人:<span class="text-primary font-medium">{{ detailPrescriptionDoctor }}</span>
</span> </span>
<el-button <el-button
v-if=" v-if="
!readonly && !readonly && isPrimaryPrescription &&
detailData.prescription_id && detailData.prescription_id &&
detailPrescription && detailPrescription &&
!String(detailData.prescription_detail_error || '').trim() !String(detailData.prescription_detail_error || '').trim()
@@ -230,16 +230,17 @@
改患者信息 改患者信息
</el-button> </el-button>
<el-button <el-button
v-if="!readonly && detailData.prescription_id && showPrescriptionAuditFilter" v-if="!readonly && selectedPrescriptionId && showPrescriptionAuditFilter"
type="primary" type="primary"
size="small" size="small"
link link
@click="emit('view-prescription')" :disabled="linkedPrescriptionLoading"
@click="emit('view-prescription', selectedPrescriptionId)"
> >
详细 详细
</el-button> </el-button>
<el-button <el-button
v-if="!readonly && detailData.id && showPrescriptionAuditFilter" v-if="!readonly && isPrimaryPrescription && detailData.id && showPrescriptionAuditFilter"
type="warning" type="warning"
size="small" size="small"
link link
@@ -250,17 +251,26 @@
测试价格 测试价格
</el-button> </el-button>
</div> </div>
<span class="text-xs text-gray-400">ID: {{ detailData.prescription_id || '—' }}</span> <span class="text-xs text-gray-400">ID: {{ selectedPrescriptionId || '—' }}</span>
</div> </div>
</template> </template>
<LinkedOrderPrescriptionSelect
:options="linkedPrescriptionOptions"
:model-value="selectedPrescriptionId"
class="mb-3"
@change="selectLinkedPrescription"
/>
<el-skeleton v-if="linkedPrescriptionLoading" :rows="5" animated />
<el-alert <el-alert
v-if="!readonly && String(detailData.prescription_detail_error || '').trim()" v-else-if="(!readonly || !isPrimaryPrescription) && selectedPrescriptionError"
:title="detailData.prescription_detail_error" :title="selectedPrescriptionError"
type="warning" type="warning"
:closable="false" :closable="false"
show-icon show-icon
class="mb-3" class="mb-3"
/> >
<el-button v-if="!isPrimaryPrescription" link type="primary" @click="selectLinkedPrescription(selectedPrescriptionId)">重试</el-button>
</el-alert>
<template v-else-if="detailPrescription"> <template v-else-if="detailPrescription">
<el-descriptions :column="2" border size="small" class="po-desc bg-white"> <el-descriptions :column="2" border size="small" class="po-desc bg-white">
<el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item> <el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
@@ -271,13 +281,13 @@
<el-descriptions-item label="手机"> <el-descriptions-item label="手机">
<span <span
:class=" :class="
detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : '' isPrimaryPrescription && detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
" "
> >
{{ detailPrescription.phone || '—' }} {{ detailPrescription.phone || '—' }}
</span> </span>
<el-tag <el-tag
v-if="detailRecipientRxPhoneMismatch" v-if="isPrimaryPrescription && detailRecipientRxPhoneMismatch"
type="danger" type="danger"
size="small" size="small"
effect="dark" effect="dark"
@@ -293,7 +303,8 @@
{{ detailPrescription.clinical_diagnosis || '—' }} {{ detailPrescription.clinical_diagnosis || '—' }}
</el-descriptions-item> </el-descriptions-item>
<el-descriptions-item label="剂数 / 用法" :span="2" v-if="showPrescriptionAuditFilter"> <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 || '—' }} {{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
</el-descriptions-item> </el-descriptions-item>
<el-descriptions-item label="处方金额"> <el-descriptions-item label="处方金额">
@@ -313,7 +324,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'"> <template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋 · {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button <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']" v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary" type="primary"
size="small" size="small"
@@ -337,7 +348,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'"> <template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋 · {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button <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']" v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary" type="primary"
size="small" size="small"
@@ -362,7 +373,7 @@
<span>服用方式</span> <span>服用方式</span>
<el-button <el-button
v-if=" v-if="
!readonly && !readonly && isPrimaryPrescription &&
detailData.prescription_id && detailData.prescription_id &&
detailPrescription && detailPrescription &&
!String(detailData.prescription_detail_error || '').trim() !String(detailData.prescription_detail_error || '').trim()
@@ -416,7 +427,7 @@
}} }}
</div> </div>
</template> </template>
<div> <div v-if="isPrimaryPrescription">
<span class="text-gray-500">订单设置:</span> <span class="text-gray-500">订单设置:</span>
{{ {{
detailData.medication_days != null && detailData.medication_days != null &&
@@ -500,6 +511,17 @@
{{ formatOrderTime(row.create_time) }} {{ formatOrderTime(row.create_time) }}
</template> </template>
</el-table-column> </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-table>
<el-empty v-else description="无未关联的收款单" :image-size="60" /> <el-empty v-else description="无未关联的收款单" :image-size="60" />
</el-card> </el-card>
@@ -563,16 +585,15 @@
{{ formatOrderTime(row.create_time) }} {{ formatOrderTime(row.create_time) }}
</template> </template>
</el-table-column> </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 }"> <template #default="{ row }">
<el-button <el-button
type="danger" type="danger"
size="small" size="small"
link link
:loading="unlinkPayOrderId === Number(row.id)" :loading="unlinkingReceiptId === Number(row.id)"
:disabled="unlinkPayOrderId !== null || ![2, 5].includes(Number(row.status))" :disabled="changingReceipts || ![2, 4, 5].includes(Number(row.status))"
:title="Number(row.status) === 4 ? '已退款收款记录不可移除' : '解除关联并更新已付金额,总金额不变'" @click="confirmUnlinkReceipt(row)"
@click="confirmUnlinkPayOrder(row)"
>移除</el-button> >移除</el-button>
</template> </template>
</el-table-column> </el-table-column>
@@ -964,6 +985,22 @@
:rules="patchUsageRules" :rules="patchUsageRules"
label-width="108px" 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> <div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
<el-form-item <el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'" v-if="detailPrescription?.prescription_type === '浓缩水丸'"
@@ -988,6 +1025,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="patchUsageForm.usage_days" v-model="patchUsageForm.usage_days"
:disabled="daysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -1022,6 +1060,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="patchUsageForm.aux_usage_days" v-model="patchUsageForm.aux_usage_days"
:disabled="daysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -1037,6 +1076,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="patchUsageForm.medication_days" v-model="patchUsageForm.medication_days"
:disabled="daysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -1066,13 +1106,14 @@ import {
prescriptionOrderAddLog, prescriptionOrderAddLog,
prescriptionOrderLogisticsTrace, prescriptionOrderLogisticsTrace,
prescriptionOrderLogisticsJdUpdate, prescriptionOrderLogisticsJdUpdate,
prescriptionOrderPaidPayOrders,
prescriptionOrderUnlinkPayOrder,
prescriptionOrderPatchPrescriptionUsage prescriptionOrderPatchPrescriptionUsage
} from '@/api/tcm' } from '@/api/tcm'
import { getDictData } from '@/api/app' import { getDictData } from '@/api/app'
import feedback from '@/utils/feedback' import feedback from '@/utils/feedback'
import useUserStore from '@/stores/modules/user' import useUserStore from '@/stores/modules/user'
import LinkedOrderPrescriptionSelect from './LinkedOrderPrescriptionSelect.vue'
import { useLinkedOrderPrescription } from './useLinkedOrderPrescription'
import { usePrescriptionOrderReceipts } from './usePrescriptionOrderReceipts'
import { import {
TCM_ASSISTANT_ROLE_ID, TCM_ASSISTANT_ROLE_ID,
PRESCRIPTION_AUDIT_ROLE_IDS, PRESCRIPTION_AUDIT_ROLE_IDS,
@@ -1130,13 +1171,13 @@ defineSlots<{
/** 抽屉头部左侧扩展(完整版的发货类型切换等) */ /** 抽屉头部左侧扩展(完整版的发货类型切换等) */
'header-extra'?: (props: { detail: any }) => any 'header-extra'?: (props: { detail: any }) => any
/** 抽屉头部右侧操作按钮(审核/发货/退款等) */ /** 抽屉头部右侧操作按钮(审核/发货/退款等) */
'header-actions'?: (props: { detail: any }) => any 'header-actions'?: (props: { detail: any; isPrimaryPrescription: boolean }) => any
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'update-amount'): void (e: 'update-amount'): void
(e: 'patch-rx-patient'): void (e: 'patch-rx-patient'): void
(e: 'view-prescription'): void (e: 'view-prescription', prescriptionId: number): void
(e: 'test-gancao-preview'): void (e: 'test-gancao-preview'): void
(e: 'view-patient'): void (e: 'view-patient'): void
(e: 'detail-changed'): void (e: 'detail-changed'): void
@@ -1159,46 +1200,35 @@ const showPrescriptionAuditFilter = computed(() => {
const detailVisible = ref(false) const detailVisible = ref(false)
const detailLoading = ref(false) const detailLoading = ref(false)
const detailData = ref<Record<string, any> | null>(null) const detailData = ref<Record<string, any> | null>(null)
const detailLogs = ref<any[]>([]) const {
const detailUnlinkedPayOrders = ref<any[]>([]) options: linkedPrescriptionOptions,
const unlinkPayOrderId = ref<number | null>(null) selectedId: selectedPrescriptionId,
const canUnlinkPayOrder = computed(() => isPrimary: isPrimaryPrescription,
!props.readonly && canUpdateAmount(detailData.value) && hasPerm('tcm.prescriptionOrder/unlinkPayOrder') 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
) )
const detailLogs = ref<any[]>([])
async function confirmUnlinkPayOrder(row: { id: number; order_no?: string; amount: number | string; status: number | string }) { const {
const orderId = Number(detailData.value?.id) unlinkedReceipts: detailUnlinkedPayOrders,
const payOrderId = Number(row.id) loadUnlinkedReceipts,
if (!canUnlinkPayOrder.value || !orderId || !payOrderId || unlinkPayOrderId.value !== null) return linkingReceiptId,
if (![2, 5].includes(Number(row.status))) return unlinkingReceiptId,
changingReceipts,
unlinkPayOrderId.value = payOrderId canAttachReceipt,
try { canUnlinkReceipt,
await feedback.confirm( confirmAttachReceipt,
`确定移除收款记录「${row.order_no || '#' + payOrderId}」(¥${formatMoney(row.amount)})?` + confirmUnlinkReceipt
'仅解除关联,原收款记录保留;订单总金额不变,已付金额与需代收金额按剩余关联收款重新计算。' } = usePrescriptionOrderReceipts(detailData, detailVisible, (orderId) => {
) emit('detail-changed')
if (!detailVisible.value || Number(detailData.value?.id) !== orderId) return if (detailVisible.value && Number(detailData.value?.id) === orderId) void fetchLogs(orderId)
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 detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo)) const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo))
const detailLinkedPayOrders = computed(() => { const detailLinkedPayOrders = computed(() => {
@@ -1275,13 +1305,13 @@ const workflowFulfillStatus = computed(() => {
/** 详情抽屉:业务收货手机 vs 处方登记手机 */ /** 详情抽屉:业务收货手机 vs 处方登记手机 */
const detailRecipientRxPhoneMismatch = computed(() => { const detailRecipientRxPhoneMismatch = computed(() => {
const rx = detailPrescription.value?.phone const rx = detailData.value?.prescription?.phone
const biz = detailData.value?.recipient_phone const biz = detailData.value?.recipient_phone
return recipientVsPrescriptionPhoneMismatch(biz, rx) return recipientVsPrescriptionPhoneMismatch(biz, rx)
}) })
const detailPrescriptionPhoneDisplay = computed(() => { const detailPrescriptionPhoneDisplay = computed(() => {
const s = normalizeBizPhone(detailPrescription.value?.phone) const s = normalizeBizPhone(detailData.value?.prescription?.phone)
return s || '—' return s || '—'
}) })
@@ -1353,7 +1383,14 @@ const detailLinkedAppointmentChannelText = computed(() => {
const detailRxHerbs = computed(() => normalizeSlipHerbs(detailPrescription.value?.herbs)) 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 经规范化后的对象,与处方类型一致) */ /** 详情:辅方用法(aux_usage JSON 经规范化后的对象,与处方类型一致) */
const detailAuxUsage = computed(() => { const detailAuxUsage = computed(() => {
@@ -1364,9 +1401,6 @@ const detailAuxUsage = computed(() => {
return normalizeSlipAuxUsageForm(raw, rx.prescription_type || '浓缩水丸') return normalizeSlipAuxUsageForm(raw, rx.prescription_type || '浓缩水丸')
}) })
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
/** 内部成本(财务字段):仅完整版展示 */ /** 内部成本(财务字段):仅完整版展示 */
const showInternalCost = computed( const showInternalCost = computed(
() => !props.readonly && detailData.value?.internal_cost != null && detailData.value?.internal_cost !== '' () => !props.readonly && detailData.value?.internal_cost != null && detailData.value?.internal_cost !== ''
@@ -1440,6 +1474,7 @@ function canAddPrescriptionOrderLog() {
/** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */ /** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */
const canSetRxAuditOnAddLog = computed(() => { const canSetRxAuditOnAddLog = computed(() => {
if (!isPrimaryPrescription.value) return false
if (Number(detailData.value?.prescription_audit_status) === 0 if (Number(detailData.value?.prescription_audit_status) === 0
&& detailData.value?.can_review_prescription === false) return false && detailData.value?.can_review_prescription === false) return false
const u = userStore.userInfo const u = userStore.userInfo
@@ -1508,6 +1543,7 @@ function openPatchUsageDialog() {
feedback.msgWarning('无处方数据') feedback.msgWarning('无处方数据')
return return
} }
if (rx.id && Number(rx.id) !== Number(ord.prescription_id)) return
const aux = detailAuxUsage.value const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1 patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day = 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 detailLogisticsExpress = ref<string>('auto')
const logisticsTraceLoading = ref(false) const logisticsTraceLoading = ref(false)
@@ -1769,11 +1783,15 @@ function requestDetail(id: number) {
return props.detailLoader ? props.detailLoader({ id }) : prescriptionOrderDetail({ id }) 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 去重取消),打开时兜底重试 // 页面级同参数字典请求会取消抽屉挂载时的那次(axios 去重取消),打开时兜底重试
void loadServicePackageOptions() void loadServicePackageOptions()
// 显式彻底清空缓存,防止前一次弹窗的数据残留 // 显式彻底清空缓存,防止前一次弹窗的数据残留
detailData.value = null detailData.value = null
resetLinkedPrescription()
detailUnlinkedPayOrders.value = [] detailUnlinkedPayOrders.value = []
bumpLogisticsTraceRequestToken() bumpLogisticsTraceRequestToken()
detailLogisticsExpress.value = 'auto' detailLogisticsExpress.value = 'auto'
@@ -1784,6 +1802,7 @@ async function open(id: number) {
detailLoading.value = true detailLoading.value = true
try { try {
const res: any = await requestDetail(id) const res: any = await requestDetail(id)
if (request !== detailOpenRequest || !detailVisible.value) return
const d = res?.data ?? res ?? null const d = res?.data ?? res ?? null
detailData.value = d detailData.value = d
if (d) { if (d) {
@@ -1795,29 +1814,27 @@ async function open(id: number) {
} }
if (props.loadRelatedData) fetchLogs(id) if (props.loadRelatedData) fetchLogs(id)
// 加载未关联的支付单 if (props.loadRelatedData) void loadUnlinkedReceipts(d)
const diagId = d.diagnosis_id if (prescriptionId) void selectLinkedPrescription(prescriptionId)
const linkedIds = d.pay_order_ids || []
if (props.loadRelatedData && diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, linkedIds)
}
} }
} catch (e: any) { } catch (e: any) {
if (request !== detailOpenRequest || !detailVisible.value) return
feedback.msgError(e?.message || '加载失败') feedback.msgError(e?.message || '加载失败')
detailVisible.value = false detailVisible.value = false
} finally { } finally {
detailLoading.value = false if (request === detailOpenRequest) detailLoading.value = false
} }
} }
/** 静默刷新当前详情(含日志/未关联支付单;快递单号变化时重拉轨迹),供父页面操作成功后调用 */ /** 静默刷新当前详情(含日志/未关联支付单;快递单号变化时重拉轨迹),供父页面操作成功后调用 */
async function refresh() { async function refresh() {
const id = Number(detailData.value?.id) const current = detailData.value
const id = Number(current?.id)
if (!id) return if (!id) return
try { try {
const res: any = await requestDetail(id) const res: any = await requestDetail(id)
const d = res?.data ?? res ?? null const d = res?.data ?? res ?? null
if (!d) return if (!d || detailData.value !== current) return
const prevTracking = String(detailData.value?.tracking_number || '').trim() const prevTracking = String(detailData.value?.tracking_number || '').trim()
detailData.value = d detailData.value = d
const nextTracking = String(d.tracking_number || '').trim() const nextTracking = String(d.tracking_number || '').trim()
@@ -1827,10 +1844,7 @@ async function refresh() {
void fetchLogisticsTrace() void fetchLogisticsTrace()
} }
if (props.loadRelatedData) await fetchLogs(id) if (props.loadRelatedData) await fetchLogs(id)
const diagId = d.diagnosis_id if (props.loadRelatedData) void loadUnlinkedReceipts(d)
if (props.loadRelatedData && diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
}
} catch { } catch {
/* 静默失败,避免打断当前抽屉 */ /* 静默失败,避免打断当前抽屉 */
} }
@@ -168,6 +168,7 @@ export function logActionText(act: string) {
ship: '确认发货', ship: '确认发货',
withdraw: '撤销', withdraw: '撤销',
link_pay_order: '关联支付单', link_pay_order: '关联支付单',
bind_prescription: '绑定关联处方',
unlink_pay_order: '移除收款关联', unlink_pay_order: '移除收款关联',
completion_request: '完单申请', completion_request: '完单申请',
auto_complete: '自动完成', 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
}
}
+217 -159
View File
@@ -221,11 +221,17 @@
{{ formatListCreateTime(row.create_time) }} {{ formatListCreateTime(row.create_time) }}
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="操作" width="340" fixed="right"> <el-table-column label="操作" width="390" fixed="right">
<template #default="{ row }"> <template #default="{ row }">
<el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']"> <el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']">
查看 查看
</el-button> </el-button>
<el-button
v-if="canViewLinkedOrders"
type="primary"
link
@click="linkedOrdersDialog?.open(row)"
>关联订单</el-button>
<el-button <el-button
v-if="Number(row.void_status) !== 1" v-if="Number(row.void_status) !== 1"
type="primary" type="primary"
@@ -283,7 +289,7 @@
审核 审核
</el-button> </el-button>
<el-button <el-button
v-if="canVoidPendingPrescription(row)" v-if="canVoidPrescription(row)"
v-perms="['tcm.prescription/void']" v-perms="['tcm.prescription/void']"
type="danger" type="danger"
link link
@@ -378,7 +384,7 @@
class="cf-prescription-drawer" class="cf-prescription-drawer"
:close-on-click-modal="false" :close-on-click-modal="false"
destroy-on-close destroy-on-close
@close="showEdit = false" @close="showEdit = false"
@closed="onEditDialogClosed" @closed="onEditDialogClosed"
> >
<!-- 查看:A4 处方笺 --> <!-- 查看:A4 处方笺 -->
@@ -388,13 +394,13 @@
{{ viewDetailError }} {{ viewDetailError }}
<el-button v-if="slipView?.id" link type="primary" @click="handleView(slipView)">重试加载</el-button> <el-button v-if="slipView?.id" link type="primary" @click="handleView(slipView)">重试加载</el-button>
</div> </div>
<EsignPrescriptionPanel <EsignPrescriptionPanel
v-if="showEdit && slipView?.id && !viewDetailLoading && !viewDetailError" v-if="showEdit && slipView?.id && !viewDetailLoading && !viewDetailError"
:key="slipView.id" :key="slipView.id"
:prescription-id="Number(slipView.id)" :prescription-id="Number(slipView.id)"
:initial-state="slipView.esign" :initial-state="slipView.esign"
@status-change="onEsignStatusChange" @status-change="onEsignStatusChange"
/> />
<!-- 顶部工具栏(不打印 / 不下载) --> <!-- 顶部工具栏(不打印 / 不下载) -->
<div class="rx-toolbar"> <div class="rx-toolbar">
<el-tag <el-tag
@@ -420,17 +426,17 @@
size="small" size="small"
>{{ listAuditStatusLabel(slipView) }}</el-tag> >{{ listAuditStatusLabel(slipView) }}</el-tag>
<el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag> <el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag>
<el-tag v-if="slipView && pendingEsignAudit(slipView)" type="warning" size="small" effect="plain"> <el-tag v-if="slipView && pendingEsignAudit(slipView)" type="warning" size="small" effect="plain">
{{ slipView.esign.status_label }} {{ slipView.esign.status_label }}
</el-tag> </el-tag>
<div class="flex-1" /> <div class="flex-1" />
<el-button <el-button
v-if="slipView && !viewDetailLoading && canOpenPrescriptionAudit(slipView)" v-if="slipView && !viewDetailLoading && canOpenPrescriptionAudit(slipView)"
v-perms="['cf.prescription/audit']" v-perms="['cf.prescription/audit']"
type="warning" type="warning"
size="small" size="small"
@click="openAuditDialog(slipView)" @click="openAuditDialog(slipView)"
>审核</el-button> >审核</el-button>
<el-button <el-button
v-if="slipView && !viewDetailLoading && !viewDetailError && canReissuePrescription(slipView)" v-if="slipView && !viewDetailLoading && !viewDetailError && canReissuePrescription(slipView)"
type="primary" type="primary"
@@ -439,17 +445,27 @@
:disabled="reissuingPrescriptionId !== 0" :disabled="reissuingPrescriptionId !== 0"
@click="handleReissue(slipView)" @click="handleReissue(slipView)"
>重新开方</el-button> >重新开方</el-button>
<el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button> <el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
<el-button <el-dropdown
type="primary" trigger="click"
:icon="Download" :disabled="viewDetailLoading || downloadingSlip"
size="small" @command="handleDownloadSlip"
:loading="downloadingSlip"
:disabled="viewDetailLoading || (requiresOriginalEsignPdf(slipView?.esign) && !slipView?.esign?.can_download)"
@click="handleDownloadSlip"
> >
{{ requiresOriginalEsignPdf(slipView?.esign) ? '下载已签原始 PDF' : '下载 PDF (A4)' }} <el-button type="primary" :icon="Download" size="small" :loading="downloadingSlip">
</el-button> 下载 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> </div>
<!-- 状态提示(不进入打印区) --> <!-- 状态提示(不进入打印区) -->
@@ -480,10 +496,21 @@
:before-leave="() => !downloadingSlip" :before-leave="() => !downloadingSlip"
> >
<el-tab-pane label="药房联" name="internal"> <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>
<el-tab-pane label="处方联" name="user"> <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-tab-pane>
</el-tabs> </el-tabs>
@@ -1126,12 +1153,12 @@
<el-input v-model="editForm.doctor_name" placeholder="请输入医师姓名" /> <el-input v-model="editForm.doctor_name" placeholder="请输入医师姓名" />
</el-form-item> </el-form-item>
<el-alert v-if="esignError" type="error" :closable="false" class="mb-3"> <el-alert v-if="esignError" type="error" :closable="false" class="mb-3">
{{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button> {{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button>
</el-alert> </el-alert>
<el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3" <el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3"
:title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,先上传处方,再由开方医生本人签署。' : '保存草稿后,先上传处方,再由开方医生本人签署。'" /> :title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,先上传处方,再由开方医生本人签署。' : '保存草稿后,先上传处方,再由开方医生本人签署。'" />
<el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required> <el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required>
<div class="signature-pad-wrap"> <div class="signature-pad-wrap">
<canvas <canvas
ref="signatureCanvasRef" ref="signatureCanvasRef"
@@ -1156,8 +1183,8 @@
</template> </template>
<template v-else> <template v-else>
<el-button @click="showEdit = false">取消</el-button> <el-button @click="showEdit = false">取消</el-button>
<el-button type="primary" @click="handleSubmit" :loading="submitLoading || esignLoading" :disabled="!esignReady"> <el-button type="primary" @click="handleSubmit" :loading="submitLoading || esignLoading" :disabled="!esignReady">
{{ esignEnabled ? '保存处方草稿' : '确定' }} {{ esignEnabled ? '保存处方草稿' : '确定' }}
</el-button> </el-button>
</template> </template>
</template> </template>
@@ -1679,7 +1706,7 @@
<el-dialog v-model="auditDialogVisible" title="处方审核" width="min(1280px, 96vw)" top="5vh" append-to-body destroy-on-close @closed="auditRemark = ''"> <el-dialog v-model="auditDialogVisible" title="处方审核" width="min(1280px, 96vw)" top="5vh" append-to-body destroy-on-close @closed="auditRemark = ''">
<PrescriptionAuditLayout <PrescriptionAuditLayout
:prescription-id="auditTargetId" :prescription-id="auditTargetId"
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at" :doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time" :pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
> >
@@ -1708,11 +1735,13 @@
</PrescriptionAuditLayout> </PrescriptionAuditLayout>
<template #footer> <template #footer>
<el-button @click="auditDialogVisible = false">取消</el-button> <el-button @click="auditDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="auditLoading" :disabled="!canApproveAudit" @click="submitAudit('approve')">审核通过</el-button> <el-button type="primary" :loading="auditLoading" :disabled="!canApproveAudit" @click="submitAudit('approve')">审核通过</el-button>
<el-button type="danger" :loading="auditLoading" @click="submitAudit('reject')">驳回处方</el-button> <el-button type="danger" :loading="auditLoading" @click="submitAudit('reject')">驳回处方</el-button>
</template> </template>
</el-dialog> </el-dialog>
<PrescriptionLinkedOrdersDialog v-if="canViewLinkedOrders" ref="linkedOrdersDialog" @bound="getLists()" />
<!-- 与 tcm/diagnosis/edit 同一套诊单界面(只读 + 全部分页签) --> <!-- 与 tcm/diagnosis/edit 同一套诊单界面(只读 + 全部分页签) -->
<TcmDiagnosisEditView ref="diagnosisViewRef" /> <TcmDiagnosisEditView ref="diagnosisViewRef" />
</div> </div>
@@ -1748,13 +1777,14 @@ import DaterangePicker from '@/components/daterange-picker/index.vue'
import MedicineNameSelect from '@/components/medicine-name-select/index.vue' import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
import PrescriptionSlip from '@/components/prescription-slip/index.vue' import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue' import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue' import PrescriptionLinkedOrdersDialog from './components/PrescriptionLinkedOrdersDialog.vue'
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig' import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign' import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
import type { PrescriptionEsignStatus } from '@/api/tcm' 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 { prescriptionListSigningStatus } from './components/prescription-list-signing-status'
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue' import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue' import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import html2canvas from 'html2canvas' import html2canvas from 'html2canvas'
import jsPDF from 'jspdf' import jsPDF from 'jspdf'
@@ -1896,6 +1926,8 @@ const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄
const userStore = useUserStore() const userStore = useUserStore()
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
const linkedOrdersDialog = ref<InstanceType<typeof PrescriptionLinkedOrdersDialog>>()
const canViewLinkedOrders = computed(() => hasPermission(['tcm.prescriptionOrder/prescriptionOrdersForBinding']))
function goBusinessOrderList() { function goBusinessOrderList() {
const hit = router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists') const hit = router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists')
@@ -1938,51 +1970,51 @@ const SIGNATURE_CSS_W = 560
const SIGNATURE_CSS_H = 168 const SIGNATURE_CSS_H = 168
/** 查看模式:处方笺数据源(先列表行,再详情覆盖) */ /** 查看模式:处方笺数据源(先列表行,再详情覆盖) */
const slipView = ref<Record<string, any> | null>(null) const slipView = ref<Record<string, any> | null>(null)
const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig() const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig()
const canManageCaSigning = computed(() => Number(userStore.userInfo?.root) === 1) const canManageCaSigning = computed(() => Number(userStore.userInfo?.root) === 1)
const caSigningSettingsVisible = ref(false) const caSigningSettingsVisible = ref(false)
const caSigningSettingsEnabled = ref(false) const caSigningSettingsEnabled = ref(false)
const caSigningSettingsSaving = ref(false) const caSigningSettingsSaving = ref(false)
const caSigningSettingsSaveError = ref('') const caSigningSettingsSaveError = ref('')
const canSaveCaSigningSettings = computed( const canSaveCaSigningSettings = computed(
() => canManageCaSigning.value && esignReady.value && !esignLoading.value && !caSigningSettingsSaving.value () => canManageCaSigning.value && esignReady.value && !esignLoading.value && !caSigningSettingsSaving.value
) )
async function loadCaSigningSettings() { async function loadCaSigningSettings() {
if (!canManageCaSigning.value || caSigningSettingsSaving.value) return if (!canManageCaSigning.value || caSigningSettingsSaving.value) return
caSigningSettingsSaveError.value = '' caSigningSettingsSaveError.value = ''
if (await loadEsignConfig()) { if (await loadEsignConfig()) {
caSigningSettingsEnabled.value = esignConfig.value?.enabled === true caSigningSettingsEnabled.value = esignConfig.value?.enabled === true
} }
} }
function openCaSigningSettings() { function openCaSigningSettings() {
if (!canManageCaSigning.value) return if (!canManageCaSigning.value) return
caSigningSettingsVisible.value = true caSigningSettingsVisible.value = true
void loadCaSigningSettings() void loadCaSigningSettings()
} }
async function saveCaSigningSettings() { async function saveCaSigningSettings() {
if (!canSaveCaSigningSettings.value) return if (!canSaveCaSigningSettings.value) return
caSigningSettingsSaving.value = true caSigningSettingsSaving.value = true
caSigningSettingsSaveError.value = '' caSigningSettingsSaveError.value = ''
try { try {
const enabled = caSigningSettingsEnabled.value const enabled = caSigningSettingsEnabled.value
const config = await prescriptionEsignSetConfig({ enabled }) const config = await prescriptionEsignSetConfig({ enabled })
if (config?.enabled !== enabled) throw new Error('保存结果与所选设置不一致') if (config?.enabled !== enabled) throw new Error('保存结果与所选设置不一致')
esignConfig.value = config esignConfig.value = config
caSigningSettingsVisible.value = false caSigningSettingsVisible.value = false
feedback.msgSuccess('CA 签名设置已保存') feedback.msgSuccess('CA 签名设置已保存')
void getLists({ silent: true }).catch(() => {}) void getLists({ silent: true }).catch(() => {})
} catch { } catch {
caSigningSettingsSaveError.value = '保存未完成,当前选择已保留,请重试。' caSigningSettingsSaveError.value = '保存未完成,当前选择已保留,请重试。'
} finally { } finally {
caSigningSettingsSaving.value = false caSigningSettingsSaving.value = false
} }
} }
const onEsignStatusChange = (state: PrescriptionEsignStatus) => { const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
const previous = slipView.value?.esign const previous = slipView.value?.esign
if (slipView.value && state.review_submitted_at !== undefined) { if (slipView.value && state.review_submitted_at !== undefined) {
slipView.value.review_submitted_at = state.review_submitted_at slipView.value.review_submitted_at = state.review_submitted_at
@@ -1995,7 +2027,7 @@ const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
|| previous?.can_review_prescription !== state.can_review_prescription) { || previous?.can_review_prescription !== state.can_review_prescription) {
void getLists({ silent: true }).catch(() => {}) void getLists({ silent: true }).catch(() => {})
} }
} }
const viewDetailLoading = ref(false) const viewDetailLoading = ref(false)
const viewDetailError = ref('') const viewDetailError = ref('')
let viewDetailRequest: AbortController | undefined let viewDetailRequest: AbortController | undefined
@@ -2009,7 +2041,7 @@ const reissuingPrescriptionId = ref(0)
const auditTargetId = ref(0) const auditTargetId = ref(0)
const auditRemark = ref('') const auditRemark = ref('')
const auditLoading = ref(false) const auditLoading = ref(false)
const auditEsign = ref<PrescriptionEsignStatus | null>(null) const auditEsign = ref<PrescriptionEsignStatus | null>(null)
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null) const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
const canApproveAudit = computed(() => ( const canApproveAudit = computed(() => (
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
@@ -2028,7 +2060,10 @@ const patchPatientForm = reactive({
const patchPatientRules: FormRules = { const patchPatientRules: FormRules = {
patient_name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }], patient_name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
gender: [{ required: true, message: '请选择性别', trigger: 'change' }], 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>) { function openPatchPatientDialog(row: Record<string, unknown>) {
@@ -2859,18 +2894,25 @@ function handlePrintSlip() {
}) })
} }
/* === 下载 PDF(A4) === */ /* === 下载 PDF(A4):CA 签署原件,或按当前笺面样式导出药房联 / 处方联 === */
async function handleDownloadSlip() { async function handleDownloadSlip(command: 'esign' | 'internal' | 'user') {
if (downloadingSlip.value) return if (downloadingSlip.value || !slipView.value) return
downloadingSlip.value = true if (command === 'esign') {
try { downloadingSlip.value = true
if (await downloadPrescriptionPdfIfRequired(Number(slipView.value?.id))) return try {
} catch (e: any) { await downloadOriginalEsignPdf(Number(slipView.value.id))
feedback.msgError(e?.message || '下载签署文件失败') } catch (e: any) {
return feedback.msgError(e?.message || '下载签署文件失败')
} finally { } finally {
downloadingSlip.value = false downloadingSlip.value = false
} }
return
}
// 切到对应联次再截图,导出与页面一致的样式(含医师 / 药师签章)。
if (prescriptionTabType.value !== command) {
prescriptionTabType.value = command
await nextTick()
}
const node = getRxPaperEl() const node = getRxPaperEl()
if (!node) { if (!node) {
feedback.msgWarning('处方笺尚未渲染完成') feedback.msgWarning('处方笺尚未渲染完成')
@@ -2957,7 +2999,8 @@ async function handleDownloadSlip() {
const name = (slipView.value as any)?.patient_name || '处方' const name = (slipView.value as any)?.patient_name || '处方'
const id = (slipView.value as any)?.id || '' const id = (slipView.value as any)?.id || ''
const date = (slipView.value as any)?.prescription_date || '' 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) { } catch (e: any) {
console.error('下载处方 PDF 失败:', e) console.error('下载处方 PDF 失败:', e)
feedback.msgError(e?.message || '下载失败,请重试') feedback.msgError(e?.message || '下载失败,请重试')
@@ -3138,7 +3181,7 @@ const rules: FormRules = {
{ {
required: true, required: true,
validator: (_rule, v, cb) => { validator: (_rule, v, cb) => {
if (!esignEnabled.value && (!v || !String(v).trim())) { if (!esignEnabled.value && (!v || !String(v).trim())) {
cb(new Error('请使用电子签名板手写医师签名')) cb(new Error('请使用电子签名板手写医师签名'))
} else { } else {
cb() cb()
@@ -3327,10 +3370,10 @@ function isApprovedActivePrescription(row: { audit_status?: number; void_status?
return Number(row.audit_status) === 1 && Number(row.void_status) !== 1 return Number(row.audit_status) === 1 && Number(row.void_status) !== 1
} }
function isPendingPrescriptionAudit(row: { audit_status?: number | string; void_status?: number | string }) { function isPendingPrescriptionAudit(row: { audit_status?: number | string; void_status?: number | string }) {
return (row.audit_status === 0 || row.audit_status === '0') && Number(row.void_status) !== 1 return (row.audit_status === 0 || row.audit_status === '0') && Number(row.void_status) !== 1
} }
type VoidablePrescriptionRow = Parameters<typeof isPendingPrescriptionAudit>[0] & { type VoidablePrescriptionRow = Parameters<typeof isPendingPrescriptionAudit>[0] & {
id?: number | string id?: number | string
can_void?: boolean can_void?: boolean
@@ -3338,17 +3381,20 @@ type VoidablePrescriptionRow = Parameters<typeof isPendingPrescriptionAudit>[0]
can_review_prescription?: boolean can_review_prescription?: boolean
} }
function canVoidPendingPrescription(row: VoidablePrescriptionRow) { /** 作废不再限于待审核:签署、审核通过或已有业务订单后也可作废(以服务端 can_void 为准) */
return isPendingPrescriptionAudit(row) && row.can_void === true function canVoidPrescription(row: VoidablePrescriptionRow) {
return Number(row.void_status) !== 1 && row.can_void === true
} }
async function voidPendingPrescription(row: VoidablePrescriptionRow) { async function voidPendingPrescription(row: VoidablePrescriptionRow) {
const id = Number(row.id) 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 voidingPrescriptionId.value = id
try { try {
await feedback.confirm('确定作废这张处方吗?作废后可重新开方。') await feedback.confirm(Number((row as { has_prescription_order?: number }).has_prescription_order) === 1
await prescriptionVoid({ id, pending_only: true }) ? '确定作废这张处方吗?已提交洛阳药房的订单会先撤销药房订单;关联的业务订单将退回待审核,同诊单重新开方后自动关联到新处方。'
: '确定作废这张处方吗?作废后可重新开方。')
await prescriptionVoid({ id })
row.void_status = 1 row.void_status = 1
row.can_void = false row.can_void = false
row.can_submit_for_review = false row.can_submit_for_review = false
@@ -3366,11 +3412,11 @@ function canOpenPrescriptionAudit(row: { audit_status?: number | string; void_st
return isPendingPrescriptionAudit(row) && row.can_review_prescription === true return isPendingPrescriptionAudit(row) && row.can_review_prescription === true
} }
function pendingEsignAudit(row: { audit_status?: number | string; void_status?: number | string; esign?: PrescriptionEsignStatus }) { function pendingEsignAudit(row: { audit_status?: number | string; void_status?: number | string; esign?: PrescriptionEsignStatus }) {
return isPendingPrescriptionAudit(row) && row.esign?.required === true && row.esign.awaiting_upload !== true return isPendingPrescriptionAudit(row) && row.esign?.required === true && row.esign.awaiting_upload !== true
&& !canApprovePrescriptionEsign(row.esign) && !canApprovePrescriptionEsign(row.esign)
} }
function formatAuditTime(ts: number | null | undefined) { function formatAuditTime(ts: number | null | undefined) {
if (!ts) return '' if (!ts) return ''
const d = new Date(ts * 1000) const d = new Date(ts * 1000)
@@ -3616,21 +3662,21 @@ async function submitPrescriptionForReview(row: Record<string, any>) {
function openAuditDialog(row: Record<string, any>) { function openAuditDialog(row: Record<string, any>) {
if (auditLoading.value || !canOpenPrescriptionAudit(row)) return if (auditLoading.value || !canOpenPrescriptionAudit(row)) return
auditTargetId.value = Number(row.id) auditTargetId.value = Number(row.id)
auditEsign.value = null auditEsign.value = null
auditReview.value = null auditReview.value = null
auditRemark.value = '' auditRemark.value = ''
auditDialogVisible.value = true auditDialogVisible.value = true
} }
function onAuditEsignStatusChange(state: PrescriptionEsignStatus) { function onAuditEsignStatusChange(state: PrescriptionEsignStatus) {
const justSigned = auditEsign.value && !canApproveAudit.value && state.status === 'signed' const justSigned = auditEsign.value && !canApproveAudit.value && state.status === 'signed'
&& canApprovePrescriptionEsign(state) && canApprovePrescriptionEsign(state)
auditEsign.value = state auditEsign.value = state
if (justSigned) { if (justSigned) {
if (Number(slipView.value?.id) === auditTargetId.value && slipView.value) slipView.value.esign = state if (Number(slipView.value?.id) === auditTargetId.value && slipView.value) slipView.value.esign = state
else void getLists() else void getLists()
} }
} }
function onAuditReviewChange(state: import('@/api/tcm').PrescriptionEsignReviewStatus | null) { function onAuditReviewChange(state: import('@/api/tcm').PrescriptionEsignReviewStatus | null) {
auditReview.value = state auditReview.value = state
@@ -3641,9 +3687,9 @@ function onAuditReviewChange(state: import('@/api/tcm').PrescriptionEsignReviewS
void getLists() void getLists()
} }
} }
async function submitAudit(action: 'approve' | 'reject') { async function submitAudit(action: 'approve' | 'reject') {
if (auditLoading.value || (action === 'approve' && !canApproveAudit.value)) return if (auditLoading.value || (action === 'approve' && !canApproveAudit.value)) return
if (action === 'reject' && !auditRemark.value.trim()) { if (action === 'reject' && !auditRemark.value.trim()) {
feedback.msgError('驳回时请填写审核意见') feedback.msgError('驳回时请填写审核意见')
return return
@@ -3660,7 +3706,7 @@ async function submitAudit(action: 'approve' | 'reject') {
feedback.msgWarning(auditData.wecom_notify_hint) feedback.msgWarning(auditData.wecom_notify_hint)
} }
auditDialogVisible.value = false auditDialogVisible.value = false
if (showEdit.value && Number(slipView.value?.id) === auditTargetId.value) showEdit.value = false if (showEdit.value && Number(slipView.value?.id) === auditTargetId.value) showEdit.value = false
getLists() getLists()
} catch { } catch {
/* 拦截器已提示 */ /* 拦截器已提示 */
@@ -4056,7 +4102,7 @@ const resetForm = () => {
const handleAdd = () => openNewPrescription() const handleAdd = () => openNewPrescription()
function openNewPrescription(source?: Record<string, any>) { function openNewPrescription(source?: Record<string, any>) {
void loadEsignConfig() void loadEsignConfig()
isLoadingData.value = !!source isLoadingData.value = !!source
resetForm() resetForm()
if (source) { if (source) {
@@ -4083,10 +4129,22 @@ function openNewPrescription(source?: Record<string, any>) {
}) })
} }
/** 开方权限:与后端 PrescriptionLogic::PRESCRIBE_PERMISSIONS 一致,任一即可(重新开方保存走 /tcm.prescription/add) */
const PRESCRIBE_PERMISSIONS = [
'tcm.prescription/add',
'cf.prescription/add',
'tcm.diagnosis/chufang',
'tcm.diagnosis/kaifang'
]
/** 已作废处方(含他人所开、他人作废)均可由有开方权限的账号重新开方;新处方以当前账号为开方医生 */
function canReissuePrescription(row: { creator_id?: number | string; void_status?: number | string }) { function canReissuePrescription(row: { creator_id?: number | string; void_status?: number | string }) {
const doctorId = Number(userStore.userInfo?.id) const doctorId = Number(userStore.userInfo?.id)
return Number(row.void_status) === 1 && doctorId > 0 && Number(row.creator_id) === doctorId return (
&& hasPermission(['cf.prescription/add']) Number(row.void_status) === 1 &&
doctorId > 0 &&
PRESCRIBE_PERMISSIONS.some((perm) => hasPermission([perm]))
)
} }
async function handleReissue(row: { id?: number | string; creator_id?: number | string; void_status?: number | string }) { async function handleReissue(row: { id?: number | string; creator_id?: number | string; void_status?: number | string }) {
@@ -4141,7 +4199,7 @@ const handleView = async (row: any) => {
// 编辑处方 // 编辑处方
const handleEdit = async (row: any) => { const handleEdit = async (row: any) => {
await loadEsignConfig() await loadEsignConfig()
editingWasVoid.value = Number(row.void_status) === 1 editingWasVoid.value = Number(row.void_status) === 1
editingWasRejected.value = Number(row.audit_status) === 2 editingWasRejected.value = Number(row.audit_status) === 2
editMode.value = 'edit' editMode.value = 'edit'
@@ -4240,8 +4298,8 @@ function fillPrescriptionContents(src: Record<string, any>) {
// 提交表单 // 提交表单
const handleSubmit = async () => { const handleSubmit = async () => {
if (submitLoading.value) return if (submitLoading.value) return
if (!esignReady.value && !(await loadEsignConfig())) return if (!esignReady.value && !(await loadEsignConfig())) return
if (!formRef.value) return if (!formRef.value) return
try { try {
@@ -4250,7 +4308,7 @@ const handleSubmit = async () => {
// Element Plus:校验失败会 reject,表单项已展示错误,勿再向外抛成 Uncaught // Element Plus:校验失败会 reject,表单项已展示错误,勿再向外抛成 Uncaught
return return
} }
if (submitLoading.value) return if (submitLoading.value) return
// 验证药材 // 验证药材
if (!editForm.herbs || editForm.herbs.length === 0) { if (!editForm.herbs || editForm.herbs.length === 0) {
@@ -4276,25 +4334,25 @@ const handleSubmit = async () => {
try { try {
const params: Record<string, unknown> = { ...editForm } const params: Record<string, unknown> = { ...editForm }
let result: any let result: any
if (editMode.value === 'add') { if (editMode.value === 'add') {
params.audit_status = 0 params.audit_status = 0
if (reissueContext.value) { if (reissueContext.value) {
Object.assign(params, reissueContext.value) Object.assign(params, reissueContext.value)
if (!editForm.visit_no.trim()) delete params.visit_no if (!editForm.visit_no.trim()) delete params.visit_no
} }
result = await prescriptionAdd(params) result = await prescriptionAdd(params)
} else { } else {
result = await prescriptionEdit(params) result = await prescriptionEdit(params)
} }
if (esignEnabled.value || requiresOriginalEsignPdf(result?.esign)) { if (esignEnabled.value || requiresOriginalEsignPdf(result?.esign)) {
const id = Number(result?.id || editForm.id) const id = Number(result?.id || editForm.id)
feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态') feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态')
await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign }) await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign })
} else { } else {
feedback.msgSuccess('处方已保存,请在「已开处方」上传') feedback.msgSuccess('处方已保存,请在「已开处方」上传')
showEdit.value = false showEdit.value = false
} }
getLists() getLists()
} catch (error) { } catch (error) {
console.error(error) console.error(error)
@@ -4311,19 +4369,19 @@ const handleDelete = async (id: number) => {
getLists() getLists()
} }
// 从订单页返回缓存的处方列表时,重新读取退款后的占用状态。 // 从订单页返回缓存的处方列表时,重新读取退款后的占用状态。
let refreshOnReturn = false let refreshOnReturn = false
onDeactivated(() => { onDeactivated(() => {
refreshOnReturn = true refreshOnReturn = true
}) })
onActivated(() => { onActivated(() => {
if (!refreshOnReturn) return if (!refreshOnReturn) return
refreshOnReturn = false refreshOnReturn = false
getLists() getLists()
}) })
onMounted(async () => { onMounted(async () => {
void loadEsignConfig() void loadEsignConfig()
await loadRoleOptions() await loadRoleOptions()
await loadRegionData() await loadRegionData()
await loadServicePackageOptions() await loadServicePackageOptions()
@@ -626,7 +626,7 @@
:gancao-preview-loading="gancaoPreviewLoading" :gancao-preview-loading="gancaoPreviewLoading"
@update-amount="openUpdateAmount" @update-amount="openUpdateAmount"
@patch-rx-patient="openPatchRxPatientDialog" @patch-rx-patient="openPatchRxPatientDialog"
@view-prescription="detailData && openPrescriptionView(detailData)" @view-prescription="(id) => detailData && openPrescriptionView(detailData, id)"
@test-gancao-preview="testGancaoPreviewFromDetail" @test-gancao-preview="testGancaoPreviewFromDetail"
@view-patient="openDiagnosisPatientDetailFromOrder" @view-patient="openDiagnosisPatientDetailFromOrder"
@detail-changed="getLists" @detail-changed="getLists"
@@ -655,18 +655,19 @@
>{{ shipModeLabel(detail.ship_mode) }}</el-tag> >{{ shipModeLabel(detail.ship_mode) }}</el-tag>
</div> </div>
</template> </template>
<template #header-actions="{ detail }"> <template #header-actions="{ detail, isPrimaryPrescription }">
<el-button <el-button
v-perms="['tcm.prescriptionOrder/editTime']" v-perms="['tcm.prescriptionOrder/editTime']"
size="small" size="small"
@click="orderTimeDialogRef?.open(detail)" @click="orderTimeDialogRef?.open(detail)"
>修改创建时间</el-button> >修改创建时间</el-button>
<gancao-submission-reconcile-button <gancao-submission-reconcile-button
v-if="isPrimaryPrescription"
:order="detail" :order="detail"
@resolved="handleGancaoSubmissionResolved" @resolved="handleGancaoSubmissionResolved"
/> />
<el-button <el-button
v-if="canUploadPharmacyRow(detail)" v-if="isPrimaryPrescription && canUploadPharmacyRow(detail)"
v-perms="['tcm.prescriptionOrder/uploadToPharmacy']" v-perms="['tcm.prescriptionOrder/uploadToPharmacy']"
type="warning" type="warning"
size="small" size="small"
@@ -675,7 +676,7 @@
@click="confirmUploadToPharmacy(detail)" @click="confirmUploadToPharmacy(detail)"
>上传药房</el-button> >上传药房</el-button>
<el-button <el-button
v-if="canRxAudit(detail)" v-if="isPrimaryPrescription && canRxAudit(detail)"
v-perms="['tcm.prescriptionOrder/auditPrescription']" v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="warning" type="warning"
size="small" size="small"
@@ -685,7 +686,7 @@
处方审核 处方审核
</el-button> </el-button>
<el-button <el-button
v-if="canRevokeRxAudit(detail)" v-if="isPrimaryPrescription && canRevokeRxAudit(detail)"
v-perms="['tcm.prescriptionOrder/auditPrescription']" v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="info" type="info"
size="small" size="small"
@@ -990,6 +991,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="editForm.medication_days" v-model="editForm.medication_days"
:disabled="editDaysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -1636,7 +1638,7 @@
<el-radio-group v-model="addPayOrderForm.add_mode"> <el-radio-group v-model="addPayOrderForm.add_mode">
<el-radio value="create">付呗</el-radio> <el-radio value="create">付呗</el-radio>
<el-radio value="create_express">快递代收</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 value="completion_only">直接完单申请</el-radio>
</el-radio-group> </el-radio-group>
</el-form-item> </el-form-item>
@@ -1800,7 +1802,7 @@
<template #header> <template #header>
<div class="flex items-center justify-between w-full pr-2 gap-3"> <div class="flex items-center justify-between w-full pr-2 gap-3">
<span class="text-base font-medium text-gray-800">查看处方</span> <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 <el-button
size="small" size="small"
:loading="prescriptionSlipExporting" :loading="prescriptionSlipExporting"
@@ -1809,18 +1811,39 @@
> >
下载图片 下载图片
</el-button> </el-button>
<el-button <el-dropdown
size="small" trigger="click"
:loading="prescriptionSlipExporting" :disabled="prescriptionSlipExporting"
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download" @command="downloadPrescriptionSlipPdf"
@click="downloadPrescriptionSlipPdf"
> >
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }} <el-button size="small" type="primary" :loading="prescriptionSlipExporting">下载 PDF (A4)</el-button>
</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>
</div> </div>
</template> </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 <el-tabs
v-if="prescriptionViewData" v-if="prescriptionViewData"
@@ -1856,6 +1879,9 @@
size="small" size="small"
>待审核</el-tag> >待审核</el-tag>
<el-tag v-else type="danger" 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>
<div <div
@@ -1882,7 +1908,7 @@
</div> </div>
<EsignPrescriptionPanel <EsignPrescriptionPanel
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading" v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading && previewIsPrimary"
:key="prescriptionViewData.id" :key="prescriptionViewData.id"
:prescription-id="Number(prescriptionViewData.id)" :prescription-id="Number(prescriptionViewData.id)"
:initial-state="prescriptionViewData.esign" :initial-state="prescriptionViewData.esign"
@@ -1890,11 +1916,13 @@
/> />
<PrescriptionSlip <PrescriptionSlip
v-if="prescriptionViewData" v-if="prescriptionViewData"
:key="previewPrescriptionId"
ref="rxSlipRef" ref="rxSlipRef"
:data="prescriptionViewData" :data="prescriptionViewData"
:variant="prescriptionTabType" :variant="prescriptionTabType"
:aux-library-name="slipAuxLibraryName" :aux-library-name="slipAuxLibraryName"
:title="SLIP_TITLE" :title="SLIP_TITLE"
show-pharmacist-signature-sample
/> />
<!-- 审核痕迹(不进入导出) --> <!-- 审核痕迹(不进入导出) -->
@@ -2086,11 +2114,14 @@
</template> </template>
<script lang="ts" setup name="prescriptionOrderList"> <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 { useRoute } from 'vue-router'
import { ArrowDown, InfoFilled, QuestionFilled, Search, Calendar, Document, Link as LinkIcon, Wallet } from '@element-plus/icons-vue' 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 ListTimeFilter from '@/components/list-time-filter/index.vue'
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.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 PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue' import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
import { import {
@@ -2150,16 +2181,16 @@ import {
prescriptionOrderLinkPayOrder, prescriptionOrderLinkPayOrder,
prescriptionOrderUploadToPharmacy, prescriptionOrderUploadToPharmacy,
prescriptionOrderPreviewGancaoRecipel, prescriptionOrderPreviewGancaoRecipel,
prescriptionDetail,
prescriptionLibraryLists, prescriptionLibraryLists,
getDoctors, getDoctors,
getAssistants getAssistants
} from '@/api/tcm' } 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 EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue' import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import type { PrescriptionEsignStatus } from '@/api/tcm' 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 html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf' import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app' 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 TcmDiagnosisEditView = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
const userStore = useUserStore() const userStore = useUserStore()
const canLinkExistingReceipt = computed(() =>
userStore.perms.includes('*') || userStore.perms.includes('tcm.prescriptionOrder/attachReceipt')
)
const route = useRoute() const route = useRoute()
const orderListPath = route.fullPath
const diagnosisViewRef = ref<{ const diagnosisViewRef = ref<{
openViewOnly: (id: number) => Promise<void> openViewOnly: (id: number) => Promise<void>
@@ -3317,8 +3352,8 @@ async function submitUpdateAmount() {
} }
} }
async function openDetail(id: number) { async function openDetail(id: number, prescriptionId?: number) {
await detailDrawerRef.value?.open(id) await detailDrawerRef.value?.open(id, prescriptionId)
} }
const editVisible = ref(false) const editVisible = ref(false)
@@ -3356,6 +3391,7 @@ const editFormRef = ref<FormInstance>()
const editForm = reactive({ const editForm = reactive({
id: 0, id: 0,
prescription_id: 0, prescription_id: 0,
linked_prescriptions: [] as LinkedPrescription[],
diagnosis_id: 0, diagnosis_id: 0,
recipient_name: '', recipient_name: '',
recipient_phone: '', recipient_phone: '',
@@ -3515,6 +3551,7 @@ const editRules = computed<FormRules>(() => {
function resetEditOrderDialog() { function resetEditOrderDialog() {
editOrderStep.value = 0 editOrderStep.value = 0
editOrderPrescription.value = null editOrderPrescription.value = null
editForm.linked_prescriptions = []
editGancaoLogisticsOnlyMode.value = false editGancaoLogisticsOnlyMode.value = false
editGancaoDisplayNo.value = '' editGancaoDisplayNo.value = ''
editFormRef.value?.clearValidate() editFormRef.value?.clearValidate()
@@ -3543,6 +3580,9 @@ async function goEditOrderNextStep() {
} }
} }
/** 已发货订单服用天数锁定(来自订单详情 days_locked,服务端同样拦截) */
const editDaysLocked = ref(false)
async function openEdit(row: { async function openEdit(row: {
id: number id: number
creator_id?: number creator_id?: number
@@ -3564,6 +3604,7 @@ async function openEdit(row: {
} }
editOrderStep.value = 0 editOrderStep.value = 0
editOrderPrescription.value = null editOrderPrescription.value = null
editForm.linked_prescriptions = []
editVisible.value = true editVisible.value = true
editDialogLoading.value = true editDialogLoading.value = true
try { try {
@@ -3574,6 +3615,7 @@ async function openEdit(row: {
editVisible.value = false editVisible.value = false
return return
} }
editForm.linked_prescriptions = d.linked_prescriptions ?? []
const rx = d.prescription const rx = d.prescription
if (rx && typeof rx === 'object') { if (rx && typeof rx === 'object') {
editOrderPrescription.value = rx as Record<string, any> editOrderPrescription.value = rx as Record<string, any>
@@ -3616,7 +3658,8 @@ async function openEdit(row: {
editForm.shipping_address = d.shipping_address || '' editForm.shipping_address = d.shipping_address || ''
editForm.is_follow_up = d.is_follow_up ? 1 : 0 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_count = d.dose_count > 0 ? d.dose_count : 1
editForm.dose_unit = d.dose_unit || '剂' editForm.dose_unit = d.dose_unit || '剂'
editForm.prev_staff = d.prev_staff || '' 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 () => { onMounted(async () => {
await loadRegionData() await loadRegionData()
await loadServicePackageOptions() await loadServicePackageOptions()
@@ -3970,8 +4024,8 @@ onMounted(async () => {
applyRouteQueryToPrescriptionOrderList() applyRouteQueryToPrescriptionOrderList()
await nextTick() await nextTick()
getLists() getLists()
const reviewOrderId = Number(route.query.review_order) orderListInitialized = true
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId) await openOrderFromRoute()
}) })
// ─── 快捷填写快递单号 ──────────────────────────────────────────── // ─── 快捷填写快递单号 ────────────────────────────────────────────
@@ -4465,7 +4519,7 @@ function openAddPayOrder(row: {
// 加载可用支付单列表,排除当前订单已关联的 // 加载可用支付单列表,排除当前订单已关联的
const diagId = row.diagnosis_id || detailData.value?.diagnosis_id const diagId = row.diagnosis_id || detailData.value?.diagnosis_id
const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || [] const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || []
if (diagId) { if (diagId && canLinkExistingReceipt.value) {
void loadAddPayOrderAvailable(diagId, currentLinkedIds) void loadAddPayOrderAvailable(diagId, currentLinkedIds)
} }
} }
@@ -4585,13 +4639,20 @@ const SLIP_TITLE = `${SLIP_HOSPITAL_NAME} 处方笺`
const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339' const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339'
const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号' const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号'
const prescriptionViewVisible = ref(false) const {
const prescriptionViewLoading = ref(false) visible: prescriptionViewVisible,
const prescriptionViewData = ref<any>(null) loading: prescriptionViewLoading,
/** 药房联辅方标题:处方库中该辅方模板的 prescription_name(导入或药材匹配解析) */ error: prescriptionViewError,
const slipAuxLibraryName = ref('') prescription: prescriptionViewData,
/** 查看处方联次:药房联 / 处方联 */ auxLibraryName: slipAuxLibraryName,
const prescriptionTabType = ref<'internal' | 'user'>('internal') 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 rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
const prescriptionSlipExporting = ref(false) const prescriptionSlipExporting = ref(false)
@@ -4980,64 +5041,6 @@ async function resolveSlipAuxLibraryName(data: Record<string, unknown>): Promise
return '' 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> { async function preloadSlipImagesToDataUrl(el: HTMLElement): Promise<void> {
const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]') const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]')
const tasks = Array.from(imgs).map(async (img) => { const tasks = Array.from(imgs).map(async (img) => {
@@ -5130,7 +5133,8 @@ async function capturePrescriptionSlipCanvas(): Promise<HTMLCanvasElement> {
function slipDownloadBaseName() { function slipDownloadBaseName() {
const name = prescriptionViewData.value?.patient_name const name = prescriptionViewData.value?.patient_name
const safe = typeof name === 'string' && name.trim() ? name.trim().replace(/[\\/:*?"<>|]/g, '_') : '未命名' 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() { async function downloadPrescriptionSlipImage() {
@@ -5150,11 +5154,19 @@ async function downloadPrescriptionSlipImage() {
} }
} }
async function downloadPrescriptionSlipPdf() { /** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
if (!prescriptionViewData.value) return async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
if (!prescriptionViewData.value || !previewCanExport.value) return
prescriptionSlipExporting.value = true prescriptionSlipExporting.value = true
try { 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 canvas = await capturePrescriptionSlipCanvas()
const imgData = canvas.toDataURL('image/jpeg', 0.95) const imgData = canvas.toDataURL('image/jpeg', 0.95)
/** /**
@@ -554,11 +554,12 @@
</div> </div>
<div v-if="detailData" class="po-detail-drawer-actions flex flex-wrap items-center gap-2"> <div v-if="detailData" class="po-detail-drawer-actions flex flex-wrap items-center gap-2">
<gancao-submission-reconcile-button <gancao-submission-reconcile-button
v-if="isPrimaryPrescription"
:order="detailData" :order="detailData"
@resolved="handleGancaoSubmissionResolved" @resolved="handleGancaoSubmissionResolved"
/> />
<el-button <el-button
v-if="canRxAudit(detailData)" v-if="isPrimaryPrescription && canRxAudit(detailData)"
v-perms="['tcm.prescriptionOrder/auditPrescription']" v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="warning" type="warning"
size="small" size="small"
@@ -568,7 +569,7 @@
处方审核 处方审核
</el-button> </el-button>
<el-button <el-button
v-if="canRevokeRxAudit(detailData)" v-if="isPrimaryPrescription && canRevokeRxAudit(detailData)"
v-perms="['tcm.prescriptionOrder/auditPrescription']" v-perms="['tcm.prescriptionOrder/auditPrescription']"
type="info" type="info"
size="small" size="small"
@@ -769,10 +770,10 @@
<!-- 左侧:处方单 --> <!-- 左侧:处方单 -->
<el-card shadow="never" class="po-panel po-panel-rx border-gray-100 h-full relative overflow-hidden"> <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 class="stamp-inner">审核通过</div>
</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 class="stamp-inner">已驳回</div>
</div> </div>
<template #header> <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"> <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="po-panel-rx-header__title font-medium text-[15px] leading-snug">处方详情</span>
<span class="shrink-0 text-xs text-gray-400 tabular-nums"> <span class="shrink-0 text-xs text-gray-400 tabular-nums">
ID: {{ detailData.prescription_id || '—' }} ID: {{ selectedPrescriptionId || '—' }}
</span> </span>
</div> </div>
<div v-if="detailData.doctor_name" class="min-w-0 text-xs leading-snug text-gray-500"> <div v-if="detailPrescriptionDoctor" class="min-w-0 text-xs leading-snug text-gray-500">
开方人:<span class="text-primary font-medium">{{ detailData.doctor_name }}</span> 开方人:<span class="text-primary font-medium">{{ detailPrescriptionDoctor }}</span>
</div> </div>
<div class="flex w-full min-w-0 flex-wrap items-center gap-x-3 gap-y-1"> <div class="flex w-full min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
<el-button <el-button
v-if=" v-if="
isPrimaryPrescription &&
detailData.prescription_id && detailData.prescription_id &&
detailPrescription && detailPrescription &&
!String(detailData.prescription_detail_error || '').trim() !String(detailData.prescription_detail_error || '').trim()
@@ -802,16 +804,17 @@
改患者信息 改患者信息
</el-button> </el-button>
<el-button <el-button
v-if="detailData.prescription_id && showPrescriptionAuditFilter" v-if="selectedPrescriptionId && showPrescriptionAuditFilter"
type="primary" type="primary"
size="small" size="small"
link link
@click="openPrescriptionView(detailData)" :disabled="linkedPrescriptionLoading"
@click="openPrescriptionView(detailData, selectedPrescriptionId)"
> >
详细 详细
</el-button> </el-button>
<el-button <el-button
v-if="detailData.id && showPrescriptionAuditFilter" v-if="isPrimaryPrescription && detailData.id && showPrescriptionAuditFilter"
type="warning" type="warning"
size="small" size="small"
link link
@@ -824,14 +827,23 @@
</div> </div>
</div> </div>
</template> </template>
<LinkedOrderPrescriptionSelect
:options="detailPrescriptionOptions"
:model-value="selectedPrescriptionId"
class="mb-3"
@change="selectLinkedPrescription"
/>
<el-skeleton v-if="linkedPrescriptionLoading" :rows="5" animated />
<el-alert <el-alert
v-if="String(detailData.prescription_detail_error || '').trim()" v-else-if="selectedPrescriptionError"
:title="detailData.prescription_detail_error" :title="selectedPrescriptionError"
type="warning" type="warning"
:closable="false" :closable="false"
show-icon show-icon
class="mb-3" class="mb-3"
/> >
<el-button v-if="!isPrimaryPrescription" link type="primary" @click="selectLinkedPrescription(selectedPrescriptionId)">重试</el-button>
</el-alert>
<template v-else-if="detailPrescription"> <template v-else-if="detailPrescription">
<el-descriptions :column="1" border size="small" class="po-desc bg-white"> <el-descriptions :column="1" border size="small" class="po-desc bg-white">
<el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item> <el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
@@ -842,13 +854,13 @@
<el-descriptions-item label="手机"> <el-descriptions-item label="手机">
<span <span
:class=" :class="
detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : '' isPrimaryPrescription && detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
" "
> >
{{ detailPrescription.phone || '—' }} {{ detailPrescription.phone || '—' }}
</span> </span>
<el-tag <el-tag
v-if="detailRecipientRxPhoneMismatch" v-if="isPrimaryPrescription && detailRecipientRxPhoneMismatch"
type="danger" type="danger"
size="small" size="small"
effect="dark" effect="dark"
@@ -864,7 +876,8 @@
{{ detailPrescription.clinical_diagnosis || '—' }} {{ detailPrescription.clinical_diagnosis || '—' }}
</el-descriptions-item> </el-descriptions-item>
<el-descriptions-item label="剂数 / 用法" :span="2" v-if="showPrescriptionAuditFilter"> <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 || '—' }} {{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
</el-descriptions-item> </el-descriptions-item>
<el-descriptions-item label="处方金额"> <el-descriptions-item label="处方金额">
@@ -884,7 +897,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'"> <template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋 · {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button <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']" v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary" type="primary"
size="small" size="small"
@@ -908,7 +921,7 @@
<template v-if="detailPrescription.prescription_type === '浓缩水丸'"> <template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋 · {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button <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']" v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary" type="primary"
size="small" size="small"
@@ -933,6 +946,7 @@
<span>服用方式</span> <span>服用方式</span>
<el-button <el-button
v-if=" v-if="
isPrimaryPrescription &&
detailData.prescription_id && detailData.prescription_id &&
detailPrescription && detailPrescription &&
!String(detailData.prescription_detail_error || '').trim() !String(detailData.prescription_detail_error || '').trim()
@@ -986,7 +1000,7 @@
}} }}
</div> </div>
</template> </template>
<div> <div v-if="isPrimaryPrescription">
<span class="text-gray-500">订单设置:</span> <span class="text-gray-500">订单设置:</span>
{{ {{
detailData.medication_days != null && detailData.medication_days != null &&
@@ -1079,6 +1093,17 @@
{{ formatOrderTime(row.create_time) }} {{ formatOrderTime(row.create_time) }}
</template> </template>
</el-table-column> </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-table>
<el-empty v-else description="无未关联的收款单" :image-size="60" /> <el-empty v-else description="无未关联的收款单" :image-size="60" />
</el-card> </el-card>
@@ -1142,6 +1167,17 @@
{{ formatOrderTime(row.create_time) }} {{ formatOrderTime(row.create_time) }}
</template> </template>
</el-table-column> </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-table>
<el-empty v-else description="未关联收款单" :image-size="60" /> <el-empty v-else description="未关联收款单" :image-size="60" />
</el-card> </el-card>
@@ -1570,6 +1606,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="editForm.medication_days" v-model="editForm.medication_days"
:disabled="editDaysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -2134,7 +2171,7 @@
<el-radio-group v-model="addPayOrderForm.add_mode"> <el-radio-group v-model="addPayOrderForm.add_mode">
<el-radio value="create">付呗</el-radio> <el-radio value="create">付呗</el-radio>
<el-radio value="create_express">快递代收</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 value="completion_only">直接完单申请</el-radio>
</el-radio-group> </el-radio-group>
</el-form-item> </el-form-item>
@@ -2323,6 +2360,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="patchUsageForm.usage_days" v-model="patchUsageForm.usage_days"
:disabled="patchUsageDaysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -2357,6 +2395,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="patchUsageForm.aux_usage_days" v-model="patchUsageForm.aux_usage_days"
:disabled="patchUsageDaysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -2372,6 +2411,7 @@
<div class="flex items-center gap-1 w-full"> <div class="flex items-center gap-1 w-full">
<el-input-number <el-input-number
v-model="patchUsageForm.medication_days" v-model="patchUsageForm.medication_days"
:disabled="patchUsageDaysLocked"
:min="1" :min="1"
:max="999" :max="999"
:step="1" :step="1"
@@ -2400,7 +2440,7 @@
<template #header> <template #header>
<div class="flex items-center justify-between w-full pr-2 gap-3"> <div class="flex items-center justify-between w-full pr-2 gap-3">
<span class="text-base font-medium text-gray-800">查看处方</span> <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 <el-button
size="small" size="small"
:loading="prescriptionSlipExporting" :loading="prescriptionSlipExporting"
@@ -2409,18 +2449,39 @@
> >
下载图片 下载图片
</el-button> </el-button>
<el-button <el-dropdown
size="small" trigger="click"
:loading="prescriptionSlipExporting" :disabled="prescriptionSlipExporting"
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download" @command="downloadPrescriptionSlipPdf"
@click="downloadPrescriptionSlipPdf"
> >
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }} <el-button size="small" type="primary" :loading="prescriptionSlipExporting">下载 PDF (A4)</el-button>
</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>
</div> </div>
</template> </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 <el-tabs
v-if="prescriptionViewData" v-if="prescriptionViewData"
@@ -2456,6 +2517,9 @@
size="small" size="small"
>待审核</el-tag> >待审核</el-tag>
<el-tag v-else type="danger" 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>
<div <div
@@ -2482,7 +2546,7 @@
</div> </div>
<EsignPrescriptionPanel <EsignPrescriptionPanel
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading" v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading && previewIsPrimary"
:key="prescriptionViewData.id" :key="prescriptionViewData.id"
:prescription-id="Number(prescriptionViewData.id)" :prescription-id="Number(prescriptionViewData.id)"
:initial-state="prescriptionViewData.esign" :initial-state="prescriptionViewData.esign"
@@ -2490,10 +2554,12 @@
/> />
<PrescriptionSlip <PrescriptionSlip
v-if="prescriptionViewData" v-if="prescriptionViewData"
:key="previewPrescriptionId"
ref="rxSlipRef" ref="rxSlipRef"
:data="prescriptionViewData" :data="prescriptionViewData"
:variant="prescriptionTabType" :variant="prescriptionTabType"
:title="SLIP_TITLE" :title="SLIP_TITLE"
show-pharmacist-signature-sample
/> />
<!-- 审核痕迹(不进入导出) --> <!-- 审核痕迹(不进入导出) -->
@@ -2660,7 +2726,7 @@
</template> </template>
<script lang="ts" setup name="prescriptionOrderListH5"> <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 { useRoute } from 'vue-router'
import { import {
Refresh, Refresh,
@@ -2677,6 +2743,7 @@ import {
import ListTimeFilter from '@/components/list-time-filter/index.vue' import ListTimeFilter from '@/components/list-time-filter/index.vue'
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue' import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue' import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
import { usePrescriptionOrderReceipts } from './components/usePrescriptionOrderReceipts'
import { useListTimeFilter } from '@/hooks/useListTimeFilter' import { useListTimeFilter } from '@/hooks/useListTimeFilter'
import { import {
prescriptionOrderAuditPayment, prescriptionOrderAuditPayment,
@@ -2702,7 +2769,6 @@ import {
prescriptionOrderRequestCompletion, prescriptionOrderRequestCompletion,
prescriptionOrderUploadToPharmacy, prescriptionOrderUploadToPharmacy,
prescriptionOrderPreviewGancaoRecipel, prescriptionOrderPreviewGancaoRecipel,
prescriptionDetail,
getDoctors, getDoctors,
getAssistants getAssistants
} from '@/api/tcm' } from '@/api/tcm'
@@ -2719,11 +2785,15 @@ import {
supplyModeLabel, supplyModeLabel,
supplyModeTagType supplyModeTagType
} from './components/prescription-order-utils' } 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 EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue' import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
import type { PrescriptionEsignStatus } from '@/api/tcm' 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 html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf' import { jsPDF } from 'jspdf'
import { getDictData } from '@/api/app' 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 TcmDiagnosisEditView = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
const userStore = useUserStore() const userStore = useUserStore()
const canLinkExistingReceipt = computed(() =>
userStore.perms.includes('*') || userStore.perms.includes('tcm.prescriptionOrder/attachReceipt')
)
const diagnosisViewRef = ref<{ const diagnosisViewRef = ref<{
openViewOnly: (id: number) => Promise<void> openViewOnly: (id: number) => Promise<void>
@@ -3615,6 +3688,20 @@ function canUpdateAmount(row: { id?: number; fulfillment_status?: number } | nul
const detailVisible = ref(false) const detailVisible = ref(false)
const detailLoading = ref(false) const detailLoading = ref(false)
const detailData = ref<Record<string, any> | null>(null) 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>>() const orderTimeDialogRef = ref<InstanceType<typeof PrescriptionOrderTimeDialog>>()
async function onOrderTimeSaved(id: number) { async function onOrderTimeSaved(id: number) {
@@ -3700,28 +3787,20 @@ const detailAgencyToCollect = computed(() => {
return Math.round((total - paid) * 100) / 100 return Math.round((total - paid) * 100) / 100
}) })
const detailUnlinkedPayOrders = ref<any[]>([]) const {
unlinkedReceipts: detailUnlinkedPayOrders,
async function loadDetailUnlinkedPayOrders(diagnosisId: number, prescriptionOrderId: number, linkedIds: number[]) { loadUnlinkedReceipts,
if (!diagnosisId) { linkingReceiptId,
detailUnlinkedPayOrders.value = [] unlinkingReceiptId,
return changingReceipts,
} canAttachReceipt,
try { canUnlinkReceipt,
const res: any = await prescriptionOrderPaidPayOrders({ confirmAttachReceipt,
diagnosis_id: diagnosisId, confirmUnlinkReceipt
prescription_order_id: prescriptionOrderId } = usePrescriptionOrderReceipts(detailData, detailVisible, (orderId) => {
}) void getLists()
const lists = res?.lists ?? res?.data?.lists ?? [] if (detailVisible.value && Number(detailData.value?.id) === orderId) void fetchLogs(orderId)
// 列表已由服务端限制为 2026-04-20 及之后创建的支付单(本单已关联除外);此处再过滤已关联项 })
const filtered = Array.isArray(lists)
? lists.filter((item: any) => !linkedIds.includes(item.id))
: []
detailUnlinkedPayOrders.value = filtered
} catch {
detailUnlinkedPayOrders.value = []
}
}
function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number }> { function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number }> {
if (!raw) return [] if (!raw) return []
@@ -3734,11 +3813,6 @@ function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number
return [] return []
} }
const detailPrescription = computed(() => {
const p = detailData.value?.prescription
return p && typeof p === 'object' ? p : null
})
const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo)) const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo))
function normalizeBizPhone(v: unknown): string { function normalizeBizPhone(v: unknown): string {
@@ -3755,13 +3829,13 @@ function recipientVsPrescriptionPhoneMismatch(recipient: unknown, rxPhone: unkno
/** 详情抽屉:业务收货手机 vs 处方登记手机 */ /** 详情抽屉:业务收货手机 vs 处方登记手机 */
const detailRecipientRxPhoneMismatch = computed(() => { const detailRecipientRxPhoneMismatch = computed(() => {
const rx = detailPrescription.value?.phone const rx = detailData.value?.prescription?.phone
const biz = detailData.value?.recipient_phone const biz = detailData.value?.recipient_phone
return recipientVsPrescriptionPhoneMismatch(biz, rx) return recipientVsPrescriptionPhoneMismatch(biz, rx)
}) })
const detailPrescriptionPhoneDisplay = computed(() => { const detailPrescriptionPhoneDisplay = computed(() => {
const s = normalizeBizPhone(detailPrescription.value?.phone) const s = normalizeBizPhone(detailData.value?.prescription?.phone)
return s || '—' return s || '—'
}) })
@@ -3784,7 +3858,9 @@ const detailLinkedAppointmentResolvedFromTag = computed(() => {
const detailRxHerbs = computed(() => normalizeSlipHerbs(detailPrescription.value?.herbs)) 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 detailAuxUsage = computed(() => {
const rx = detailPrescription.value as any const rx = detailPrescription.value as any
@@ -3795,7 +3871,6 @@ const detailAuxUsage = computed(() => {
}) })
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */ /** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
// 完整收货地址(省市区 + 详细地址) // 完整收货地址(省市区 + 详细地址)
const detailFullAddress = computed(() => { const detailFullAddress = computed(() => {
@@ -3939,6 +4014,7 @@ function logActionText(act: string) {
ship: '确认发货', ship: '确认发货',
withdraw: '撤销', withdraw: '撤销',
link_pay_order: '关联支付单', link_pay_order: '关联支付单',
bind_prescription: '绑定关联处方',
revoke_rx_audit: '撤回处方审核', revoke_rx_audit: '撤回处方审核',
revoke_pay_audit: '撤回支付审核', revoke_pay_audit: '撤回支付审核',
gancao_submit: '甘草下单', gancao_submit: '甘草下单',
@@ -4061,6 +4137,7 @@ function openPatchUsageDialog() {
feedback.msgWarning('无处方数据') feedback.msgWarning('无处方数据')
return return
} }
if (rx.id && Number(rx.id) !== Number(ord.prescription_id)) return
const aux = detailAuxUsage.value const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1 patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day = patchUsageForm.times_per_day =
@@ -4140,6 +4217,7 @@ async function submitPatchUsage() {
} }
function openPatchRxPatientDialog() { function openPatchRxPatientDialog() {
if (!isPrimaryPrescription.value) return
const rx = detailPrescription.value const rx = detailPrescription.value
const ord = detailData.value const ord = detailData.value
if (!rx || !ord?.id || !ord.prescription_id) { if (!rx || !ord?.id || !ord.prescription_id) {
@@ -4177,12 +4255,13 @@ function openUpdateAmount() {
} }
async function refreshCurrentPrescriptionOrderDetail() { async function refreshCurrentPrescriptionOrderDetail() {
const id = detailData.value?.id const current = detailData.value
const id = current?.id
if (!id) return if (!id) return
try { try {
const res: any = await prescriptionOrderDetail({ id }) const res: any = await prescriptionOrderDetail({ id })
const d = res?.data ?? res ?? null const d = res?.data ?? res ?? null
if (d) detailData.value = d if (d && detailData.value === current) detailData.value = d
} catch { } 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:显式彻底清空缓存,防止前一次弹窗的数据残留 // 修复 Bug:显式彻底清空缓存,防止前一次弹窗的数据残留
detailData.value = null detailData.value = null
resetLinkedPrescription()
detailUnlinkedPayOrders.value = [] detailUnlinkedPayOrders.value = []
bumpLogisticsTraceRequestToken() bumpLogisticsTraceRequestToken()
detailLogisticsExpress.value = 'auto' detailLogisticsExpress.value = 'auto'
@@ -4259,6 +4342,7 @@ async function openDetail(id: number) {
detailLoading.value = true detailLoading.value = true
try { try {
const res: any = await prescriptionOrderDetail({ id }) const res: any = await prescriptionOrderDetail({ id })
if (request !== detailOpenRequest || !detailVisible.value) return
const d = res?.data ?? res ?? null const d = res?.data ?? res ?? null
detailData.value = d detailData.value = d
if (d) { if (d) {
@@ -4270,18 +4354,15 @@ async function openDetail(id: number) {
} }
fetchLogs(id) fetchLogs(id)
// 加载未关联的支付单 void loadUnlinkedReceipts(d)
const diagId = d.diagnosis_id if (prescriptionId) void selectLinkedPrescription(prescriptionId)
const linkedIds = d.pay_order_ids || []
if (diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, linkedIds)
}
} }
} catch (e: any) { } catch (e: any) {
if (request !== detailOpenRequest || !detailVisible.value) return
feedback.msgError(e?.message || '加载失败') feedback.msgError(e?.message || '加载失败')
detailVisible.value = false detailVisible.value = false
} finally { } finally {
detailLoading.value = false if (request === detailOpenRequest) detailLoading.value = false
} }
} }
@@ -4316,6 +4397,7 @@ const editFormRef = ref<FormInstance>()
const editForm = reactive({ const editForm = reactive({
id: 0, id: 0,
prescription_id: 0, prescription_id: 0,
linked_prescriptions: [] as LinkedPrescription[],
diagnosis_id: 0, diagnosis_id: 0,
recipient_name: '', recipient_name: '',
recipient_phone: '', recipient_phone: '',
@@ -4494,6 +4576,7 @@ const editRules = computed<FormRules>(() => {
function resetEditOrderDialog() { function resetEditOrderDialog() {
editOrderStep.value = 0 editOrderStep.value = 0
editOrderPrescription.value = null editOrderPrescription.value = null
editForm.linked_prescriptions = []
editFormRef.value?.clearValidate() editFormRef.value?.clearValidate()
} }
@@ -4520,6 +4603,9 @@ async function goEditOrderNextStep() {
} }
} }
/** 已发货订单服用天数锁定(来自订单详情 days_locked,服务端同样拦截) */
const editDaysLocked = ref(false)
async function openEdit(row: { async function openEdit(row: {
id: number id: number
creator_id?: number creator_id?: number
@@ -4541,6 +4627,7 @@ async function openEdit(row: {
} }
editOrderStep.value = 0 editOrderStep.value = 0
editOrderPrescription.value = null editOrderPrescription.value = null
editForm.linked_prescriptions = []
editVisible.value = true editVisible.value = true
editDialogLoading.value = true editDialogLoading.value = true
try { try {
@@ -4551,6 +4638,7 @@ async function openEdit(row: {
editVisible.value = false editVisible.value = false
return return
} }
editForm.linked_prescriptions = d.linked_prescriptions ?? []
const rx = d.prescription const rx = d.prescription
if (rx && typeof rx === 'object') { if (rx && typeof rx === 'object') {
editOrderPrescription.value = rx as Record<string, any> editOrderPrescription.value = rx as Record<string, any>
@@ -4593,7 +4681,8 @@ async function openEdit(row: {
editForm.shipping_address = d.shipping_address || '' editForm.shipping_address = d.shipping_address || ''
editForm.is_follow_up = d.is_follow_up ? 1 : 0 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_count = d.dose_count > 0 ? d.dose_count : 1
editForm.dose_unit = d.dose_unit || '剂' editForm.dose_unit = d.dose_unit || '剂'
editForm.prev_staff = d.prev_staff || '' editForm.prev_staff = d.prev_staff || ''
@@ -4688,6 +4777,7 @@ async function submitEdit() {
const auditVisible = ref(false) const auditVisible = ref(false)
const route = useRoute() const route = useRoute()
const orderListPath = route.fullPath
const auditKind = ref<'prescription' | 'payment'>('prescription') const auditKind = ref<'prescription' | 'payment'>('prescription')
const auditTargetId = ref(0) const auditTargetId = ref(0)
const auditRowData = ref<any>(null) 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 () => { onMounted(async () => {
await loadRegionData() await loadRegionData()
await loadServicePackageOptions() await loadServicePackageOptions()
await loadDoctorAssistantOptions() await loadDoctorAssistantOptions()
getLists() getLists()
const reviewOrderId = Number(route.query.review_order) orderListInitialized = true
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId) 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 diagId = row.diagnosis_id || detailData.value?.diagnosis_id
const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || [] const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || []
if (diagId) { if (diagId && canLinkExistingReceipt.value) {
void loadAddPayOrderAvailable(diagId, currentLinkedIds) void loadAddPayOrderAvailable(diagId, currentLinkedIds)
} }
} }
@@ -5471,11 +5572,19 @@ const SLIP_TITLE = `${SLIP_HOSPITAL_NAME} 处方笺`
const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339' const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339'
const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号' const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号'
const prescriptionViewVisible = ref(false) const {
const prescriptionViewLoading = ref(false) visible: prescriptionViewVisible,
const prescriptionViewData = ref<any>(null) loading: prescriptionViewLoading,
/** 查看处方联次:药房联 / 处方联 */ error: prescriptionViewError,
const prescriptionTabType = ref<'internal' | 'user'>('internal') 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 rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
const prescriptionSlipExporting = ref(false) const prescriptionSlipExporting = ref(false)
@@ -5734,60 +5843,6 @@ function openPrescriptionViewFromEdit() {
openPrescriptionView(editForm) 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> { async function preloadSlipImagesToDataUrl(el: HTMLElement): Promise<void> {
const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]') const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]')
const tasks = Array.from(imgs).map(async (img) => { const tasks = Array.from(imgs).map(async (img) => {
@@ -5880,7 +5935,8 @@ async function capturePrescriptionSlipCanvas(): Promise<HTMLCanvasElement> {
function slipDownloadBaseName() { function slipDownloadBaseName() {
const name = prescriptionViewData.value?.patient_name const name = prescriptionViewData.value?.patient_name
const safe = typeof name === 'string' && name.trim() ? name.trim().replace(/[\\/:*?"<>|]/g, '_') : '未命名' 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() { async function downloadPrescriptionSlipImage() {
@@ -5900,11 +5956,19 @@ async function downloadPrescriptionSlipImage() {
} }
} }
async function downloadPrescriptionSlipPdf() { /** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
if (!prescriptionViewData.value) return async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
if (!prescriptionViewData.value || !previewCanExport.value) return
prescriptionSlipExporting.value = true prescriptionSlipExporting.value = true
try { 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 canvas = await capturePrescriptionSlipCanvas()
const imgData = canvas.toDataURL('image/jpeg', 0.95) const imgData = canvas.toDataURL('image/jpeg', 0.95)
/** /**
+50 -8
View File
@@ -8,7 +8,7 @@
clearable clearable
filterable filterable
placeholder="全部" placeholder="全部"
class="w-[160px]" class="!w-[160px]"
@change="doSearch" @change="doSearch"
> >
<el-option <el-option
@@ -30,7 +30,7 @@
node-key="id" node-key="id"
:default-expand-all="true" :default-expand-all="true"
:props="deptTreeProps" :props="deptTreeProps"
class="w-[200px]" class="!w-[200px]"
@change="doSearch" @change="doSearch"
/> />
</el-form-item> </el-form-item>
@@ -39,7 +39,7 @@
v-model="queryParams.state" v-model="queryParams.state"
clearable clearable
placeholder="全部" placeholder="全部"
class="w-[170px]" class="!w-[170px]"
@change="doSearch" @change="doSearch"
> >
<el-option <el-option
@@ -55,7 +55,7 @@
v-model="queryParams.days_bucket" v-model="queryParams.days_bucket"
clearable clearable
placeholder="全部" placeholder="全部"
class="w-[120px]" class="!w-[120px]"
@change="doSearch" @change="doSearch"
> >
<el-option <el-option
@@ -66,6 +66,22 @@
/> />
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="诊次">
<el-select
v-model="queryParams.slot"
clearable
placeholder="全部"
class="!w-[130px]"
@change="doSearch"
>
<el-option
v-for="opt in slotOptions"
:key="opt.value"
:label="opt.label"
:value="opt.value"
/>
</el-select>
</el-form-item>
<el-form-item label="延迟次数 ≥"> <el-form-item label="延迟次数 ≥">
<el-input-number <el-input-number
v-model="minSnooze" v-model="minSnooze"
@@ -84,7 +100,7 @@
v-model="queryParams.keyword" v-model="queryParams.keyword"
placeholder="患者姓名" placeholder="患者姓名"
clearable clearable
class="w-[160px]" class="!w-[160px]"
@keyup.enter="doSearch" @keyup.enter="doSearch"
@clear="doSearch" @clear="doSearch"
/> />
@@ -97,7 +113,7 @@
:fetch-fun="revisitDueLists" :fetch-fun="revisitDueLists"
:params="queryParams" :params="queryParams"
:page-size="pager.size" :page-size="pager.size"
export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 延迟次数 / 患者)" export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 诊次 / 延迟次数 / 患者)"
/> />
</el-form-item> </el-form-item>
</el-form> </el-form>
@@ -117,6 +133,8 @@
stripe stripe
row-key="id" row-key="id"
:row-class-name="rowClassName" :row-class-name="rowClassName"
:default-sort="{ prop: 'due_date', order: 'descending' }"
@sort-change="onSortChange"
> >
<el-table-column label="患者" min-width="120" fixed="left"> <el-table-column label="患者" min-width="120" fixed="left">
<template #default="{ row }"> <template #default="{ row }">
@@ -165,7 +183,13 @@
<span v-else class="text-missing">缺开药天数</span> <span v-else class="text-missing">缺开药天数</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="预计复诊" width="110"> <el-table-column
label="预计复诊"
prop="due_date"
width="120"
sortable="custom"
:sort-orders="['descending', 'ascending']"
>
<template #default="{ row }"> <template #default="{ row }">
<div class="cell-main">{{ row.due_date || '—' }}</div> <div class="cell-main">{{ row.due_date || '—' }}</div>
<div v-if="row.anchor_date" class="cell-sub"> <div v-if="row.anchor_date" class="cell-sub">
@@ -377,6 +401,13 @@ const router = useRouter()
/** 状态筛选:诊单列表的 7 个状态 + 主管视图专有「人工关闭」 */ /** 状态筛选:诊单列表的 7 个状态 + 主管视图专有「人工关闭」 */
const stateOptions = [...REVISIT_STATE_FILTER_OPTIONS, { label: '人工关闭', value: 'closed' }] const stateOptions = [...REVISIT_STATE_FILTER_OPTIONS, { label: '人工关闭', value: 'closed' }]
/** 诊次筛选(按当前已完成诊次 current_slot):0 = 未成交,1~5 精确,6+ = 第 6 诊及以上 */
const slotOptions = [
{ label: '未成交', value: '0' },
...[1, 2, 3, 4, 5].map((n) => ({ label: `第 ${n} 诊`, value: String(n) })),
{ label: '第 6 诊及以上', value: '6+' }
]
const assistantOptions = ref<Array<{ id: number; name: string }>>([]) const assistantOptions = ref<Array<{ id: number; name: string }>>([])
const deptTreeOptions = ref<DeptTreeNode[]>([]) const deptTreeOptions = ref<DeptTreeNode[]>([])
const deptTreeProps = { value: 'id', label: 'name', children: 'children' } const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
@@ -386,8 +417,11 @@ const queryParams = reactive<RevisitDueListsParams>({
dept_id: '', dept_id: '',
state: '', state: '',
days_bucket: '', days_bucket: '',
slot: '',
min_snooze: '', min_snooze: '',
keyword: '' keyword: '',
sort_field: 'due_date',
sort_order: 'desc'
}) })
/** el-input-number 清空时为 null/undefined,单独持有后再写回 queryParams 的 '' */ /** el-input-number 清空时为 null/undefined,单独持有后再写回 queryParams 的 '' */
const minSnooze = ref<number | undefined>(undefined) const minSnooze = ref<number | undefined>(undefined)
@@ -399,6 +433,13 @@ const { pager, getLists, resetPage } = usePaging({
const doSearch = () => resetPage() const doSearch = () => resetPage()
/** 表头排序:只在倒序 / 正序间切换(sort-orders 不含 null),切换后回到第 1 页 */
const onSortChange = ({ order }: { prop: string | null; order: string | null }) => {
queryParams.sort_field = 'due_date'
queryParams.sort_order = order === 'ascending' ? 'asc' : 'desc'
doSearch()
}
const onMinSnoozeChange = (val: number | undefined | null) => { const onMinSnoozeChange = (val: number | undefined | null) => {
queryParams.min_snooze = val === null || val === undefined ? '' : Number(val) queryParams.min_snooze = val === null || val === undefined ? '' : Number(val)
doSearch() doSearch()
@@ -409,6 +450,7 @@ const handleReset = () => {
queryParams.dept_id = '' queryParams.dept_id = ''
queryParams.state = '' queryParams.state = ''
queryParams.days_bucket = '' queryParams.days_bucket = ''
queryParams.slot = ''
queryParams.min_snooze = '' queryParams.min_snooze = ''
queryParams.keyword = '' queryParams.keyword = ''
minSnooze.value = undefined minSnooze.value = undefined
+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, '测试药师') 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 () => { test('the slip reloads a newly verified physician seal once from prescription detail', async () => {
const requests = [] const requests = []
const { updatePrescriptionSlipEsign } = loadModule('utils/prescription-esign.ts', { '@/api/tcm': { 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], /请完成医师签署/) 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 calls = []
const messages = [] const messages = []
let cancel = true let cancel = true
@@ -1443,24 +1485,26 @@ test('issued prescriptions can void pending drafts with permission and keep the
msgSuccess: (message) => messages.push(message) msgSuccess: (message) => messages.push(message)
} }
} }
const { canVoidPendingPrescription, voidPendingPrescription } = pageDeclarations( const { canVoidPrescription, voidPendingPrescription } = pageDeclarations(
'views/consumer/prescription/index.vue', 'views/consumer/prescription/index.vue',
['isPendingPrescriptionAudit', 'canVoidPendingPrescription', 'voidPendingPrescription'], globals ['canVoidPrescription', 'voidPendingPrescription'], globals
) )
assert.equal(canVoidPendingPrescription(row), true) assert.equal(canVoidPrescription(row), true)
for (const other of [{ audit_status: 1 }, { audit_status: 2 }, { void_status: 1 }, { can_void: false }]) { // 审核通过(药师已签署)后仍可作废;以服务端 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, ...other })
} }
await voidPendingPrescription(row) await voidPendingPrescription(row)
assert.deepEqual(calls, []) assert.deepEqual(calls, [])
cancel = false cancel = false
await voidPendingPrescription(row) await voidPendingPrescription(row)
assert.equal(canVoidPendingPrescription(row), true) assert.equal(canVoidPrescription(row), true)
await Promise.all([voidPendingPrescription(row), voidPendingPrescription(row)]) 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.void_status, 1)
assert.equal(row.can_submit_for_review, false) assert.equal(row.can_submit_for_review, false)
assert.equal(canVoidPendingPrescription(row), false) assert.equal(canVoidPrescription(row), false)
assert.equal(refreshes, 1) assert.equal(refreshes, 1)
assert.deepEqual(messages, ['处方已作废']) 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 ['resetForm', 'fillPrescriptionContents', 'openNewPrescription', 'handleAdd', 'canReissuePrescription', 'handleReissue', 'handleSubmit'], globals
) )
assert.equal(canReissuePrescription(source), true) assert.equal(canReissuePrescription(source), true)
// 他人所开、已作废的处方也可由有开方权限的账号重新开方。
assert.equal(canReissuePrescription({ ...source, creator_id: 9 }), true)
await handleReissue({ ...source, void_status: 0 }) await handleReissue({ ...source, void_status: 0 })
await handleReissue({ ...source, creator_id: 9 })
permitted = false permitted = false
await handleReissue(source) await handleReissue(source)
assert.deepEqual(reads, []) assert.deepEqual(reads, [])
+1 -1
View File
@@ -3,7 +3,7 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"] __all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions. # Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.5.5" __version__ = "1.5.6"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。 # 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。 # 正式发布请保持 False;此时程序只使用下面配置的线上域名。
@@ -454,10 +454,9 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
def can_void_prescription(record: Any) -> bool: def can_void_prescription(record: Any) -> bool:
# 已有业务订单、已审核签署的处方也可作废:订单随同诊单重新开方自动关联新处方;权限与药房锁由服务端判定。
_, mode = prescription_action(record) _, mode = prescription_action(record)
return mode in {"edit", "view"} and not _as_bool( return mode in {"edit", "view"}
first_value(record, "has_prescription_order", default=False)
)
def _prescription_action_label(record: Any, *, force_open: bool = False) -> str: def _prescription_action_label(record: Any, *, force_open: bool = False) -> str:
@@ -33,6 +33,7 @@ from PySide6.QtCore import (
QObject, QObject,
QPoint, QPoint,
QRectF, QRectF,
QRegularExpression,
QSize, QSize,
Qt, Qt,
QTimer, QTimer,
@@ -52,6 +53,7 @@ from PySide6.QtGui import (
QPainter, QPainter,
QPdfWriter, QPdfWriter,
QPen, QPen,
QRegularExpressionValidator,
QStandardItem, QStandardItem,
QStandardItemModel, QStandardItemModel,
QTextDocument, QTextDocument,
@@ -98,7 +100,7 @@ from PySide6.QtWidgets import (
) )
from shiboken6 import isValid 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 .. import icons
from ..design_system import clinical_stylesheet from ..design_system import clinical_stylesheet
from ..diagnosis_terms import shared_terms from ..diagnosis_terms import shared_terms
@@ -993,6 +995,7 @@ _REISSUE_FIELDS = (
"herbs", "dose_count", "dose_unit", "dosage_amount", "dosage_unit", "dosage_bag_count", "herbs", "dose_count", "dose_unit", "dosage_amount", "dosage_unit", "dosage_bag_count",
"need_decoction", "bags_per_dose", "usage_days", "times_per_day", "usage_instruction", "need_decoction", "bags_per_dose", "usage_days", "times_per_day", "usage_instruction",
"usage_time", "usage_way", "dietary_taboo", "usage_notes", "aux_usage", "ai_assisted", "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")) 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: def can_reissue_prescription(prescription: Any, current_user: Any, permissions: Any) -> bool:
# 已作废处方(含他人作废、他人所开)均可由有开方权限的账号重新开方;新处方以当前账号为开方医生并由其签署。
actor_id = _int(first_value(current_user, "id", "user_id", "admin_id")) 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
return (prescription_is_voided(prescription) and actor_id > 0 and actor_id == creator_id
and has_permission(permissions, PRESCRIBE_PERMISSIONS)) and has_permission(permissions, PRESCRIBE_PERMISSIONS))
@@ -3451,12 +3465,24 @@ class PrescriptionEditorDialog(QDialog):
self.age.setRange(0, 150) self.age.setRange(0, 150)
self.visit_no = QLineEdit() self.visit_no = QLineEdit()
self.visit_no.setPlaceholderText("自动生成或手动输入") 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()) self.date_edit = PrescriptionDateEdit(QDate.currentDate())
name_grid = QGridLayout() name_grid = QGridLayout()
self._prepare_grid(name_grid, 2) self._prepare_grid(name_grid, 2)
self._place_field(name_grid, 0, 0, "患者姓名", self.patient_name, required=True) 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, 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) layout.addLayout(name_grid)
self._register_responsive_grid(name_grid, 2) self._register_responsive_grid(name_grid, 2)
@@ -3855,6 +3881,8 @@ class PrescriptionEditorDialog(QDialog):
appointment_id=_int(source.get("appointment_id"), 0), appointment_id=_int(source.get("appointment_id"), 0),
) )
self.visit_no.setText(visit_no) 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._set_gender(source.get("gender", 1))
self.age.setValue(_int(source.get("age"), 0)) self.age.setValue(_int(source.get("age"), 0))
date_value = QDate.fromString( date_value = QDate.fromString(
@@ -4301,6 +4329,8 @@ class PrescriptionEditorDialog(QDialog):
"need_decoction": int(self.need_decoction.isChecked()), "need_decoction": int(self.need_decoction.isChecked()),
"bags_per_dose": self.bags_per_dose.value(), "bags_per_dose": self.bags_per_dose.value(),
"patient_name": self.patient_name.text().strip(), "patient_name": self.patient_name.text().strip(),
"phone": self.phone.text().strip(),
"id_card": self.id_card.text().strip().upper(),
"gender": self._gender_value(), "gender": self._gender_value(),
"age": self.age.value(), "age": self.age.value(),
"visit_no": self.visit_no.text().strip(), "visit_no": self.visit_no.text().strip(),
@@ -4398,6 +4428,21 @@ class PrescriptionEditorDialog(QDialog):
self.validation.show_message(message, "warning") self.validation.show_message(message, "warning")
widget.setFocus() widget.setFocus()
return 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 = ( length_checks = (
( (
payload["clinical_diagnosis"], payload["clinical_diagnosis"],
@@ -5061,6 +5106,14 @@ def render_prescription_html(
bags = positive_number(source.get("dosage_bag_count"), 1) bags = positive_number(source.get("dosage_bag_count"), 1)
if prescription_type == "浓缩水丸" and days and times and amount: if prescription_type == "浓缩水丸" and days and times and amount:
out_pellet = f"{number_text(days * times * amount * bags)}克" 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: elif herbs:
total_weight = sum(_float(row.get("dosage")) for row in herbs) * dose_count total_weight = sum(_float(row.get("dosage")) for row in herbs) * dose_count
out_pellet = f"{number_text(total_weight)}克" 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 assert abs(centers[0] - centers[1]) <= 1
finally: finally:
dialog.close() 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.windowTitle() == "编辑处方"
assert editor.patient_name.isReadOnly() assert editor.patient_name.isReadOnly()
assert editor.visit_no.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.gender_male.isChecked()
assert editor.payload()["gender"] == 1 assert editor.payload()["gender"] == 1
assert editor.tongue.text() == "面象哨兵" assert editor.tongue.text() == "面象哨兵"
@@ -1640,3 +1641,20 @@ def test_demo_repository_pages_render_offscreen(
library.close() library.close()
issued.close() issued.close()
application.processEvents() 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 >> << /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents 7 0 R >>
endobj endobj
7 0 obj 7 0 obj
<< /Length 1969>> << /Length 1889>>
stream stream
BT /F1 20 Tf 1 0 0 1 235 795 Tm <4e2d533b590465b97b3a> Tj ET 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 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 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 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 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 558 Tm <8f8565b9670d752859296570ff1a0038> Tj ET
BT /F1 11 Tf 1 0 0 1 45 540 Tm <8f8565b9670d752859296570ff1a0038> Tj ET
0.7 w 45 133 m 550 133 l S 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 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 BT /F1 11 Tf 1 0 0 1 420 104 Tm <533b5e0875355b507b7e7ae0> Tj ET
@@ -55,5 +54,5 @@ xref
0000000735 00000 n 0000000735 00000 n
trailer << /Size 8 /Root 1 0 R >> trailer << /Size 8 /Root 1 0 R >>
startxref startxref
2754 2674
%%EOF %%EOF
@@ -45,7 +45,7 @@ class PrescriptionController extends BaseAdminController
public function edit() public function edit()
{ {
$params = (new PrescriptionValidate())->post()->goCheck('edit'); $params = (new PrescriptionValidate())->post()->goCheck('edit');
$result = PrescriptionLogic::edit($params, $this->adminId); $result = PrescriptionLogic::edit($params, $this->adminId, $this->adminInfo);
if (!$result) { if (!$result) {
return $this->fail(PrescriptionLogic::getError()); return $this->fail(PrescriptionLogic::getError());
} }
@@ -72,7 +72,9 @@ class PrescriptionOrderController extends BaseAdminController
public function detail() public function detail()
{ {
$params = (new PrescriptionOrderValidate())->get()->goCheck('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) { if ($detail === null) {
return $this->fail(PrescriptionOrderLogic::getError()); return $this->fail(PrescriptionOrderLogic::getError());
} }
@@ -80,6 +82,29 @@ class PrescriptionOrderController extends BaseAdminController
return $this->data($detail); 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;未配置时仍可跳转顺丰/京东官网) * 快递轨迹查询(对接快递100;未配置时仍可跳转顺丰/京东官网)
*/ */
@@ -437,6 +462,18 @@ class PrescriptionOrderController extends BaseAdminController
return $this->success('关联支付单成功', $result); 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() public function unlinkPayOrder()
{ {
@@ -13,6 +13,7 @@ use app\common\model\tcm\Prescription;
use app\common\model\tcm\PrescriptionOrder; use app\common\model\tcm\PrescriptionOrder;
use app\common\service\esign\PrescriptionEsignService; use app\common\service\esign\PrescriptionEsignService;
use think\db\Query; use think\db\Query;
use think\facade\Cache;
/** /**
* 处方列表 * 处方列表
@@ -21,51 +22,92 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
{ {
use HasDataScopeFilter; 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(用于全局置顶排序) * 识别「有业务订单且处方药材为空白/重复」的处方 ID(用于全局置顶排序)
* *
* @param array<int,int|string> $candidateIds * 风险是处方自身的属性,与筛选条件无关:这里在全库范围计算一次并短时缓存,
* 筛选范围的交集由 pinnedIds() 在当前查询里取。以前每次请求都先把筛选结果的
* 全部 ID 拉出来,再逐个读药材,处方表行很宽(病历快照、签名图),整表扫描
* 是列表慢的主因。
*
* @return array<int,int> * @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 { $cached = Cache::get(self::RISK_IDS_CACHE_KEY);
return $id > 0; if (is_array($cached)) {
}))); return $cached;
if ($candidateIds === []) {
return [];
} }
// 仅在「存在有效业务订单」的处方里做风险判定 // 仅在「存在有效业务订单」的处方里做风险判定;订单表很小,从订单侧出发
$orderRxIds = PrescriptionOrder::whereIn('prescription_id', $candidateIds) $orderRxIds = PrescriptionOrder::whereNull('delete_time')
->whereNull('delete_time')
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES) ->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
->column('prescription_id'); ->column('prescription_id');
$orderRxIds = array_values(array_unique(array_filter(array_map('intval', $orderRxIds), static function (int $id): bool { $orderRxIds = array_values(array_unique(array_filter(array_map('intval', $orderRxIds), static function (int $id): bool {
return $id > 0; 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 []; return [];
} }
$rows = Prescription::whereIn('id', $orderRxIds) $riskIds = $this->collectRiskPrescriptionIds();
->whereNull('delete_time') $pinned = [];
->field(['id', 'herbs']) if ($riskIds !== []) {
->select() $pinned = array_map('intval', (clone $query)->whereIn('id', $riskIds)->order('id', 'desc')->column('id'));
->toArray();
$riskIds = [];
foreach ($rows as $row) {
$rid = (int) ($row['id'] ?? 0);
if ($rid <= 0) {
continue;
}
if ($this->isRiskHerbs($row['herbs'] ?? null)) {
$riskIds[] = $rid;
}
} }
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 public function lists(): array
{ {
$query = $this->buildFilteredQuery();
// 全局置顶:有业务订单且处方药材为空白/重复 // 全局置顶:有业务订单且处方药材为空白/重复
$candidateIds = (clone $query)->column('id'); $pageIds = $this->pageIds($this->buildFilteredQuery());
$riskIds = $this->collectRiskPrescriptionIds(is_array($candidateIds) ? $candidateIds : []); if ($pageIds === []) {
return [];
$listQuery = $query;
if ($riskIds !== []) {
$riskIdStr = implode(',', array_map('intval', $riskIds));
$listQuery->orderRaw("CASE WHEN id IN ({$riskIdStr}) THEN 0 ELSE 1 END ASC");
} }
$lists = $listQuery $rowsById = [];
->order('id', 'desc') $rows = Prescription::whereIn('id', $pageIds)
->limit($this->limitOffset, $this->limitLength) ->withoutField(self::LIST_OMIT_FIELDS)
->select() ->select()
->toArray(); ->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_column($lists, 'id');
$rxIds = array_map('intval', $rxIds); $rxIds = array_map('intval', $rxIds);
@@ -325,8 +370,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
$rid = (int) $item['id']; $rid = (int) $item['id'];
$item['can_void'] = empty($item['void_status']) $item['can_void'] = empty($item['void_status'])
&& PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess) && PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess)
&& !PrescriptionLogic::hasBlockingVoidOrder($item, $ordersByPrescription[$rid] ?? []) && (empty($ordersByPrescription[$rid]) || PrescriptionOrderLogic::voidBlockerForPrescription($rid) === null);
&& (empty($ordersByPrescription[$rid]) || PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($rid) === null);
$item['can_restore_rejected'] = PrescriptionLogic::canRestoreRejected($item); $item['can_restore_rejected'] = PrescriptionLogic::canRestoreRejected($item);
$item = PrescriptionLogic::withSigningStatus($item, $this->adminId, $maySubmit); $item = PrescriptionLogic::withSigningStatus($item, $this->adminId, $maySubmit);
// 设置默认值 // 设置默认值
@@ -885,8 +885,8 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
'export_supply_mode' => '供货方式', 'export_supply_mode' => '供货方式',
'export_gancao_prescription_cost' => '处方成本', 'export_gancao_prescription_cost' => '处方成本',
'export_first_visit_assistant' => '初诊医助', 'export_first_visit_assistant' => '初诊医助',
'export_rx_audit_time' => '审核时间', 'export_payment_audit_time' => '审核时间',
'export_rx_auditor' => '审核人', 'export_payment_auditor' => '审核人',
]; ];
} }
@@ -22,10 +22,10 @@ use think\facade\Db;
* 复诊到期跟进 - 主管团队视图列表(P2,方案 §3.3 tcm.revisitDue/lists) * 复诊到期跟进 - 主管团队视图列表(P2,方案 §3.3 tcm.revisitDue/lists)
* *
* 数据来源:tcm_diagnosis_revisit_due 快照表(别名 rd),一诊单一行;时间相关状态由 RevisitDueCalculator::deriveState 按 today 推导。 * 数据来源:tcm_diagnosis_revisit_due 快照表(别名 rd),一诊单一行;时间相关状态由 RevisitDueCalculator::deriveState 按 today 推导。
* 筛选:assistant_id / dept_id(经 admin_dept 子查询,含下级部门)/ state / days_bucket / min_snooze / keyword(患者姓名);默认排除失效行(closed_state<>5)。 * 筛选:assistant_id / dept_id(经 admin_dept 子查询,含下级部门)/ state / days_bucket / slot(诊次,N 或 N+)/ min_snooze / keyword(患者姓名);默认排除失效行(closed_state<>5)。
* state 的 SQL 条件与 DiagnosisLists::applyRevisitDueFilters 完全一致,另加 closed = closed_state=4(人工关闭,主管视图标记)。 * state 的 SQL 条件与 DiagnosisLists::applyRevisitDueFilters 完全一致,另加 closed = closed_state=4(人工关闭,主管视图标记)。
* 数据范围:HasDataScopeFilter::applyDataScopeByOwner('rd.assistant_id'),主管按角色 data_scope 看下属。 * 数据范围:HasDataScopeFilter::applyDataScopeByOwner('rd.assistant_id'),主管按角色 data_scope 看下属。
* 排序:escalation_level desc(越点越上心优先),due_date asc(NULL 置后),id asc。 * 排序:sort_field=due_date + sort_order=asc|desc,默认 due_date desc(最新预计复诊在前),NULL 始终置后,见 orderSql()。
* 导出:export=1/2,字段见 setExcelFields。 * 导出:export=1/2,字段见 setExcelFields。
*/ */
class RevisitDueLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface class RevisitDueLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface
@@ -51,7 +51,7 @@ class RevisitDueLists extends BaseAdminDataLists implements ListsSearchInterface
public function lists(): array public function lists(): array
{ {
$rows = $this->buildQuery() $rows = $this->buildQuery()
->orderRaw('rd.escalation_level DESC, rd.due_date IS NULL ASC, rd.due_date ASC, rd.id ASC') ->orderRaw($this->orderSql())
->limit($this->limitOffset, $this->limitLength) ->limit($this->limitOffset, $this->limitLength)
->select() ->select()
->toArray(); ->toArray();
@@ -113,6 +113,20 @@ class RevisitDueLists extends BaseAdminDataLists implements ListsSearchInterface
// ---------------------------------------------------------------- 内部 // ---------------------------------------------------------------- 内部
/**
* 排序:sort_field 仅白名单列(目前 due_date = 预计复诊),sort_order asc|desc,默认 desc(最新的预计复诊日在前)。
* 无论正序倒序,缺预计复诊日(NULL)的行始终置后;同日按 id 同向排序保证分页稳定。
*/
private function orderSql(): string
{
$fieldMap = ['due_date' => 'rd.due_date'];
$field = (string) ($this->params['sort_field'] ?? '');
$col = $fieldMap[$field] ?? $fieldMap['due_date'];
$dir = strtolower((string) ($this->params['sort_order'] ?? '')) === 'asc' ? 'ASC' : 'DESC';
return "{$col} IS NULL ASC, {$col} {$dir}, rd.id {$dir}";
}
/** /**
* @return \think\db\Query * @return \think\db\Query
*/ */
@@ -152,10 +166,28 @@ class RevisitDueLists extends BaseAdminDataLists implements ListsSearchInterface
$this->applyStateFilter($query, strtolower(trim((string) ($this->params['state'] ?? '')))); $this->applyStateFilter($query, strtolower(trim((string) ($this->params['state'] ?? ''))));
$this->applyBucketFilter($query, strtolower(trim((string) ($this->params['days_bucket'] ?? '')))); $this->applyBucketFilter($query, strtolower(trim((string) ($this->params['days_bucket'] ?? ''))));
$this->applySlotFilter($query, trim((string) ($this->params['slot'] ?? '')));
return $query; return $query;
} }
/**
* 诊次筛选(按 current_slot = 当前已完成诊次):'N' 精确命中第 N 诊;'N+' 为第 N 诊及以上。非法值忽略。
*
* @param mixed $query
*/
private function applySlotFilter($query, string $slot): void
{
if ($slot === '') {
return;
}
if (preg_match('/^(\d{1,3})\+$/', $slot, $m) === 1) {
$query->where('rd.current_slot', '>=', (int) $m[1]);
} elseif (ctype_digit($slot)) {
$query->where('rd.current_slot', (int) $slot);
}
}
/** /**
* state 筛选:SQL 条件与 DiagnosisLists::applyRevisitDueFilters 完全一致(表别名 rd),另加 closed。 * state 筛选:SQL 条件与 DiagnosisLists::applyRevisitDueFilters 完全一致(表别名 rd),另加 closed。
* *
+14 -13
View File
@@ -10,7 +10,6 @@ use app\common\model\OrderDetail;
use app\common\model\auth\Admin; use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole; use app\common\model\auth\AdminRole;
use app\common\model\tcm\Diagnosis; use app\common\model\tcm\Diagnosis;
use app\common\model\tcm\PrescriptionOrder;
use app\common\model\tcm\PrescriptionOrderPayOrder; use app\common\model\tcm\PrescriptionOrderPayOrder;
use app\common\service\wechat\WechatWorkExternalPayService; use app\common\service\wechat\WechatWorkExternalPayService;
use think\facade\Db; use think\facade\Db;
@@ -1300,7 +1299,7 @@ class OrderLogic
/** /**
* 某诊单下可关联的支付单(待支付/已支付),供关联业务订单多选(主管/诊单医助看该诊单全部;否则仅本人创建) * 某诊单下可关联的支付单(待支付/已支付),供关联业务订单多选(主管/诊单医助看该诊单全部;否则仅本人创建)
* 已占用(关联到未撤回/未取消的业务订单)的支付单会排除;编辑某业务订单时传 $exceptPrescriptionOrderId 以保留当前单已选中的项 * 已关联到未删除业务订单的支付单会排除;编辑时保留当前单已选中的项
* 列表仅含 2026-04-20 及之后创建的支付单(已关联到当前编辑业务订单的除外) * 列表仅含 2026-04-20 及之后创建的支付单(已关联到当前编辑业务订单的除外)
* *
* @return array<int, array<string, mixed>> * @return array<int, array<string, mixed>>
@@ -1332,15 +1331,8 @@ class OrderLogic
->select() ->select()
->toArray(); ->toArray();
$activePoIds = PrescriptionOrder::whereNull('delete_time') $busyPayIds = $rows === [] ? [] : array_map('intval', self::prescriptionOrderReceiptLinks(array_column($rows, 'id'))
->where('fulfillment_status', '<>', 4) ->column('link.pay_order_id'));
->column('id');
$busyPayIds = [];
if ($activePoIds !== []) {
$busyPayIds = PrescriptionOrderPayOrder::whereIn('prescription_order_id', $activePoIds)
->column('pay_order_id');
$busyPayIds = array_unique(array_map('intval', $busyPayIds));
}
$whiteList = []; $whiteList = [];
if ($exceptPrescriptionOrderId !== null && $exceptPrescriptionOrderId > 0) { if ($exceptPrescriptionOrderId !== null && $exceptPrescriptionOrderId > 0) {
$whiteList = array_map( $whiteList = array_map(
@@ -1372,8 +1364,17 @@ class OrderLogic
return $out; 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,已关联到该业务订单的旧单除外 * 默认仅允许关联 2026-04-20 及之后创建的支付单;编辑业务订单时传入 $prescriptionOrderIdForDateGrace,已关联到该业务订单的旧单除外
* *
* @param int[] $ids zyt_order.id * @param int[] $ids zyt_order.id
@@ -1402,7 +1403,7 @@ class OrderLogic
$assistantId = (int) Diagnosis::where('id', $diagnosisId)->value('assistant_id'); $assistantId = (int) Diagnosis::where('id', $diagnosisId)->value('assistant_id');
$isDiagAssistant = $assistantId === $adminId; $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)) { if (count($orders) !== count($ids)) {
return '部分支付单不存在或已删除'; return '部分支付单不存在或已删除';
} }
@@ -41,6 +41,7 @@ use app\common\service\storage\Driver as StorageDriver;
use app\common\service\tcm\RevisitDueHook; use app\common\service\tcm\RevisitDueHook;
use app\common\service\tcm\RevisitDueService; use app\common\service\tcm\RevisitDueService;
use app\common\service\tcm\RevisitVisitSlotService; use app\common\service\tcm\RevisitVisitSlotService;
use think\db\Query;
use think\facade\Db; use think\facade\Db;
/** /**
* 中医辨房病因诊单逻辑 * 中医辨房病因诊单逻辑
@@ -4356,7 +4357,18 @@ class DiagnosisLogic extends BaseLogic
return false; 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); $selfRoles = DataScopeService::selfOnlyRoleIds($adminId, $adminInfo);
if (in_array(2, $selfRoles, true)) { if (in_array(2, $selfRoles, true)) {
@@ -4366,22 +4378,13 @@ class DiagnosisLogic extends BaseLogic
if (DataScopeService::isEnabled()) { if (DataScopeService::isEnabled()) {
$visibleIds = DataScopeService::getVisibleAdminIds($adminId, $adminInfo); $visibleIds = DataScopeService::getVisibleAdminIds($adminId, $adminInfo);
if ($visibleIds === []) { if ($visibleIds === []) {
self::setError('诊单不存在或无权访问'); $query->whereRaw('1 = 0');
} elseif (is_array($visibleIds)) {
return false;
}
if (is_array($visibleIds)) {
$query->whereIn('assistant_id', $visibleIds); $query->whereIn('assistant_id', $visibleIds);
} }
} }
if (!$query->find()) { return $query;
self::setError('诊单不存在或无权访问');
return false;
}
return true;
} }
/** /**
@@ -169,23 +169,30 @@ final class PrescriptionAiLogic
if (!$task) { if (!$task) {
throw new DomainException('资料尚未准备完成,请查看分析状态'); throw new DomainException('资料尚未准备完成,请查看分析状态');
} }
if ($task['status'] === 'success' || in_array($task['status'], Policy::ACTIVE_TASKS, true)) { $now = time();
return ['batch_id' => $batchId, 'status' => $task['status']]; $newRetry = $task['status'] === 'failed';
} if ($newRetry) {
if ($task['status'] !== 'failed') { if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) {
throw new DomainException('该模型已达手动重试上限,请检查失败原因');
}
$changes = [
'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => $now,
'manual_retries' => (int) $task['manual_retries'] + 1,
'lock_token' => '', 'lock_until' => 0, 'error_code' => '', 'updated_at' => $now,
];
$task = array_replace($task, $changes);
} elseif ($task['status'] !== 'success' && !in_array($task['status'], Policy::ACTIVE_TASKS, true)) {
throw new DomainException('该任务不能重试'); throw new DomainException('该任务不能重试');
} }
if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) { $state = self::taskStates([$task], $now)[0];
throw new DomainException('该模型已达手动重试上限,请检查失败原因'); if ($newRetry) {
// Keep audit history and the encrypted resume checkpoint across retry rounds.
$changes['next_run_at'] = $state['progress']['next_run_at'];
$changes['error_code'] = $state['error_code'];
Db::name('prescription_ai_task')->where('id', $task['id'])->update($changes);
Store::refreshBatch($batchId);
} }
// Attempt history and lifetime counter remain immutable across retry rounds. return ['batch_id' => $batchId, 'model_key' => $model] + $state;
Db::name('prescription_ai_task')->where('id', $task['id'])->update([
'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => time(), 'lock_token' => '',
'manual_retries' => (int) $task['manual_retries'] + 1,
'lock_until' => 0, 'error_code' => '', 'updated_at' => time(),
]);
Store::refreshBatch($batchId);
return ['batch_id' => $batchId, 'status' => 'retry_wait'];
}); });
} }
@@ -280,12 +287,54 @@ final class PrescriptionAiLogic
'metric_label' => '药味与剂量一致度(不代表临床准确率)']; 'metric_label' => '药味与剂量一致度(不代表临床准确率)'];
} }
/** Project the retry response and polled model states from the same task, ledger and attempt history. */
private static function taskStates(array $tasks, int $now): array
{
$budgetModels = [];
$attemptTaskIds = [];
foreach ($tasks as $task) {
if ($task['status'] !== 'retry_wait') { continue; }
if ($task['error_code'] !== 'BUDGET_PAUSED' || (int) $task['next_run_at'] <= $now) {
$budgetModels[] = $task['model_key'];
}
if ((int) $task['total_attempts'] > 0) {
$attemptTaskIds[] = $task['id'];
}
}
$exhausted = Store::exhaustedModels($budgetModels, $now);
$lastErrors = $attemptTaskIds ? Db::name('prescription_ai_attempt')->alias('a')
->join('prescription_ai_task t', 't.id = a.task_id AND t.total_attempts = a.attempt_no')
->whereIn('a.task_id', $attemptTaskIds)->whereIn('a.status', ['failed', 'expired'])
->column('a.error_code', 'task_id') : [];
$maxRetries = (int) config('prescription_analysis.max_manual_retries', 2);
$states = [];
foreach ($tasks as $task) {
$code = $task['error_code'];
$lastError = $task['status'] === 'failed' ? $code : ($lastErrors[$task['id']] ?? '');
if ($task['status'] === 'retry_wait') {
if (in_array($task['model_key'], $exhausted, true)) {
$code = 'BUDGET_PAUSED';
$task['next_run_at'] = max((int) $task['next_run_at'], strtotime('tomorrow', $now));
} elseif ($code === 'BUDGET_PAUSED' && (int) $task['next_run_at'] <= $now) {
$code = ''; // Yesterday's pause has expired; eligibility still awaits a real claim.
}
}
$task['error_code'] = $code;
$states[] = ['status' => $task['status'], 'error_code' => $code,
'error_message' => $code !== '' ? Policy::errorMessage($code) : '',
'last_error_code' => $lastError, 'last_error_message' => $lastError !== '' ? Policy::errorMessage($lastError) : '',
'manual_retries' => (int) $task['manual_retries'], 'max_manual_retries' => $maxRetries,
'progress' => Progress::task($task, $now)];
}
return $states;
}
private static function models(array $batchIds, bool $full, bool $agreementVisible = true): array private static function models(array $batchIds, bool $full, bool $agreementVisible = true): array
{ {
if ($batchIds === []) { if ($batchIds === []) {
return []; return [];
} }
$taskFields = ['batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'result_id', $taskFields = ['id', 'batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'manual_retries', 'result_id',
'started_at', 'finished_at', 'updated_at', 'next_run_at']; 'started_at', 'finished_at', 'updated_at', 'next_run_at'];
if (Store::supportsProgress()) { if (Store::supportsProgress()) {
$taskFields[] = 'progress_json'; $taskFields[] = 'progress_json';
@@ -298,14 +347,11 @@ final class PrescriptionAiLogic
} }
$results = Db::name('prescription_ai_result')->whereIn('batch_id', $batchIds)->field($fields)->select()->toArray(); $results = Db::name('prescription_ai_result')->whereIn('batch_id', $batchIds)->field($fields)->select()->toArray();
$map = []; $map = [];
foreach ($tasks as $task) { $taskStates = self::taskStates($tasks, time());
$map[(int) $task['batch_id']][$task['model_key']] = [ foreach ($tasks as $index => $task) {
'status' => $task['status'], 'score' => null, 'herb_score' => null, $state = $taskStates[$index];
'error_code' => $task['error_code'], 'error_message' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '', $map[(int) $task['batch_id']][$task['model_key']] = $state + ['score' => null, 'herb_score' => null,
'reason' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '', 'reason' => $state['error_message'], 'report_id' => (int) $task['result_id']];
'report_id' => (int) $task['result_id'],
'progress' => Progress::task($task),
];
} }
foreach ($results as $result) { foreach ($results as $result) {
$body = $full ? (new Cipher())->decrypt($result['body_cipher'], 'result:' . $result['batch_id'] . ':' . $result['model_key']) : []; $body = $full ? (new Cipher())->decrypt($result['body_cipher'], 'result:' . $result['batch_id'] . ':' . $result['model_key']) : [];
@@ -248,36 +248,20 @@ class PrescriptionLogic
!in_array((int) $order['fulfillment_status'], PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) !== []; !in_array((int) $order['fulfillment_status'], PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) !== [];
$row['has_prescription_order'] = $hasBizOrder ? 1 : 0; $row['has_prescription_order'] = $hasBizOrder ? 1 : 0;
$row['can_restore_rejected'] = self::canRestoreRejected($row); $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( && self::hasVoidAccess(
$row, $row,
$viewerAdminId, $viewerAdminId,
$viewerAdminInfo, $viewerAdminInfo,
self::getVoidAccess($viewerAdminId, $viewerAdminInfo) self::getVoidAccess($viewerAdminId, $viewerAdminInfo)
) )
&& PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($id) === null; // 已提交洛阳药房的订单在作废时自动撤单;甘草等无法自动撤单的才阻止作废。
&& PrescriptionOrderLogic::voidBlockerForPrescription($id) === null;
return $row; 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 private static function generateSn(): string
{ {
return 'RX' . date('Ymd') . str_pad((string)mt_rand(1, 9999), 4, '0', STR_PAD_LEFT); 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'; $data['esign_status'] = 'pending';
} }
try { 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); $replayed = PrescriptionAiRequest::replay($params, $adminId, true);
if ($replayed !== null) { if ($replayed !== null) {
return $replayed; return $replayed;
@@ -549,10 +534,18 @@ class PrescriptionLogic
if (!self::assertUniquePrescriptionPerDiagnosisDay($diagnosisIdRule, $adminId, $dateYmd, null)) { if (!self::assertUniquePrescriptionPerDiagnosisDay($diagnosisIdRule, $adminId, $dateYmd, null)) {
throw new \DomainException(self::getError()); 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 = new Prescription();
$prescription->save($data); $prescription->save($data);
$id = (int) $prescription->id; $id = (int) $prescription->id;
// 原处方作废后挂起的业务订单,随本次重新开方自动关联到新处方。
$relinkedOrderIds = PrescriptionOrderLogic::relinkOrdersToReissue($diagnosisIdRule, $id, $data['sn'], $adminId, $adminInfo);
// Read database defaults and JSON exactly as workers will fingerprint them. // Read database defaults and JSON exactly as workers will fingerprint them.
$saved = Db::name('tcm_prescription')->where('id', $id)->find(); $saved = Db::name('tcm_prescription')->where('id', $id)->find();
self::scheduleAiSaved($saved, $adminId, $adminInfo, self::scheduleAiSaved($saved, $adminId, $adminInfo,
@@ -560,6 +553,10 @@ class PrescriptionLogic
PrescriptionAiRequest::complete($params, $adminId, $id); PrescriptionAiRequest::complete($params, $adminId, $id);
return $id; return $id;
}); });
foreach ($relinkedOrderIds as $orderId) {
\app\common\service\tcm\RevisitDueHook::onOrderChanged($diagnosisIdRule, $orderId, 'reissue');
}
return $newId;
} catch (\Throwable $e) { } catch (\Throwable $e) {
self::setError($e instanceof \DomainException ? $e->getMessage() : '处方保存失败,请稍后重试'); self::setError($e instanceof \DomainException ? $e->getMessage() : '处方保存失败,请稍后重试');
return null; 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); $prescriptionId = (int) ($params['id'] ?? 0);
self::setError(''); self::setError('');
try { try {
return (bool) LockedPharmacySnapshotMutation::executeForPrescription( return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
$prescriptionId, $prescriptionId,
static fn (): bool => self::editLocked($params, $adminId) static fn (): bool => self::editLocked($params, $adminId, $adminInfo)
); );
} catch (\Throwable $exception) { } catch (\Throwable $exception) {
if (self::getError() === '') { 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 { try {
$prescription = Prescription::where('id', $params['id'])->lock(true)->find(); $prescription = Prescription::where('id', $params['id'])->lock(true)->find();
@@ -732,6 +729,17 @@ class PrescriptionLogic
$data['void_by'] = null; $data['void_by'] = null;
$data['void_by_name'] = ''; $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); $prescription->save($data);
PrescriptionOrderLogic::onConsumerPrescriptionSaved((int) $params['id']); 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 private static function scheduleAiSaved(array $saved, int $actor, ?array $info, array $options): void
{ {
try { try {
@@ -826,6 +877,11 @@ class PrescriptionLogic
return false; 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)) { if (!in_array($gender, [0, 1], true)) {
self::setError('性别无效'); 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 = self::withActionAvailability($arr, $viewerAdminId, $viewerAdminInfo);
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? ''); $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('处方不存在或无权作废'); self::setError('处方不存在或无权作废');
return false; 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( return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
$id, $id,
@@ -1456,17 +1536,14 @@ class PrescriptionLogic
self::setError('处方审核状态已变化,请刷新列表后查看'); self::setError('处方审核状态已变化,请刷新列表后查看');
return false; return false;
} }
if (self::hasBlockingVoidOrder($row->toArray(), $orders)) {
self::setError('关联业务订单的审核或履约状态不允许作废此处方');
return false;
}
$row->void_status = 1; $row->void_status = 1;
$row->void_time = time(); $row->void_time = time();
$row->void_by = $adminId; $row->void_by = $adminId;
$row->void_by_name = (string) ($adminInfo['name'] ?? ''); $row->void_by_name = (string) ($adminInfo['name'] ?? '');
$saved = (bool) $row->save(); $saved = (bool) $row->save();
if ($saved) { if ($saved) {
// 关联订单挂起,待同诊单重新开方后自动关联新处方。
PrescriptionOrderLogic::holdOrdersForReissue($row->toArray(), $orders, $adminId, $adminInfo);
PrescriptionAiStore::invalidate($id, 'voided'); PrescriptionAiStore::invalidate($id, 'voided');
} }
return $saved; return $saved;
@@ -50,6 +50,10 @@ class PrescriptionOrderLogic
private static string $error = ''; private static string $error = '';
private const TRACKING_AUDIT_REQUIRED = '处方审核和支付单审核均通过后,才可填写或修改快递单号'; 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 public static function setError(string $msg): void
{ {
@@ -380,7 +384,8 @@ class PrescriptionOrderLogic
} }
$perms = AuthLogic::getAuthByAdminId((int) ($adminInfo['admin_id'] ?? 0)); $perms = AuthLogic::getAuthByAdminId((int) ($adminInfo['admin_id'] ?? 0));
foreach ($perms as $p) { 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; return true;
} }
} }
@@ -897,7 +902,7 @@ class PrescriptionOrderLogic
} }
/** /**
* 支付单不可同时关联多条「有效」业务订单(未删除且未撤回/取消);$exceptPrescriptionOrderId 为当前编辑单 ID 时跳过自检 * 收款须由调用方在同一事务中锁定。撤回会清除原关联,取消单事后补录的关联仍占用该收款。
* *
* @param int[] $payOrderIds * @param int[] $payOrderIds
*/ */
@@ -907,27 +912,13 @@ class PrescriptionOrderLogic
if ($ids === []) { if ($ids === []) {
return null; return null;
} }
$activePoIds = PrescriptionOrder::whereNull('delete_time') $links = OrderLogic::prescriptionOrderReceiptLinks($ids);
->where('fulfillment_status', '<>', 4) if ($exceptPrescriptionOrderId !== null) {
->column('id'); $links->where('link.prescription_order_id', '<>', $exceptPrescriptionOrderId);
if ($activePoIds === []) {
return null;
} }
$activeSet = array_fill_keys(array_map('intval', $activePoIds), true); // 等待收款行锁后,用当前读检查其他事务是否已经占用收款。
$links = PrescriptionOrderPayOrder::whereIn('pay_order_id', $ids)->select(); $link = $links->field('link.pay_order_id')->lock(true)->find();
foreach ($links as $link) { return $link ? '支付单 #' . $link['pay_order_id'] . ' 已关联业务订单,不可重复关联' : null;
$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;
} }
/** 收款关联增删共用订单行锁,失败时连同金额和日志一起回滚。 */ /** 收款关联增删共用订单行锁,失败时连同金额和日志一起回滚。 */
@@ -1073,22 +1064,22 @@ class PrescriptionOrderLogic
if (!$order) { if (!$order) {
return; return;
} }
$amount = round((float) $order->amount, 2); $amount = (int) round((float) $order->amount * 100);
$paid = 0.0; $paid = self::linkedPayPaidCents(self::linkedPayOrderIdList($id));
$ids = self::linkedPayOrderIdList($id); $order->agency_collect_amount = ($amount - $paid) / 100;
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);
$order->save(); $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 * @param array<string,mixed> $params
* @return array<string,mixed>|false * @return array<string,mixed>|false
@@ -1329,7 +1320,199 @@ class PrescriptionOrderLogic
return $edited; 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 = ''; self::$error = '';
$row = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find(); $row = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find();
@@ -1344,6 +1527,16 @@ class PrescriptionOrderLogic
return null; return null;
} }
$arr = $row->toArray(); $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::maskInternalCostIfNeeded($arr, $adminInfo);
self::maskRemarkExtraIfNeeded($arr, $adminInfo); self::maskRemarkExtraIfNeeded($arr, $adminInfo);
self::attachLinkedPayOrders($arr); self::attachLinkedPayOrders($arr);
@@ -1370,7 +1563,7 @@ class PrescriptionOrderLogic
if ($rxId > 0) { if ($rxId > 0) {
$rxDetail = PrescriptionLogic::detail($rxId, $adminId, $adminInfo); $rxDetail = PrescriptionLogic::detail($rxId, $adminId, $adminInfo);
if ($rxDetail !== null) { if ($rxDetail !== null) {
$arr['prescription'] = $rxDetail; $arr['prescription'] = self::applyUsageOverride($rxDetail, $arr);
// 添加开方人姓名(优先使用处方的 doctor_name,否则从 creator_id 获取) // 添加开方人姓名(优先使用处方的 doctor_name,否则从 creator_id 获取)
$doctorName = (string) ($rxDetail['doctor_name'] ?? ''); $doctorName = (string) ($rxDetail['doctor_name'] ?? '');
if ($doctorName === '') { if ($doctorName === '') {
@@ -1387,21 +1580,16 @@ class PrescriptionOrderLogic
} }
$arr = self::withReviewAvailability($arr, $arr['prescription'] ?? []); $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); $canHerbs = self::canViewPrescriptionHerbsInOrderDetail($adminInfo);
$arr['prescription_detail_herbs_visible'] = $canHerbs; $arr['prescription_detail_herbs_visible'] = $canHerbs;
if (! $canHerbs && isset($arr['prescription']) && is_array($arr['prescription'])) { if (!$canHerbs && is_array($arr['prescription'])) {
$rx = &$arr['prescription']; self::maskPrescriptionHerbs($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']);
} }
// 诊单医助 / 诊单创建人姓名(tcm_diagnosis.admin_id);部门见下方:优先业务订单 creator_id // 诊单医助 / 诊单创建人姓名(tcm_diagnosis.admin_id);部门见下方:优先业务订单 creator_id
@@ -1484,10 +1672,31 @@ class PrescriptionOrderLogic
$adminInfo, $adminInfo,
$diagIdForMeta > 0 ? [$diagIdForMeta => (int) ($arr['assistant_id'] ?? 0)] : [] $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; 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 = $params['medication_days'] ?? null;
$medDays = $medDays === '' || $medDays === null ? null : (int) $medDays; $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_name = (string) $params['recipient_name'];
$order->recipient_phone = (string) $params['recipient_phone']; $order->recipient_phone = (string) $params['recipient_phone'];
@@ -3015,7 +3230,8 @@ class PrescriptionOrderLogic
$logSummary = $summary; $logSummary = $summary;
if ($changeParts !== []) { 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); self::writeLog($id, $adminId, $adminInfo, 'manual_log', $logSummary);
@@ -3157,6 +3373,11 @@ class PrescriptionOrderLogic
*/ */
public static function linkPayOrder(array $params, int $adminId, array $adminInfo) public static function linkPayOrder(array $params, int $adminId, array $adminInfo)
{ {
self::$error = '';
if (!self::canAttachReceipt($adminId, $adminInfo)) {
self::$error = '无权限关联收款';
return false;
}
return self::mutatePayOrderLinks( return self::mutatePayOrderLinks(
(int) ($params['id'] ?? 0), (int) ($params['id'] ?? 0),
static fn () => self::linkPayOrderLocked($params, $adminId, $adminInfo) static fn () => self::linkPayOrderLocked($params, $adminId, $adminInfo)
@@ -3269,6 +3490,90 @@ class PrescriptionOrderLogic
return $out; 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 保留退款后的余额口径。 * 普通订单 paid 按剩余有效收款重算;退款订单的 paid 保留退款后的余额口径。
@@ -3298,8 +3603,8 @@ class PrescriptionOrderLogic
self::$error = '无权限操作此订单'; self::$error = '无权限操作此订单';
return false; return false;
} }
if (in_array((int) $order->fulfillment_status, [3, 4], true)) { if ((int) $order->fulfillment_status === 4) {
self::$error = '已完成或已取消的订单不允许移除收款关联'; self::$error = '已取消的订单不允许移除收款关联';
return false; return false;
} }
if (!in_array($payOrderId, self::linkedPayOrderIdList($id), true)) { if (!in_array($payOrderId, self::linkedPayOrderIdList($id), true)) {
@@ -3307,13 +3612,15 @@ class PrescriptionOrderLogic
return false; return false;
} }
$payOrder = Order::where('id', $payOrderId)->whereNull('delete_time')->lock(true)->find(); $payOrder = Order::where('id', $payOrderId)->whereNull('delete_time')->lock(true)->find();
if (!$payOrder || !in_array((int) $payOrder->status, [2, 5], true)) { // 已支付(2)、待审核(5)、已退款(4) 均可移除;已退款记录不计入已付金额,移除后已付金额不变。
self::$error = '仅已支付或待审核的收款记录可移除,已退款记录不可移除'; if (!$payOrder || !in_array((int) $payOrder->status, [2, 4, 5], true)) {
self::$error = '仅已支付、待审核或已退款的收款记录可移除';
return false; return false;
} }
$refunded = (int) $payOrder->status === 4;
$oldPaidCents = (int) round((float) $order->paid * 100); $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) { if ($removedCents < 0) {
self::$error = '收款金额异常,请先核对金额'; self::$error = '收款金额异常,请先核对金额';
return false; return false;
@@ -3324,8 +3631,7 @@ class PrescriptionOrderLogic
throw new \RuntimeException('收款关联已变化,请刷新后重试'); throw new \RuntimeException('收款关联已变化,请刷新后重试');
} }
$remainingIds = self::linkedPayOrderIdList($id); $remainingIds = self::linkedPayOrderIdList($id);
$remainingPaidCents = $remainingIds === [] ? 0 : (int) round((float) Order::whereIn('id', $remainingIds) $remainingPaidCents = self::linkedPayPaidCents($remainingIds);
->whereNull('delete_time')->whereIn('status', [2, 5])->sum('amount') * 100);
$order->linked_pay_order_id = $remainingIds[0] ?? null; $order->linked_pay_order_id = $remainingIds[0] ?? null;
// 部分退款可能未拆分收款单金额,不能用剩余收款原额覆盖退款后的 paid 余额。 // 部分退款可能未拆分收款单金额,不能用剩余收款原额覆盖退款后的 paid 余额。
$hasRefund = (float) ($order->refund_amount ?? 0) > 0 || (int) $order->fulfillment_status === 10; $hasRefund = (float) ($order->refund_amount ?? 0) > 0 || (int) $order->fulfillment_status === 10;
@@ -3334,12 +3640,15 @@ class PrescriptionOrderLogic
: $remainingPaidCents; : $remainingPaidCents;
$order->paid = $newPaidCents / 100; $order->paid = $newPaidCents / 100;
// 与详情的关联已付总额口径一致;订单 amount 不变。 // 与详情的关联已付总额口径一致;订单 amount 不变。
$order->agency_collect_amount = round((float) $order->amount - $remainingPaidCents / 100, 2); $dueCents = (int) round((float) $order->amount * 100) - $remainingPaidCents;
$order->save(); $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( self::writeLog($id, $adminId, $adminInfo, 'unlink_pay_order', sprintf(
'移除收款关联 #%d(%s,¥%.2f),订单总金额 ¥%.2f 不变;已付金额(paid)¥%.2f → ¥%.2f;原收款记录保留', '移除%s收款关联 #%d(%s,¥%.2f),订单总金额 ¥%.2f 不变;已付金额(paid)¥%.2f → ¥%.2f;原收款记录保留',
$payOrderId, (string) $payOrder->order_no, $removedCents / 100, $refunded ? '已退款' : '', $payOrderId, (string) $payOrder->order_no, (float) $payOrder->amount,
(float) $order->amount, $oldPaidCents / 100, $newPaidCents / 100 (float) $order->amount, $oldPaidCents / 100, $newPaidCents / 100
), true); ), true);
@@ -3347,6 +3656,11 @@ class PrescriptionOrderLogic
self::maskInternalCostIfNeeded($out, $adminInfo); self::maskInternalCostIfNeeded($out, $adminInfo);
self::maskRemarkExtraIfNeeded($out, $adminInfo); self::maskRemarkExtraIfNeeded($out, $adminInfo);
self::attachLinkedPayOrders($out); self::attachLinkedPayOrders($out);
if (self::canAttachReceipt($adminId, $adminInfo)) {
$out['attachable_receipts'] = OrderLogic::listPaidOrdersForDiagnosis(
(int) $order->diagnosis_id, $adminId, $adminInfo
);
}
return $out; 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) $logRows = PrescriptionOrderLog::whereIn('prescription_order_id', $poIds)
->whereIn('action', ['audit_rx_approve', 'audit_rx_reject', 'revoke_rx_audit']) ->whereIn('action', [...$paymentAuditActions, ...$paymentAuditResetActions, 'manual_log'])
->field(['prescription_order_id', 'id', 'action', 'admin_name', 'create_time']) ->field(['prescription_order_id', 'action', 'admin_name', 'create_time', 'summary'])
->order('id', 'asc') ->order('id', 'asc')
->select() ->select()
->toArray(); ->toArray();
$auditEffectiveByPo = []; $paymentAuditByPo = [];
foreach ($logRows as $lg) { foreach ($logRows as $lg) {
$pid = (int) ($lg['prescription_order_id'] ?? 0); $pid = (int) $lg['prescription_order_id'];
if ($pid <= 0) { $action = $lg['action'];
if (in_array($action, $paymentAuditActions, true)) {
$paymentAuditByPo[$pid] = $lg;
continue; continue;
} }
$act = (string) ($lg['action'] ?? ''); $summary = (string) $lg['summary'];
if ($act === 'revoke_rx_audit') { // 补录已支付收款也记为 link_pay_order,但只有发起新审核的关联操作会重置状态。
$auditEffectiveByPo[$pid] = null; if ($action === 'link_pay_order' && !str_starts_with($summary, '关联支付单 ')) {
continue; 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;只取启用项做兜底取原值) // 服务套餐字典:与前端 formatServicePackage 同口径(dict_data type_value=server_order;只取启用项做兜底取原值)
@@ -4703,16 +5026,18 @@ class PrescriptionOrderLogic
$item['export_center_label'] = '一中心'; $item['export_center_label'] = '一中心';
} }
$paSt = (int) ($item['prescription_audit_status'] ?? 0); $paymentAudit = $paymentAuditByPo[$poId] ?? [];
$aud = $auditEffectiveByPo[$poId] ?? null; $expectedAction = match ((int) ($item['payment_slip_audit_status'] ?? 0)) {
if (($paSt === 1 || $paSt === 2) && \is_array($aud)) { 1 => 'audit_pay_approve',
$at = (int) ($aud['create_time'] ?? 0); 2 => 'audit_pay_reject',
$item['export_rx_audit_time'] = $at > 0 ? date('Y-m-d H:i:s', $at) : ''; default => null,
$item['export_rx_auditor'] = (string) ($aud['admin_name'] ?? ''); };
} else { if ($expectedAction === null || ($paymentAudit['action'] ?? null) !== $expectedAction) {
$item['export_rx_audit_time'] = ''; $paymentAudit = [];
$item['export_rx_auditor'] = '';
} }
$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); unset($item);
} }
@@ -5246,6 +5571,7 @@ class PrescriptionOrderLogic
if ($prescription === null) { if ($prescription === null) {
throw new \DomainException(PrescriptionLogic::getError() ?: '处方不存在'); throw new \DomainException(PrescriptionLogic::getError() ?: '处方不存在');
} }
$prescription = self::applyUsageOverride($prescription, $order->toArray());
$herbs = PharmacyHerbIdentityResolver::resolve( $herbs = PharmacyHerbIdentityResolver::resolve(
is_array($prescription['herbs'] ?? null) ? $prescription['herbs'] : [], is_array($prescription['herbs'] ?? null) ? $prescription['herbs'] : [],
@@ -5387,6 +5713,7 @@ class PrescriptionOrderLogic
return false; return false;
} }
$rx = self::applyUsageOverride($rx, $order->toArray());
$c = Config::get('gancao_scm', []); $c = Config::get('gancao_scm', []);
$nameMap = is_array($c['herb_id_map'] ?? null) ? $c['herb_id_map'] : []; $nameMap = is_array($c['herb_id_map'] ?? null) ? $c['herb_id_map'] : [];
$herbs = is_array($rx['herbs'] ?? null) ? $rx['herbs'] : []; $herbs = is_array($rx['herbs'] ?? null) ? $rx['herbs'] : [];
@@ -5542,6 +5869,7 @@ class PrescriptionOrderLogic
self::$error = PrescriptionLogic::getError() !== '' ? PrescriptionLogic::getError() : '处方不存在'; self::$error = PrescriptionLogic::getError() !== '' ? PrescriptionLogic::getError() : '处方不存在';
return false; return false;
} }
$rx = self::applyUsageOverride($rx, $order->toArray());
$c = Config::get('gancao_scm', []); $c = Config::get('gancao_scm', []);
$nameMap = is_array($c['herb_id_map'] ?? null) ? $c['herb_id_map'] : []; $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( private static function writeLog(
int $orderId, int $orderId,
int $adminId, int $adminId,
@@ -5981,7 +6490,9 @@ class PrescriptionOrderLogic
return false; 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)) { if (!PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
self::setError('无权限修改此处方'); self::setError('无权限修改此处方');
@@ -6050,11 +6561,25 @@ class PrescriptionOrderLogic
} }
} }
$oldTimes = (int) ($rx->times_per_day ?? 0); // 已发货后天数随药品已定,不可再改;次数、袋数等仍可修正。
$oldUsageDays = (int) ($rx->usage_days ?? 0); if (self::isOrderShipped($order->toArray())) {
$oldDosageBagCount = max(1, (int) ($rx->dosage_bag_count ?? 1)); $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); $oldMedDays = (int) ($order->medication_days ?? 0);
$oldAuxUsage = $rx->aux_usage; $oldAuxUsage = $current['aux_usage'] ?? null;
if (is_string($oldAuxUsage)) { if (is_string($oldAuxUsage)) {
$decoded = json_decode($oldAuxUsage, true); $decoded = json_decode($oldAuxUsage, true);
$oldAuxUsage = is_array($decoded) ? $decoded : []; $oldAuxUsage = is_array($decoded) ? $decoded : [];
@@ -6111,15 +6636,22 @@ class PrescriptionOrderLogic
} }
$rxUpdates['aux_usage'] = $auxUsage; $rxUpdates['aux_usage'] = $auxUsage;
} }
if ($prescriptionChanged && PrescriptionEsignPolicy::isPendingReview($rx->toArray())) { if ($frozen) {
$rxUpdates['review_submitted_at'] = 0; // 签署原文不变;订单记录覆盖值(含未修改项,便于完整还原当前生效参数)。
$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->medication_days = $medDays;
$order->save(); $order->save();
$summary = '服用参数:' . implode(';', $parts); $summary = ($frozen && $prescriptionChanged ? '服用参数(仅本订单生效,CA 签署处方不变):' : '服用参数:')
. implode(';', $parts);
self::writeLog($prescriptionOrderId, $adminId, $adminInfo, 'patch_rx_usage', $summary, true); self::writeLog($prescriptionOrderId, $adminId, $adminInfo, 'patch_rx_usage', $summary, true);
return true; return true;
@@ -47,6 +47,7 @@ class PrescriptionOrderValidate extends BaseValidate
'patient_name' => 'require|max:50', 'patient_name' => 'require|max:50',
'phone' => 'require|max:20', 'phone' => 'require|max:20',
'phone_tail' => 'max:20|regex:/^\\d*$/', 'phone_tail' => 'max:20|regex:/^\\d*$/',
'order_no' => 'alphaDash|max:50',
]; ];
protected $message = [ protected $message = [
@@ -73,7 +74,6 @@ class PrescriptionOrderValidate extends BaseValidate
'is_follow_up', 'prev_staff', 'service_channel', 'service_package', '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', 'tracking_number', 'express_company', 'ship_mode', 'fee_type', 'amount', 'remark_extra', 'remark_assistant', 'pay_order_ids',
], ],
'detail' => ['id'],
'editTime' => ['id', 'create_time'], 'editTime' => ['id', 'create_time'],
'edit' => [ 'edit' => [
'id', 'recipient_name', 'recipient_phone', 'shipping_address', 'id', 'recipient_name', 'recipient_phone', 'shipping_address',
@@ -106,6 +106,30 @@ class PrescriptionOrderValidate extends BaseValidate
'confirmGancaoSubmission' => ['id', 'resolution', 'remote_order_no', 'note'], '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 public function sceneUnlinkPayOrder(): PrescriptionOrderValidate
{ {
return $this->only(['id', 'pay_order_id']) return $this->only(['id', 'pay_order_id'])
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace app\command;
use app\common\service\prescriptionai\PrescriptionAiLaneGuard;
use app\common\service\prescriptionai\PrescriptionAiStore;
use RuntimeException;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
final class PrescriptionAiDispatch extends Command
{
protected function configure(): void
{
$this->setName('prescription-ai:dispatch')->setDescription('巡检处方 AI 消费者,对缺失的队列派发一轮处理')
->addOption('check', null, Option::VALUE_NONE, '只输出巡检状态');
}
protected function execute(Input $input, Output $output): int
{
$enabled = PrescriptionAiStore::enabled();
$checkOnly = (bool) $input->getOption('check');
if (!$enabled && !$checkOnly) {
$output->writeln('PRESCRIPTION_AI_DISPATCH {"enabled":false}');
return 0;
}
$root = $this->app->getRootPath();
$think = $root . 'think';
if (PHP_SAPI !== 'cli' || !is_readable($think)) {
throw new RuntimeException('处方 AI 巡检需要 PHP CLI 和可读的 think 入口');
}
$present = PHP_OS_FAMILY === 'Linux' ? PrescriptionAiLaneGuard::linuxWorkers($think) : [];
$null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';
$streams = [['file', $null, 'r'], ['file', $null, 'w'], ['file', $null, 'w']];
$states = [];
foreach (PrescriptionAiLaneGuard::LANES as $lane) {
if (isset($present[$lane])) {
$states[$lane] = $present[$lane];
continue;
}
if ($checkOnly) {
$states[$lane] = PrescriptionAiLaneGuard::busy($this->app->getRuntimePath(), $lane) ? 'busy' : 'missing';
continue;
}
// Surface runtime permission errors in the admin schedule before detaching the worker.
$probe = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane, LOCK_EX | LOCK_NB);
if ($probe === null) {
$states[$lane] = 'busy';
continue;
}
fclose($probe);
if (!function_exists('proc_open')) {
throw new RuntimeException('处方 AI 单轮接管需要启用 proc_open');
}
$process = proc_open([PHP_BINARY, $think, 'prescription-ai:work', '--lane=' . $lane, '--once', '--scheduled'],
$streams, $pipes, $root);
if (!is_resource($process)) {
throw new RuntimeException('无法启动处方 AI 消费者 ' . $lane);
}
// proc_close waits for the model. Releasing a pipe-free handle lets the cron runner continue immediately.
unset($process);
$states[$lane] = 'dispatched';
}
$output->writeln('PRESCRIPTION_AI_DISPATCH ' . json_encode(['enabled' => $enabled, 'lanes' => $states]));
return 0;
}
}
+28 -2
View File
@@ -4,11 +4,13 @@ declare(strict_types=1);
namespace app\command; namespace app\command;
use app\common\service\prescriptionai\PrescriptionAiLaneGuard;
use app\common\service\prescriptionai\PrescriptionAiStore; use app\common\service\prescriptionai\PrescriptionAiStore;
use app\common\service\prescriptionai\PrescriptionAiWorker; use app\common\service\prescriptionai\PrescriptionAiWorker;
use think\console\Command; use think\console\Command;
use think\facade\Config; use think\facade\Config;
use think\facade\Db; use think\facade\Db;
use think\facade\Log;
use think\console\Input; use think\console\Input;
use think\console\input\Option; use think\console\input\Option;
use think\console\Output; use think\console\Output;
@@ -19,16 +21,26 @@ final class PrescriptionAiWork extends Command
{ {
$this->setName('prescription-ai:work')->setDescription('处方AI独立后台任务;分别运行prepare/qwen/openai') $this->setName('prescription-ai:work')->setDescription('处方AI独立后台任务;分别运行prepare/qwen/openai')
->addOption('lane', null, Option::VALUE_REQUIRED, 'prepare、qwen、openai', 'prepare') ->addOption('lane', null, Option::VALUE_REQUIRED, 'prepare、qwen、openai', 'prepare')
->addOption('once', null, Option::VALUE_NONE, '只处理一轮'); ->addOption('once', null, Option::VALUE_NONE, '只处理一轮')
->addOption('scheduled', null, Option::VALUE_NONE, '定时任务单轮接管,当前队列已占用时跳过');
} }
protected function execute(Input $input, Output $output): int protected function execute(Input $input, Output $output): int
{ {
$lane = (string) $input->getOption('lane'); $lane = (string) $input->getOption('lane');
if (!in_array($lane, ['prepare', 'qwen', 'openai'], true)) { if (!in_array($lane, PrescriptionAiLaneGuard::LANES, true)) {
$output->writeln('Invalid lane'); $output->writeln('Invalid lane');
return 1; return 1;
} }
$scheduled = $input->getOption('scheduled');
if ($scheduled && !$input->getOption('once')) {
$output->writeln('--scheduled requires --once');
return 1;
}
// This handle stays open until execute() returns. Process exit also releases it after a crash.
$laneLock = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane,
$scheduled ? LOCK_EX | LOCK_NB : LOCK_SH);
if ($laneLock === null) { return 0; }
$running = true; $running = true;
if (function_exists('pcntl_async_signals')) { if (function_exists('pcntl_async_signals')) {
pcntl_async_signals(true); pcntl_async_signals(true);
@@ -48,6 +60,11 @@ final class PrescriptionAiWork extends Command
$sweepAt = 0; $sweepAt = 0;
$sourceCursor = 0; $sourceCursor = 0;
$rxCursor = 0; $rxCursor = 0;
if ($scheduled && $lane === 'prepare') {
$saved = json_decode((string) stream_get_contents($laneLock), true);
$sourceCursor = (int) ($saved['source'] ?? 0);
$rxCursor = (int) ($saved['prescription'] ?? 0);
}
do { do {
$worked = false; $worked = false;
try { try {
@@ -60,6 +77,12 @@ final class PrescriptionAiWork extends Command
$sourceCursor = $sweep['selected'] > 0 ? $sweep['last_id'] : 0; $sourceCursor = $sweep['selected'] > 0 ? $sweep['last_id'] : 0;
$rx = $worker->reconcile($rxCursor); $rx = $worker->reconcile($rxCursor);
$rxCursor = $rx['selected'] > 0 ? $rx['last_id'] : 0; $rxCursor = $rx['selected'] > 0 ? $rx['last_id'] : 0;
if ($scheduled) {
rewind($laneLock);
ftruncate($laneLock, 0);
fwrite($laneLock, json_encode(['source' => $sourceCursor, 'prescription' => $rxCursor]));
fflush($laneLock);
}
$sweepAt = time() + 60; $sweepAt = time() + 60;
} }
} }
@@ -73,6 +96,9 @@ final class PrescriptionAiWork extends Command
$detail .= ' ' . $sqlState[0]; $detail .= ' ' . $sqlState[0];
} }
$output->writeln('PRESCRIPTION_AI storage_or_configuration_error ' . $detail); $output->writeln('PRESCRIPTION_AI storage_or_configuration_error ' . $detail);
if ($scheduled) {
Log::write('PRESCRIPTION_AI ' . $lane . ' storage_or_configuration_error ' . $detail, 'error');
}
// Drop a possibly dead connection so the next round reconnects instead of looping. // Drop a possibly dead connection so the next round reconnects instead of looping.
try { try {
Db::connect()->close(); Db::connect()->close();
@@ -1627,6 +1627,10 @@ class DifyChatService
$patterns = [ $patterns = [
'authentication' => '/\b(?:api[ _-]?key|credentials?|authentication|authorization)\b.{0,80}\b(?:invalid|missing|failed|unauthorized)\b|\b(?:invalid|missing)\b.{0,40}\b(?:api[ _-]?key|credentials?)\b/i', 'authentication' => '/\b(?:api[ _-]?key|credentials?|authentication|authorization)\b.{0,80}\b(?:invalid|missing|failed|unauthorized)\b|\b(?:invalid|missing)\b.{0,40}\b(?:api[ _-]?key|credentials?)\b/i',
'quota' => '/\b(?:quota|rate[ _-]?limit)\b.{0,60}\b(?:exceeded|exhausted|reached|insufficient)\b|\binsufficient\s+(?:quota|credits?|balance)\b/i', 'quota' => '/\b(?:quota|rate[ _-]?limit)\b.{0,60}\b(?:exceeded|exhausted|reached|insufficient)\b|\binsufficient\s+(?:quota|credits?|balance)\b/i',
// Dify 把工作流内模型节点的失败包成 400 invalid_param「Run failed: ...」返回,
// 与真正的参数错误同码。只有带模型插件调用痕迹、且是网关无可用账号、5xx/408/429、
// 过载或超时这类暂时性故障时才归为 unavailable(可重试);404 等配置错误不在此列。
'unavailable' => '/\b(?:Run failed|PluginInvokeError|PluginDaemon\w*Error|InvokeError)\b.{0,4000}?(?:\bstatus code (?:408|429|5\d\d)\b|no_available_provider|no eligible account|service_unavailable|upstream_unavailable|\bserver_error\b|\boverloaded\b|killed by timeout|\btimed out\b)/is',
'response_mode_unsupported' => '/\bresponse_mode\b.{0,100}\b(?:invalid|unsupported|not supported|blocking|streaming)\b|\bstreaming\b.{0,50}\b(?:not supported|unsupported|disabled)\b/i', 'response_mode_unsupported' => '/\bresponse_mode\b.{0,100}\b(?:invalid|unsupported|not supported|blocking|streaming)\b|\bstreaming\b.{0,50}\b(?:not supported|unsupported|disabled)\b/i',
'file_count' => '/\b(?:number|count)\s+of\s+(?:uploaded\s+)?(?:files|images|attachments)\b.{0,100}\b(?:limit|exceed|maximum)\b|\btoo many\s+(?:files|images|attachments)\b|\b(?:file|image|attachment)[ _-]?(?:count|number|limit)\b.{0,80}\b(?:exceed|maximum|limit)\b/i', 'file_count' => '/\b(?:number|count)\s+of\s+(?:uploaded\s+)?(?:files|images|attachments)\b.{0,100}\b(?:limit|exceed|maximum)\b|\btoo many\s+(?:files|images|attachments)\b|\b(?:file|image|attachment)[ _-]?(?:count|number|limit)\b.{0,80}\b(?:exceed|maximum|limit)\b/i',
'file_size' => '/\b(?:file|image|attachment)(?:\s+size)?\b.{0,80}\b(?:too large|size limit|maximum size|exceeds? (?:the )?(?:size|maximum))\b/i', 'file_size' => '/\b(?:file|image|attachment)(?:\s+size)?\b.{0,80}\b(?:too large|size limit|maximum size|exceeds? (?:the )?(?:size|maximum))\b/i',
@@ -79,6 +79,9 @@ final class PrescriptionPdf
$label = ['dosage_amount' => '单次用量', 'dosage_bag_count' => '单次袋数', 'need_decoction' => '代煎', $label = ['dosage_amount' => '单次用量', 'dosage_bag_count' => '单次袋数', 'need_decoction' => '代煎',
'times_per_day' => '每日次数', 'usage_days' => '服用天数', 'times_per_day' => '每日次数', 'usage_days' => '服用天数',
'prescription_name' => '方名'][$key] ?? $key; 'prescription_name' => '方名'][$key] ?? $key;
if ($key === 'prescription_name') {
continue; // 辅方方名仅内部使用,不提交签署原文。
}
if ($key === 'need_decoction') { if ($key === 'need_decoction') {
// 辅方不代煎(0)时不写;代煎时与主方一样显示「是」。 // 辅方不代煎(0)时不写;代煎时与主方一样显示「是」。
if ((int) $value === 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} */ /** @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 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 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'] ?? '')) !== '') { if (trim((string) ($order['gancao_reciperl_order_no'] ?? '')) !== '') {
return true; 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> $order
* @param array<string,mixed>|null $claim * @param array<string,mixed>|null $claim
@@ -400,7 +400,8 @@ final class PharmacySubmissionClaimService
if ($target !== 'direct') { if ($target !== 'direct') {
return false; 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'; || strtoupper(trim((string) ($order['ej_pharmacy_review_status'] ?? ''))) === 'REJECTED';
} }
@@ -12,8 +12,10 @@ use app\common\service\TcmAncientBooksReference;
/** One model branch. It receives a saved context and never queries patient data. */ /** One model branch. It receives a saved context and never queries patient data. */
final class PrescriptionAiGenerator final class PrescriptionAiGenerator
{ {
public const PROMPT_VERSION = 'manual-prescription-tcm-four-diagnoses-v7'; public const PROMPT_VERSION = 'manual-prescription-tcm-four-diagnoses-v8';
private const REPORT_KEYS = ['summary', 'diagnosis', 'risk_assessment', 'treatment_advice', 'evidence_references', 'missing_information']; 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', private const RETRYABLE = ['UPSTREAM_TIMEOUT', 'UPSTREAM_BUSY', 'UPSTREAM_UNAVAILABLE', 'INCOMPLETE_RESPONSE', 'EMPTY_RESPONSE',
'CANDIDATE_WITHHELD_BY_MODEL', 'INVALID_EVIDENCE_OUTPUT', 'INVALID_REPORT_OUTPUT']; 'CANDIDATE_WITHHELD_BY_MODEL', 'INVALID_EVIDENCE_OUTPUT', 'INVALID_REPORT_OUTPUT'];
/** Reserved prompt budget for one refusal re-ask plus one format repair. */ /** Reserved prompt budget for one refusal re-ask plus one format repair. */
@@ -36,6 +38,8 @@ final class PrescriptionAiGenerator
'files_top' => '必须返回{"files":[...]}这一个对象,没有其他顶层键,也不要输出解释文字。', 'files_top' => '必须返回{"files":[...]}这一个对象,没有其他顶层键,也不要输出解释文字。',
'files_entry' => '每个附件对象只能有file_id、status、findings、evidence_references四个键;status只能是processed、unreadable或unsupported;findings必须是非空字符串。', 'files_entry' => '每个附件对象只能有file_id、status、findings、evidence_references四个键;status只能是processed、unreadable或unsupported;findings必须是非空字符串。',
'files_refs' => 'evidence_references只能逐字使用本批清单中的file_id或已给出的来源编号,不得自造、改写或留空以外的无效编号。', 'files_refs' => 'evidence_references只能逐字使用本批清单中的file_id或已给出的来源编号,不得自造、改写或留空以外的无效编号。',
'syndrome_shape' => '只能返回disease、syndrome、treatment_principle、uncertainty四个键;syndrome与treatment_principle为非空字符串,证据不完整时也给出最可能的一个证名,不写待定。',
'textbook_shape' => '必须返回prescription_name、herbs、times_per_day、usage_days、rationale;herbs为非空数组,每味只含name、dosage、unit,dosage为每剂克数的正数且药名不重复;请选能按每味克数给出组成的教材汤剂或散剂代表方,不选中成药。',
'files_ids' => 'files数组必须与清单一一对应:条数相同、file_id逐字照抄且不重复,不要合并、跳过或新增编号。', 'files_ids' => 'files数组必须与清单一一对应:条数相同、file_id逐字照抄且不重复,不要合并、跳过或新增编号。',
]; ];
@@ -271,10 +275,22 @@ final class PrescriptionAiGenerator
$parsed = $retried; $parsed = $retried;
$value = $asked['value']; $value = $asked['value'];
} }
// 追问后仍拒绝针对本病例给剂量时,分两步取候选:先只做辨证,再在不含病例资料的
// 方剂学问答里按证名、治法取教材代表方及常用量。结果在 reason 里标明来源。
$textbook = false;
if ($requireCandidate && !self::candidateAvailable($parsed['candidate'] ?? null)) {
$derived = self::textbookCandidate($summaries, $parsed, $modelKey, $context, $progress, $transport, $checkpoint,
$inputBudget, $maxCalls, $dispensing, $catalogNames, $readIds);
if ($derived !== null) {
$parsed['candidate'] = $derived;
$textbook = true;
}
}
// A single medicine name outside the institution dictionary makes the whole plan // A single medicine name outside the institution dictionary makes the whole plan
// unmappable, so name it and re-ask instead of accepting an uncomparable candidate. // unmappable, so name it and re-ask instead of accepting an uncomparable candidate.
// The server never substitutes a medicine on the model's behalf. // The server never substitutes a medicine on the model's behalf.
for ($fix = 1; $catalogNames !== [] && $fix <= $insistRounds; $fix++) { // 教材代表方不走这一步:改名追问用的是整份病例提示词,模型会再次拒绝并覆盖已得到的候选方。
for ($fix = 1; !$textbook && $catalogNames !== [] && $fix <= $insistRounds; $fix++) {
$unknown = self::unknownNames($parsed['candidate'] ?? null, $catalogNames); $unknown = self::unknownNames($parsed['candidate'] ?? null, $catalogNames);
if ($unknown === []) { if ($unknown === []) {
break; break;
@@ -298,6 +314,8 @@ final class PrescriptionAiGenerator
for ($insist = 1; $insist <= $insistRounds; $insist++) { for ($insist = 1; $insist <= $insistRounds; $insist++) {
self::invalidateStep('final:insist:' . $insist, $progress, $checkpoint); self::invalidateStep('final:insist:' . $insist, $progress, $checkpoint);
} }
self::invalidateStep('final:syndrome', $progress, $checkpoint);
self::invalidateStep('final:textbook', $progress, $checkpoint);
throw new \RuntimeException('CANDIDATE_WITHHELD_BY_MODEL'); throw new \RuntimeException('CANDIDATE_WITHHELD_BY_MODEL');
} }
if ($candidateBlocked) { if ($candidateBlocked) {
@@ -655,6 +673,127 @@ final class PrescriptionAiGenerator
. "\n" . $base; . "\n" . $base;
} }
/**
* 分步候选:模型对带病例的开方请求坚持不给剂量,但会做辨证,也会回答不含病例的方剂学问题。
* 第一步只问证名与治法(带本分支已读证据);第二步只把病名、证名、治法交给方剂学问答,
* 取教材代表方及教材常用量。第二步不含任何患者资料。任何一步失败都返回 null,由调用方按
* 「模型未给出候选方」处理,绝不由服务端自行拼方。
*/
private static function textbookCandidate(array $summaries, array $parsed, string $modelKey, array $context, array &$progress,
callable $transport, ?callable $checkpoint, int $inputBudget, int $maxCalls, array $dispensing, array $catalogNames, array $readIds): ?array
{
$asked = self::askStrict('final:syndrome', self::syndromePrompt($summaries, $readIds), [], $modelKey, $context, $progress,
$transport, $checkpoint, $inputBudget, $maxCalls, static fn (string $content): ?array => self::parseSyndrome($content));
$syndrome = $asked['parsed'];
if ($syndrome === null) {
return null;
}
$asked = self::askStrict('final:textbook', self::textbookPrompt($syndrome, $catalogNames), [], $modelKey, $context, $progress,
$transport, $checkpoint, $inputBudget, $maxCalls, static fn (string $content): ?array => self::parseTextbook($content));
$formula = $asked['parsed'];
if ($formula === null) {
return null;
}
$basis = in_array($dispensing['dose_basis'] ?? '', ['per_dose', 'per_day'], true) ? $dispensing['dose_basis'] : 'per_dose';
$unit = trim((string) ($dispensing['unit'] ?? '')) !== '' ? trim((string) $dispensing['unit']) : '克';
$references = array_values(array_intersect((array) ($parsed['report']['evidence_references'] ?? []), $readIds));
if ($references === []) {
$references = array_slice($readIds, 0, 20);
}
if ($references === []) {
return null;
}
$herbs = [];
foreach ($formula['herbs'] as $herb) {
$herbs[] = ['name' => trim($herb['name']), 'dosage' => $herb['dosage'], 'unit' => $unit, 'dose_basis' => $basis,
'processing' => '明确无', 'formula_type' => '主方', 'instructions' => '明确无', 'evidence_references' => $references];
}
$refusal = is_array($parsed['candidate'] ?? null) ? trim((string) ($parsed['candidate']['reason'] ?? '')) : '';
$label = ($syndrome['disease'] !== '' ? $syndrome['disease'] . '·' : '') . $syndrome['syndrome'];
$warnings = ['教材代表方及教材常用量,未按本例个体加减;药味、剂量、服次与疗程须医师逐项核定。',
'模型未针对本病例直接开方,本方由其辨证结果推导,研究比较时应与直接开方的结果分开统计。'];
if ($syndrome['uncertainty'] !== '') {
$warnings[] = '辨证待核:' . mb_substr($syndrome['uncertainty'], 0, 70);
}
return ['status' => 'available_for_review',
'reason' => mb_substr('【教材代表方】模型未针对本病例给出剂量' . ($refusal !== '' ? '(' . mb_substr($refusal, 0, 80) . ')' : '')
. '。以下按其辨证「' . $label . '」、治法「' . $syndrome['treatment_principle'] . '」选取《方剂学》教材代表方及常用量,须医师复核后决定是否采用。', 0, 300),
'prescription_name' => mb_substr($formula['prescription_name'] . '(教材代表方)', 0, 150),
'prescription_type' => trim((string) ($dispensing['formulation'] ?? '')) !== '' ? trim((string) $dispensing['formulation']) : '汤剂',
'dose_basis' => $basis, 'herbs' => $herbs,
'usage_instruction' => '按教材常用量列出;具体剂型折算、用法、服次与疗程由医师确定。',
'times_per_day' => $formula['times_per_day'], 'usage_days' => $formula['usage_days'],
'rationale' => mb_substr($formula['rationale'], 0, 300), 'risk_warnings' => $warnings, 'evidence_references' => $references];
}
private static function syndromePrompt(array $summaries, array $allowedIds): string
{
return self::boundary() . '\n阶段=final:syndrome。供执业中医师参考的辨证辅助,本阶段只做辨证,不选方、不开药、不给剂量。'
. '请根据下列本分支已读证据,给出最可能的中医病名、证名(主证,可带兼证)与相应治法;证据不完整时也必须给出最可能的一个证名,不得写“待定”,'
. '把不确定之处与待核实事项写进uncertainty。不编造患者事实。'
. '只输出一个JSON对象:{"disease":"中医病名,无法判断时为空字符串","syndrome":"证名,不超过30字","treatment_principle":"治法,不超过30字","uncertainty":"不超过120字"}。'
. ($allowedIds !== [] ? "\nALLOWED_EVIDENCE_IDS=" . self::json($allowedIds) : '')
. "\nBRANCH_EVIDENCE_JSON=" . self::json($summaries);
}
/** 不含任何患者资料:只给病名、证名与治法,问教材代表方。 */
private static function textbookPrompt(array $syndrome, array $catalogNames): string
{
return '方剂学知识问答(不涉及具体患者)。' . ($syndrome['disease'] !== '' ? '病名:' . $syndrome['disease'] . '。' : '')
. '证候:' . $syndrome['syndrome'] . '。治法:' . $syndrome['treatment_principle'] . '。'
. '请选出《方剂学》《中医内科学》教材中与此证候、治法最对应的一首代表方,按教材所载组成与常用剂量给出,药味不超过20味。'
. '证候含兼证或有多首可选时,取最贴近主证的一首汤剂或散剂方,不选中成药,herbs不得为空。'
. '只输出一个JSON对象:{"prescription_name":"方名","herbs":[{"name":"药名","dosage":数值,"unit":"克"}],"times_per_day":数值或null,"usage_days":数值或null,"rationale":"方义,不超过300字"}。'
. ($catalogNames !== []
? '药名优先逐字使用MEDICINE_CATALOG中的对应名称(含炮制品,如“生山药”),清单中没有的药味照常写教材药名,不得因此删减原方药味;'
: '')
. 'dosage为每剂克数(JSON数字);教材载有常用服次、疗程时填写,否则为null。'
. ($catalogNames !== [] ? "\nMEDICINE_CATALOG=" . self::json($catalogNames) : '');
}
private static function parseSyndrome(string $content): ?array
{
$value = self::object($content);
if ($value === null) {
return null;
}
$value += ['disease' => '', 'uncertainty' => ''];
if (!self::keys($value, ['disease', 'syndrome', 'treatment_principle', 'uncertainty'])
|| !self::text($value['syndrome'] ?? null, 60) || !self::text($value['treatment_principle'] ?? null, 60)
|| !is_string($value['disease']) || mb_strlen($value['disease']) > 30 || !is_string($value['uncertainty'])
|| preg_match('/待定|不明|无法/u', $value['syndrome'])) {
return self::reject('syndrome_shape', strlen($content));
}
return ['disease' => trim($value['disease']), 'syndrome' => trim($value['syndrome']),
'treatment_principle' => trim($value['treatment_principle']), 'uncertainty' => trim(mb_substr($value['uncertainty'], 0, 400))];
}
private static function parseTextbook(string $content): ?array
{
$value = self::object($content);
if ($value === null) {
return null;
}
if (!self::keys($value, ['prescription_name', 'herbs', 'times_per_day', 'usage_days', 'rationale', 'usage_instruction'])
|| !self::text($value['prescription_name'] ?? null, 100) || !self::text($value['rationale'] ?? null, 6000)
|| !is_array($value['herbs'] ?? null) || !array_is_list($value['herbs']) || $value['herbs'] === [] || count($value['herbs']) > 30) {
return self::reject('textbook_shape', strlen($content));
}
$seen = [];
foreach ($value['herbs'] as $herb) {
if (!is_array($herb) || !self::text($herb['name'] ?? null, 50) || !self::positiveNumber($herb['dosage'] ?? null) || $herb['dosage'] > 500
|| isset($seen[trim($herb['name'])])) {
return self::reject('textbook_shape', strlen($content));
}
$seen[trim($herb['name'])] = true;
}
foreach (['times_per_day' => 6, 'usage_days' => 365] as $key => $maximum) {
$number = $value[$key] ?? null;
$value[$key] = self::positiveNumber($number) && $number <= $maximum ? $number : null;
}
return $value;
}
private static function candidateAvailable($candidate): bool private static function candidateAvailable($candidate): bool
{ {
return is_array($candidate) && ($candidate['status'] ?? '') === 'available_for_review' return is_array($candidate) && ($candidate['status'] ?? '') === 'available_for_review'
@@ -742,10 +881,16 @@ final class PrescriptionAiGenerator
return self::reject('candidate_shape', strlen($content)); return self::reject('candidate_shape', strlen($content));
} }
if ($candidate['status'] !== 'available_for_review') { if ($candidate['status'] !== 'available_for_review') {
return self::keys($candidate, ['status', 'reason', 'herbs']) && $candidate['herbs'] === [] // 模型拒绝开方时常把完整候选键一并带上(置空或附说明)。拒绝回答只认 status、reason
? $value : self::reject('candidate_shape', strlen($content)); // 与空 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 || !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::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'] === []) { || !self::strings($candidate['risk_warnings'] ?? null) || !self::references($candidate['evidence_references'] ?? null, $knownIds) || $candidate['evidence_references'] === []) {
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace app\common\service\prescriptionai;
use RuntimeException;
final class PrescriptionAiLaneGuard
{
public const LANES = ['prepare', 'qwen', 'openai'];
/** Shared locks allow several supervised workers. A scheduled fallback needs the lane exclusively. */
public static function acquire(string $runtime, string $lane, int $operation)
{
if (!in_array($lane, self::LANES, true)) {
throw new RuntimeException('未知处方 AI 队列');
}
$directory = $runtime . 'lock';
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) {
throw new RuntimeException('无法创建处方 AI 队列锁目录');
}
return self::lock($directory . '/prescription_ai_' . $lane . '.lock', 'c+', $operation);
}
public static function busy(string $runtime, string $lane): bool
{
$path = $runtime . 'lock/prescription_ai_' . $lane . '.lock';
if (!is_file($path)) { return false; }
$probe = self::lock($path, 'r', LOCK_EX | LOCK_NB);
if ($probe === null) { return true; }
fclose($probe);
return false;
}
private static function lock(string $path, string $mode, int $operation)
{
$handle = @fopen($path, $mode);
if ($handle === false) {
throw new RuntimeException('无法打开处方 AI 队列锁');
}
if (flock($handle, $operation, $wouldBlock)) {
return $handle;
}
fclose($handle);
if ($wouldBlock) {
return null;
}
throw new RuntimeException('无法锁定处方 AI 队列');
}
/** Detect workers started before lane locks were introduced, without requiring a service restart. */
public static function linuxWorkers(string $think, string $proc = '/proc'): array
{
$target = realpath($think);
$processFiles = glob($proc . '/[0-9]*/comm');
if (!$target || !is_readable($proc . '/self/cmdline') || $processFiles === false) {
throw new RuntimeException('处方 AI 巡检无法读取 Linux 进程信息');
}
$found = [];
foreach ($processFiles as $file) {
$name = trim((string) @file_get_contents($file));
if (!preg_match('/^php(?:-?cli|[0-9.]+)?$/iD', $name) && $name !== basename(PHP_BINARY)) {
continue;
}
$pid = dirname($file);
$arguments = explode("\0", rtrim((string) @file_get_contents($pid . '/cmdline'), "\0"));
$index = array_search('prescription-ai:work', $arguments, true);
if ($index === false || $index < 2) {
continue;
}
$script = $arguments[$index - 1];
if (basename($script) !== 'think') {
continue;
}
if ($script[0] !== '/') {
$cwd = realpath($pid . '/cwd');
if ($cwd === false) {
if (!is_dir($pid)) { continue; } // A short-lived worker can exit during inspection.
throw new RuntimeException('无法核对处方 AI 消费者的工作目录,请使用消费者的系统账号运行巡检');
}
$script = $cwd . '/' . $script;
}
if (realpath($script) !== $target) {
continue;
}
$lane = 'prepare';
foreach (array_slice($arguments, $index + 1) as $offset => $argument) {
if (str_starts_with($argument, '--lane=')) {
$lane = substr($argument, 7);
} elseif ($argument === '--lane') {
$lane = $arguments[$index + $offset + 2] ?? '';
}
}
if (in_array($lane, self::LANES, true)) {
if (!in_array('--once', $arguments, true)) {
$found[$lane] = 'resident';
} elseif (!isset($found[$lane])) {
$found[$lane] = 'single_run';
}
if (count(array_keys($found, 'resident', true)) === count(self::LANES)) { break; }
}
}
return $found;
}
}
@@ -110,9 +110,17 @@ final class PrescriptionAiPolicy
? 'cancelled' : 'failed'; ? 'cancelled' : 'failed';
} }
public static function retryAt(int $attempts, int $now, bool $retryable, int $maxAttempts): ?int public static function retryAt(int $attempts, int $now, bool $retryable, int $maxAttempts, string $code = ''): ?int
{ {
return $retryable && $attempts < $maxAttempts ? $now + ($attempts <= 1 ? 30 : 120) : null; if (!$retryable || $attempts >= $maxAttempts) {
return null;
}
// 模型网关暂时无可用账号/繁忙时往往持续数分钟,30 秒内重试只会再撞一次;
// 拉长等待让重试越过这段时间。已完成的阶段有缓存,重试从失败处继续。
if (in_array($code, ['UPSTREAM_BUSY', 'UPSTREAM_UNAVAILABLE'], true)) {
return $now + ($attempts <= 1 ? 120 : 600);
}
return $now + ($attempts <= 1 ? 30 : 120);
} }
public static function errorMessage(string $code): string public static function errorMessage(string $code): string
@@ -70,9 +70,15 @@ final class PrescriptionAiProgress
$result = self::present($meta, $now, self::number($task['started_at'] ?? null), $end); $result = self::present($meta, $now, self::number($task['started_at'] ?? null), $end);
$result['attempt'] = self::number($task['total_attempts'] ?? $task['attempts'] ?? null, 1000000) ?? 0; $result['attempt'] = self::number($task['total_attempts'] ?? $task['attempts'] ?? null, 1000000) ?? 0;
if ($status === 'retry_wait') { if ($status === 'retry_wait') {
$result['wait_remaining_seconds'] = self::remaining($task['next_run_at'] ?? null, $now); $result['next_run_at'] = self::number($task['next_run_at'] ?? null);
$result['notice'] = ($task['error_code'] ?? '') === 'BUDGET_PAUSED' $result['wait_remaining_seconds'] = self::remaining($result['next_run_at'], $now);
? '今日模型任务额度已用完,到时间后自动继续。' : '本次未完成,已安排自动重试。'; if ($result['wait_remaining_seconds'] === 0) {
$result['notice'] = '已到可重试时间,等待后台领取任务。';
} elseif (($task['error_code'] ?? '') === 'BUDGET_PAUSED' && $result['next_run_at'] > 0) {
$result['notice'] = '今日模型任务额度已用完,最早可于 ' . date('Y-m-d H:i:s', $result['next_run_at']) . '(服务器时间)领取重试。';
} else {
$result['notice'] = '本次未完成,已安排自动重试。';
}
} }
if (in_array($status, ['failed', 'retry_wait'], true) if (in_array($status, ['failed', 'retry_wait'], true)
&& in_array($lastStage, ['text', 'files', 'reduce', 'final', 'validating', 'comparing'], true)) { && in_array($lastStage, ['text', 'files', 'reduce', 'final', 'validating', 'comparing'], true)) {
@@ -234,6 +234,24 @@ final class PrescriptionAiStore
]); ]);
} }
/** Read-only snapshot for retry scheduling. Only a successful claim reserves a daily slot. */
public static function exhaustedModels(array $models, int $now): array
{
if (!$models) { return []; }
$keys = [];
foreach ($models as $model) {
$keys[date('Y-m-d', $now) . ':' . $model] = $model;
}
$exhausted = Db::name('prescription_ai_limit')->whereIn('limit_key', array_keys($keys))
->where('used_count', '>=', self::dailyModelTaskLimit())->column('limit_key');
return array_map(static fn ($key): string => $keys[$key], $exhausted);
}
private static function dailyModelTaskLimit(): int
{
return max(1, (int) config('prescription_analysis.daily_model_tasks', 200));
}
public static function claimTask(string $model): ?array public static function claimTask(string $model): ?array
{ {
if (!in_array($model, PrescriptionAiPolicy::MODELS, true)) { if (!in_array($model, PrescriptionAiPolicy::MODELS, true)) {
@@ -272,7 +290,7 @@ final class PrescriptionAiStore
self::refreshBatch((int) $row['batch_id']); self::refreshBatch((int) $row['batch_id']);
return null; return null;
} }
if ((int) $budget['used_count'] >= max(1, (int) config('prescription_analysis.daily_model_tasks', 200))) { if ((int) $budget['used_count'] >= self::dailyModelTaskLimit()) {
Db::name('prescription_ai_task')->where('id', $id)->update([ Db::name('prescription_ai_task')->where('id', $id)->update([
'status' => 'retry_wait', 'error_code' => 'BUDGET_PAUSED', 'status' => 'retry_wait', 'error_code' => 'BUDGET_PAUSED',
'next_run_at' => strtotime('tomorrow', $now), 'updated_at' => $now, 'next_run_at' => strtotime('tomorrow', $now), 'updated_at' => $now,
@@ -386,7 +404,7 @@ final class PrescriptionAiStore
$now = time(); $now = time();
$code = preg_match('/^[A-Z0-9_]{1,64}$/D', $code) ? $code : 'INTERNAL_ERROR'; $code = preg_match('/^[A-Z0-9_]{1,64}$/D', $code) ? $code : 'INTERNAL_ERROR';
$next = PrescriptionAiPolicy::retryAt((int) $task['attempts'], $now, $retryable, $next = PrescriptionAiPolicy::retryAt((int) $task['attempts'], $now, $retryable,
max(1, (int) config('prescription_analysis.max_attempts', 3))); max(1, (int) config('prescription_analysis.max_attempts', 3)), $code);
Db::name('prescription_ai_task')->where('id', $task['id'])->where('lock_token', $task['lock_token']) Db::name('prescription_ai_task')->where('id', $task['id'])->where('lock_token', $task['lock_token'])
->where('status', 'running')->update([ ->where('status', 'running')->update([
'status' => $next === null ? 'failed' : 'retry_wait', 'next_run_at' => $next ?? $now, 'status' => $next === null ? 'failed' : 'retry_wait', 'next_run_at' => $next ?? $now,
+1
View File
@@ -19,6 +19,7 @@ return [
'followup-audio:probe' => 'app\\command\\FollowupAudioProbe', 'followup-audio:probe' => 'app\\command\\FollowupAudioProbe',
'followup-audio:cleanup' => 'app\\command\\FollowupAudioCleanup', 'followup-audio:cleanup' => 'app\\command\\FollowupAudioCleanup',
'prescription-ai:work' => 'app\\command\\PrescriptionAiWork', 'prescription-ai:work' => 'app\\command\\PrescriptionAiWork',
'prescription-ai:dispatch' => 'app\\command\\PrescriptionAiDispatch',
'prescription-ai:backfill' => 'app\\command\\PrescriptionAiBackfill', 'prescription-ai:backfill' => 'app\\command\\PrescriptionAiBackfill',
// 定时任务 // 定时任务
'crontab' => 'app\common\command\Crontab', 'crontab' => 'app\common\command\Crontab',
+1 -1
View File
@@ -10,7 +10,7 @@ return [
'lease_seconds' => 600, 'lease_seconds' => 600,
'max_attempts' => 3, 'max_attempts' => 3,
'max_manual_retries' => 2, 'max_manual_retries' => 2,
'daily_model_tasks' => (int) env('prescription_analysis.DAILY_MODEL_TASKS', 200), 'daily_model_tasks' => (int) env('prescription_analysis.DAILY_MODEL_TASKS', 5000),
// Analyses of one prescription per day. Regenerating after each change is the normal way to // Analyses of one prescription per day. Regenerating after each change is the normal way to
// review a case, so this is a budget guard, not a correctness limit. // review a case, so this is a budget guard, not a correctness limit.
'daily_patient_batches' => (int) env('prescription_analysis.DAILY_PATIENT_BATCHES', 20), 'daily_patient_batches' => (int) env('prescription_analysis.DAILY_PATIENT_BATCHES', 20),
+2 -2
View File
@@ -113,10 +113,10 @@ return [
'order_edit_all_roles' => [0, 3, 4, 9, 6], 'order_edit_all_roles' => [0, 3, 4, 9, 6],
// 处方库:以下角色ID + 超级管理员(root) 可查看/编辑/删除全部;他人仅可管理自己创建的,公开处方对他人只读 // 处方库:以下角色ID + 超级管理员(root) 可查看/编辑/删除全部;他人仅可管理自己创建的,公开处方对他人只读
'prescription_library_manage_all_roles' => [0, 3, 4, 9, 6], 'prescription_library_manage_all_roles' => [0, 3, 4, 9, 6, 13],
// 消费者处方单:以下角色 + root 可对「待审核」处方进行通过/驳回(驳回即作废处方) // 消费者处方单:以下角色 + root 可对「待审核」处方进行通过/驳回(驳回即作废处方)
'prescription_audit_roles' => [0, 3, 4, 9, 6], 'prescription_audit_roles' => [0, 3, 4, 9, 6, 13],
// 处方业务订单 internal_cost 等财务字段:以下角色 ID + root 可见 // 处方业务订单 internal_cost 等财务字段:以下角色 ID + root 可见
'prescription_order_finance_roles' => [0, 3, 4, 9, 6], 'prescription_order_finance_roles' => [0, 3, 4, 9, 6],
@@ -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');
@@ -0,0 +1,4 @@
-- 非默认表前缀需替换 zyt_。保留管理员已有的暂停状态和运行周期。
INSERT INTO `zyt_dev_crontab` (`name`, `type`, `system`, `remark`, `command`, `params`, `status`, `expression`, `last_time`, `create_time`, `update_time`)
SELECT '处方 AI 分析队列', 1, 0, '每分钟巡检资料准备、通义千问和 OpenAI 消费者,只对缺失的队列派发单轮处理', 'prescription-ai:dispatch', '', 1, '* * * * *', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
WHERE NOT EXISTS (SELECT 1 FROM `zyt_dev_crontab` WHERE `command` = 'prescription-ai:dispatch' AND `delete_time` IS NULL);
View File

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

File diff suppressed because one or more lines are too long
@@ -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-cb8kiyQ6.js";import{o,q as r,r as a,v as n,D as c,s}from"./.pnpm-Be4vLD2y.js";import"./index-Bu-41eax.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-cb8kiyQ6.js";import{o,q as r,r as t,v as s}from"./.pnpm-Be4vLD2y.js";import"./index-Bu-41eax.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-Be4vLD2y.js";import{a as V}from"./doctor-B0xKWrQv.js";import{s as q,_ as A}from"./index-Bu-41eax.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
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,cm as w,bq as K,M as x}from"./.pnpm-Be4vLD2y.js";import{bB as z,_ as H}from"./index-Bu-41eax.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 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
@@ -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 P,v as U,K as $,L as j,a2 as H,p as K,M as v,dk as c}from"./.pnpm-Be4vLD2y.js";import{bC as Y,_ as q}from"./index-Bu-41eax.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 C(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=C(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 N(){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(),N();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=$,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)),U(o,{type:"primary",onClick:e[0]||(e[0]=d=>y.value=!1)},{default:I(()=>[...e[2]||(e[2]=[j("离开",-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),[[P,!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,dm 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-Be4vLD2y.js";import M from"./RecordingPlaybackBlock-sW-ftWGW.js";import{U as x}from"./index-CyrXCy7a.js";import{bG as G,f as c,bH as R,bI as H,_ as K}from"./index-Bu-41eax.js";import"./RecordingVideoPlayer-C-NchRlR.js";import"./file-DB9QoM56.js";const j={class:"call-record-panel"},A={key:0,class:"call-record-toolbar"},F={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 G({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 I(e){const t=b(e);if(!t){c.msgError("上传成功但未返回视频地址");return}try{const a=await H({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,E=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:I},{default:i(()=>[o(a,{type:"primary"},{default:i(()=>[...t[0]||(t[0]=[n("上传视频",-1)])]),_:1})]),_:1},512)])),D((r(),w(E,{data:g.value,border:"",stripe:""},{empty:i(()=>[y("div",F,[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};
View File
File diff suppressed because one or more lines are too long
View File
@@ -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-Be4vLD2y.js";import{bJ as A,_ as H}from"./index-Bu-41eax.js";const J={class:"case-record-list"},K={key:0,class:"mb-3 flex justify-end"},Y={key:0},G={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",J,[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",G,"—"))]),_: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};
File diff suppressed because one or more lines are too long
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
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-CKpxwCDa.js";import"./.pnpm-Be4vLD2y.js";import"./index-Bu-41eax.js";export{o as default};

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