Compare commits

...
56 Commits
Author SHA1 Message Date
Your Name 735b607f80 更新 2026-09-28 14:13:15 +08:00
Your Name 4ef3cef6a0 更新 2026-09-28 11:32:28 +08:00
gr 49fc974421 Merge branch 'master' into mcp 2026-09-28 10:05:13 +08:00
gr 88ce52620a i更新 2026-09-28 10:04:24 +08:00
gr 0a17f071fc i更新 2026-09-28 10:03:20 +08:00
gr 8e2b4fc763 更新 2026-09-24 16:18:52 +08:00
gr b7e91f5fe3 更新 2026-09-24 11:48:20 +08:00
gr 68fc86a167 ;rgb:0000/0000/0000
gengx
2026-09-24 11:03:44 +08:00
gr bd22e5f476 更新 2026-09-24 09:45:44 +08:00
Your Name dbf474ddd7 更新 2026-09-21 10:26:14 +08:00
Your Name bbe3e870a1 更新 2026-09-10 15:33:21 +08:00
Your Name caab2cabe3 更新 2026-09-10 15:23:03 +08:00
Your Name 3c7b88bb15 i
`Merge branch 'master' into chufang-9-9
2026-09-10 15:20:45 +08:00
Your Name 36975c6c1b 更新 2026-09-10 15:19:17 +08:00
long 6325ba88ff feat(iam): provision authorized first-login users as medical assistants 2026-09-10 12:15:15 +08:00
long f8b6196205 fix(auth): 快捷登录 - 保留顶部切换并优化底部入口 2026-09-10 11:49:24 +08:00
long aa0d22bbe2 feat(auth): 统一身份 - 增加可选IAM快捷登录并保留原业务权限 2026-09-10 10:33:03 +08:00
Your Name 27fbef9321 gengx 2026-09-09 15:52:46 +08:00
Your Name cb10e75ead 更新 2026-09-09 15:47:48 +08:00
Your Name bd5d5c5f08 更新 2026-09-09 14:08:11 +08:00
Your Name 083fd857e8 更新 2026-09-09 14:04:09 +08:00
Your Name 9be2e18ea6 更新 2026-09-09 12:25:20 +08:00
Your Name 691c749f34 Merge branch 'master' into UI-09-03 2026-09-09 12:19:39 +08:00
Your Name 40319eea41 更新 2026-09-09 12:18:17 +08:00
gr c1f7287331 igengx 2026-09-09 10:48:05 +08:00
gr 9d91ff90ae ;rgb:0000/0000/0000 2026-09-09 10:02:43 +08:00
gr 1b8e166b33 i更新 2026-09-09 09:58:12 +08:00
Your Name 0cea43b027 Merge branch 'master' into UI-09-03 2026-09-08 16:16:25 +08:00
long d0e2422155 revert(iam): 统一登录 - 撤销 IAM Hub 接入 2026-09-08 16:14:59 +08:00
long 9206d5ea62 docs: record ZYT IAM integration evidence 2026-09-08 13:42:22 +08:00
long bd0a3d3b96 fix: complete IAM login after OIDC callback 2026-09-08 13:34:18 +08:00
long a5f4c4472d feat: integrate ZYT admin with IAM Hub 2026-09-08 13:26:41 +08:00
Your Name 9ef6eb8d67 更新 2026-09-07 12:30:42 +08:00
Your Name d5164b7369 更新 2026-09-07 10:07:47 +08:00
Your Name cf3fbdc5ef 更新 2026-09-03 18:05:32 +08:00
Your Name 928f72ec3d 更新 2026-09-03 16:03:41 +08:00
Your Name b4c11881b4 更新 2026-09-01 18:12:39 +08:00
Your Name 58ffde808f 更新 2026-09-01 17:49:29 +08:00
Your Name 486acc465d 更新 2026-09-01 17:18:42 +08:00
Your Name 398f9f3726 更新 2026-09-01 11:26:47 +08:00
Your Name 5bd5eae62d 更新 2026-09-01 10:42:16 +08:00
Your Name 456dd667df 更新 2026-08-31 15:17:34 +08:00
Your Name ed48f8be31 更新 2026-08-28 18:24:37 +08:00
gr 5e22d423d4 更新 2026-08-28 14:07:30 +08:00
gr 7f1ed49cc8 更新 2026-08-28 14:06:56 +08:00
Your Name 43ad07208f 更新 2026-08-27 16:26:14 +08:00
Your Name 4b8b4eb649 更新 2026-08-27 16:02:38 +08:00
Your Name 75e214dc08 更新 2026-08-27 15:41:09 +08:00
Your Name 74ff568ba4 更新 2026-08-27 14:54:18 +08:00
Your Name 2fa8492c56 更新 2026-08-27 14:23:23 +08:00
Your Name b5b14516a1 更新 2026-08-25 15:05:49 +08:00
Your Name 381fe65367 更新 2026-08-25 14:53:17 +08:00
Your Name af603a4e9a 更新 2026-08-25 14:16:31 +08:00
Your Name f24afa116f 更新 2026-08-25 11:40:58 +08:00
Your Name b8ccbaf567 更新 2026-08-25 10:45:24 +08:00
Your Name af1db59c07 更新 2026-08-25 09:41:26 +08:00
1349 changed files with 113859 additions and 21408 deletions
+1
View File
@@ -32,3 +32,4 @@ app/.test-tmp-stream/
/.spool
TUICallKit-Vue3/.env
/.codegraph
app/artifacts/
+475 -423
View File
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const ts = require('typescript')
const { parse, compileScript, compileTemplate, compileStyleAsync } = require('@vue/compiler-sfc')
const root = path.resolve(__dirname, '..')
const read = (relative) => fs.readFileSync(path.join(root, 'src', relative), 'utf8')
const utils = ts.transpileModule(read('utils/appointment-type.ts'), {
compilerOptions: { module: ts.ModuleKind.CommonJS }
}).outputText
const exportsObject = {}
vm.runInNewContext(utils, { exports: exportsObject })
for (const [value, expected] of [
['video', '视频问诊'], ['text', '图文问诊'], [undefined, '视频问诊'],
[null, '视频问诊'], ['', '视频问诊'], [' ', '视频问诊'],
['phone', '电话问诊'], ['other', '未知']
]) {
assert.equal(exportsObject.appointmentTypeDescription(value), expected)
}
const callers = [
'views/tcm/appointment/list.vue',
'views/tcm/appointment/list_h5.vue',
'views/patient/reception/index.vue'
]
for (const caller of callers) {
assert.match(read(caller), /chatDialogRef\.value\?\.open\(\{[\s\S]*?appointmentType: row\.appointment_type,/)
assert.match(read(caller), /appointmentId: Number\(row\.id\)/)
}
const chat = read('components/chat-dialog/index.vue')
assert.match(chat, /appointmentType\.value = data\.appointmentType/)
assert.match(chat, /class="chat-appointment-type">\{\{ appointmentTypeLabel \}\}/)
const form = read('views/tcm/diagnosis/appointment.vue')
assert.match(form, /<el-radio value="text">图文问诊<\/el-radio>/)
assert.match(form, /appointmentType: 'video'/)
assert.match(form, /form\.appointmentType = 'video'/)
assert.match(form, /appointment_type: form\.appointmentType/)
async function main() {
const components = [
...callers, 'components/chat-dialog/index.vue',
'views/tcm/diagnosis/appointment.vue', 'views/consumer/prescription/guahao.vue',
'views/first_visit/my_patients/index.vue', 'views/tcm/diagnosis/index.vue', 'views/tcm/diagnosis/index_h5.vue'
]
for (const filename of components) {
const { descriptor, errors } = parse(read(filename), { filename })
assert.deepEqual(errors, [], `${filename} parses`)
const script = compileScript(descriptor, { id: filename })
const template = compileTemplate({
source: descriptor.template.content,
filename, id: filename,
compilerOptions: { bindingMetadata: script.bindings }
})
assert.deepEqual(template.errors, [], `${filename} template compiles`)
for (const style of descriptor.styles) {
const result = await compileStyleAsync({
source: style.content, filename: path.join(root, 'src', filename),
id: filename, scoped: style.scoped, preprocessLang: style.lang
})
assert.deepEqual(result.errors, [], `${filename} styles compile`)
}
}
console.log(`Appointment type defaults/labels, ${callers.length} chat entry contracts, ${components.length} Vue components: OK`)
}
main().catch((error) => { console.error(error); process.exitCode = 1 })
+24
View File
@@ -0,0 +1,24 @@
import request from '@/utils/request'
/** AI 助手(MCP)后台接口:挂在 /mcp/admin 下,沿用后台登录令牌 */
const opts = { urlPrefix: 'mcp' }
/** AI 授权列表(有 ai.grant/lists 看全部,否则只看自己的) */
export function aiGrantLists(params: any) {
return request.get({ url: '/admin/grants', params }, opts)
}
/** 撤销 AI 授权 */
export function aiGrantRevoke(params: { id: number }) {
return request.post({ url: '/admin/revoke', params }, opts)
}
/** AI 访问日志 */
export function aiAccessLogLists(params: any) {
return request.get({ url: '/admin/logs', params }, opts)
}
/** AI 数据目录与覆盖情况 */
export function aiCatalogLists(params: any) {
return request.get({ url: '/admin/catalog', params }, opts)
}
+5 -2
View File
@@ -100,6 +100,7 @@ export interface OssCredentialsResponse {
host?: string
cdn_domain?: string
key_prefix?: string
object_key?: string
max_size?: number
duration?: number
expired_time?: number
@@ -111,8 +112,10 @@ export interface OssCredentialsResponse {
}
}
export type OssDirectUploadType = 'video' | 'voice' | 'desktop_package'
/** 申请 STS 临时凭证 */
export function getOssCredentials(params: { type: 'video' }) {
export function getOssCredentials(params: { type: OssDirectUploadType; name?: string }) {
return request.post({
url: '/upload/ossCredentials',
params
@@ -121,7 +124,7 @@ export function getOssCredentials(params: { type: 'video' }) {
/** 直传完成回执:写 file 表 + HEAD 校验 */
export function confirmOssUpload(params: {
type: 'video'
type: OssDirectUploadType
key: string
name: string
size: number
+169 -10
View File
@@ -154,6 +154,51 @@ export function firstVisitConversionOverview(params: FirstVisitConversionParams)
)
}
export interface FirstVisitConversionFansDetailParams extends FirstVisitConversionParams {
entity_type: 'dept' | 'member'
entity_id: string | number
admin_id?: number
page_no: number
page_size: number
}
export interface FirstVisitConversionFanDetailRow {
external_userid: string
customer_name: string
wecom_userid: string
wecom_staff_name: string
add_time: string | null
is_deleted?: boolean
delete_time?: string | null
}
export interface FirstVisitConversionFansDetailResult {
can_view_deleted_fans?: boolean
lists?: FirstVisitConversionFanDetailRow[]
rows?: FirstVisitConversionFanDetailRow[]
total?: number
count?: number
page_no?: number
page_size?: number
entity?: {
type?: 'dept' | 'member'
id?: string | number
admin_id?: number
name?: string
add_fans_count?: number
deleted_fans_count?: number
}
date_range?: [string, string]
}
/** 一诊加粉明细:时间、渠道及行实体均由调用方显式透传,服务端仍需按 DataScope 收窄。 */
export function firstVisitConversionFansDetail(params: FirstVisitConversionFansDetailParams) {
return request.get(
{ url: '/firstvisit.conversion/fansDetail', params, timeout: 120000 },
{ ignoreCancelToken: true }
)
}
export interface FirstVisitRegistrationStatsParams {
time_type: 'today' | 'yesterday' | 'week' | 'month'
dept_id?: number
@@ -193,14 +238,109 @@ export function wecomPromotionOverview() {
export function wecomPromotionSavePool(params: Record<string, unknown>) {
return request.post({ url: '/firstvisit.wecomPromotion/savePool', params, timeout: 120000 })
}
export interface WecomPromotionTagGroup {
group_id: string
group_name: string
tag: Array<{ id: string; name: string }>
}
export function wecomPromotionTagOptions() {
return request.get<{ tag_groups: WecomPromotionTagGroup[] }>({
url: '/firstvisit.wecomPromotion/tagOptions'
})
}
export function wecomPromotionCreateTag(params: { name: string }) {
return request.post<{ tag: { id: string; name: string }; group_id: string; group_name: string; reused: boolean }>({
url: '/firstvisit.wecomPromotion/createTag', params, timeout: 30000
}, { ignoreCancelToken: true })
}
export function wecomPromotionUploadWelcomeMedia(file: File, type: 'image' | 'video' | 'file') {
const data = new FormData()
data.append('file', file)
data.append('type', type)
return request.post<{ asset_id: string; name: string; type: string }>({
url: '/firstvisit.wecomPromotion/uploadWelcomeMedia',
data,
headers: { 'Content-Type': 'multipart/form-data' },
timeout: 120000
}, { ignoreCancelToken: true })
}
export function wecomPromotionSaveWidget(params: Record<string, unknown>) {
return request.post({ url: '/firstvisit.wecomPromotion/saveWidget', params })
}
export function wecomPromotionDeletePool(params: { id: number }) {
return request.post({ url: '/firstvisit.wecomPromotion/deletePool', params })
}
export function wecomPromotionSaveWidget(params: Record<string, unknown>) {
return request.post({ url: '/firstvisit.wecomPromotion/saveWidget', params })
}
export interface WecomPromotionBatchSetOperatorsParams {
pool_ids: number[]
operator_admin_ids: number[]
action: 'grant' | 'revoke'
}
export interface WecomPromotionBatchSetOperatorsResult {
action: 'grant' | 'revoke'
pool_ids: number[]
operator_admin_ids: number[]
affected: number
}
export function wecomPromotionBatchSetOperators(params: WecomPromotionBatchSetOperatorsParams) {
return request.post<WecomPromotionBatchSetOperatorsResult>({
url: '/firstvisit.wecomPromotion/batchSetOperators',
params
})
}
export interface WecomPromotionBatchUpdatePoolsParams {
pool_ids: number[]
changes: {
skip_verify?: 0 | 1
fallback_url?: string
status?: 0 | 1
automation_config?: Record<string, unknown>
member_status?: {
member_admin_ids: number[]
status: 0 | 1
}
}
}
export interface WecomPromotionBatchUpdatePoolResult {
id: number
name: string
success: boolean
sync_error?: string
sync_queued?: boolean
sync_status?: WecomPromotionMemberSyncStatus
member_matched?: number
member_updated?: number
error?: string
}
export interface WecomPromotionBatchUpdatePoolsResult {
pool_ids: number[]
updated: number
failed: number
sync_error_count: number
sync_queued_count: number
member_matched: number
member_updated: number
results: WecomPromotionBatchUpdatePoolResult[]
}
export function wecomPromotionBatchUpdatePools(params: WecomPromotionBatchUpdatePoolsParams) {
return request.post<WecomPromotionBatchUpdatePoolsResult>({
url: '/firstvisit.wecomPromotion/batchUpdatePools',
params,
timeout: 120000
}, { ignoreCancelToken: true })
}
export function wecomPromotionDeletePool(params: { id: number }) {
return request.post({ url: '/firstvisit.wecomPromotion/deletePool', params, timeout: 120000 })
}
export function wecomPromotionSaveLink(params: Record<string, unknown>) {
return request.post({ url: '/firstvisit.wecomPromotion/saveLink', params })
@@ -218,9 +358,28 @@ export function wecomPromotionCheckApiPermission() {
return request.post({ url: '/firstvisit.wecomPromotion/checkApiPermission' })
}
export function wecomPromotionSyncRemoteLinks(params: { pool_id: number }) {
return request.post({ url: '/firstvisit.wecomPromotion/syncRemoteLinks', params, timeout: 120000 })
}
export function wecomPromotionSyncRemoteLinks(params: { pool_id: number }) {
return request.post({ url: '/firstvisit.wecomPromotion/syncRemoteLinks', params, timeout: 120000 })
}
export type WecomPromotionMemberSyncStatus = 'synced' | 'pending' | 'failed' | 'blocked'
export interface WecomPromotionMemberSyncResult {
pool_id: number
sync_status: WecomPromotionMemberSyncStatus
sync_error: string
sync_queued: boolean
range_userids: string[]
range_department_ids: string[]
}
export function wecomPromotionSyncMemberRange(params: { pool_id: number }) {
return request.post<WecomPromotionMemberSyncResult>({
url: '/firstvisit.wecomPromotion/syncMemberRange',
params,
timeout: 120000
}, { ignoreCancelToken: true, isOpenRetry: false })
}
export function wecomPromotionRemoteLinkDetail(params: { id: number }) {
return request.get({ url: '/firstvisit.wecomPromotion/remoteLinkDetail', params })
+5
View File
@@ -5,6 +5,11 @@ export function qywxCustomerLists(params: any) {
return request.get({ url: '/qywx.customer/lists', params })
}
// 删除一条本地企业微信客户同步记录
export function qywxCustomerDelete(params: { id: number }) {
return request.post({ url: '/qywx.customer/delete', params })
}
// 同步企业微信客户
export function qywxCustomerSync() {
return request.post({ url: '/qywx.customer/sync' })
+55 -7
View File
@@ -275,14 +275,52 @@ export function generateOrderQrcode(params: any) {
// ========== IM / 企业微信聊天记录 ==========
/** 腾讯云 IM 单聊漫游消息(诊单维度:患者 patient_* 与医生 doctor_*) */
export function getImChatMessages(params: { diagnosis_id: number; only_archived?: 0 | 1 }) {
return request.get({ url: '/tcm.diagnosis/getImChatMessages', params })
export interface ImChatMessagesResponse {
lists: any[]
patient_im_id?: string
patient_name?: string
sync_error?: string
}
/** 触发后台异步同步:从腾讯云 IM 拉取诊单聊天记录入归档表,请求即返回 */
export function triggerImChatSync(data: { diagnosis_id: number }) {
return request.post({ url: '/tcm.diagnosis/triggerImChatSync', data })
export interface ImChatSyncProgress {
sync_token?: string
completed: boolean
phase?: 'checking_accounts' | 'syncing' | 'completed'
checked_accounts?: number
candidate_accounts?: number
skipped_accounts?: number
inserted: number
processed_peers: number
total_peers: number
error?: string
errors?: string[]
}
/** 保留接口错误原因,并由面板决定何时提示同步完成。 */
function unwrapImChatResponse<T>(response: { code: number; data: T; msg?: string }): T {
if (Number(response?.code) !== 1) {
const detail = response?.data as any
throw new Error(response?.msg || detail?.error || detail?.message || '聊天记录请求失败')
}
return response.data
}
/** 当前患者所有诊单的 IM 归档消息。 */
export async function getImChatMessages(params: { diagnosis_id: number; only_archived?: 0 | 1 }): Promise<ImChatMessagesResponse> {
const response = await request.get(
{ url: '/tcm.diagnosis/getImChatMessages', params, timeout: 30000 },
{ isTransformResponse: false, ignoreCancelToken: true, isOpenRetry: false, retryCount: 0 }
)
return unwrapImChatResponse<ImChatMessagesResponse>(response)
}
/** 同步一页云端消息,继续传入返回的 token,直到 completed 为 true。 */
export async function triggerImChatSync(data: { diagnosis_id: number; sync_token?: string; scope?: 'current' }): Promise<ImChatSyncProgress> {
const response = await request.post(
{ url: '/tcm.diagnosis/triggerImChatSync', data, timeout: 30000 },
{ isTransformResponse: false, ignoreCancelToken: true, isOpenRetry: false, retryCount: 0 }
)
return unwrapImChatResponse<ImChatSyncProgress>(response)
}
// 获取企业微信聊天记录
@@ -424,7 +462,12 @@ export function prescriptionOrderEdit(params: Record<string, unknown>) {
return request.post({ url: '/tcm.prescriptionOrder/edit', params })
}
/** 仅修改业务订单的承运商与快递单号;所有履约状态均可使用 */
/** 仅修改处方业务订单创建时间,需独立的 editTime 权限 */
export function prescriptionOrderEditTime(params: { id: number; create_time: string }) {
return request.post({ url: '/tcm.prescriptionOrder/editTime', params })
}
/** 仅修改业务订单的承运商与快递单号;处方和支付单均审核通过后,所有履约状态均可使用 */
export function prescriptionOrderDdcode(params: {
id: number
express_company: string
@@ -578,6 +621,11 @@ export function prescriptionOrderAddLog(params: {
return request.post({ url: '/tcm.prescriptionOrder/addLog', params })
}
/** 移除单笔收款关联,总金额不变,同步更新已付金额和需代收 */
export function prescriptionOrderUnlinkPayOrder(params: { id: number; pay_order_id: number }) {
return request.post({ url: '/tcm.prescriptionOrder/unlinkPayOrder', params })
}
/** 修改订单金额 */
export function prescriptionOrderUpdateAmount(params: { id: number; amount: number }) {
return request.post({ url: '/tcm.prescriptionOrder/updateAmount', params })
+13
View File
@@ -45,3 +45,16 @@ export function unbindWorkWechat() {
export function changeFirstPassword(params: { password: string; password_confirm: string }) {
return request.post({ url: '/login/changeFirstPassword', params })
}
// 统一账号登录开关和服务器生成的固定登录入口
export function getIamConfig() {
return request.get({ url: '/iam/config' }, { withToken: false })
}
// 浏览器绑定的一次性兑换码;不重试,也不将旧业务 token 带入认证
export function iamLogin(ticket: string) {
return request.post(
{ url: '/iam/exchange', params: { ticket, terminal: config.terminal }, withCredentials: true },
{ withToken: false, isOpenRetry: false }
)
}
+138 -9
View File
@@ -11,7 +11,10 @@
class="chat-window-header"
@mousedown="onHeaderMouseDown"
>
<span class="chat-window-title" :title="patientName">与 {{ patientName }} 通讯</span>
<div class="chat-window-heading">
<span class="chat-window-title" :title="patientName">与 {{ patientName }} 通讯</span>
<el-tag size="small" type="info" class="chat-appointment-type">{{ appointmentTypeLabel }}</el-tag>
</div>
<div class="chat-header-actions" @mousedown.stop>
<el-button type="danger" link class="chat-close-btn" @click="handleClose">
<el-icon><Close /></el-icon>
@@ -52,18 +55,19 @@
<ImagePicker />
<FilePicker />
<!-- 仅在 TUICallKit 初始化成功后展示音视频入口,避免“初始化登录未完成”错误 -->
<AudioCallPicker v-if="isCallReady" />
<AudioCallPicker v-if="isCallReady && canAudioCall" />
<!-- 视频接通后 doBindCallRoom → 后端 bindCallRoom 会调 CreateCloudRecording,RecordParams.RecordMode=2(混流/合流),见 TrtcCloudRecordingService -->
<VideoCallPicker v-if="isCallReady" />
<VideoCallPicker v-if="isCallReady && canVideoCall" />
<!-- 群组视频通话(基于 TUICallKitServer.calls,多人通话入口) -->
<el-button
v-if="isCallReady"
v-if="isCallReady && canVideoCall"
size="small"
type="primary"
@click="startGroupVideoCall"
>
群视频
</el-button>
<span v-if="appointmentType === 'text'" class="text-consultation-hint">图文问诊,不支持音视频通话</span>
</div>
</template>
</MessageInput>
@@ -135,11 +139,15 @@ import {
bindCallRoom,
endCall,
getCallSignature,
triggerImChatSync,
startCall
} from '@/api/tcm'
import { CallLocalRecorder } from '@/utils/call-local-recorder'
import { createImChatArchiveTrigger } from '@/utils/im-chat-archive-trigger'
import { captureVideoFrameFromElement } from '@/utils/call-video-screenshot'
import feedback from '@/utils/feedback'
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import { checkAppointmentOutgoingCall, registerAppointmentCallGuard } from '@/utils/appointment-call-guard'
import {
formatTUICallUserError,
getTUICallPackageArrearsMessage,
@@ -180,6 +188,18 @@ const visible = ref(false)
const isReady = ref(false)
const error = ref('')
const patientName = ref('')
const appointmentType = ref<string | null | undefined>('video')
const appointmentId = ref(0)
const confirmedTypeLabel = ref('')
const appointmentTypeLabel = computed(() => confirmedTypeLabel.value || appointmentTypeDescription(appointmentType.value))
const serverAllowsVideo = ref(false)
const serverAllowsAudio = ref(false)
const callDisabledReason = ref('正在确认挂号类型')
const canVideoCall = computed(() => serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
const canAudioCall = computed(() => serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
let releaseAppointmentCallGuard: (() => void) | undefined
let chatContextVersion = 0
let outgoingCallType = 2
const patientId = ref<number | null>(null)
const diagnosisId = ref<number | null>(null)
const loadingText = ref('正在初始化...')
@@ -191,6 +211,68 @@ const { login, logout } = useLoginState()
const { setActiveConversation, createC2CConversation, activeConversation } = useConversationListState()
const userStore = useUserStore()
const syncChatArchive = createImChatArchiveTrigger(triggerImChatSync, () => {
console.warn('[chat-dialog] 聊天记录归档未完成,可在诊单聊天记录中重试同步')
})
let chatArchiveTimer: ReturnType<typeof setInterval> | undefined
let chatArchiveDebounce: ReturnType<typeof setTimeout> | undefined
function queueChatArchive() {
const id = diagnosisId.value
if (!visible.value || !isReady.value || !id) return
if (chatArchiveDebounce) clearTimeout(chatArchiveDebounce)
chatArchiveDebounce = setTimeout(() => {
chatArchiveDebounce = undefined
void syncChatArchive(id)
}, 500)
}
function stopChatArchiveWatch(flush = false) {
if (chatArchiveTimer) clearInterval(chatArchiveTimer)
if (chatArchiveDebounce) clearTimeout(chatArchiveDebounce)
chatArchiveTimer = undefined
chatArchiveDebounce = undefined
if (flush && diagnosisId.value && isReady.value) void syncChatArchive(diagnosisId.value)
TUIChatEngine?.chat?.off?.(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, queueChatArchive)
}
function startChatArchiveWatch() {
stopChatArchiveWatch()
TUIChatEngine?.chat?.on?.(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, queueChatArchive)
chatArchiveTimer = setInterval(queueChatArchive, 15000)
queueChatArchive()
}
function syncAppointmentCallPolicy(res: {
appointment_type?: string | null; appointment_type_desc?: string;
appointment_id?: number; can_video_call?: boolean; can_audio_call?: boolean; call_disabled_reason?: string
}) {
if ('appointment_type' in res) appointmentType.value = res.appointment_type
confirmedTypeLabel.value = res.appointment_type_desc || ''
serverAllowsVideo.value = res.can_video_call === true
serverAllowsAudio.value = res.can_audio_call === true
callDisabledReason.value = res.call_disabled_reason || '当前挂号不支持该通话方式'
if (Number(res.appointment_id) > 0) appointmentId.value = Number(res.appointment_id)
}
async function prepareAppointmentCall(callType: number) {
const contextVersion = chatContextVersion
const allowed = () => callType === 1 ? canAudioCall.value : canVideoCall.value
if (!visible.value || !allowed()) {
const message = appointmentType.value === 'text' ? '图文问诊不支持音视频通话' : callDisabledReason.value
feedback.msgWarning(message)
throw new Error(message)
}
// 发起前重新读取服务端挂号,防止打开聊天后问诊类型已被修改。
const res = await getCallSignature({
patient_id: patientId.value, diagnosis_id: diagnosisId.value, appointment_id: appointmentId.value
})
if (!visible.value || chatContextVersion !== contextVersion) throw new Error('当前问诊已切换,请重新发起通话')
syncAppointmentCallPolicy(res)
if (!allowed()) {
feedback.msgWarning(callDisabledReason.value)
throw new Error(callDisabledReason.value)
}
outgoingCallType = callType
}
/** TUICallKit CallStatus(与 @tencentcloud/call-uikit-vue 一致) */
const CALL_STATUS_IDLE = 'idle'
const CALL_STATUS_CALLING = 'calling'
@@ -622,6 +704,7 @@ function installTUICallKitRoomHooks() {
const original = server[methodName]
if (typeof original !== 'function') return
server[methodName] = async function patched(...args: unknown[]) {
await checkAppointmentOutgoingCall(args[0])
const result = await original.apply(server, args)
await flushAndBindRoomAfterTUICallApi(methodName)
return result
@@ -689,7 +772,8 @@ async function ensureCallRecordStarted() {
await startCall({
diagnosis_id: diagnosisId.value,
patient_id: patientId.value,
call_type: 2
appointment_id: appointmentId.value,
call_type: outgoingCallType
})
} catch (e) {
console.warn('[chat-dialog] startCall 记录失败', e)
@@ -933,6 +1017,9 @@ onMounted(() => {
})
onUnmounted(() => {
stopChatArchiveWatch(true)
chatContextVersion++
releaseAppointmentCallGuard?.()
clearLocalRecordingStartTimer()
localCallRecorder.reset()
tearDownCallRoomBinding?.()
@@ -995,7 +1082,8 @@ watch(() => activeConversation.value, async (newConversation) => {
try {
const res = await getCallSignature({
patient_id: newConversation.userProfile.userID.replace("patient_", ""),
diagnosis_id: diagnosisId.value
diagnosis_id: diagnosisId.value,
appointment_id: appointmentId.value
})
syncLochostVodFromSignature(res)
patientUserId.value = res.patientUserId
@@ -1010,13 +1098,23 @@ watch(() => activeConversation.value, async (newConversation) => {
}
})
const open = async (data: { patientId: number; patientName: string; diagnosisId?: number }) => {
const open = async (data: { patientId: number; patientName: string; diagnosisId?: number; appointmentId?: number; appointmentType?: string | null }) => {
stopChatArchiveWatch(true)
const contextVersion = ++chatContextVersion
releaseAppointmentCallGuard?.()
releaseAppointmentCallGuard = registerAppointmentCallGuard(prepareAppointmentCall)
visible.value = true
isMinimized.value = false
posX.value = 100
posY.value = 80
resetCallKitPositionToLeft()
patientName.value = data.patientName
appointmentType.value = data.appointmentType
appointmentId.value = Number(data.appointmentId || 0)
confirmedTypeLabel.value = ''
serverAllowsVideo.value = false
serverAllowsAudio.value = false
callDisabledReason.value = '正在确认挂号类型'
patientId.value = data.patientId
diagnosisId.value = data.diagnosisId || null
error.value = ''
@@ -1029,8 +1127,11 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
// 获取医生的签名信息
const res = await getCallSignature({
patient_id: data.patientId,
diagnosis_id: data.diagnosisId || 0
diagnosis_id: data.diagnosisId || 0,
appointment_id: appointmentId.value
})
if (contextVersion !== chatContextVersion || !visible.value) return
syncAppointmentCallPolicy(res)
syncLochostVodFromSignature(res)
assistant_ids.value = res.assistant_id
console.log('后端返回的签名数据:', res)
@@ -1116,7 +1217,9 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
// 等待 UIKit 初始化完成后创建并激活会话
setTimeout(async () => {
if (contextVersion !== chatContextVersion || !visible.value) return
isReady.value = true
startChatArchiveWatch()
// 使用 nextTick 确保组件已渲染
await nextTick()
@@ -1157,6 +1260,10 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
// 群组视频通话(多人通话):当前医生作为发起方,默认先邀请当前会话患者
const startGroupVideoCall = async () => {
if (!canVideoCall.value) {
feedback.msgWarning(appointmentType.value === 'text' ? '图文问诊不支持视频通话' : callDisabledReason.value)
return
}
if (!isCallReady.value) {
feedback.msgWarning('通话服务初始化中,请稍后再试')
return
@@ -1173,7 +1280,8 @@ const startGroupVideoCall = async () => {
console.warn('assistant_id 为空,尝试重新获取')
const res = await getCallSignature({
patient_id: patientId.value!,
diagnosis_id: diagnosisId.value
diagnosis_id: diagnosisId.value,
appointment_id: appointmentId.value
})
syncLochostVodFromSignature(res)
assistant_ids.value = res.assistant_id
@@ -1353,6 +1461,9 @@ const onHeaderMouseUp = () => {
}
const handleClose = async () => {
stopChatArchiveWatch(true)
chatContextVersion++
releaseAppointmentCallGuard?.()
unbindImHangupMessageListener()
// 关闭时如有通话中/拨通中,先结束本地录制再挂断(不依赖悬浮窗是否显示)
if (isCallReady.value) {
@@ -1426,6 +1537,18 @@ defineExpose({ open })
justify-content: space-between;
flex-shrink: 0;
.chat-window-heading {
display: flex;
align-items: center;
min-width: 0;
gap: 4px;
}
.chat-appointment-type {
flex-shrink: 0;
margin-right: 8px;
}
.chat-window-title {
font-size: 16px;
font-weight: 500;
@@ -1510,6 +1633,12 @@ defineExpose({ open })
}
/* 消息工具栏样式 */
.text-consultation-hint {
color: #909399;
font-size: 12px;
line-height: 20px;
}
.message-toolbar {
display: flex;
gap: 8px;
+23 -8
View File
@@ -51,8 +51,10 @@ import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import feedback from '@/utils/feedback'
import {
DirectUploadApiError,
DirectUploadFallbackError,
uploadVideoDirectToCos
uploadDirectToCos,
type DirectUploadType
} from '@/utils/oss-direct-upload'
export default defineComponent({
@@ -83,7 +85,7 @@ export default defineComponent({
type: Boolean,
default: false
},
// 视频直传到 OSS(绕开服务器中转,仅 type=video 生效)
// 直传到对象存储,绕开服务器中转
direct: {
type: Boolean,
default: false
@@ -102,8 +104,10 @@ export default defineComponent({
const visible = ref(false)
const fileList = ref<any[]>([])
// 仅 video/voice + direct 时才接管 http-request
const useDirect = computed(() => props.direct && ['video', 'voice'].includes(props.type))
const directTypes: DirectUploadType[] = ['video', 'voice', 'desktop_package']
const useDirect = computed(
() => props.direct && directTypes.includes(props.type as DirectUploadType)
)
const handleProgress = () => {
visible.value = true
@@ -131,7 +135,10 @@ export default defineComponent({
fileList.value = []
emit('allSuccess')
}
feedback.msgError(`${file.name}文件上传失败`)
if (!(event instanceof DirectUploadApiError)) {
const message = event instanceof Error ? event.message : ''
feedback.msgError(message || `${file.name}文件上传失败`)
}
uploadRefs.value?.abort(file)
visible.value = false
emit('change', file)
@@ -153,18 +160,20 @@ export default defineComponent({
return '.wmv,.avi,.mpg,.mpeg,.3gp,.mov,.mp4,.flv,.rmvb,.mkv'
case 'voice':
return '.mp3,.wav,.wma,.m4a,.aac,.amr'
case 'desktop_package':
return '.exe,.zip'
default:
return '*'
}
})
// 走 COS 直传:成功时模拟老接口的响应 envelope,失败/降级时回到默认 XHR
// 走 COS 直传:成功时模拟老接口的响应 envelope
const httpRequest = async (options: UploadRequestOptions) => {
visible.value = true
try {
const data = await uploadVideoDirectToCos({
const data = await uploadDirectToCos({
file: options.file,
type: props.type as any,
type: props.type as DirectUploadType,
cid: Number((options.data as any)?.cid ?? 0),
onProgress(info) {
// 触发 ElUpload 内部进度(保持与默认上传一致的体验)
@@ -178,6 +187,12 @@ export default defineComponent({
;(options as any).onSuccess?.({ code: RequestCodeEnum.SUCCESS, msg: 'ok', data })
} catch (err: any) {
if (err instanceof DirectUploadFallbackError) {
if (props.type === 'desktop_package') {
;(options as any).onError?.(
new Error('当前未启用腾讯云 COS,安装包无法直传,请配置 COS 后重试')
)
return
}
feedback.msgWarning('当前存储不支持直传,已切换为普通上传')
await defaultXhrUpload(options)
return
+8 -1
View File
@@ -1,7 +1,7 @@
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { getUserInfo, login, logout, workWechatLogin } from '@/api/user'
import { getUserInfo, iamLogin, login, logout, workWechatLogin } from '@/api/user'
import { TOKEN_KEY } from '@/enums/cacheEnums'
import { PageEnum } from '@/enums/pageEnum'
import router, { filterAsyncRoutes } from '@/router'
@@ -83,6 +83,13 @@ const useUserStore = defineStore({
})
})
},
async iamLogin(ticket: string) {
const data = await iamLogin(ticket)
this.token = data.token
this.isPaw = data.is_paw ?? 1
cache.set(TOKEN_KEY, data.token)
return data
},
getUserInfo() {
return new Promise((resolve, reject) => {
getUserInfo()
+19
View File
@@ -0,0 +1,19 @@
type OutgoingCallGuard = (callType: number) => Promise<void>
// 通话 SDK 为全局单例;使用当前窗口的校验器,避免首个组件闭包保留旧患者类型。
let activeGuard: OutgoingCallGuard | undefined
export function registerAppointmentCallGuard(guard: OutgoingCallGuard): () => void {
activeGuard = guard
return () => {
if (activeGuard === guard) activeGuard = undefined
}
}
export async function checkAppointmentOutgoingCall(params: unknown): Promise<void> {
const guard = activeGuard
if (!guard) throw new Error('请先打开本次挂号的聊天窗口')
const type = params && typeof params === 'object' && 'type' in params ? Number(params.type) : 2
await guard(type === 1 ? 1 : 2)
if (activeGuard !== guard) throw new Error('当前问诊已切换,请重新发起通话')
}
+13
View File
@@ -0,0 +1,13 @@
/** 展示当前挂号的问诊方式;旧记录的空值默认视频。 */
export function appointmentTypeDescription(value?: string | null): string {
if (value == null || value.trim() === '') return '视频问诊'
if (value === 'text') return '图文问诊'
if (value === 'video') return '视频问诊'
if (value === 'phone') return '电话问诊'
return '未知'
}
/** 图文及未知问诊方式不提供视频;只有已存在挂号的历史空值沿用视频。 */
export function canAppointmentVideoCall(value?: string | null): boolean {
return value == null || value.trim() === '' || value === 'video'
}
@@ -0,0 +1,42 @@
/** 合并聊天窗口的收发事件;每次同步只接受后端读取的云端消息,不上报客户端正文。 */
export function createImChatArchiveTrigger(
syncPage: (params: { diagnosis_id: number; scope: 'current'; sync_token?: string }) => Promise<{
sync_token?: string; completed: boolean; errors?: string[]
}>,
onError: (error: unknown) => void = () => {}
) {
const jobs = new Map<number, { again: boolean; promise: Promise<void> }>()
return (diagnosisId: number): Promise<void> => {
if (!Number.isInteger(diagnosisId) || diagnosisId <= 0) return Promise.resolve()
const pending = jobs.get(diagnosisId)
if (pending) {
pending.again = true
return pending.promise
}
const job = { again: false, promise: Promise.resolve() }
jobs.set(diagnosisId, job)
job.promise = (async () => {
try {
do {
job.again = false
let token: string | undefined
for (;;) {
const result = await syncPage({ diagnosis_id: diagnosisId, scope: 'current', sync_token: token })
if (result.completed) {
if (result.errors?.length) throw new Error(result.errors.join(';'))
break
}
if (!result.sync_token) throw new Error('聊天记录同步未返回进度')
token = result.sync_token
}
// 同步期间收到新消息时再追一次,覆盖新消息晚于本轮首页的情况。
} while (job.again)
} catch (error) {
onError(error)
} finally {
jobs.delete(diagnosisId)
}
})()
return job.promise
}
}
+245
View File
@@ -0,0 +1,245 @@
import { reactive } from 'vue'
import type { ImChatMessagesResponse, ImChatSyncProgress } from '@/api/tcm'
type NoticeKind = 'success' | 'warning' | 'error'
type TimerHandle = ReturnType<typeof setTimeout>
interface HistoryDependencies {
load: (diagnosisId: number) => Promise<ImChatMessagesResponse>
sync: (diagnosisId: number, token?: string) => Promise<ImChatSyncProgress>
notify?: (kind: NoticeKind, message: string) => void
now?: () => number
setTimer?: (callback: () => void, delay: number) => TimerHandle
clearTimer?: (timer: TimerHandle) => void
visible?: boolean
}
interface Session {
diagnosisId: number
generation: number
archiveRequest?: Promise<boolean>
syncRequest?: Promise<void>
}
/** Each visible diagnosis owns its requests and one timer; late responses cannot update another patient. */
export function createImChatHistory(deps: HistoryDependencies) {
const state = reactive({
rows: [] as any[],
patientImId: '',
patientName: '',
loading: false,
syncing: false,
hasLoaded: false,
readError: '',
syncError: '',
partialErrors: [] as string[],
inserted: 0,
processedPeers: 0,
totalPeers: 0,
phase: '',
checkedAccounts: 0,
candidateAccounts: 0,
skippedAccounts: 0,
lastSyncAt: null as number | null
})
const now = deps.now ?? Date.now
const setTimer = deps.setTimer ?? setTimeout
const clearTimer = deps.clearTimer ?? clearTimeout
let diagnosisId = 0
let generation = 0
let visible = deps.visible ?? true
let disposed = false
let session: Session | undefined
let timer: TimerHandle | undefined
function current(target: Session) {
return !disposed && visible && target === session && target.generation === generation && target.diagnosisId === diagnosisId
}
function clearScheduledSync() {
if (timer !== undefined) clearTimer(timer)
timer = undefined
}
function invalidate() {
generation++
clearScheduledSync()
session = undefined
state.loading = false
state.syncing = false
}
async function loadArchived(target: Session, freshAfterPending = false): Promise<boolean> {
if (!current(target)) return false
if (target.archiveRequest) {
const result = await target.archiveRequest
if (!freshAfterPending || !current(target)) return result
return loadArchived(target)
}
state.loading = true
const request = Promise.resolve().then(async () => {
if (!current(target)) return false
try {
const response = await deps.load(target.diagnosisId)
if (!current(target)) return false
if (!Array.isArray(response?.lists)) throw new Error('聊天记录接口返回的数据不完整')
state.rows = response.lists
state.patientImId = response.patient_im_id || ''
state.patientName = response.patient_name || ''
state.hasLoaded = true
state.readError = ''
return true
} catch (error) {
if (current(target)) state.readError = imChatErrorMessage(error, '读取聊天记录失败')
return false
}
})
target.archiveRequest = request
try {
return await request
} finally {
if (target.archiveRequest === request) target.archiveRequest = undefined
if (current(target)) state.loading = false
}
}
function scheduleSync(target: Session) {
clearScheduledSync()
if (!current(target)) return
timer = setTimer(() => {
timer = undefined
if (current(target)) void sync(target)
}, 30000)
}
async function sync(target: Session, manual = false): Promise<void> {
if (!current(target)) return
if (target.syncRequest) return target.syncRequest
clearScheduledSync()
state.syncing = true
state.syncError = ''
state.partialErrors = []
state.inserted = 0
state.processedPeers = 0
state.totalPeers = 0
state.phase = 'checking_accounts'
state.checkedAccounts = 0
state.candidateAccounts = 0
state.skippedAccounts = 0
const request = Promise.resolve().then(async () => {
let token: string | undefined
let pagesSinceRefresh = 0
let lastRefreshAt = now()
const errors = new Set<string>()
try {
while (current(target)) {
const progress = await deps.sync(target.diagnosisId, token)
if (!current(target)) return
if (typeof progress?.completed !== 'boolean') throw new Error('同步接口未返回有效的完成状态')
state.inserted = Number(progress.inserted) || 0
state.processedPeers = Number(progress.processed_peers) || 0
state.totalPeers = Number(progress.total_peers) || 0
state.phase = progress.phase || 'syncing'
state.checkedAccounts = Number(progress.checked_accounts) || 0
state.candidateAccounts = Number(progress.candidate_accounts) || 0
state.skippedAccounts = Number(progress.skipped_accounts) || 0
for (const error of [progress.error, ...(progress.errors || [])]) {
if (typeof error === 'string' && error.trim()) errors.add(error)
}
state.partialErrors = [...errors]
if (progress.completed) {
const refreshed = await loadArchived(target, true)
if (!current(target)) return
state.lastSyncAt = now()
if (manual) {
if (errors.size) deps.notify?.('warning', `同步完成,部分会话失败:${[...errors].join(';')}`)
else if (!refreshed) deps.notify?.('warning', `同步已完成,但读取聊天记录失败:${state.readError}`)
else deps.notify?.('success', `聊天记录已更新,本次新增 ${state.inserted} 条`)
}
return
}
if (!progress.sync_token) throw new Error('同步接口未返回继续同步所需的进度标识')
token = progress.sync_token
pagesSinceRefresh++
if (pagesSinceRefresh >= 3 || now() - lastRefreshAt >= 2000) {
await loadArchived(target, true)
pagesSinceRefresh = 0
lastRefreshAt = now()
}
}
} catch (error) {
if (!current(target)) return
state.syncError = imChatErrorMessage(error, '同步聊天记录失败')
if (manual) deps.notify?.('error', state.syncError)
}
})
target.syncRequest = request
try {
await request
} finally {
if (target.syncRequest === request) target.syncRequest = undefined
if (current(target)) {
state.syncing = false
scheduleSync(target)
}
}
}
function start() {
if (disposed || !visible || !diagnosisId) return
const target: Session = { diagnosisId, generation }
session = target
void loadArchived(target)
void sync(target)
}
function setDiagnosis(value: number) {
const nextId = Number(value) > 0 ? Number(value) : 0
if (disposed || (nextId === diagnosisId && session)) return
invalidate()
diagnosisId = nextId
state.rows = []
state.patientImId = ''
state.patientName = ''
state.hasLoaded = false
state.readError = ''
state.syncError = ''
state.partialErrors = []
state.inserted = 0
state.processedPeers = 0
state.totalPeers = 0
state.phase = ''
state.checkedAccounts = 0
state.candidateAccounts = 0
state.skippedAccounts = 0
state.lastSyncAt = null
start()
}
function setVisible(value: boolean) {
if (disposed || value === visible) return
visible = value
invalidate()
if (visible) start()
}
function dispose() {
disposed = true
invalidate()
}
return {
state,
setDiagnosis,
setVisible,
dispose,
reload: () => session ? loadArchived(session) : Promise.resolve(false),
sync: () => session ? sync(session, true) : Promise.resolve()
}
}
export function imChatErrorMessage(error: unknown, fallback: string): string {
if (typeof error === 'string' && error.trim()) return error
const detail = error as any
return detail?.response?.data?.msg || detail?.msg || detail?.error || detail?.message || fallback
}
+43 -15
View File
@@ -3,10 +3,11 @@ import COS from 'cos-js-sdk-v5'
import {
confirmOssUpload,
getOssCredentials,
type OssCredentialsResponse
type OssCredentialsResponse,
type OssDirectUploadType
} from '@/api/file'
export type DirectUploadType = 'video'
export type DirectUploadType = OssDirectUploadType
export interface DirectUploadProgress {
/** 0-100 */
@@ -37,8 +38,17 @@ export interface DirectUploadOptions {
const SLICE_SIZE = 5 * 1024 * 1024 // 5MB
const ASYNC_LIMIT = 3
async function callDirectUploadApi<T>(request: () => Promise<T>): Promise<T> {
try {
return await request()
} catch (error) {
// request 拦截器已经展示过接口/网络错误,上传组件只负责收口失败状态
throw new DirectUploadApiError(error)
}
}
function buildKey(prefix: string, file: File): string {
const ext = (file.name.split('.').pop() || 'mp4').toLowerCase()
const ext = (file.name.split('.').pop() || 'bin').toLowerCase()
const ts = Date.now()
const rand = Math.random().toString(36).slice(2, 10)
return `${prefix}${ts}-${rand}.${ext}`
@@ -48,8 +58,13 @@ function buildKey(prefix: string, file: File): string {
* 直传到腾讯云 COS(含 STS 凭证申请、分片上传、回执)
* 不支持降级 / fallback=true 时抛错,由调用方决定走老链路。
*/
export async function uploadVideoDirectToCos(options: DirectUploadOptions): Promise<DirectUploadResult> {
const credentials: OssCredentialsResponse = await getOssCredentials({ type: options.type })
export async function uploadDirectToCos(options: DirectUploadOptions): Promise<DirectUploadResult> {
const credentials: OssCredentialsResponse = await callDirectUploadApi(() =>
getOssCredentials({
type: options.type,
name: options.file.name
})
)
if (credentials.fallback) {
const handled = options.onFallback?.(credentials.provider) ?? false
@@ -66,7 +81,7 @@ export async function uploadVideoDirectToCos(options: DirectUploadOptions): Prom
if (credentials.max_size && options.file.size > credentials.max_size) {
const mb = Math.round(credentials.max_size / 1024 / 1024)
throw new Error(`视频体积超出上限(${mb}MB)`)
throw new Error(`文件体积超出上限(${mb}MB)`)
}
const cred = credentials.credentials
@@ -85,7 +100,7 @@ export async function uploadVideoDirectToCos(options: DirectUploadOptions): Prom
}
})
const key = buildKey(credentials.key_prefix, options.file)
const key = credentials.object_key || buildKey(credentials.key_prefix, options.file)
await new Promise<void>((resolve, reject) => {
cos.uploadFile(
@@ -117,14 +132,16 @@ export async function uploadVideoDirectToCos(options: DirectUploadOptions): Prom
)
})
const confirmed = await confirmOssUpload({
type: options.type,
key,
name: options.file.name,
size: options.file.size,
content_type: options.file.type || '',
cid: options.cid ?? 0
})
const confirmed = await callDirectUploadApi(() =>
confirmOssUpload({
type: options.type,
key,
name: options.file.name,
size: options.file.size,
content_type: options.file.type || '',
cid: options.cid ?? 0
})
)
options.onProgress?.({ percent: 100, loaded: options.file.size, total: options.file.size, speed: 0 })
@@ -140,3 +157,14 @@ export class DirectUploadFallbackError extends Error {
this.provider = provider
}
}
/** 请求层已经展示过错误,避免 ElUpload 再弹一条通用失败提示。 */
export class DirectUploadApiError extends Error {
readonly originalError: unknown
constructor(error: unknown) {
super('')
this.name = 'DirectUploadApiError'
this.originalError = error
}
}
+160 -5
View File
@@ -11,11 +11,11 @@
<div class="text-center text-3xl font-medium mb-8">{{ config.web_name }}</div>
<!-- 企业微信自动授权中 -->
<div v-if="wxWorkAutoLogin" class="text-center py-10">
<div v-if="wxWorkAutoLogin || iamLoading" class="text-center py-10">
<el-icon class="is-loading mb-4" :size="40" color="var(--el-color-primary)">
<Loading />
</el-icon>
<div class="text-gray-500">企业微信授权登录中...</div>
<div class="text-gray-500">{{ iamLoading ? '统一账号登录中...' : '企业微信授权登录中...' }}</div>
</div>
<template v-else>
@@ -78,6 +78,20 @@
请使用企业微信扫描二维码登录
</div>
</template>
<section v-if="iamEnabled" class="iam-login-alternative" aria-label="其他登录方式">
<div class="iam-login-divider" aria-hidden="true">其他登录方式</div>
<el-button class="iam-login-entry" size="large" @click="handleIamLogin">
<span class="iam-login-entry__content">
<icon name="local-icon-anquan" size="22" />
<span>统一账号快捷登录</span>
</span>
<span class="iam-login-entry__arrow" aria-hidden="true">
<icon name="el-icon-ArrowRight" size="16" />
</span>
</el-button>
<p class="iam-login-hint">使用统一身份平台账号登录</p>
</section>
</template>
</div>
</div>
@@ -99,7 +113,7 @@ import LayoutFooter from '@/layout/components/footer.vue'
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import cache from '@/utils/cache'
import { getWorkWechatConfig } from '@/api/user'
import { getIamConfig, getWorkWechatConfig } from '@/api/user'
const passwordRef = shallowRef<InputInstance>()
const formRef = shallowRef<FormInstance>()
@@ -118,6 +132,66 @@ const rules = {
password: [{ required: true, message: '请输入密码', trigger: ['blur'] }]
}
// 统一账号登录是可选入口,不取代账号密码或企业微信登录。
const iamEnabled = ref(false)
const iamLoginUrl = ref('')
const iamLoading = ref(false)
let iamCallbackHandled = false
const loadIamConfig = async () => {
try {
const result = await getIamConfig()
const url = new URL(result?.loginUrl || '', window.location.origin)
if (result?.enabled === true && url.protocol === 'https:') {
iamLoginUrl.value = url.href
iamEnabled.value = true
}
} catch {
// IAM 不可用时,原有登录入口保持可用。
}
}
const handleIamLogin = () => {
if (iamEnabled.value && iamLoginUrl.value) {
window.location.assign(iamLoginUrl.value)
}
}
const handleIamCallback = async (ticket: string | null, error: string | null) => {
if (iamCallbackHandled) return
iamCallbackHandled = true
// 在任何 await 和兑换前移除票据,刷新不会重复兑换;保留其他 query/hash。
const cleanUrl = new URL(window.location.href)
cleanUrl.searchParams.delete('iam_ticket')
cleanUrl.searchParams.delete('iam_error')
// 同一回调不得随后被识别为企业微信授权。
cleanUrl.searchParams.delete('code')
cleanUrl.searchParams.delete('state')
window.history.replaceState(window.history.state, '', cleanUrl.pathname + cleanUrl.search + cleanUrl.hash)
if (error || !ticket) {
ElMessage.error(error || '统一账号登录凭证无效,请重新登录')
return
}
iamLoading.value = true
try {
const result = await userStore.iamLogin(ticket)
if (result.is_paw === 0) {
await router.push('/change-password')
return
}
if (result.need_bind_work_wechat) {
await router.push('/bind-work-wechat')
return
}
redirectAfterLogin()
} catch (error: any) {
ElMessage.error(error?.msg || error?.message || '统一账号登录失败,请重新登录或使用账号密码')
loginMode.value = 'account'
} finally {
iamLoading.value = false
}
}
// 企业微信相关
const loginMode = ref<'account' | 'wxwork'>('account')
const wxWorkEnabled = ref(false)
@@ -243,7 +317,12 @@ onMounted(async () => {
// 检查 URL 中是否有企业微信回调 code
const urlParams = new URLSearchParams(window.location.search)
const wxCode = urlParams.get('code')
void loadIamConfig()
const hasIamCallback = urlParams.has('iam_ticket') || urlParams.has('iam_error')
if (hasIamCallback) {
await handleIamCallback(urlParams.get('iam_ticket'), urlParams.get('iam_error'))
}
const wxCode = hasIamCallback ? null : urlParams.get('code')
const wxState = urlParams.get('state')
if (wxCode && wxState === 'admin_login') {
@@ -263,7 +342,7 @@ onMounted(async () => {
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
// 在企业微信内:自动跳转 OAuth 授权
if (isInWxWork()) {
if (isInWxWork() && !hasIamCallback) {
const redirectUri = encodeURIComponent(getRedirectUri())
const authUrl =
`https://open.weixin.qq.com/connect/oauth2/authorize` +
@@ -286,6 +365,82 @@ onMounted(async () => {
</script>
<style lang="scss" scoped>
.iam-login-alternative {
margin-top: 28px;
}
.iam-login-divider {
display: flex;
align-items: center;
gap: 14px;
margin-bottom: 18px;
color: var(--el-text-color-secondary);
font-size: 13px;
line-height: 20px;
&::before,
&::after {
content: '';
flex: 1;
height: 1px;
background: var(--el-border-color-light);
}
}
.iam-login-entry.el-button {
--el-button-bg-color: var(--el-color-primary-light-9);
--el-button-text-color: var(--el-color-primary);
--el-button-border-color: var(--el-color-primary-light-5);
--el-button-hover-bg-color: var(--el-color-primary-light-8);
--el-button-hover-text-color: var(--el-color-primary);
--el-button-hover-border-color: var(--el-color-primary);
--el-button-active-bg-color: var(--el-color-primary-light-8);
--el-button-active-border-color: var(--el-color-primary);
position: relative;
width: 100%;
min-height: 48px;
height: auto;
margin: 0;
padding: 12px 34px;
border-radius: 8px;
font-weight: 600;
font-size: 14px;
transition: background-color 150ms ease, border-color 150ms ease;
&:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 3px;
}
}
.iam-login-entry__content {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.iam-login-entry__arrow {
position: absolute;
right: 14px;
display: inline-flex;
align-items: center;
}
.iam-login-hint {
margin: 14px 0 0;
text-align: center;
color: var(--el-text-color-secondary);
font-size: 12px;
line-height: 20px;
}
@media (prefers-reduced-motion: reduce) {
.iam-login-entry.el-button {
transition: none;
}
}
.login {
background-image: url('./images/login_bg.png');
@apply min-h-screen bg-no-repeat bg-center bg-cover;
+135
View File
@@ -0,0 +1,135 @@
<template>
<div class="ai-access-log-page">
<el-card class="!border-none" shadow="never">
<el-form :inline="true">
<el-form-item label="时间">
<el-date-picker
v-model="timeRange"
type="datetimerange"
range-separator="至"
start-placeholder="开始时间"
end-placeholder="结束时间"
value-format="YYYY-MM-DD HH:mm:ss"
clearable
@change="resetPage"
/>
</el-form-item>
<el-form-item label="结果">
<el-select v-model="queryParams.status" clearable placeholder="全部" class="w-[120px]" @change="resetPage">
<el-option v-for="(label, value) in STATUS" :key="value" :label="label" :value="value" />
</el-select>
</el-form-item>
<el-form-item label="数据资源">
<el-input v-model="queryParams.resource" placeholder="如 tcm.diagnosis" clearable class="w-[180px]" @keyup.enter="resetPage" @clear="resetPage" />
</el-form-item>
<el-form-item label="记录ID">
<el-input v-model="queryParams.record_id" placeholder="如诊单ID" clearable class="w-[130px]" @keyup.enter="resetPage" @clear="resetPage" />
</el-form-item>
<el-form-item label="任务号">
<el-input v-model="queryParams.client_task_id" placeholder="行知任务号" clearable class="w-[200px]" @keyup.enter="resetPage" @clear="resetPage" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="resetPage">查询</el-button>
<el-button @click="handleReset">重置</el-button>
</el-form-item>
</el-form>
<div class="page-hint">
记录每一次 AI 查询:谁、通过哪个客户端任务、查了哪个数据资源、返回了哪些记录。按“记录ID”可以查某个诊单被哪些账号通过 AI 看过。
</div>
</el-card>
<el-card class="!border-none mt-3" shadow="never">
<el-table :data="pager.lists" v-loading="pager.loading" size="default" stripe>
<el-table-column label="时间" width="165" prop="create_time_text" />
<el-table-column label="账号" min-width="120">
<template #default="{ row }">
<div>{{ row.admin_name || (row.admin_id ? '#' + row.admin_id : '—') }}</div>
<div class="cell-sub">{{ row.ip }}</div>
</template>
</el-table-column>
<el-table-column label="工具" width="170" prop="tool" />
<el-table-column label="数据资源" min-width="200">
<template #default="{ row }">
<div>{{ row.resource_name || row.resource || '—' }}</div>
<div class="cell-sub">{{ row.resource }}</div>
</template>
</el-table-column>
<el-table-column label="结果" width="90" align="center">
<template #default="{ row }">
<el-tag :type="row.status === 'ok' ? 'success' : 'warning'" size="small">{{ STATUS[row.status] || row.status }}</el-tag>
</template>
</el-table-column>
<el-table-column label="条数" width="70" align="right" prop="result_rows" />
<el-table-column label="记录ID / 原因" min-width="200">
<template #default="{ row }">
<el-tooltip v-if="row.record_ids" :content="row.record_ids" placement="top">
<span class="ellipsis">{{ row.record_ids }}</span>
</el-tooltip>
<span v-else class="cell-sub">{{ row.message }}</span>
</template>
</el-table-column>
<el-table-column label="参数" min-width="220">
<template #default="{ row }">
<el-tooltip v-if="row.arguments" :content="row.arguments" placement="top">
<span class="ellipsis">{{ row.arguments }}</span>
</el-tooltip>
</template>
</el-table-column>
<el-table-column label="耗时" width="80" align="right">
<template #default="{ row }">{{ row.duration_ms }}ms</template>
</el-table-column>
<el-table-column label="任务号" min-width="160" prop="client_task_id" />
</el-table>
<div class="flex justify-end mt-4">
<pagination v-model="pager" @change="getLists" />
</div>
</el-card>
</div>
</template>
<script setup lang="ts" name="aiMcpAccessLog">
import { aiAccessLogLists } from '@/api/ai_mcp'
import { usePaging } from '@/hooks/usePaging'
import { onMounted, reactive, ref, watch } from 'vue'
const STATUS: Record<string, string> = { ok: '成功', denied: '拒绝', invalid: '参数错误', limited: '超限', error: '失败' }
const timeRange = ref<[string, string] | null>(null)
const queryParams = reactive({ start_time: '', end_time: '', status: '', resource: '', record_id: '', client_task_id: '' })
watch(timeRange, (val) => {
queryParams.start_time = val?.[0] ?? ''
queryParams.end_time = val?.[1] ?? ''
})
const { pager, getLists, resetPage, resetParams } = usePaging({
fetchFun: aiAccessLogLists,
params: queryParams
})
const handleReset = () => {
timeRange.value = null
resetParams()
}
onMounted(() => getLists())
</script>
<style scoped>
.page-hint {
color: var(--el-text-color-secondary);
font-size: 13px;
line-height: 1.6;
}
.cell-sub {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.ellipsis {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: bottom;
}
</style>
+123
View File
@@ -0,0 +1,123 @@
<template>
<div class="ai-catalog-page">
<el-card class="!border-none" shadow="never">
<div class="summary">
<div class="summary-item">
<div class="summary-value success">{{ counts.open ?? 0 }}</div>
<div class="summary-label">已开放</div>
</div>
<div class="summary-item">
<div class="summary-value warning">{{ counts.pending ?? 0 }}</div>
<div class="summary-label">待整改</div>
</div>
<div class="summary-item">
<div class="summary-value">{{ counts.excluded ?? 0 }}</div>
<div class="summary-label">不开放</div>
</div>
</div>
<el-form :inline="true" class="mt-3">
<el-form-item label="状态">
<el-select v-model="queryParams.status" clearable placeholder="全部" class="w-[120px]" @change="resetPage">
<el-option label="已开放" value="open" />
<el-option label="待整改" value="pending" />
<el-option label="不开放" value="excluded" />
</el-select>
</el-form-item>
<el-form-item label="业务分组">
<el-select v-model="queryParams.domain" clearable filterable placeholder="全部" class="w-[180px]" @change="resetPage">
<el-option v-for="d in domains" :key="d" :label="d" :value="d" />
</el-select>
</el-form-item>
<el-form-item label="关键词">
<el-input v-model="queryParams.keyword" placeholder="名称或资源标识" clearable class="w-[200px]" @keyup.enter="resetPage" @clear="resetPage" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="resetPage">查询</el-button>
<el-button @click="resetParams">重置</el-button>
</el-form-item>
</el-form>
<div class="page-hint">
后台每个只读接口都是一个“数据资源”。已开放的资源由 AI 以调用账号自己的权限和数据范围执行原有接口;
待整改的资源写明了原因(如缺少逐条权限校验、会调用外部接口、权限点未登记),整改或审核通过后开放。
</div>
</el-card>
<el-card class="!border-none mt-3" shadow="never">
<el-table :data="pager.lists" v-loading="pager.loading" size="default" stripe>
<el-table-column label="资源" min-width="220">
<template #default="{ row }">
<div>{{ row.name }}</div>
<div class="cell-sub">{{ row.resource }}</div>
</template>
</el-table-column>
<el-table-column label="业务分组" width="150" prop="domain" />
<el-table-column label="类型" width="80">
<template #default="{ row }">{{ KIND[row.kind] || row.kind }}</template>
</el-table-column>
<el-table-column label="状态" width="90" align="center">
<template #default="{ row }">
<el-tag :type="STATUS[row.status]?.type" size="small">{{ STATUS[row.status]?.label || row.status }}</el-tag>
</template>
</el-table-column>
<el-table-column label="原因" min-width="260" prop="reason" />
<el-table-column label="已审核" width="80" align="center">
<template #default="{ row }">{{ row.reviewed ? '是' : '自动' }}</template>
</el-table-column>
</el-table>
<div class="flex justify-end mt-4">
<pagination v-model="pager" @change="getLists" />
</div>
</el-card>
</div>
</template>
<script setup lang="ts" name="aiMcpCatalog">
import { aiCatalogLists } from '@/api/ai_mcp'
import { usePaging } from '@/hooks/usePaging'
import { computed, onMounted, reactive } from 'vue'
const KIND: Record<string, string> = { list: '列表', detail: '详情', report: '统计', other: '其他', write: '写操作' }
const STATUS: Record<string, { label: string; type: 'success' | 'warning' | 'info' }> = {
open: { label: '已开放', type: 'success' },
pending: { label: '待整改', type: 'warning' },
excluded: { label: '不开放', type: 'info' }
}
const queryParams = reactive({ status: '', domain: '', keyword: '' })
const { pager, getLists, resetPage, resetParams } = usePaging({
fetchFun: aiCatalogLists,
params: queryParams,
size: 50
})
const counts = computed<Record<string, number>>(() => pager.extend?.counts || {})
const domains = computed<string[]>(() => pager.extend?.domains || [])
onMounted(() => getLists())
</script>
<style scoped>
.summary {
display: flex;
gap: 48px;
}
.summary-value {
font-size: 26px;
font-weight: 600;
}
.summary-value.success {
color: var(--el-color-success);
}
.summary-value.warning {
color: var(--el-color-warning);
}
.summary-label,
.page-hint,
.cell-sub {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.page-hint {
line-height: 1.6;
}
</style>
+135
View File
@@ -0,0 +1,135 @@
<template>
<div class="ai-grant-page">
<el-card class="!border-none" shadow="never">
<el-alert
v-if="pager.extend && pager.extend.enabled === false"
type="warning"
:closable="false"
show-icon
class="mb-3"
title="AI 助手接口未启用:服务器 .env 的 [AI_MCP] ENABLED 为 false,客户端暂时无法绑定和查询。"
/>
<el-form :inline="true">
<el-form-item label="状态">
<el-select v-model="queryParams.status" clearable placeholder="全部" class="w-[120px]" @change="resetPage">
<el-option label="有效" value="1" />
<el-option label="已撤销" value="2" />
<el-option label="已过期" value="3" />
</el-select>
</el-form-item>
<el-form-item label="关键词">
<el-input
v-model="queryParams.keyword"
placeholder="姓名 / 账号 / 备注"
clearable
class="w-[220px]"
@keyup.enter="resetPage"
@clear="resetPage"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="resetPage">查询</el-button>
<el-button @click="resetParams">重置</el-button>
</el-form-item>
</el-form>
<div class="page-hint">
员工在行知等 AI 助手里用甄养堂账号密码绑定后,会在这里生成一条只读授权。AI 只能按该账号自己的权限和数据范围查询;
撤销后立即失效。账号改密、停用、失去“允许 AI 助手查询”权限时,授权也会自动失效。
</div>
</el-card>
<el-card class="!border-none mt-3" shadow="never">
<el-table :data="pager.lists" v-loading="pager.loading" size="default" stripe>
<el-table-column label="账号" min-width="140">
<template #default="{ row }">
<div>{{ row.admin_name || '—' }}</div>
<div class="cell-sub">{{ row.admin_account }}</div>
</template>
</el-table-column>
<el-table-column label="客户端" min-width="150">
<template #default="{ row }">
<div>{{ row.client }}<span v-if="row.client_instance"> · {{ row.client_instance }}</span></div>
<div class="cell-sub">{{ row.label }}</div>
</template>
</el-table-column>
<el-table-column label="令牌" width="130" prop="token_prefix" />
<el-table-column label="状态" width="90" align="center">
<template #default="{ row }">
<el-tag :type="row.status_text === '有效' ? 'success' : 'info'" size="small">{{ row.status_text }}</el-tag>
</template>
</el-table-column>
<el-table-column label="最近使用" min-width="150">
<template #default="{ row }">
<div>{{ row.last_used_time_text || '—' }}</div>
<div class="cell-sub">{{ row.last_used_ip }}</div>
</template>
</el-table-column>
<el-table-column label="到期时间" width="150" prop="expire_time_text" />
<el-table-column label="签发时间" width="150" prop="create_time_text" />
<el-table-column label="撤销" min-width="140">
<template #default="{ row }">
<template v-if="row.revoke_time_text">
<div>{{ row.revoke_time_text }}</div>
<div class="cell-sub">{{ reasonText(row.revoke_reason) }}</div>
</template>
<span v-else>—</span>
</template>
</el-table-column>
<el-table-column label="操作" width="90" fixed="right">
<template #default="{ row }">
<el-button v-if="row.can_revoke" type="danger" link @click="handleRevoke(row)">撤销</el-button>
</template>
</el-table-column>
</el-table>
<div class="flex justify-end mt-4">
<pagination v-model="pager" @change="getLists" />
</div>
</el-card>
</div>
</template>
<script setup lang="ts" name="aiMcpGrant">
import { aiGrantLists, aiGrantRevoke } from '@/api/ai_mcp'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { onMounted, reactive } from 'vue'
const queryParams = reactive({ status: '', keyword: '' })
const { pager, getLists, resetPage, resetParams } = usePaging({
fetchFun: aiGrantLists,
params: queryParams
})
const REASONS: Record<string, string> = {
client_revoke: '客户端解绑',
admin_revoke: '后台撤销',
rebind: '重新绑定',
expired: '到期/闲置失效',
password_changed: '账号改密',
admin_disabled: '账号停用',
admin_deleted: '账号删除'
}
const reasonText = (reason: string) => REASONS[reason] || reason || ''
const handleRevoke = async (row: any) => {
await feedback.confirm(`确认撤销 ${row.admin_name || row.admin_account} 的这条 AI 授权?撤销后该客户端需要重新绑定。`)
await aiGrantRevoke({ id: row.id })
feedback.msgSuccess('已撤销')
getLists()
}
onMounted(() => getLists())
</script>
<style scoped>
.page-hint {
color: var(--el-text-color-secondary);
font-size: 13px;
line-height: 1.6;
}
.cell-sub {
color: var(--el-text-color-secondary);
font-size: 12px;
}
</style>
@@ -541,6 +541,19 @@
{{ formatOrderTime(row.create_time) }}
</template>
</el-table-column>
<el-table-column v-if="canUnlinkPayOrder" label="操作" width="80" fixed="right" align="center">
<template #default="{ row }">
<el-button
type="danger"
size="small"
link
:loading="unlinkPayOrderId === Number(row.id)"
:disabled="unlinkPayOrderId !== null || ![2, 5].includes(Number(row.status))"
:title="Number(row.status) === 4 ? '已退款收款记录不可移除' : '解除关联并更新已付金额,总金额不变'"
@click="confirmUnlinkPayOrder(row)"
>移除</el-button>
</template>
</el-table-column>
</el-table>
<el-empty v-else description="未关联收款单" :image-size="60" />
</el-card>
@@ -1014,6 +1027,7 @@ import {
prescriptionOrderLogisticsTrace,
prescriptionOrderLogisticsJdUpdate,
prescriptionOrderPaidPayOrders,
prescriptionOrderUnlinkPayOrder,
prescriptionOrderPatchPrescriptionUsage
} from '@/api/tcm'
import { getDictData } from '@/api/app'
@@ -1107,6 +1121,38 @@ const detailLoading = ref(false)
const detailData = ref<Record<string, any> | null>(null)
const detailLogs = ref<any[]>([])
const detailUnlinkedPayOrders = ref<any[]>([])
const unlinkPayOrderId = ref<number | null>(null)
const canUnlinkPayOrder = computed(() =>
!props.readonly && canUpdateAmount(detailData.value) && hasPerm('tcm.prescriptionOrder/unlinkPayOrder')
)
async function confirmUnlinkPayOrder(row: { id: number; order_no?: string; amount: number | string; status: number | string }) {
const orderId = Number(detailData.value?.id)
const payOrderId = Number(row.id)
if (!canUnlinkPayOrder.value || !orderId || !payOrderId || unlinkPayOrderId.value !== null) return
if (![2, 5].includes(Number(row.status))) return
unlinkPayOrderId.value = payOrderId
try {
await feedback.confirm(
`确定移除收款记录「${row.order_no || '#' + payOrderId}」(¥${formatMoney(row.amount)})?` +
'仅解除关联,原收款记录保留;订单总金额不变,已付金额与需代收金额按剩余关联收款重新计算。'
)
if (!detailVisible.value || Number(detailData.value?.id) !== orderId) return
const res: any = await prescriptionOrderUnlinkPayOrder({ id: orderId, pay_order_id: payOrderId })
const updated = res?.data ?? res
if (Number(detailData.value?.id) === orderId && Number(updated?.id) === orderId) {
Object.assign(detailData.value!, updated)
}
feedback.msgSuccess('收款关联已移除,金额已同步更新')
emit('detail-changed')
await refreshIfCurrent(orderId)
} catch {
/* 取消不提交;接口错误由拦截器提示,保留当前收款记录 */
} finally {
unlinkPayOrderId.value = null
}
}
const detailPrescription = computed(() => {
const p = detailData.value?.prescription
@@ -0,0 +1,93 @@
<template>
<el-dialog
v-model="visible"
title="修改订单创建时间"
width="min(440px, 94vw)"
append-to-body
destroy-on-close
:close-on-click-modal="false"
:close-on-press-escape="!submitting"
:show-close="!submitting"
>
<el-form ref="formRef" :model="form" :rules="rules" label-position="top">
<el-form-item label="业务订单">
<span class="break-all">{{ orderNo || `#${form.id}` }}</span>
</el-form-item>
<el-form-item label="创建时间" prop="create_time">
<el-date-picker
v-model="form.create_time"
type="datetime"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
placeholder="请选择创建时间"
:clearable="false"
:disabled="submitting"
class="!w-full"
/>
</el-form-item>
</el-form>
<p class="text-xs text-gray-500">保存后,列表和业绩统计将按新的创建时间归属日期,修改记录可在订单日志中查看。</p>
<template #footer>
<el-button :disabled="submitting" @click="visible = false">取消</el-button>
<el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
</template>
</el-dialog>
</template>
<script lang="ts" setup>
import { nextTick, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { prescriptionOrderEditTime } from '@/api/tcm'
import feedback from '@/utils/feedback'
const emit = defineEmits<{ (event: 'saved', id: number): void }>()
const visible = ref(false)
const submitting = ref(false)
const orderNo = ref('')
const formRef = ref<FormInstance>()
const form = reactive({ id: 0, create_time: '' })
const rules: FormRules = {
create_time: [{ required: true, message: '请选择创建时间', trigger: 'change' }]
}
// 列表可能返回日期字符串或历史 Unix 时间戳;保留秒,避免只打开弹窗就丢失精度。
function editableTime(value: unknown): string {
const raw = String(value ?? '').trim()
if (/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?$/.test(raw)) {
return raw.replace('T', ' ').padEnd(19, ':00')
}
if (!/^\d+$/.test(raw) || Number(raw) <= 0) return ''
const timestamp = Number(raw)
const date = new Date(timestamp < 1e11 ? timestamp * 1000 : timestamp)
if (Number.isNaN(date.getTime())) return ''
const pad = (part: number) => String(part).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
function open(row: { id?: unknown; order_no?: unknown; create_time?: unknown }) {
if (submitting.value || !Number(row.id)) return
form.id = Number(row.id)
form.create_time = editableTime(row.create_time)
orderNo.value = String(row.order_no || '')
visible.value = true
nextTick(() => formRef.value?.clearValidate())
}
async function submit() {
if (submitting.value || !formRef.value) return
submitting.value = true
try {
if (!(await formRef.value.validate().catch(() => false))) return
await prescriptionOrderEditTime({ id: form.id, create_time: form.create_time })
feedback.msgSuccess('订单创建时间已修改')
visible.value = false
emit('saved', form.id)
} catch {
// 请求拦截器展示错误,保留已填写的时间便于重试。
} finally {
submitting.value = false
}
}
defineExpose({ open })
</script>
@@ -168,6 +168,7 @@ export function logActionText(act: string) {
ship: '确认发货',
withdraw: '撤销',
link_pay_order: '关联支付单',
unlink_pay_order: '移除收款关联',
completion_request: '完单申请',
auto_complete: '自动完成',
revoke_rx_audit: '撤回处方审核',
@@ -177,7 +178,8 @@ export function logActionText(act: string) {
ej_pharmacy_callback: '洛阳药房状态',
patch_rx_patient: '处方患者信息',
patch_rx_usage: '服用参数',
update_amount: '修改订单金额',
update_amount: '修改订单金额',
edit_time: '修改创建时间',
complete: '完成订单',
refund: '退款',
manual_log: '手工备注',
@@ -42,6 +42,13 @@
/>
</el-select>
</el-form-item>
<el-form-item label="挂号类型">
<el-select v-model="queryParams.appointment_type" placeholder="全部" clearable class="!w-[140px]">
<el-option label="全部" value="" />
<el-option label="视频问诊" value="video" />
<el-option label="图文问诊" value="text" />
</el-select>
</el-form-item>
<el-form-item label="状态">
<el-select v-model="queryParams.status" placeholder="全部" clearable class="!w-[130px]">
<el-option label="已预约" :value="1" />
@@ -115,7 +122,9 @@
<div class="text-gray-500">{{ formatHm(row.appointment_time) }} · {{ row.period_desc }}</div>
</template>
</el-table-column>
<el-table-column label="类型" prop="appointment_type_desc" width="100" />
<el-table-column label="挂号类型" width="110">
<template #default="{ row }">{{ appointmentTypeDescription(row.appointment_type) }}</template>
</el-table-column>
<el-table-column label="渠道" min-width="130" show-overflow-tooltip>
<template #default="{ row }">
<div class="text-sm">{{ row.channel_source_desc || '—' }}</div>
@@ -178,11 +187,10 @@
<el-radio-button label="all">全天</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item label="问诊类型" required>
<el-form-item label="挂号类型" required>
<el-select v-model="editForm.appointment_type" class="!w-full">
<el-option label="视频问诊" value="video" />
<el-option label="图文问诊" value="text" />
<el-option label="电话问诊" value="phone" />
</el-select>
</el-form-item>
<el-form-item label="渠道来源" required>
@@ -293,6 +301,7 @@
import DaterangePicker from '@/components/daterange-picker/index.vue'
import { getDictData } from '@/api/app'
import { appointmentAdminEdit, appointmentBatchEditChannel, appointmentLists } from '@/api/doctor'
import { appointmentTypeDescription } from '@/utils/appointment-type'
import { getAssistants } from '@/api/tcm'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
@@ -303,6 +312,7 @@ const queryParams = reactive({
patient_name: '',
doctor_name: '',
assistant_id: undefined as number | undefined,
appointment_type: '',
status: '' as number | '',
channel_source: '' as string
})
@@ -313,6 +323,7 @@ const queryInit = {
patient_name: '',
doctor_name: '',
assistant_id: undefined as number | undefined,
appointment_type: '',
status: '' as number | '',
channel_source: ''
}
@@ -1585,7 +1585,7 @@ import DaterangePicker from '@/components/daterange-picker/index.vue'
import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
import { computed, onMounted, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
@@ -3882,7 +3882,18 @@ const handleDelete = async (id: number) => {
getLists()
}
onMounted(async () => {
// 从订单页返回缓存的处方列表时,重新读取退款后的占用状态。
let refreshOnReturn = false
onDeactivated(() => {
refreshOnReturn = true
})
onActivated(() => {
if (!refreshOnReturn) return
refreshOnReturn = false
getLists()
})
onMounted(async () => {
await loadRoleOptions()
await loadRegionData()
await loadServicePackageOptions()
@@ -550,7 +550,13 @@
type="primary"
link
@click="openEdit(row)"
>编辑</el-button>
>编辑</el-button>
<el-button
v-perms="['tcm.prescriptionOrder/editTime']"
type="primary"
link
@click="orderTimeDialogRef?.open(row)"
>修改创建时间</el-button>
<el-button
v-if="canQuickTrackRow(row)"
v-perms="['tcm.prescriptionOrder/ddcode']"
@@ -649,7 +655,12 @@
>{{ shipModeLabel(detail.ship_mode) }}</el-tag>
</div>
</template>
<template #header-actions="{ detail }">
<template #header-actions="{ detail }">
<el-button
v-perms="['tcm.prescriptionOrder/editTime']"
size="small"
@click="orderTimeDialogRef?.open(detail)"
>修改创建时间</el-button>
<gancao-submission-reconcile-button
:order="detail"
@resolved="handleGancaoSubmissionResolved"
@@ -860,8 +871,17 @@
<el-option label="京东快递" value="jd" />
<el-option label="极兔速递" value="jt" />
</el-select>
<el-input v-model="editForm.tracking_number" maxlength="80" placeholder="快递单号" class="flex-1 min-w-0" />
</div>
<el-input
v-model="editForm.tracking_number"
disabled
maxlength="80"
placeholder="快递单号"
class="flex-1 min-w-0"
/>
</div>
<div class="text-xs text-gray-400 mt-1">
编辑订单后需重新审核;双审通过后,请通过列表的单号操作填写或修改
</div>
</el-form-item>
</el-col>
</el-row>
@@ -1056,8 +1076,17 @@
<el-option label="京东快递" value="jd" />
<el-option label="极兔速递" value="jt" />
</el-select>
<el-input v-model="editForm.tracking_number" maxlength="80" placeholder="快递单号" class="flex-1 min-w-0" />
</div>
<el-input
v-model="editForm.tracking_number"
disabled
maxlength="80"
placeholder="快递单号"
class="flex-1 min-w-0"
/>
</div>
<div class="text-xs text-gray-400 mt-1">
编辑订单后需重新审核;双审通过后,请通过列表的单号操作填写或修改
</div>
</el-form-item>
</el-col>
<el-col :span="24">
@@ -1511,7 +1540,9 @@
</el-button>
</template>
</el-dialog>
<!-- 订单退款:须填写原因 -->
<prescription-order-time-dialog ref="orderTimeDialogRef" @saved="onOrderTimeSaved" />
<!-- 订单退款:须填写原因 -->
<el-dialog
v-model="refundOrderDialogVisible"
title="订单退款"
@@ -2031,7 +2062,8 @@ import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncCompone
import { useRoute } from 'vue-router'
import { ArrowDown, InfoFilled, QuestionFilled, Search, Calendar, Document, Link as LinkIcon, Wallet } from '@element-plus/icons-vue'
import ListTimeFilter from '@/components/list-time-filter/index.vue'
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.vue'
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.vue'
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
import {
TCM_ASSISTANT_ROLE_ID,
@@ -2961,9 +2993,13 @@ function canWithdrawRow(row: { fulfillment_status?: number }) {
return Number(row.fulfillment_status) === 1
}
function canShipRow(row: { fulfillment_status?: number }) {
// 履约中(2) 可发货
return Number(row.fulfillment_status) === 2
function canShipRow(row: {
fulfillment_status?: number
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
// 履约中(2) 且处方、支付单均审核通过才可发货
return Number(row.fulfillment_status) === 2 && isDualAuditPassed(row)
}
type ShipMode = 'gancao' | 'direct'
@@ -3059,8 +3095,11 @@ function canRefundRow(row: { fulfillment_status?: number; payment_slip_audit_sta
return (fs === 5 || fs === 6 || fs === 3 || fs === 9) && Number(row.payment_slip_audit_status) === 1
}
function canQuickTrackRow(_row: { fulfillment_status?: number }) {
return true
function canQuickTrackRow(row: {
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
return isDualAuditPassed(row)
}
function canUploadPharmacyRow(row: {
@@ -3087,7 +3126,13 @@ function canUploadPharmacyRow(row: {
}
// ─── 详情抽屉(共享组件 PrescriptionOrderDetailDrawer):状态桥接 ───
const detailDrawerRef = ref<InstanceType<typeof PrescriptionOrderDetailDrawer>>()
const detailDrawerRef = ref<InstanceType<typeof PrescriptionOrderDetailDrawer>>()
const orderTimeDialogRef = ref<InstanceType<typeof PrescriptionOrderTimeDialog>>()
async function onOrderTimeSaved(id: number) {
getLists()
await detailDrawerRef.value?.refreshIfCurrent(id)
}
/** 当前详情数据(组件内部 ref 的桥接;可原地修改属性,整体刷新请用 detailDrawerRef.refresh()) */
const detailData = computed(() => (detailDrawerRef.value?.detail ?? null) as Record<string, any> | null)
@@ -3250,7 +3295,7 @@ const editSaving = ref(false)
/** 编辑订单分步:0 收货 / 1 服务与支付单 / 2 金额与确认(与处方列表「创建业务订单」一致) */
const editOrderStep = ref(0)
/** 顶部「关联处方」卡片数据(来自业务订单详情中的 prescription) */
const editOrderPrescription = ref<Record<string, any> | null>(null)
const editOrderPrescription = ref<Record<string, any> | null>(null)
/** 甘草 SCM 已提交:弹窗仅展示并提交快递单号与承运商 */
const editGancaoLogisticsOnlyMode = ref(false)
/** 用于提示文案展示甘草处方单号 */
@@ -3435,7 +3480,7 @@ const editRules = computed<FormRules>(() => {
return rules
})
function resetEditOrderDialog() {
function resetEditOrderDialog() {
editOrderStep.value = 0
editOrderPrescription.value = null
editGancaoLogisticsOnlyMode.value = false
@@ -3487,8 +3532,8 @@ async function openEdit(row: {
}
editOrderStep.value = 0
editOrderPrescription.value = null
editVisible.value = true
editDialogLoading.value = true
editVisible.value = true
editDialogLoading.value = true
try {
const res: any = await prescriptionOrderDetail({ id: row.id })
const d = res?.data ?? res
@@ -3511,7 +3556,7 @@ async function openEdit(row: {
editOrderPrescription.value = null
}
editForm.id = d.id
editForm.id = d.id
editForm.prescription_id = Number(d.prescription_id) || 0
editForm.diagnosis_id = Number(d.diagnosis_id) || 0
editForm.assistant_id = Number(d.assistant_id) || 0
@@ -3607,7 +3652,6 @@ async function submitEdit() {
service_channel: editForm.service_channel || '',
service_package: Array.isArray(editForm.service_package) ? editForm.service_package.join(',') : '',
express_company: editForm.express_company || 'auto',
tracking_number: editForm.tracking_number || '',
fee_type: editForm.fee_type,
amount: editForm.amount,
remark_extra: editForm.remark_extra || '',
@@ -3895,7 +3939,17 @@ const quickTrackForm = reactive({
tracking_number: ''
})
function openQuickTrack(row: { id: number; express_company?: unknown; tracking_number?: unknown }) {
function openQuickTrack(row: {
id: number
express_company?: unknown
tracking_number?: unknown
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
if (!canQuickTrackRow(row)) {
feedback.msgWarning('处方审核和支付单审核均通过后,才可填写或修改快递单号')
return
}
quickTrackRowId.value = row.id
quickTrackForm.express_company = String(row.express_company || 'auto') || 'auto'
quickTrackForm.tracking_number = String(row.tracking_number || '')
@@ -3943,7 +3997,19 @@ function resolveShipModeForRow(row: { id: number; ship_mode?: unknown }) {
return normalizeShipMode(row.ship_mode)
}
function openShip(row: { id: number; express_company?: unknown; tracking_number?: unknown; ship_mode?: unknown }) {
function openShip(row: {
id: number
express_company?: unknown
tracking_number?: unknown
ship_mode?: unknown
fulfillment_status?: number
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
if (!canShipRow(row)) {
feedback.msgWarning('仅处方审核和支付单审核均通过的履约中订单可填写单号并发货')
return
}
shipRowId.value = Number(row.id)
shipForm.ship_mode = resolveShipModeForRow(row)
shipForm.express_company = String(row.express_company || 'auto') || 'auto'
@@ -474,7 +474,12 @@
v-perms="['tcm.prescriptionOrder/edit']"
size="small"
@click="openEdit(row)"
>编辑</el-button>
>编辑</el-button>
<el-button
v-perms="['tcm.prescriptionOrder/editTime']"
size="small"
@click="orderTimeDialogRef?.open(row)"
>修改创建时间</el-button>
<el-button
v-if="canQuickTrackRow(row)"
v-perms="['tcm.prescriptionOrder/ddcode']"
@@ -592,8 +597,13 @@
>
撤回支付审核
</el-button>
<el-button
v-if="canShipRow(detailData)"
<el-button
v-perms="['tcm.prescriptionOrder/editTime']"
size="small"
@click="orderTimeDialogRef?.open(detailData)"
>修改创建时间</el-button>
<el-button
v-if="canShipRow(detailData)"
v-perms="['tcm.prescriptionOrder/ship']"
type="primary"
size="small"
@@ -1614,8 +1624,17 @@
<el-option label="京东快递" value="jd" />
<el-option label="极兔速递" value="jt" />
</el-select>
<el-input v-model="editForm.tracking_number" maxlength="80" placeholder="快递单号" class="flex-1 min-w-0" />
</div>
<el-input
v-model="editForm.tracking_number"
disabled
maxlength="80"
placeholder="快递单号"
class="flex-1 min-w-0"
/>
</div>
<div class="text-xs text-gray-400 mt-1">
编辑订单后需重新审核;双审通过后,请通过列表的单号操作填写或修改
</div>
</el-form-item>
</el-col>
<el-col :span="24">
@@ -2566,12 +2585,13 @@
</div>
</el-drawer>
<!-- 与 consumer/prescription/index、诊单 edit 同一套界面:只读诊单与全部分页签 -->
<TcmDiagnosisEditView ref="diagnosisViewRef" />
<!-- 与 consumer/prescription/index、诊单 edit 同一套界面:只读诊单与全部分页签 -->
<TcmDiagnosisEditView ref="diagnosisViewRef" />
<prescription-order-time-dialog ref="orderTimeDialogRef" @saved="onOrderTimeSaved" />
</div>
</template>
<script lang="ts" setup name="prescriptionOrderListH5">
<script lang="ts" setup name="prescriptionOrderListH5">
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
import {
Refresh,
@@ -2585,7 +2605,8 @@ import {
Wallet,
User
} from '@element-plus/icons-vue'
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 GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
import { useListTimeFilter } from '@/hooks/useListTimeFilter'
import {
@@ -3410,9 +3431,13 @@ function canWithdrawRow(row: { fulfillment_status?: number }) {
return Number(row.fulfillment_status) === 1
}
function canShipRow(row: { fulfillment_status?: number }) {
// 履约中(2) 可发货
return Number(row.fulfillment_status) === 2
function canShipRow(row: {
fulfillment_status?: number
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
// 履约中(2) 且处方、支付单均审核通过才可发货
return Number(row.fulfillment_status) === 2 && isDualAuditPassed(row)
}
function canAddPayOrderRow(row: { fulfillment_status?: number }) {
@@ -3432,8 +3457,11 @@ function canRefundRow(row: { fulfillment_status?: number; payment_slip_audit_sta
return (fs === 5 || fs === 6 || fs === 3 || fs === 9) && Number(row.payment_slip_audit_status) === 1
}
function canQuickTrackRow(_row: { fulfillment_status?: number }) {
return true
function canQuickTrackRow(row: {
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
return isDualAuditPassed(row)
}
function canUploadPharmacyRow(row: {
@@ -3513,7 +3541,15 @@ function canUpdateAmount(row: { id?: number; fulfillment_status?: number } | nul
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<Record<string, any> | null>(null)
const detailData = ref<Record<string, any> | null>(null)
const orderTimeDialogRef = ref<InstanceType<typeof PrescriptionOrderTimeDialog>>()
async function onOrderTimeSaved(id: number) {
getLists()
if (detailVisible.value && Number(detailData.value?.id) === id) {
await openDetail(id)
}
}
const detailServicePackageText = computed(() =>
formatServicePackageLabels(detailData.value?.service_package, servicePackageOptions.value)
@@ -3838,7 +3874,8 @@ function logActionText(act: string) {
patch_rx_patient: '处方患者信息',
update_amount: '修改订单金额',
complete: '完成订单',
refund: '退款'
refund: '退款',
edit_time: '修改创建时间'
}
return m[act] || act
}
@@ -4160,7 +4197,7 @@ const editSaving = ref(false)
/** 编辑订单分步:0 收货 / 1 服务与支付单 / 2 金额与确认(与处方列表「创建业务订单」一致) */
const editOrderStep = ref(0)
/** 顶部「关联处方」卡片数据(来自业务订单详情中的 prescription) */
const editOrderPrescription = ref<Record<string, any> | null>(null)
const editOrderPrescription = ref<Record<string, any> | null>(null)
const editOrderStepLead = computed(() => {
const texts = [
@@ -4360,7 +4397,7 @@ const editRules = computed<FormRules>(() => {
return rules
})
function resetEditOrderDialog() {
function resetEditOrderDialog() {
editOrderStep.value = 0
editOrderPrescription.value = null
editFormRef.value?.clearValidate()
@@ -4410,8 +4447,8 @@ async function openEdit(row: {
}
editOrderStep.value = 0
editOrderPrescription.value = null
editVisible.value = true
editDialogLoading.value = true
editVisible.value = true
editDialogLoading.value = true
try {
const res: any = await prescriptionOrderDetail({ id: row.id })
const d = res?.data ?? res
@@ -4434,7 +4471,7 @@ async function openEdit(row: {
editOrderPrescription.value = null
}
editForm.id = d.id
editForm.id = d.id
editForm.prescription_id = Number(d.prescription_id) || 0
editForm.diagnosis_id = Number(d.diagnosis_id) || 0
editForm.assistant_id = Number(d.assistant_id) || 0
@@ -4519,7 +4556,6 @@ async function submitEdit() {
service_channel: editForm.service_channel || '',
service_package: Array.isArray(editForm.service_package) ? editForm.service_package.join(',') : '',
express_company: editForm.express_company || 'auto',
tracking_number: editForm.tracking_number || '',
fee_type: editForm.fee_type,
amount: editForm.amount,
remark_extra: editForm.remark_extra || '',
@@ -4767,7 +4803,17 @@ const quickTrackForm = reactive({
tracking_number: ''
})
function openQuickTrack(row: { id: number; express_company?: unknown; tracking_number?: unknown }) {
function openQuickTrack(row: {
id: number
express_company?: unknown
tracking_number?: unknown
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
if (!canQuickTrackRow(row)) {
feedback.msgWarning('处方审核和支付单审核均通过后,才可填写或修改快递单号')
return
}
quickTrackRowId.value = row.id
quickTrackForm.express_company = String(row.express_company || 'auto') || 'auto'
quickTrackForm.tracking_number = String(row.tracking_number || '')
@@ -4819,7 +4865,19 @@ const shipDialogModeDisplay = computed(() =>
shipForm.ship_mode === 'direct' ? '洛阳药房直发' : '甘草药房直发'
)
function openShip(row: { id: number; express_company?: unknown; tracking_number?: unknown; ship_mode?: unknown }) {
function openShip(row: {
id: number
express_company?: unknown
tracking_number?: unknown
ship_mode?: unknown
fulfillment_status?: number
prescription_audit_status?: number
payment_slip_audit_status?: number
}) {
if (!canShipRow(row)) {
feedback.msgWarning('仅处方审核和支付单审核均通过的履约中订单可填写单号并发货')
return
}
shipRowId.value = row.id
shipForm.ship_mode = String(row.ship_mode || 'gancao') || 'gancao'
shipForm.express_company = String(row.express_company || 'auto') || 'auto'
+299 -21
View File
@@ -94,15 +94,32 @@
@keyup.enter="resetPage"
/>
</el-form-item>
<el-form-item label="跟进人">
<el-input
v-model="queryParams.follow_user"
<el-form-item label="跟进人">
<el-input
v-model="queryParams.follow_user"
placeholder="跟进人姓名(后台姓名或企微账号)"
clearable
@keyup.enter="resetPage"
/>
</el-form-item>
<el-form-item label="添加时间">
@keyup.enter="resetPage"
/>
</el-form-item>
<el-form-item label="渠道">
<el-select
v-model="queryParams.add_way"
clearable
filterable
placeholder="选择或搜索添加渠道"
style="width: 240px"
@change="resetPage"
>
<el-option
v-for="option in ADD_WAY_OPTIONS"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</el-form-item>
<el-form-item label="添加时间">
<el-date-picker
v-model="addTimeRange"
type="daterange"
@@ -235,6 +252,32 @@
<span v-else class="text-gray-400">—</span>
</template>
</el-table-column>
<el-table-column label="添加渠道" min-width="160">
<template #default="{ row }">
<div v-if="customerAddSources(row).length" class="flex items-center gap-1">
<el-tooltip
v-for="source in customerAddSources(row).slice(0, 1)"
:key="source.key"
:content="addSourceTooltip(source)"
placement="top"
>
<span class="inline-block max-w-[150px] truncate align-middle">
{{ source.label }}
</span>
</el-tooltip>
<el-tooltip
v-if="customerAddSources(row).length > 1"
:content="remainingAddSourcesTooltip(row)"
placement="top"
>
<span class="text-primary whitespace-nowrap cursor-help">
另 {{ customerAddSources(row).length - 1 }} 条
</span>
</el-tooltip>
</div>
<span v-else class="text-gray-400">未记录</span>
</template>
</el-table-column>
<el-table-column label="添加时间" width="160">
<template #default="{ row }">
{{ formatTime(firstExternalAddTime(row)) }}
@@ -245,9 +288,19 @@
{{ formatTime(row.update_time) }}
</template>
</el-table-column>
<el-table-column label="操作" width="120" fixed="right">
<el-table-column label="操作" width="160" fixed="right">
<template #default="{ row }">
<el-button type="primary" link @click="viewDetail(row)">查看详情</el-button>
<el-button
v-perms="['qywx.customer/delete']"
type="danger"
link
:loading="deletingCustomerId === Number(row.id)"
:disabled="deletingCustomerId !== null"
@click="handleDelete(row)"
>
删除
</el-button>
</template>
</el-table-column>
</el-table>
@@ -500,6 +553,21 @@
</el-descriptions-item>
<el-descriptions-item label="添加时间" :span="2">
{{ formatTime(firstExternalAddTime(currentCustomer)) }}
</el-descriptions-item>
<el-descriptions-item label="添加渠道" :span="2">
<div v-if="customerAddSources(currentCustomer).length" class="flex flex-wrap gap-1">
<el-tooltip
v-for="source in customerAddSources(currentCustomer)"
:key="source.key"
:content="addSourceTooltip(source)"
placement="top"
>
<el-tag size="small" type="info" effect="plain">
{{ source.label }}
</el-tag>
</el-tooltip>
</div>
<span v-else class="text-gray-400">未记录</span>
</el-descriptions-item>
<el-descriptions-item label="更新时间" :span="2">
{{ formatTime(currentCustomer.update_time) }}
@@ -549,8 +617,9 @@ import { Refresh, Setting, DataLine, CollectionTag } from '@element-plus/icons-v
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import {
qywxCustomerLists,
qywxCustomerSync,
qywxCustomerLists,
qywxCustomerDelete,
qywxCustomerSync,
qywxCustomerStats,
qywxSyncSettingsGet,
qywxSyncSettingsSave,
@@ -563,6 +632,7 @@ const syncing = ref(false)
const showSyncSettings = ref(false)
const showDetail = ref(false)
const currentCustomer = ref<any>(null)
const deletingCustomerId = ref<number | null>(null)
const stats = reactive({
total: 0,
@@ -591,17 +661,19 @@ const syncSettings = reactive({
interval: 3600
})
const queryParams = reactive<{
name: string
follow_user: string
tag_ids: string[]
const queryParams = reactive<{
name: string
follow_user: string
add_way: number | ''
tag_ids: string[]
add_time_start: string
add_time_end: string
dedupe_mode: 'first' | 'any'
}>({
name: '',
follow_user: '',
tag_ids: [],
name: '',
follow_user: '',
add_way: '',
tag_ids: [],
add_time_start: '',
add_time_end: '',
dedupe_mode: 'first'
@@ -639,6 +711,22 @@ interface TagStatsPayload {
groups: TagGroup[]
}
interface AddChannel {
state: string
label: string
source_type: 'promotion_pool' | 'state'
pool_id: number
user_id: string
event_time: number
}
interface AddSource extends AddChannel {
key: string
add_way: number | null
channel_label: string
staff_name: string
}
const tagStats = reactive<TagStatsPayload>({
total_tags: 0,
total_relations: 0,
@@ -847,10 +935,11 @@ const { pager, getLists, resetPage, resetParams } = usePaging({
params: queryParams
})
function handleReset() {
queryParams.name = ''
queryParams.follow_user = ''
queryParams.tag_ids = []
function handleReset() {
queryParams.name = ''
queryParams.follow_user = ''
queryParams.add_way = ''
queryParams.tag_ids = []
queryParams.add_time_start = ''
queryParams.add_time_end = ''
queryParams.dedupe_mode = 'first'
@@ -964,6 +1053,34 @@ function viewDetail(row: any) {
showDetail.value = true
}
async function handleDelete(row: Record<string, any>) {
const id = Number(row.id)
if (!Number.isInteger(id) || id <= 0 || deletingCustomerId.value !== null) return
const customerName = String(row.name || row.external_userid || '该客户')
try {
await feedback.confirm(
`确定删除企业微信客户“${customerName}”吗?此操作仅删除系统内的同步记录,不会删除企业微信中的客户关系;后续重新同步时可能再次出现。`
)
} catch {
return
}
deletingCustomerId.value = id
try {
await qywxCustomerDelete({ id })
if (pager.page > 1 && pager.lists.length === 1) {
pager.page -= 1
}
await Promise.all([getLists(), loadStats(), loadTagStats()])
feedback.msgSuccess('删除成功')
} catch (e: any) {
feedback.msgError(e?.message || e?.msg || '删除失败')
} finally {
deletingCustomerId.value = null
}
}
/** 列表接口会写入 admin_name(admin.work_wechat_userid = userid) */
function formatFollowUser(user: Record<string, any>) {
const adminName = String(user?.admin_name ?? '').trim()
@@ -985,6 +1102,167 @@ function followStaffTooltip(user: Record<string, any>) {
return parts.join('|')
}
function customerAddChannels(row: Record<string, any> | null | undefined): AddChannel[] {
if (!row) return []
if (Array.isArray(row.add_channels)) {
return row.add_channels
.map((channel: Record<string, any>): AddChannel => ({
state: String(channel?.state ?? '').trim(),
label: String(channel?.label ?? channel?.state ?? '').trim(),
source_type: channel?.source_type === 'promotion_pool' ? 'promotion_pool' : 'state',
pool_id: Number(channel?.pool_id ?? 0),
user_id: String(channel?.user_id ?? '').trim(),
event_time: Number(channel?.event_time ?? 0)
}))
.filter((channel: AddChannel) => channel.state !== '')
}
// 兼容仅返回原始渠道数组的旧接口/灰度节点。
if (!Array.isArray(row.add_channel_states)) return []
return row.add_channel_states
.map((state: unknown) => String(state ?? '').trim())
.filter((state: string) => state !== '')
.map((state: string) => ({
state,
label: state,
source_type: 'state' as const,
pool_id: 0,
user_id: '',
event_time: 0
}))
}
const ADD_WAY_LABELS: Record<number, string> = {
0: '未知添加方式',
1: '通过扫描二维码添加',
2: '通过搜索手机号添加',
3: '通过名片分享添加',
4: '通过群聊添加',
5: '通过手机通讯录添加',
6: '通过微信联系人添加',
8: '安装第三方应用时自动添加',
9: '通过搜索邮箱添加',
10: '通过视频号添加',
11: '通过日程参与人添加',
12: '通过会议参与人添加',
13: '通过微信好友添加',
14: '通过智慧硬件专属客服添加',
15: '通过上门服务客服添加',
16: '通过获客链接添加',
17: '通过定制开发添加',
18: '通过需求回复添加',
21: '通过第三方售前客服添加',
22: '通过可能的商务伙伴添加',
24: '通过接受微信好友申请添加',
201: '通过内部成员共享添加',
202: '通过管理员或负责人分配添加'
}
const ADD_WAY_OPTIONS = Object.entries(ADD_WAY_LABELS).map(([value, label]) => ({
value: Number(value),
label
}))
function normalizeAddWay(value: unknown): number | null {
if (typeof value === 'number' && Number.isInteger(value) && value >= 0) return value
if (typeof value !== 'string' || !/^\d+$/.test(value.trim())) return null
return Number(value.trim())
}
function addWayLabel(addWay: number) {
return ADD_WAY_LABELS[addWay] || `其他添加方式(${addWay})`
}
function customerAddSources(row: Record<string, any> | null | undefined): AddSource[] {
if (!row) return []
const channels = customerAddChannels(row)
const usedChannelIndexes = new Set<number>()
const sources: AddSource[] = []
const followUsers = Array.isArray(row.follow_users) ? row.follow_users : []
followUsers.forEach((user: Record<string, any>, index: number) => {
const userId = String(user?.userid ?? user?.UserId ?? '').trim()
const state = String(user?.state ?? user?.State ?? '').trim()
const addWay = normalizeAddWay(user?.add_way ?? user?.AddWay)
let channelIndex = channels.findIndex(
(channel, i) =>
!usedChannelIndexes.has(i) &&
userId !== '' &&
state !== '' &&
channel.user_id === userId &&
channel.state === state
)
if (channelIndex < 0 && state !== '') {
channelIndex = channels.findIndex(
(channel, i) => !usedChannelIndexes.has(i) && channel.state === state
)
}
if (channelIndex < 0 && userId !== '') {
channelIndex = channels.findIndex(
(channel, i) => !usedChannelIndexes.has(i) && channel.user_id === userId
)
}
const channel = channelIndex >= 0 ? channels[channelIndex] : undefined
if (channelIndex >= 0) usedChannelIndexes.add(channelIndex)
if (addWay === null && state === '' && !channel) return
const labelFromApi = String(user?.add_way_label ?? '').trim()
const sourceType = channel?.source_type ?? (/^zyt_pool:[1-9]\d*$/.test(state) ? 'promotion_pool' : 'state')
const label = labelFromApi || (addWay !== null
? addWayLabel(addWay)
: sourceType === 'promotion_pool'
? '通过获客链接添加'
: '通过其他渠道添加')
sources.push({
key: `follow:${index}:${userId}:${addWay ?? 'unknown'}:${state}`,
add_way: addWay,
label,
state: state || channel?.state || '',
channel_label: channel?.label || '',
source_type: sourceType,
pool_id: channel?.pool_id || 0,
user_id: userId || channel?.user_id || '',
staff_name: formatFollowUser(user),
event_time: channel?.event_time || Number(user?.createtime ?? 0)
})
})
// 兼容事件日志中仍有记录、但当前 follow_users 已不存在或旧接口未返回 add_way 的客户。
channels.forEach((channel, index) => {
if (usedChannelIndexes.has(index)) return
sources.push({
...channel,
key: `channel:${index}:${channel.user_id}:${channel.state}`,
add_way: channel.source_type === 'promotion_pool' ? 16 : null,
label: channel.source_type === 'promotion_pool' ? '通过获客链接添加' : '通过其他渠道添加',
channel_label: channel.label,
staff_name: channel.user_id || '—'
})
})
return sources.sort((a, b) => b.event_time - a.event_time)
}
function addSourceTooltip(source: AddSource) {
const parts: string[] = []
parts.push(`添加方式:${source.label}`)
if (source.source_type === 'promotion_pool' && source.channel_label) {
parts.push(`获客助手方案:${source.channel_label}`)
}
if (source.staff_name && source.staff_name !== '—') parts.push(`跟进人:${source.staff_name}`)
if (source.event_time > 0) parts.push(`添加时间:${formatTime(source.event_time)}`)
if (source.state) parts.push(`渠道参数:${source.state}`)
return parts.join('|')
}
function remainingAddSourcesTooltip(row: Record<string, any>) {
return customerAddSources(row).slice(1).map(addSourceTooltip).join('\n')
}
/**
* 添加时间:优先接口字段 external_first_add_time(同步写入 + 列表对未回填行按 JSON 兜底);
* 再解析 follow_users;最后退回 create_time
@@ -108,7 +108,7 @@
(-{{ formatNumber(dashboard.summary.deleted_fans_count) }})
</em>
</strong>
<small>{{ metric.hint }}</small>
<small>{{ metric.hint }}<template v-if="metric.key === 'add_fans_count' && canViewDeletedFans">;(-N)为其中已删除</template></small>
</article>
</section>
@@ -154,7 +154,7 @@
<div class="panel-heading panel-heading--table">
<div>
<h2>明细数据列表</h2>
<p>展开部门可查看人员明细;加粉=总进线=区间新增加粉(按员工+客户去重,包含区间内添加后已删客户,剔除继承客户、扫一扫/搜手机号/名片分享添加及区间前已加过的重加),(-N)表示加粉总数中已删除;挂号=已支付且实收低于 10 元的订单,预约=有效预约记录;开口率=开口/加粉,挂号率=挂号/加粉,面诊率=面诊/挂号(看挂号后流失),预约率=面诊/预约(看预约后未面诊),面诊接诊率=接诊诊单/面诊,接诊率=接诊诊单/总进线</p>
<p>展开部门可查看人员明细;加粉=总进线=区间新增“员工+客户”组合(同一员工的同一客户只计一次,同一客户进入不同员工分别计数;包含区间内添加后已删客户,剔除继承客户、扫一扫/搜手机号/名片分享添加及区间前已存在的相同组合)<template v-if="canViewDeletedFans">,(-N)表示加粉组合中已删除</template>;开口=获客客户首次发起会话事件,按开口时间计入,同一员工的同一客户只计一次;挂号=已支付且实收低于 10 元的订单,预约=有效预约记录;开口率=开口/加粉,挂号率=挂号/加粉,面诊率=面诊/挂号(看挂号后流失),预约率=面诊/预约(看预约后未面诊),面诊接诊率=接诊诊单/面诊,接诊率=接诊诊单/总进线</p>
</div>
<span>{{ dashboard.rows.length }} 个顶层节点</span>
</div>
@@ -189,7 +189,13 @@
</el-table-column>
<el-table-column prop="add_fans_count" label="加粉" min-width="92" align="right">
<template #default="{ row }">
<span class="fan-count-value">
<button
v-if="hasFans(row.add_fans_count)"
type="button"
class="fan-count-value fan-detail-trigger fan-detail-trigger--table"
title="查看该行加粉组合明细"
@click.stop="openFansDetail(row)"
>
{{ formatNumber(row.add_fans_count) }}
<em
v-if="hasDeletedFans(row.deleted_fans_count)"
@@ -198,7 +204,8 @@
>
(-{{ formatNumber(row.deleted_fans_count) }})
</em>
</span>
</button>
<span v-else class="fan-count-value is-empty">0</span>
</template>
</el-table-column>
<el-table-column prop="total_open_count" label="开口" min-width="72" align="right" />
@@ -292,6 +299,75 @@
</div>
</div>
</section>
<el-dialog
v-model="fansDetailVisible"
:title="fansDetailTitle"
width="920px"
top="7vh"
append-to-body
destroy-on-close
class="fans-detail-dialog"
@closed="resetFansDetail"
>
<div class="fans-detail-context">
<span><b>统计区间</b>{{ detailRangeText }}</span>
<span><b>媒体渠道</b>{{ detailChannelText }}</span>
<span><b>数据范围</b>{{ dashboard.meta.scope_label || '当前权限范围' }}</span>
</div>
<el-table
v-loading="fansDetailLoading"
:data="fansDetailRows"
:row-class-name="fansDetailRowClassName"
height="430"
class="fans-detail-table"
>
<el-table-column label="客户" min-width="190">
<template #default="{ row }">
<div class="customer-cell">
<strong class="customer-name" :class="{ 'is-deleted': isDeletedFan(row) }">
{{ fanCustomerName(row) }}
</strong>
<small v-if="row.customer_name && row.external_userid">{{ row.external_userid }}</small>
</div>
</template>
</el-table-column>
<el-table-column label="归属员工" min-width="160">
<template #default="{ row }">{{ fanOwnerName(row) }}</template>
</el-table-column>
<el-table-column label="添加时间" min-width="180">
<template #default="{ row }">{{ fanAddTime(row) }}</template>
</el-table-column>
<el-table-column v-if="canViewDeletedFansDetail" label="状态" width="150" align="center">
<template #default="{ row }">
<div v-if="isDeletedFan(row)" class="deleted-status">
<el-tag type="danger" effect="dark" size="small">已删除</el-tag>
<small v-if="row.delete_time">{{ row.delete_time }}</small>
</div>
<el-tag v-else type="success" effect="plain" size="small">正常</el-tag>
</template>
</el-table-column>
<template #empty>
<el-empty :image-size="68" description="当前条件下暂无加粉组合明细" />
</template>
</el-table>
<div class="fans-detail-footer">
<span>共 {{ formatNumber(fansDetailPager.total) }} 位客户</span>
<el-pagination
v-if="fansDetailPager.total > 0"
v-model:current-page="fansDetailPager.page_no"
v-model:page-size="fansDetailPager.page_size"
:page-sizes="[10, 20, 50, 100]"
:total="fansDetailPager.total"
layout="total, sizes, prev, pager, next"
background
@current-change="loadFansDetail"
@size-change="handleFansDetailSizeChange"
/>
</div>
</el-dialog>
</div>
</template>
@@ -300,7 +376,14 @@ import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock, Refresh } from '@element-plus/icons-vue'
import vCharts from 'vue-echarts'
import { firstVisitConversionOverview, type FirstVisitConversionParams } from '@/api/first_visit'
import {
firstVisitConversionFansDetail,
firstVisitConversionOverview,
type FirstVisitConversionFanDetailRow,
type FirstVisitConversionFansDetailParams,
type FirstVisitConversionFansDetailResult,
type FirstVisitConversionParams
} from '@/api/first_visit'
type MetricType = 'count' | 'money' | 'ratio'
type MediaChannelOption = {
@@ -320,7 +403,7 @@ const emptyDashboard = () => ({
time_type: 'today', time_label: '今日', start_date: '', end_date: '', generated_at: '',
scope_value: 4, scope_label: '', selected_dept_name: '', selected_assistant_name: '',
selected_media_channel_code: '', selected_media_channel_name: '', open_count_source: '', ranking_kind: 'hidden',
can_view_finance: false
can_view_finance: false, can_view_deleted_fans: false
},
filters: {
departments: [] as any[],
@@ -346,6 +429,14 @@ const query = reactive<FirstVisitConversionParams>({
media_channel_code: ''
})
const customDateRange = ref<string[]>([])
const fansDetailVisible = ref(false)
const fansDetailLoading = ref(false)
const fansDetailCanViewDeletedFans = ref(false)
const fansDetailRows = ref<FirstVisitConversionFanDetailRow[]>([])
const fansDetailPager = reactive({ page_no: 1, page_size: 20, total: 0 })
const fansDetailEntity = ref<{ type: 'dept' | 'member'; id: string | number; adminId?: number; name: string }>({
type: 'dept', id: 0, name: '当前行'
})
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
const timeOptions = [
{ label: '今日', value: 'today' },
@@ -357,8 +448,8 @@ const timeOptions = [
{ label: '自定义', value: 'custom' }
]
const metricCards: Array<{ key: string; label: string; type: MetricType; hint: string }> = [
{ key: 'add_fans_count', label: '加粉数', type: 'count', hint: '区间新增加粉(含已删除);(-N)为其中已删除' },
{ key: 'total_open_count', label: '开口数', type: 'count', hint: '来源于个人业绩录入' },
{ key: 'add_fans_count', label: '加粉数', type: 'count', hint: '区间新增员工+客户组合(不同员工分别计数,含已删除)' },
{ key: 'total_open_count', label: '开口数', type: 'count', hint: '获客客户首次发起会话;按开口时间统计,同一员工的同一客户只计一次' },
{ key: 'interview_count', label: '面诊', type: 'count', hint: '已完成预约' },
{ key: 'completed_order_count', label: '接诊诊单', type: 'count', hint: '业务订单,按创建人归属并过滤无效单' },
{ key: 'completed_order_amount', label: '诊单金额', type: 'money', hint: '排除取消、拒收、退款及已退款订单' },
@@ -375,6 +466,9 @@ const scopeDescription = computed(() => {
return parts.join(' · ')
})
const canViewFinance = computed(() => Boolean(dashboard.meta.can_view_finance))
// 仅服务端按登录账号精确判定为admin时放行;缺失、字符串或角色权限均不能兜底放行。
const canViewDeletedFans = computed(() => dashboard.meta.can_view_deleted_fans === true)
const canViewDeletedFansDetail = computed(() => canViewDeletedFans.value && fansDetailCanViewDeletedFans.value)
const visibleMetricCards = computed(() =>
canViewFinance.value
? metricCards
@@ -424,6 +518,13 @@ const rankingKind = computed(() => dashboard.meta.ranking_kind || (
))
const showRankings = computed(() => rankingKind.value !== 'hidden')
const rankingSubject = computed(() => rankingKind.value === 'member' ? '组内成员' : '小组')
const fansDetailTitle = computed(() => `${fansDetailEntity.value.name} · 加粉组合明细`)
const detailRangeText = computed(() => {
const startDate = dashboard.meta.start_date || query.start_date || ''
const endDate = dashboard.meta.end_date || query.end_date || ''
return startDate && endDate ? `${startDate} 至 ${endDate}` : (dashboard.meta.time_label || '当前区间')
})
const detailChannelText = computed(() => dashboard.meta.selected_media_channel_name || '全部渠道')
const totalOrderValue = computed(() => dashboard.rankings.orders.reduce((total, item) => total + Number(item.value || 0), 0))
const totalAmountValue = computed(() => dashboard.rankings.amounts.reduce((total, item) => total + Number(item.value || 0), 0))
const targetChartOption = computed(() => ({
@@ -440,10 +541,12 @@ const targetChartOption = computed(() => ({
}))
let latestDashboardRequestId = 0
let latestFansDetailRequestId = 0
async function loadDashboard() {
const requestId = ++latestDashboardRequestId
loading.value = true
dashboard.meta.can_view_deleted_fans = false
try {
const params: FirstVisitConversionParams = { ...query }
if (params.time_type === 'custom') {
@@ -492,6 +595,92 @@ function handleDeptChange() {
loadDashboard()
}
function openFansDetail(row: any) {
fansDetailEntity.value = {
type: row.type ? 'member' : 'dept',
id: row.id,
adminId: Number(row.admin_id || 0) || undefined,
name: row.name || '当前行'
}
fansDetailPager.page_no = 1
fansDetailRows.value = []
fansDetailPager.total = 0
fansDetailVisible.value = true
loadFansDetail()
}
async function loadFansDetail() {
if (!fansDetailVisible.value) return
const requestId = ++latestFansDetailRequestId
fansDetailLoading.value = true
fansDetailCanViewDeletedFans.value = false
try {
const params: FirstVisitConversionFansDetailParams = {
...query,
time_type: query.time_type,
start_date: dashboard.meta.start_date || query.start_date,
end_date: dashboard.meta.end_date || query.end_date,
media_channel_code: dashboard.meta.selected_media_channel_code || query.media_channel_code || '',
entity_type: fansDetailEntity.value.type,
entity_id: fansDetailEntity.value.id,
admin_id: fansDetailEntity.value.adminId,
page_no: fansDetailPager.page_no,
page_size: fansDetailPager.page_size
}
const result = await firstVisitConversionFansDetail(params) as FirstVisitConversionFansDetailResult
if (requestId !== latestFansDetailRequestId) return
fansDetailCanViewDeletedFans.value = result?.can_view_deleted_fans === true
const rows = Array.isArray(result?.lists) ? result.lists : (Array.isArray(result?.rows) ? result.rows : [])
fansDetailRows.value = rows
fansDetailPager.total = Number(result?.count ?? result?.total ?? rows.length) || 0
} catch (error: any) {
if (requestId !== latestFansDetailRequestId) return
fansDetailRows.value = []
fansDetailPager.total = 0
ElMessage.error(error?.message || '加粉组合明细加载失败')
} finally {
if (requestId === latestFansDetailRequestId) fansDetailLoading.value = false
}
}
function handleFansDetailSizeChange() {
fansDetailPager.page_no = 1
loadFansDetail()
}
function resetFansDetail() {
++latestFansDetailRequestId
fansDetailLoading.value = false
fansDetailCanViewDeletedFans.value = false
fansDetailRows.value = []
fansDetailPager.page_no = 1
fansDetailPager.total = 0
}
function hasFans(value: any) {
return Math.round(Number(value || 0)) > 0
}
function isDeletedFan(row: FirstVisitConversionFanDetailRow) {
return canViewDeletedFansDetail.value && Boolean(row.is_deleted)
}
function fanCustomerName(row: FirstVisitConversionFanDetailRow) {
return row.customer_name || row.external_userid || '未知客户'
}
function fanOwnerName(row: FirstVisitConversionFanDetailRow) {
return row.wecom_staff_name || row.wecom_userid || '未绑定员工'
}
function fanAddTime(row: FirstVisitConversionFanDetailRow) {
return row.add_time || '-'
}
function fansDetailRowClassName({ row }: { row: FirstVisitConversionFanDetailRow }) {
return isDeletedFan(row) ? 'is-deleted-fan-row' : ''
}
function formatMetric(key: string, type: MetricType) {
const value = dashboard.summary[key]
if (type === 'money') return formatMoney(value)
@@ -504,7 +693,7 @@ function formatNumber(value: any) {
}
function hasDeletedFans(value: any) {
return Math.round(Number(value || 0)) > 0
return canViewDeletedFans.value && Math.round(Number(value || 0)) > 0
}
function formatMoney(value: any) {
@@ -658,6 +847,18 @@ onMounted(loadDashboard)
}
.metric-value { display: flex; justify-content: flex-start; }
.fan-detail-trigger {
margin: 0;
padding: 0;
border: 0;
color: inherit;
background: transparent;
font: inherit;
cursor: pointer;
&:focus-visible { outline: 2px solid #2f78df; outline-offset: 3px; border-radius: 3px; }
&:disabled { cursor: default; }
}
.deleted-fans-marker {
color: #c65f26;
font-size: .58em;
@@ -666,6 +867,9 @@ onMounted(loadDashboard)
}
.fan-count-value .deleted-fans-marker { font-size: 11px; }
.fan-detail-trigger--table { color: #1769aa; font-weight: 650; }
.fan-detail-trigger--table:hover { color: #0f4f82; }
.fan-count-value.is-empty { color: #98a2b3; }
.ranking-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
.panel { min-width: 0; max-width: 100%; padding: 16px; border-radius: 10px; box-sizing: border-box; }
@@ -729,6 +933,47 @@ onMounted(loadDashboard)
.legend-line.is-target { border-color: #2f78df; border-top-style: dashed; }
.target-chart { width: 100%; height: 260px; }
.fans-detail-context {
display: flex;
flex-wrap: wrap;
gap: 8px 20px;
margin: -4px 0 14px;
padding: 10px 12px;
border: 1px solid #e4e9ef;
border-radius: 7px;
color: #5d6b7e;
background: #f7f9fb;
font-size: 12px;
span { display: inline-flex; gap: 7px; }
b { color: #8a95a5; font-weight: 500; }
}
.fans-detail-table {
width: 100%;
.customer-cell { display: grid; gap: 3px; }
.customer-name { color: #273347; font-weight: 650; }
.customer-name.is-deleted { color: #c24137; text-decoration: line-through; text-decoration-color: #e8a39e; }
.customer-cell small { overflow: hidden; color: #98a2b3; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
:deep(.is-deleted-fan-row > td.el-table__cell) { background: #fff3f2 !important; }
}
.deleted-status {
display: inline-grid;
justify-items: center;
gap: 4px;
small { color: #b14e47; font-size: 10px; }
}
.fans-detail-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-top: 14px;
color: #8491a2;
font-size: 12px;
}
@media (max-width: 1180px) {
.filter-strip { align-items: flex-start; flex-wrap: wrap; }
.range-text { margin-left: 0; }
@@ -744,5 +989,7 @@ onMounted(loadDashboard)
.employee-select, .dept-select, .channel-select { width: 100%; }
.bar-row { grid-template-columns: 100px minmax(70px, 1fr) 96px; }
.target-summary { grid-template-columns: 1fr; }
.fans-detail-footer { align-items: flex-start; flex-direction: column; }
.fans-detail-footer :deep(.el-pagination) { max-width: 100%; flex-wrap: wrap; justify-content: flex-start; }
}
</style>
@@ -125,7 +125,12 @@
</div>
</template>
</el-table-column>
<el-table-column label="预约时间" min-width="165">
<el-table-column label="挂号类型" min-width="110">
<template #default="{ row }">
{{ Number(row.appointment_id) > 0 ? appointmentTypeDescription(row.appointment_type) : '—' }}
</template>
</el-table-column>
<el-table-column label="预约时间" min-width="165">
<template #default="{ row }">
<span :class="['appointment-time', { empty: !row.appointment_time_text }]">
{{ row.appointment_time_text || '暂无预约' }}
@@ -324,7 +329,8 @@
</div>
</template>
<script setup lang="ts">
<script setup lang="ts">
import { appointmentTypeDescription } from '@/utils/appointment-type'
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
@@ -0,0 +1,252 @@
<template>
<div class="automation-form">
<el-alert class="automation-note" type="info" show-icon :closable="false" title="自动化设置只作用于之后新添加的客户,不会写入企微获客链接详情中的“欢迎语/客户标签”配置。" description="系统会在客户添加回调中立即发送渠道欢迎语并添加标签,后台任务负责失败重试及其他补偿。测试时请使用系统复制的、带渠道参数的链接。" />
<section class="automation-section" :class="{ 'is-disabled': receptionDisabled }">
<h3 class="form-section-title">接待设置</h3>
<el-form-item label="接待模式">
<el-radio-group v-model="config.reception_mode" :disabled="receptionDisabled">
<el-radio value="always">全天接待</el-radio>
<el-radio value="scheduled">按星期时段自动上下线</el-radio>
</el-radio-group>
<p class="field-help">成员仍受每日上限、有效期及启用状态限制;时间统一使用北京时间。</p>
</el-form-item>
<div v-if="config.reception_mode === 'scheduled'" class="reception-schedules">
<div v-for="(slot, index) in config.reception_schedule" :key="index" class="schedule-card">
<div class="schedule-heading"><strong>接待时段 {{ index + 1 }}</strong><el-button type="danger" text size="small" :disabled="receptionDisabled" @click="config.reception_schedule.splice(index, 1)">删除时段</el-button></div>
<el-checkbox-group v-model="slot.weekdays" class="weekday-select" :disabled="receptionDisabled"><el-checkbox v-for="(day, i) in weekdays" :key="day" :value="i + 1">{{ day }}</el-checkbox></el-checkbox-group>
<div class="time-row"><el-time-picker v-model="slot.start" :disabled="receptionDisabled" format="HH:mm" value-format="HH:mm" placeholder="开始时间" :clearable="false" /><span>至</span><el-time-picker v-model="slot.end" :disabled="receptionDisabled" format="HH:mm" value-format="HH:mm" placeholder="结束时间" :clearable="false" /><small v-if="slot.end < slot.start">次日结束</small></div>
<el-select v-model="slot.member_admin_ids" :disabled="receptionDisabled" multiple filterable clearable placeholder="从上方主接待成员中选择" style="width: 100%">
<el-option v-for="member in mainMembers" :key="member.id" :value="Number(member.id)" :label="memberLabel(member)" />
</el-select>
<p v-if="slot.member_admin_ids.some((id) => !mainMemberIds.includes(id))" class="inline-error">该时段含已从主接待移除的成员,请重新选择。</p>
</div>
<el-button :icon="Plus" :disabled="receptionDisabled || config.reception_schedule.length >= 30" @click="addReceptionSlot">添加接待时段</el-button>
<p class="field-help">最多 30 个时段。跨午夜时段归属开始日,例如星期一 22:00 至 02:00 包含星期二凌晨;接待时段重叠时取成员并集。</p>
</div>
<el-form-item label="备用成员" :required="config.reception_mode === 'scheduled'">
<el-select v-model="config.backup_member_admin_ids" :disabled="receptionDisabled" multiple filterable clearable collapse-tags collapse-tags-tooltip :max-collapse-tags="3" :multiple-limit="500" placeholder="主接待成员均不可用时由备用成员接待" style="width: 100%">
<el-option v-for="member in members" :key="member.id" :value="Number(member.id)" :label="memberLabel(member)" :disabled="backupExcludedIds.includes(Number(member.id))" />
<el-option v-for="id in missingBackupIds" :key="`missing-${id}`" :value="id" :label="`成员 ${id}(当前不可选,请移除后重新选择)`" disabled />
</el-select>
<p class="field-help">备用成员不能与主接待重复。按时段模式至少配置一名备用成员;仅当无可用主接待时进入官方成员范围。</p>
</el-form-item>
</section>
<section class="automation-section" :class="{ 'is-disabled': customerDisabled }">
<h3 class="form-section-title">客户设置</h3>
<el-form-item label="自动添加客户标签">
<el-switch v-model="config.tags_enabled" :disabled="customerDisabled || tagsCreating" />
<div v-if="hasMultipleTags" class="legacy-tags-warning full-width" role="alert">
<p>原方案设置了多个标签:{{ selectedTagNames }}。现在仅支持单选,请重新选择一个标签,或清空原标签。</p>
<el-button size="small" :disabled="customerDisabled || tagsCreating" @click="selectedTag = ''">清空原标签</el-button>
</div>
<div v-if="config.tags_enabled" class="full-width tags-content">
<div class="tag-select-row">
<el-select v-model="selectedTag" :disabled="customerDisabled || tagsCreating" :loading="tagsLoading" filterable clearable placeholder="选择一个企业微信客户标签" aria-label="企业微信客户标签" class="tag-select">
<el-option-group v-for="group in tagGroups" :key="group.group_id" :label="group.group_name">
<el-option v-for="tag in group.tag" :key="tag.id" :value="tag.id" :label="tag.name" />
</el-option-group>
<el-option-group v-if="unknownTagIds.length" label="已选标签(名称暂不可用)"><el-option v-for="id in unknownTagIds" :key="id" :value="id" :label="`已选标签 · ${id}`" /></el-option-group>
</el-select>
<el-button :icon="Plus" :disabled="customerDisabled || tagsCreating" @click="showCustomTag = !showCustomTag">自定义标签</el-button>
<el-button :icon="Refresh" :disabled="customerDisabled || tagsCreating" :loading="tagsLoading" @click="loadTags">{{ tagsError ? '重试' : '刷新标签' }}</el-button>
</div>
<p v-if="tagsError" role="alert" class="inline-error">{{ tagsError }} 已保留原有标签,点击“重试”重新加载。</p>
<p v-else class="field-help">每个方案只选一个标签,可选择已有企业微信标签,也可自定义创建。客户添加成功后由系统调用企微接口打标,不会显示在企微获客链接详情的“客户标签”配置中。</p>
<div v-if="showCustomTag" class="custom-tag-editor">
<label for="promotion-custom-tag-name">自定义标签名称</label>
<div class="custom-tag-row">
<el-input id="promotion-custom-tag-name" v-model="customTagName" :disabled="customerDisabled || tagsCreating" maxlength="30" show-word-limit placeholder="例如:官网咨询" @input="customTagError = ''" @keydown.enter.prevent="createCustomTag" />
<el-button type="primary" :disabled="customerDisabled || tagsLoading" :loading="tagsCreating" @click="createCustomTag">创建并选用</el-button>
</div>
<p class="field-help">创建到企业微信“推广渠道”分组,同组同名标签会复用。创建后即保存到企微标签库,取消方案编辑不会删除标签。</p>
<p v-if="customTagError" role="alert" class="inline-error">{{ customTagError }} 原有选择未改变。</p>
</div>
<p v-if="customTagSuccess" role="status" class="tag-success">{{ customTagSuccess }}</p>
</div>
</el-form-item>
<el-form-item label="自动设置客户备注">
<el-switch v-model="config.remark_enabled" :disabled="customerDisabled" />
<div v-if="config.remark_enabled" class="full-width remark-content">
<div class="token-buttons"><el-button v-for="token in templateTokens" :key="token.value" size="small" :disabled="customerDisabled" @click="insertRemark(token.value)">插入{{ token.label }}</el-button></div>
<el-input ref="remarkInput" v-model="config.remark_template" :disabled="customerDisabled" maxlength="200" show-word-limit placeholder="例如:官网-{customer_name}" @select="rememberRemarkSelection" @keyup="rememberRemarkSelection" @click="rememberRemarkSelection" @blur="rememberRemarkSelection" />
<div class="remark-preview"><span>备注预览</span><strong>{{ remarkPreview || '—' }}</strong><small>{{ Array.from(remarkPreview).length }}/20 字</small></div>
<p class="field-help">示例客户:张女士;员工:{{ employeeName }}。添加时间格式为 YYYY-MM-DD,生成后的备注最多保留前 20 字。</p>
</div>
</el-form-item>
<el-form-item label="自动设置客户描述">
<el-switch v-model="config.description_enabled" :disabled="customerDisabled" />
<el-input v-if="config.description_enabled" v-model="config.description" class="description-input" :disabled="customerDisabled" type="textarea" :rows="3" maxlength="150" show-word-limit placeholder="请输入客户描述,最多 150 字" />
</el-form-item>
</section>
<section class="automation-section" :class="{ 'is-disabled': welcomeDisabled }">
<h3 class="form-section-title">欢迎语设置</h3>
<el-form-item label="欢迎语模式">
<el-radio-group v-model="config.welcome_mode" :disabled="welcomeDisabled || anyUploading">
<el-radio value="channel">渠道欢迎语</el-radio>
<el-radio value="default">默认欢迎语</el-radio>
<el-radio value="none">不发送欢迎语</el-radio>
</el-radio-group>
<p v-if="config.welcome_mode === 'default'" class="field-help">沿用企业微信后台配置,本系统不发送欢迎语。</p>
<p v-else-if="config.welcome_mode === 'none'" class="field-help warning-help">仅关闭本系统欢迎语,无法覆盖或关闭企业微信后台已配置的欢迎语。</p>
<p v-else class="field-help warning-help">渠道欢迎语由客户添加回调即时发送,不会显示在企微获客链接详情中。同一接待成员若已配置企微原生欢迎语,企微可能不再下发欢迎码,请先关闭冲突配置。</p>
</el-form-item>
<template v-if="config.welcome_mode === 'channel'">
<div class="welcome-block"><h4>基础渠道欢迎语</h4><p class="field-help">未开启分时欢迎语,或新客户添加时间未匹配任何时段时,使用以下内容。</p>
<WelcomeMessageEditor v-model="config.welcome" :disabled="welcomeDisabled" :employee-name="employeeName" @busy="(busy) => updateBusy('basic', busy)" />
</div>
<el-form-item class="schedule-switch" label="分时欢迎语"><el-switch v-model="config.welcome_schedule_enabled" :disabled="welcomeDisabled || anyUploading" /><span class="switch-help">按客户添加时的北京时间匹配,时段不能重叠</span></el-form-item>
<div v-if="config.welcome_schedule_enabled">
<div v-for="(slot, index) in config.welcome_schedule" :key="index" class="schedule-card welcome-schedule">
<div class="schedule-heading"><strong>欢迎语时段 {{ index + 1 }}</strong><el-button type="danger" text size="small" :disabled="welcomeDisabled || anyUploading" @click="removeWelcomeSlot(index)">删除时段</el-button></div>
<el-checkbox-group v-model="slot.weekdays" class="weekday-select" :disabled="welcomeDisabled"><el-checkbox v-for="(day, i) in weekdays" :key="day" :value="i + 1">{{ day }}</el-checkbox></el-checkbox-group>
<div class="time-row"><el-time-picker v-model="slot.start" :disabled="welcomeDisabled" format="HH:mm" value-format="HH:mm" placeholder="开始时间" :clearable="false" /><span>至</span><el-time-picker v-model="slot.end" :disabled="welcomeDisabled" format="HH:mm" value-format="HH:mm" placeholder="结束时间" :clearable="false" /><small v-if="slot.end < slot.start">次日结束</small></div>
<WelcomeMessageEditor :model-value="slot" :disabled="welcomeDisabled" :employee-name="employeeName" @update:model-value="(message) => Object.assign(slot, message)" @busy="(busy) => updateBusy(`slot-${index}`, busy)" />
</div>
<el-button :icon="Plus" :disabled="welcomeDisabled || anyUploading || config.welcome_schedule.length >= 30" @click="addWelcomeSlot">添加欢迎语时段</el-button>
<p class="field-help">最多 30 个时段,支持跨午夜。时段外自动使用基础渠道欢迎语,不会随机选择内容。</p>
</div>
</template>
</section>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { wecomPromotionCreateTag, wecomPromotionTagOptions } from '@/api/first_visit'
import type { WecomPromotionTagGroup } from '@/api/first_visit'
import WelcomeMessageEditor from './WelcomeMessageEditor.vue'
import { previewTemplate, templateTokens, validateCustomTagName, weekdays } from './promotion-automation'
import type { PromotionAutomationConfig, PromotionMemberChoice } from './promotion-automation'
type AutomationSection = 'reception' | 'customer' | 'welcome'
const props = defineProps<{
modelValue: PromotionAutomationConfig
mainMemberIds: number[]
members: PromotionMemberChoice[]
disabled?: boolean
disabledSections?: AutomationSection[]
backupExcludedMemberIds?: number[]
}>()
const emit = defineEmits<{ 'update:modelValue': [config: PromotionAutomationConfig]; busy: [value: boolean] }>()
const config = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value) })
const sectionDisabled = (section: AutomationSection) => Boolean(props.disabled || props.disabledSections?.includes(section))
const receptionDisabled = computed(() => sectionDisabled('reception'))
const customerDisabled = computed(() => sectionDisabled('customer'))
const welcomeDisabled = computed(() => sectionDisabled('welcome'))
const backupExcludedIds = computed(() => props.backupExcludedMemberIds || props.mainMemberIds)
const mainMembers = computed(() => props.members.filter((member) => props.mainMemberIds.includes(Number(member.id))))
const missingBackupIds = computed(() => config.value.backup_member_admin_ids.filter((id) => !props.members.some((member) => Number(member.id) === id)))
const employeeName = computed(() => mainMembers.value[0]?.name || '小陈')
const remarkPreview = computed(() => previewTemplate(config.value.remark_template, employeeName.value, 20))
const remarkInput = ref<{ input?: HTMLInputElement }>()
const remarkSelection = ref({ start: 0, end: 0 })
const tagGroups = ref<WecomPromotionTagGroup[]>([])
const tagsLoading = ref(false)
const tagsError = ref('')
const tagsLoaded = ref(false)
const tagsCreating = ref(false)
const showCustomTag = ref(false)
const customTagName = ref('')
const customTagError = ref('')
const customTagSuccess = ref('')
const hasMultipleTags = computed(() => config.value.tag_ids.length > 1)
const selectedTag = computed({
get: () => config.value.tag_ids.length === 1 ? config.value.tag_ids[0] : '',
set: (id: string | undefined) => {
config.value.tag_ids = id ? [id] : []
customTagSuccess.value = ''
}
})
const selectedTagNames = computed(() => {
const tags = tagGroups.value.flatMap((group) => group.tag)
return config.value.tag_ids.map((id) => tags.find((tag) => tag.id === id)?.name || id).join('、')
})
const busyEditors = ref(new Set<string>())
const anyUploading = computed(() => busyEditors.value.size > 0)
watch([tagsCreating, anyUploading], ([creating, uploading]) => emit('busy', creating || uploading), { flush: 'sync' })
const unknownTagIds = computed(() => {
const ids = new Set(tagGroups.value.flatMap((group) => group.tag.map((tag) => tag.id)))
return config.value.tag_ids.filter((id) => !ids.has(id))
})
watch([() => config.value.tags_enabled, customerDisabled], ([enabled, sectionIsDisabled]) => {
if (enabled && !sectionIsDisabled && !tagsLoaded.value && !tagsLoading.value) void loadTags()
}, { immediate: true })
function memberLabel(member: PromotionMemberChoice) { return `${member.name} · ${member.dept_names?.join(' / ') || member.userid || '未分部门'}` }
function addReceptionSlot() { config.value.reception_schedule.push({ weekdays: [1, 2, 3, 4, 5], start: '09:00', end: '18:00', member_admin_ids: [...props.mainMemberIds] }) }
function addWelcomeSlot() { config.value.welcome_schedule.push({ weekdays: [1, 2, 3, 4, 5], start: '09:00', end: '18:00', text: '', attachments: [] }) }
function removeWelcomeSlot(index: number) { config.value.welcome_schedule.splice(index, 1); busyEditors.value.clear() }
function updateBusy(key: string, busy: boolean) { busy ? busyEditors.value.add(key) : busyEditors.value.delete(key) }
async function loadTags() {
if (tagsCreating.value || tagsLoading.value) return
tagsLoading.value = true
tagsError.value = ''
try {
const result = await wecomPromotionTagOptions()
if (!Array.isArray(result?.tag_groups)) throw new Error('标签接口未返回有效的标签列表。')
tagGroups.value = result.tag_groups.map((group) => ({ ...group, tag: Array.isArray(group.tag) ? group.tag : [] }))
tagsLoaded.value = true
} catch (error: unknown) {
tagsError.value = error instanceof Error ? error.message : typeof error === 'string' ? error : '企业微信标签加载失败。'
} finally { tagsLoading.value = false }
}
async function createCustomTag() {
if (customerDisabled.value || tagsCreating.value || tagsLoading.value) return
customTagError.value = validateCustomTagName(customTagName.value)
customTagSuccess.value = ''
if (customTagError.value) return
tagsCreating.value = true
try {
const result = await wecomPromotionCreateTag({ name: customTagName.value.trim() })
if (!result?.tag?.id || !result.tag.name || !result.group_id) throw new Error('企业微信未返回有效的标签 ID,请刷新标签后确认。')
let group = tagGroups.value.find((item) => item.group_id === result.group_id)
if (!group) {
group = { group_id: result.group_id, group_name: result.group_name, tag: [] }
tagGroups.value.push(group)
}
const existing = group.tag.findIndex((tag) => tag.id === result.tag.id)
if (existing >= 0) group.tag[existing] = result.tag
else group.tag.push(result.tag)
selectedTag.value = result.tag.id
customTagSuccess.value = `${result.reused ? '已选用已有' : '已创建并选用'}标签“${result.tag.name}”,保存方案后生效。`
customTagName.value = ''
showCustomTag.value = false
} catch (error: unknown) {
customTagError.value = error instanceof Error ? error.message : typeof error === 'string' ? error : '自定义标签创建失败,请刷新确认或重试。'
} finally { tagsCreating.value = false }
}
function rememberRemarkSelection() {
const input = remarkInput.value?.input
if (input) remarkSelection.value = { start: input.selectionStart || 0, end: input.selectionEnd || 0 }
}
async function insertRemark(token: string) {
const { start, end } = remarkSelection.value
config.value.remark_template = config.value.remark_template.slice(0, start) + token + config.value.remark_template.slice(end)
await nextTick()
const cursor = start + token.length
remarkInput.value?.input?.focus()
remarkInput.value?.input?.setSelectionRange(cursor, cursor)
remarkSelection.value = { start: cursor, end: cursor }
}
onBeforeUnmount(() => emit('busy', false))
</script>
<style scoped>
.automation-form { width: 100%; }.automation-note { margin-top: 22px; }.automation-note :deep(.el-alert__description) { line-height: 1.7; }
.automation-section { min-width: 0; transition: opacity .2s ease; }.automation-section.is-disabled { opacity: .58; }
.form-section-title { margin: 28px 0 18px; padding: 0 0 12px; border-bottom: 1px solid #ebeef5; font-size: 15px; font-weight: 600; color: #303133; }.field-help { width: 100%; font-size: 12px; line-height: 1.7; margin: 6px 0 0; color: #909399; }.warning-help { color: #9f6d14; }.full-width { width: 100%; }.inline-error { width: 100%; color: #d93026; font-size: 12px; line-height: 1.7; margin: 8px 0 0; }
.schedule-card { padding: 16px; border: 1px solid #e4e7ed; border-radius: 6px; background: #fafbfd; margin-bottom: 12px; }.schedule-heading { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; font-size: 13px; }.weekday-select { display: flex; flex-wrap: wrap; gap: 0 18px; }.weekday-select :deep(.el-checkbox) { margin-right: 0; }.time-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 12px 0; }.time-row :deep(.el-date-editor.el-input) { width: 150px; }.time-row > span { font-size: 12px; color: #909399; }.time-row > small { font-size: 12px; color: #b88230; }.reception-schedules { margin: 0 0 20px; }
.tags-content, .remark-content, .description-input { margin-top: 12px; }.tag-select-row { display: flex; gap: 10px; width: 100%; }.tag-select { flex: 1; min-width: 0; }.token-buttons { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 8px; }.token-buttons .el-button + .el-button { margin-left: 0; }.remark-preview { display: flex; gap: 14px; align-items: center; padding: 10px 12px; background: #f5f7fa; margin-top: 8px; border-radius: 4px; line-height: 1.7; }.remark-preview span, .remark-preview small { color: #909399; font-size: 12px; }.remark-preview strong { color: #303133; font-size: 13px; font-weight: 500; overflow-wrap: anywhere; }.remark-preview small { margin-left: auto; white-space: nowrap; }.welcome-block h4 { font-size: 13px; font-weight: 600; margin: 0 0 4px; }.welcome-block > .field-help { margin-bottom: 12px; }.schedule-switch { margin-top: 24px; }.switch-help { margin-left: 12px; color: #909399; font-size: 12px; }.welcome-schedule { background: #fff; }
.tag-select-row .el-button + .el-button { margin-left: 0; }
.custom-tag-editor { margin-top: 12px; padding: 14px; background: #f5f7fa; border: 1px solid #e4e7ed; border-radius: 4px; }
.custom-tag-editor label { display: block; font-size: 13px; color: #606266; margin-bottom: 8px; }
.custom-tag-row { display: flex; align-items: center; gap: 10px; }
.custom-tag-row .el-input { flex: 1; min-width: 0; }
.legacy-tags-warning { margin-top: 10px; padding: 10px 12px; background: #fdf6ec; border: 1px solid #faecd8; border-radius: 4px; color: #9f6d14; }
.legacy-tags-warning p { margin: 0 0 6px; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.tag-success { margin: 8px 0 0; color: #27864c; font-size: 12px; line-height: 1.7; }
@media (max-width: 620px) { .tag-select-row { flex-direction: column; }.remark-preview { flex-wrap: wrap; }.automation-form :deep(.el-radio) { margin-right: 14px; }.weekday-select { gap: 0 12px; } }
</style>
@@ -0,0 +1,246 @@
<template>
<div class="welcome-editor">
<div class="welcome-editor__fields">
<div class="text-tools">
<el-popover placement="bottom-start" trigger="click" :width="240" :disabled="disabled">
<template #reference><el-button size="small" :disabled="disabled">☺ 插入表情</el-button></template>
<div class="emoji-grid"><button v-for="emoji in emojis" :key="emoji" type="button" @click="insertText(emoji)">{{ emoji }}</button></div>
</el-popover>
<el-button v-for="token in templateTokens" :key="token.value" size="small" :disabled="disabled" @click="insertText(token.value)">{{ token.label }}</el-button>
</div>
<el-input
ref="textInput"
:model-value="modelValue.text"
type="textarea"
:rows="6"
:disabled="disabled"
placeholder="请输入欢迎语,也可插入客户昵称、员工昵称和添加日期"
@update:model-value="updateText"
@select="rememberSelection"
@keyup="rememberSelection"
@click="rememberSelection"
@blur="rememberSelection"
/>
<div class="text-count" :class="{ 'is-error': textTooLong }">{{ Array.from(modelValue.text).length }}/1200 字 · {{ utf8Length(modelValue.text) }}/4000 字节</div>
<div class="attachments-heading">
<strong>附件 <span>{{ modelValue.attachments.length }}/9</span></strong>
<el-dropdown :disabled="disabled || modelValue.attachments.length >= 9 || uploading" @command="addAttachment">
<el-button size="small" :disabled="disabled || modelValue.attachments.length >= 9 || uploading" :icon="Plus">添加附件</el-button>
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item v-for="item in attachmentTypes" :key="item.value" :command="item.value">{{ item.label }}</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
<div v-if="!modelValue.attachments.length" class="attachment-empty">可添加图片、网页、小程序、视频或文件。</div>
<div v-for="(attachment, index) in modelValue.attachments" :key="index" class="attachment-card">
<div class="attachment-card__heading">
<strong>{{ index + 1 }}. {{ attachmentLabel(attachment.msgtype) }}</strong>
<div>
<el-button text size="small" :disabled="disabled || uploading || index === 0" @click="moveAttachment(index, -1)">上移</el-button>
<el-button text size="small" :disabled="disabled || uploading || index === modelValue.attachments.length - 1" @click="moveAttachment(index, 1)">下移</el-button>
<el-button text type="danger" size="small" :disabled="disabled || uploading" @click="removeAttachment(index)">删除</el-button>
</div>
</div>
<template v-if="attachment.msgtype === 'image' || attachment.msgtype === 'video' || attachment.msgtype === 'file'">
<div class="upload-field">
<el-button size="small" :icon="Upload" :loading="uploadingIndex === index" :disabled="disabled || uploading" @click="selectFile(index, attachment.msgtype)">{{ assetId(attachment) ? '重新上传' : '上传' }}{{ attachmentLabel(attachment.msgtype) }}</el-button>
<span :class="assetId(attachment) ? 'asset-ready' : 'muted'">{{ assetName(attachment) }}</span>
</div>
<small class="field-tip">{{ attachment.msgtype === 'image' ? 'JPG / PNG,最多 10MB。' : attachment.msgtype === 'video' ? 'MP4,最多 10MB。' : '文件最多 20MB。' }}上传成功后由服务端保存素材;未上传完成不能提交。</small>
</template>
<template v-else-if="attachment.msgtype === 'link'">
<label class="attachment-label">网页标题 <span>{{ utf8Length(attachment.link.title) }}/128 字节</span></label>
<el-input v-model="attachment.link.title" :disabled="disabled" placeholder="必填:网页标题" />
<label class="attachment-label">网页地址</label>
<el-input v-model="attachment.link.url" :disabled="disabled" placeholder="https://" />
<label class="attachment-label">网页描述 <span>{{ utf8Length(attachment.link.desc) }}/512 字节</span></label>
<el-input v-model="attachment.link.desc" :disabled="disabled" type="textarea" :rows="2" placeholder="选填:网页摘要" />
<label class="attachment-label">网页封面地址</label>
<el-input v-model="attachment.link.picurl" :disabled="disabled" placeholder="选填:公网可访问的 HTTPS 图片地址" />
</template>
<template v-else-if="attachment.msgtype === 'miniprogram'">
<label class="attachment-label">小程序标题 <span>{{ utf8Length(attachment.miniprogram.title) }}/64 字节</span></label>
<el-input v-model="attachment.miniprogram.title" :disabled="disabled" placeholder="必填:小程序标题" />
<label class="attachment-label">AppID</label>
<el-input v-model="attachment.miniprogram.appid" :disabled="disabled" placeholder="必填:小程序 AppID" />
<label class="attachment-label">页面路径</label>
<el-input v-model="attachment.miniprogram.page" :disabled="disabled" placeholder="pages/index/index,可包含查询参数" />
<div class="upload-field mini-upload">
<el-button size="small" :icon="Upload" :loading="uploadingIndex === index" :disabled="disabled || uploading" @click="selectFile(index, 'image')">{{ attachment.miniprogram.pic_asset_id ? '更换封面' : '上传小程序封面' }}</el-button>
<span :class="assetId(attachment) ? 'asset-ready' : 'muted'">{{ assetName(attachment) }}</span>
</div>
<small class="field-tip">JPG / PNG,最多 10MB。</small>
</template>
<div v-if="uploadErrors[index]" role="alert" class="upload-error">{{ uploadErrors[index] }} 请重试上传,原素材未被替换。</div>
</div>
<input ref="fileInput" class="file-input" type="file" :accept="fileAccept" @change="uploadSelectedFile" />
</div>
<aside class="welcome-preview" aria-label="欢迎语手机预览">
<div class="phone-heading"><span>‹</span><strong>{{ employeeName || '接待员工' }}</strong><span>···</span></div>
<div class="phone-content">
<div class="preview-time">添加成功 · 预览示例</div>
<div v-if="modelValue.text" class="chat-row"><span class="chat-avatar">{{ (employeeName || '员').slice(0, 1) }}</span><div class="chat-bubble">{{ previewTemplate(modelValue.text, employeeName) }}</div></div>
<div v-for="(attachment, index) in modelValue.attachments" :key="index" class="chat-row">
<span class="chat-avatar">{{ (employeeName || '员').slice(0, 1) }}</span>
<div class="chat-bubble attachment-preview">
<template v-if="attachment.msgtype === 'image'">
<img v-if="assetPreview(attachment)" :src="assetPreview(attachment)" alt="欢迎语图片预览" />
<div v-else class="media-placeholder"><el-icon><Picture /></el-icon><span>{{ assetId(attachment) ? '已保存的图片素材' : '待上传图片' }}</span></div>
</template>
<template v-else-if="attachment.msgtype === 'link'">
<strong>{{ attachment.link.title || '网页标题' }}</strong><p>{{ attachment.link.desc || '网页摘要' }}</p><small>网页链接</small>
</template>
<template v-else-if="attachment.msgtype === 'miniprogram'">
<small>小程序</small><strong>{{ attachment.miniprogram.title || '小程序标题' }}</strong>
<img v-if="assetPreview(attachment)" :src="assetPreview(attachment)" alt="小程序封面预览" />
<div v-else class="media-placeholder"><el-icon><Grid /></el-icon><span>小程序封面</span></div>
</template>
<template v-else><el-icon class="file-icon"><VideoPlay v-if="attachment.msgtype === 'video'" /><Document v-else /></el-icon><strong>{{ assetName(attachment) }}</strong><small>{{ attachmentLabel(attachment.msgtype) }}</small></template>
</div>
</div>
<div v-if="!modelValue.text && !modelValue.attachments.length" class="preview-empty">编辑内容后在这里预览</div>
</div>
<div class="phone-input"><span>⊕</span><span class="phone-input__blank" /><span>☺</span></div>
<p class="preview-note">仅为排版示意,昵称与时间会替换为实际值。</p>
</aside>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Grid, Picture, Plus, Upload, VideoPlay } from '@element-plus/icons-vue'
import { wecomPromotionUploadWelcomeMedia } from '@/api/first_visit'
import { previewTemplate, templateTokens, utf8Length } from './promotion-automation'
import type { WelcomeAttachment, WelcomeMessage } from './promotion-automation'
const props = defineProps<{ modelValue: WelcomeMessage; disabled?: boolean; employeeName?: string }>()
const emit = defineEmits<{ 'update:modelValue': [value: WelcomeMessage]; busy: [value: boolean] }>()
const textInput = ref<{ textarea?: HTMLTextAreaElement }>()
const fileInput = ref<HTMLInputElement>()
const selection = ref({ start: 0, end: 0 })
const uploadingIndex = ref(-1)
const uploading = computed(() => uploadingIndex.value >= 0)
const uploadErrors = ref<Record<number, string>>({})
const assetCache = ref<Record<string, { name: string; url?: string }>>({})
const selectedUpload = ref<{ index: number; type: 'image' | 'video' | 'file' }>({ index: 0, type: 'image' })
const fileAccept = ref('image/jpeg,image/png')
const emojis = ['😊', '😀', '👋', '🌹', '❤️', '👍', '🙏', '🎉', '☀️', '✨', '💐', '🤝', '💬', '✅', '🌿', '🍀']
const attachmentTypes: Array<{ value: WelcomeAttachment['msgtype']; label: string }> = [
{ value: 'image', label: '图片' }, { value: 'link', label: '网页' }, { value: 'miniprogram', label: '小程序' },
{ value: 'video', label: '视频' }, { value: 'file', label: '文件' }
]
const textTooLong = computed(() => Array.from(props.modelValue.text).length > 1200 || utf8Length(props.modelValue.text) > 4000)
function updateText(text: string) { emit('update:modelValue', { ...props.modelValue, text }) }
function rememberSelection() {
const textarea = textInput.value?.textarea
if (textarea) selection.value = { start: textarea.selectionStart, end: textarea.selectionEnd }
}
async function insertText(text: string) {
if (props.disabled) return
const { start, end } = selection.value
updateText(props.modelValue.text.slice(0, start) + text + props.modelValue.text.slice(end))
await nextTick()
const cursor = start + text.length
textInput.value?.textarea?.focus()
textInput.value?.textarea?.setSelectionRange(cursor, cursor)
selection.value = { start: cursor, end: cursor }
}
function attachmentLabel(type: string) { return attachmentTypes.find((item) => item.value === type)?.label || '附件' }
function addAttachment(type: WelcomeAttachment['msgtype']) {
if (props.disabled || uploading.value || props.modelValue.attachments.length >= 9) return
let attachment: WelcomeAttachment
if (type === 'image') attachment = { msgtype: 'image', image: { asset_id: '' } }
else if (type === 'video') attachment = { msgtype: 'video', video: { asset_id: '' } }
else if (type === 'file') attachment = { msgtype: 'file', file: { asset_id: '' } }
else if (type === 'link') attachment = { msgtype: 'link', link: { title: '', url: '', desc: '', picurl: '' } }
else attachment = { msgtype: 'miniprogram', miniprogram: { title: '', appid: '', page: '', pic_asset_id: '' } }
emit('update:modelValue', { ...props.modelValue, attachments: [...props.modelValue.attachments, attachment] })
}
function removeAttachment(index: number) {
uploadErrors.value = {}
emit('update:modelValue', { ...props.modelValue, attachments: props.modelValue.attachments.filter((_, position) => position !== index) })
}
function moveAttachment(index: number, direction: number) {
const attachments = [...props.modelValue.attachments]
;[attachments[index], attachments[index + direction]] = [attachments[index + direction], attachments[index]]
uploadErrors.value = {}
emit('update:modelValue', { ...props.modelValue, attachments })
}
function assetId(attachment: WelcomeAttachment): string {
if (attachment.msgtype === 'image') return attachment.image.asset_id || ''
if (attachment.msgtype === 'video') return attachment.video.asset_id
if (attachment.msgtype === 'file') return attachment.file.asset_id
if (attachment.msgtype === 'miniprogram') return attachment.miniprogram.pic_asset_id
return ''
}
function assetName(attachment: WelcomeAttachment) {
const id = assetId(attachment)
if (id) return assetCache.value[id]?.name || `已保存素材 ${id.slice(-10)}`
return attachment.msgtype === 'image' && attachment.image.pic_url ? '已保存的企微图片' : '尚未上传'
}
function assetPreview(attachment: WelcomeAttachment) { return assetCache.value[assetId(attachment)]?.url || '' }
async function selectFile(index: number, type: 'image' | 'video' | 'file') {
selectedUpload.value = { index, type }
fileAccept.value = type === 'image' ? '.jpg,.jpeg,.png' : type === 'video' ? '.mp4' : '*'
await nextTick()
fileInput.value?.click()
}
async function uploadSelectedFile(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) return
const { index, type } = selectedUpload.value
const limit = type === 'file' ? 20 : 10
let error = ''
if (file.size <= 5 || file.size > limit * 1024 * 1024) error = `文件必须大于 5 字节且不超过 ${limit}MB`
else if (type === 'image' && !/\.(jpe?g|png)$/i.test(file.name)) error = '图片仅支持 JPG / PNG 格式'
else if (type === 'video' && !/\.mp4$/i.test(file.name)) error = '视频仅支持 MP4 格式'
if (error) { uploadErrors.value[index] = error; return }
const attachment = props.modelValue.attachments[index]
if (!attachment) return
uploadingIndex.value = index
emit('busy', true)
delete uploadErrors.value[index]
try {
const result = await wecomPromotionUploadWelcomeMedia(file, type)
if (!result?.asset_id) throw new Error('上传接口未返回素材 ID')
const id = String(result.asset_id)
assetCache.value[id] = { name: result.name || file.name, url: type === 'image' ? URL.createObjectURL(file) : undefined }
if (attachment.msgtype === 'image') { attachment.image = { asset_id: id } }
else if (attachment.msgtype === 'video') attachment.video.asset_id = id
else if (attachment.msgtype === 'file') attachment.file.asset_id = id
else if (attachment.msgtype === 'miniprogram') attachment.miniprogram.pic_asset_id = id
ElMessage.success('素材已上传')
} catch (error: unknown) {
uploadErrors.value[index] = error instanceof Error ? error.message : typeof error === 'string' ? error : '素材上传失败'
} finally {
uploadingIndex.value = -1
emit('busy', false)
}
}
onBeforeUnmount(() => {
Object.values(assetCache.value).forEach((asset) => { if (asset.url) URL.revokeObjectURL(asset.url) })
emit('busy', false)
})
</script>
<style scoped>
.welcome-editor { display: grid; grid-template-columns: minmax(0, 1fr) 260px; align-items: start; gap: 22px; width: 100%; }
.welcome-editor__fields { min-width: 0; }
.text-tools { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }.text-tools .el-button + .el-button { margin-left: 0; }
.emoji-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 4px; }.emoji-grid button { border: 0; background: none; padding: 4px; cursor: pointer; font-size: 20px; }
.text-count { text-align: right; font-size: 12px; color: #909399; margin-top: 4px; }.text-count.is-error, .upload-error { color: #d93026; }
.attachments-heading, .attachment-card__heading { display: flex; justify-content: space-between; align-items: center; gap: 8px; }.attachments-heading { margin: 16px 0 10px; }.attachments-heading strong { font-size: 13px; }.attachments-heading strong span { color: #909399; font-weight: 400; }
.attachment-empty { padding: 18px 12px; color: #909399; background: #f7f8fa; border: 1px dashed #dcdfe6; border-radius: 4px; font-size: 12px; }
.attachment-card { border: 1px solid #e4e7ed; border-radius: 5px; padding: 12px; margin-top: 10px; }.attachment-card__heading { margin-bottom: 10px; }.attachment-card__heading strong { font-size: 13px; }.attachment-card__heading .el-button { padding: 4px; margin: 0; }
.attachment-label { display: block; font-size: 12px; color: #606266; margin: 10px 0 4px; }.attachment-label span { color: #909399; float: right; }.upload-field { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; font-size: 12px; overflow-wrap: anywhere; }.mini-upload { margin-top: 12px; }.asset-ready { color: #178758; }.muted { color: #909399; }.field-tip { display: block; color: #909399; line-height: 1.6; margin-top: 6px; }.upload-error { font-size: 12px; line-height: 1.6; margin-top: 6px; }.file-input { display: none; }
.welcome-preview { width: 260px; border: 1px solid #dcdfe6; border-radius: 20px; padding: 7px; background: #fff; overflow: hidden; }
.phone-heading { display: flex; justify-content: space-between; align-items: center; padding: 13px 12px; background: #ededed; border-radius: 14px 14px 0 0; font-size: 13px; }.phone-heading > span { font-size: 19px; }
.phone-content { min-height: 330px; max-height: 520px; overflow: auto; background: #ededed; padding: 0 10px 18px; }.preview-time { font-size: 10px; text-align: center; color: #999; padding: 12px 0 18px; }.chat-row { display: flex; gap: 7px; margin-bottom: 12px; align-items: flex-start; }.chat-avatar { width: 27px; height: 27px; background: #6e92ae; color: white; flex-shrink: 0; border-radius: 4px; display: grid; place-items: center; font-size: 11px; }.chat-bubble { background: #fff; padding: 9px 10px; border-radius: 4px; font-size: 12px; line-height: 1.65; white-space: pre-wrap; overflow-wrap: anywhere; min-width: 0; max-width: 172px; }.attachment-preview { width: 172px; }.attachment-preview strong { display: block; font-weight: 500; font-size: 12px; }.attachment-preview p { color: #909399; font-size: 10px; margin: 6px 0; }.attachment-preview small { display: block; font-size: 9px; color: #909399; margin-top: 7px; }.attachment-preview img { width: 100%; max-height: 160px; object-fit: contain; display: block; }.media-placeholder { background: #f2f5f7; height: 85px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; color: #909399; font-size: 10px; }.media-placeholder .el-icon, .file-icon { font-size: 28px; color: #8babc3; }.preview-empty { text-align: center; color: #aaa; font-size: 12px; margin-top: 100px; }.phone-input { display: flex; gap: 10px; padding: 9px; background: #f6f6f6; border-radius: 0 0 14px 14px; align-items: center; color: #909399; }.phone-input__blank { flex: 1; height: 24px; border-radius: 3px; background: white; }.preview-note { margin: 10px 6px 6px; font-size: 11px; color: #909399; line-height: 1.6; }
@media (max-width: 850px) { .welcome-editor { grid-template-columns: 1fr; }.welcome-preview { margin: 8px auto 0; } }
</style>
@@ -0,0 +1,214 @@
export interface PromotionMemberChoice {
id: number
name: string
userid: string
dept_names: string[]
}
export type WelcomeAttachment =
| { msgtype: 'image'; image: { asset_id?: string; pic_url?: string } }
| { msgtype: 'video'; video: { asset_id: string } }
| { msgtype: 'file'; file: { asset_id: string } }
| { msgtype: 'link'; link: { title: string; url: string; desc: string; picurl?: string } }
| { msgtype: 'miniprogram'; miniprogram: { title: string; appid: string; page: string; pic_asset_id: string } }
export interface WelcomeMessage {
text: string
attachments: WelcomeAttachment[]
}
export interface WeeklySlot {
weekdays: number[]
start: string
end: string
}
export interface ReceptionSlot extends WeeklySlot {
member_admin_ids: number[]
}
export interface WelcomeSlot extends WeeklySlot, WelcomeMessage {}
export interface PromotionAutomationConfig {
reception_mode: 'always' | 'scheduled'
reception_schedule: ReceptionSlot[]
backup_member_admin_ids: number[]
tags_enabled: boolean
tag_ids: string[]
remark_enabled: boolean
remark_template: string
description_enabled: boolean
description: string
welcome_mode: 'default' | 'channel' | 'none'
welcome: WelcomeMessage
welcome_schedule_enabled: boolean
welcome_schedule: WelcomeSlot[]
}
export type PromotionAutomationSaveConfig = Omit<PromotionAutomationConfig,
'tags_enabled' | 'remark_enabled' | 'description_enabled' | 'welcome_schedule_enabled'> & {
tags_enabled: 0 | 1
remark_enabled: 0 | 1
description_enabled: 0 | 1
welcome_schedule_enabled: 0 | 1
}
export const weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
export const templateTokens = [
{ label: '客户昵称', value: '{customer_name}' },
{ label: '员工昵称', value: '{employee_name}' },
{ label: '添加时间', value: '{add_time}' }
]
export const utf8Length = (value: string): number => new TextEncoder().encode(value).length
export function validateCustomTagName(value: string): string {
if (!value.trim()) return '请输入自定义标签名称'
if (/[\p{C}\u2028\u2029]/u.test(value)) return '标签名称不能包含换行、控制字符或不可见格式字符'
if (Array.from(value.trim()).length > 30) return '标签名称最多 30 个字符'
return ''
}
export function defaultAutomationConfig(): PromotionAutomationConfig {
return {
reception_mode: 'always', reception_schedule: [], backup_member_admin_ids: [],
tags_enabled: false, tag_ids: [], remark_enabled: false, remark_template: '{customer_name}',
description_enabled: false, description: '', welcome_mode: 'default',
welcome: { text: '', attachments: [] }, welcome_schedule_enabled: false, welcome_schedule: []
}
}
// Only copy the editable contract. Server-resolved userids never come back in a save payload.
export function cloneAutomationConfig(source?: Partial<PromotionAutomationConfig> | null): PromotionAutomationConfig {
const defaults = defaultAutomationConfig()
if (!source) return defaults
const copy = JSON.parse(JSON.stringify(source)) as PromotionAutomationConfig
return {
reception_mode: copy.reception_mode === 'scheduled' ? 'scheduled' : 'always',
reception_schedule: (copy.reception_schedule || []).map(({ weekdays, start, end, member_admin_ids }) => ({
weekdays: [...weekdays], start, end, member_admin_ids: member_admin_ids.map(Number)
})),
backup_member_admin_ids: (copy.backup_member_admin_ids || []).map(Number),
tags_enabled: Boolean(copy.tags_enabled), tag_ids: [...(copy.tag_ids || [])],
remark_enabled: Boolean(copy.remark_enabled), remark_template: copy.remark_template ?? defaults.remark_template,
description_enabled: Boolean(copy.description_enabled), description: copy.description || '',
welcome_mode: copy.welcome_mode || 'default',
welcome: { text: copy.welcome?.text || '', attachments: copy.welcome?.attachments || [] },
welcome_schedule_enabled: Boolean(copy.welcome_schedule_enabled),
welcome_schedule: (copy.welcome_schedule || []).map(({ weekdays, start, end, text, attachments }) => ({
weekdays: [...weekdays], start, end, text: text || '', attachments: attachments || []
}))
}
}
/** Keep the save payload compatible with backends and transports that use 0/1 switches. */
export function serializeAutomationConfig(config: PromotionAutomationConfig): PromotionAutomationSaveConfig {
return {
...config,
tags_enabled: config.tags_enabled ? 1 : 0,
remark_enabled: config.remark_enabled ? 1 : 0,
description_enabled: config.description_enabled ? 1 : 0,
welcome_schedule_enabled: config.welcome_schedule_enabled ? 1 : 0
}
}
export function previewTemplate(template: string, employee = '小陈', limit?: number): string {
const date = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit'
}).format(new Date())
const text = template.replace(/\{(customer_name|employee_name|add_time)\}/g, (token) => ({
'{customer_name}': '张女士', '{employee_name}': employee, '{add_time}': date
}[token] || token))
return limit ? Array.from(text).slice(0, limit).join('') : text
}
export function isWebUrl(value: string): boolean {
try { return ['https:', 'http:'].includes(new URL(value).protocol) } catch { return false }
}
function validateSlot(slot: WeeklySlot, label: string): string {
if (!slot.weekdays.length || slot.weekdays.some((day) => day < 1 || day > 7)) return `${label}请选择星期`
if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(slot.start) || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(slot.end)) return `${label}请填写有效的起止时间`
if (slot.start === slot.end) return `${label}开始与结束时间不能相同,全天接待请选择全天模式`
return ''
}
export function validateWelcomeMessage(message: WelcomeMessage, label: string, required = true): string {
if (Array.from(message.text).length > 1200) return `${label}正文不能超过 1200 字`
if (utf8Length(message.text) > 4000) return `${label}正文不能超过 4000 UTF-8 字节,请减少表情或文字`
if (message.attachments.length > 9) return `${label}最多添加 9 个附件`
if (required && !message.text.trim() && !message.attachments.length) return `${label}请填写正文或添加附件`
for (const [index, attachment] of message.attachments.entries()) {
const prefix = `${label}第 ${index + 1} 个附件:`
switch (attachment.msgtype) {
case 'image':
if (!attachment.image.asset_id && !isWebUrl(attachment.image.pic_url || '')) return prefix + '请上传图片或填写有效图片地址'
break
case 'video':
if (!attachment.video.asset_id) return prefix + '请先上传视频'
break
case 'file':
if (!attachment.file.asset_id) return prefix + '请先上传文件'
break
case 'link':
if (!attachment.link.title.trim() || !isWebUrl(attachment.link.url)) return prefix + '请填写网页标题和有效的 HTTP/HTTPS 链接'
if (utf8Length(attachment.link.title) > 128 || utf8Length(attachment.link.desc) > 512) return prefix + '网页标题限 128 字节,描述限 512 字节'
if (attachment.link.picurl && !isWebUrl(attachment.link.picurl)) return prefix + '网页封面地址无效'
break
case 'miniprogram':
if (!attachment.miniprogram.title.trim() || !attachment.miniprogram.appid.trim() || !attachment.miniprogram.page.trim() || !attachment.miniprogram.pic_asset_id) return prefix + '请填写小程序标题、AppID、页面路径并上传封面'
if (utf8Length(attachment.miniprogram.title) > 64) return prefix + '小程序标题不能超过 64 字节'
break
}
}
return ''
}
/** Weekly minute occupancy also catches Sunday-to-Monday and overnight overlap. */
export function welcomeScheduleOverlap(slots: WeeklySlot[]): boolean {
const minutes = new Set<number>()
for (const slot of slots) {
const [sh, sm] = slot.start.split(':').map(Number)
const [eh, em] = slot.end.split(':').map(Number)
const start = sh * 60 + sm
const duration = (eh * 60 + em - start + 1440) % 1440
for (const day of new Set(slot.weekdays)) {
for (let offset = 0; offset < duration; offset++) {
const minute = ((day - 1) * 1440 + start + offset) % 10080
if (minutes.has(minute)) return true
minutes.add(minute)
}
}
}
return false
}
export function validateAutomationConfig(config: PromotionAutomationConfig, mainMemberIds: number[]): string {
if (config.backup_member_admin_ids.some((id) => mainMemberIds.includes(id))) return '备用成员不能与主接待成员重复'
if (config.reception_schedule.length > 30 || config.welcome_schedule.length > 30) return '每类时段最多添加 30 条'
if (config.reception_mode === 'scheduled') {
if (!config.reception_schedule.length) return '按时段接待至少需要一个接待时段'
if (!config.backup_member_admin_ids.length) return '按时段接待至少需要一名备用成员,以承接非接待时段的客户'
}
for (const [index, slot] of config.reception_schedule.entries()) {
const error = validateSlot(slot, `接待时段 ${index + 1}:`)
if (error) return error
if (!slot.member_admin_ids.length) return `接待时段 ${index + 1}:请至少选择一名成员`
if (slot.member_admin_ids.some((id) => !mainMemberIds.includes(id))) return `接待时段 ${index + 1}:成员必须来自主接待成员,请重新选择`
}
if (config.tags_enabled && !config.tag_ids.length) return '启用客户标签后,请选择一个企业微信标签,或创建自定义标签'
if (config.tag_ids.length > 1) return '客户标签只能选择一个,请重新选择或清空原标签'
if (config.remark_enabled && !config.remark_template.trim()) return '请填写客户备注模板'
if (Array.from(config.remark_template).length > 200) return '客户备注模板不能超过 200 字'
if (config.description_enabled && !config.description.trim()) return '请填写客户描述'
if (Array.from(config.description).length > 150) return '客户描述不能超过 150 字'
const error = validateWelcomeMessage(config.welcome, '基础渠道欢迎语:', config.welcome_mode === 'channel')
if (error) return error
if (config.welcome_mode === 'channel' && config.welcome_schedule_enabled && !config.welcome_schedule.length) return '请至少添加一个分时欢迎语时段'
for (const [index, slot] of config.welcome_schedule.entries()) {
const error = validateSlot(slot, `欢迎语时段 ${index + 1}:`) || validateWelcomeMessage(slot, `欢迎语时段 ${index + 1}:`)
if (error) return error
}
if (welcomeScheduleOverlap(config.welcome_schedule)) return '分时欢迎语的时间范围不能重叠(跨午夜时段归属开始日)'
return ''
}
File diff suppressed because it is too large Load Diff
+89 -5
View File
@@ -677,6 +677,32 @@
<el-option label="驼奶费用" :value="8" />
</el-select>
</el-form-item>
<el-form-item
v-if="canEditOrderTime && isEditPaymentTimeEditable"
label="支付时间"
prop="payment_time"
>
<el-date-picker
v-model="editOrderForm.payment_time"
type="datetime"
placeholder="请选择支付时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
:clearable="false"
class="w-full"
/>
</el-form-item>
<el-form-item v-if="canEditOrderTime" label="创建时间" prop="create_time">
<el-date-picker
v-model="editOrderForm.create_time"
type="datetime"
placeholder="请选择创建时间"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
:clearable="false"
class="w-full"
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="editOrderDialogVisible = false">取消</el-button>
@@ -782,6 +808,7 @@
<script setup lang="ts" name="orderList">
import { computed } from 'vue'
import { usePaging } from '@/hooks/usePaging'
import { hasPermission } from '@/utils/perm'
import {
orderLists,
orderDetail,
@@ -1015,9 +1042,33 @@ const editOrderFormRef = ref()
const editOrderLoading = ref(false)
const editPatientLoading = ref(false)
const editPatientList = ref<any[]>([])
const editOrderForm = ref<{ id: number; patient_id: number | null; order_type: number } | null>(null)
type EditOrderForm = {
id: number
patient_id: number | null
order_type: number
status: number
payment_time: string
create_time: string
}
const editOrderForm = ref<EditOrderForm | null>(null)
const canEditOrderTime = computed(() => hasPermission(['order.order/editTime']))
const isEditPaymentTimeEditable = computed(() => [2, 4].includes(editOrderForm.value?.status ?? 0))
const editOrderRules = {
order_type: [{ required: true, message: '请选择订单类型', trigger: 'change' }]
order_type: [{ required: true, message: '请选择订单类型', trigger: 'change' }],
payment_time: [
{
validator: (_rule: unknown, value: string, callback: (error?: Error) => void) => {
if (isEditPaymentTimeEditable.value && !value) {
callback(new Error('请选择支付时间'))
return
}
callback()
},
trigger: 'change'
}
],
create_time: [{ required: true, message: '请选择创建时间', trigger: 'change' }]
}
// 搜索患者
@@ -1289,11 +1340,37 @@ const getCreateTypeText = (row: any) => {
}
// 编辑订单
const normalizeOrderDateTime = (value: unknown) => {
if (value === null || value === undefined || value === '' || value === '-') return ''
const raw = String(value).trim()
const canonicalDateTime = raw.match(/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/)?.[0]
if (canonicalDateTime) return canonicalDateTime.replace('T', ' ')
const numericTimestamp = /^\d{10,13}$/.test(raw) ? Number(raw) : 0
const parsed = new Date(
numericTimestamp
? numericTimestamp < 1_000_000_000_000
? numericTimestamp * 1000
: numericTimestamp
: raw
)
if (Number.isNaN(parsed.getTime())) return ''
const pad = (part: number) => String(part).padStart(2, '0')
return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(
parsed.getHours()
)}:${pad(parsed.getMinutes())}:${pad(parsed.getSeconds())}`
}
const handleEditOrder = (row: any) => {
editOrderForm.value = {
id: row.id,
patient_id: row.patient_id || null,
order_type: row.order_type
order_type: row.order_type,
status: Number(row.status),
payment_time: [2, 4].includes(Number(row.status)) ? normalizeOrderDateTime(row.payment_time) : '',
create_time: normalizeOrderDateTime(row.create_time)
}
editPatientList.value = row.patient ? [row.patient] : []
editOrderDialogVisible.value = true
@@ -1320,11 +1397,18 @@ const submitEditOrder = async () => {
try {
await editOrderFormRef.value?.validate()
editOrderLoading.value = true
await orderEdit({
const payload: Record<string, unknown> = {
id: editOrderForm.value.id,
patient_id: editOrderForm.value.patient_id ?? 0,
order_type: editOrderForm.value.order_type
})
}
if (canEditOrderTime.value) {
payload.create_time = editOrderForm.value.create_time
if (isEditPaymentTimeEditable.value) {
payload.payment_time = editOrderForm.value.payment_time
}
}
await orderEdit(payload)
feedback.msgSuccess('保存成功')
editOrderDialogVisible.value = false
getLists()
@@ -225,6 +225,7 @@ interface QueueRow {
assistant_name?: string
appointment_date?: string
appointment_time?: string
appointment_type?: string | null
gender?: number
age?: number | null
status?: number
@@ -450,12 +451,15 @@ const handleCall = async (row: QueueRow) => {
try {
const res = await getCallSignature({
patient_id: sourcePatientId,
appointment_id: Number(row.id),
diagnosis_id: diagnosisId
})
chatDialogRef.value?.open({
patientId: sourcePatientId,
patientName: row.patient_name,
diagnosisId,
appointmentId: Number(row.id),
appointmentType: row.appointment_type,
signatureData: res
})
} catch (error: any) {
@@ -16,7 +16,8 @@
<code>一键打包</code>
产物一致的安装包,并填入打包目录中的 SHA-256。Windows 推荐使用
Setup.exe,用户点击“立即更新”后会自动安装并重启;macOS 继续使用 ZIP。
安装包通常超过 200MB,优先传到对象存储 / CDN 后粘贴地址。
安装包通常超过 200MB,本页上传按钮会直传到已配置的腾讯云 COS;也可以
自行上传到其他对象存储 / CDN 后粘贴地址。
</div>
</el-alert>
<div class="text-xl font-medium mb-[20px]">升级策略</div>
@@ -125,7 +126,9 @@
<el-form-item label="上传安装包">
<div>
<upload
type="file"
v-perms="['setting.desktop_workstation/setConfig']"
type="desktop_package"
direct
:limit="1"
:multiple="false"
:show-progress="true"
@@ -136,8 +139,8 @@
<el-button type="primary" plain>选择安装包并上传</el-button>
</upload>
<div class="form-tips">
仅建议上传较小的包。大文件请先传到对象存储,再把地址和 SHA-256
填到上方。Windows 自动安装程序必须使用 HTTPS 地址并开启证书校验。
安装包将分片直传腾讯云 COS,不经过业务服务器(支持 EXE / ZIP,最大
2GB)。Windows 自动安装程序必须使用 HTTPS 地址并开启证书校验。
</div>
</div>
</el-form-item>
+20 -9
View File
@@ -163,7 +163,9 @@
</el-table-column>
<!-- <el-table-column label="预约类型" prop="appointment_type_desc" width="100" show-overflow-tooltip /> -->
<el-table-column label="面诊类型" width="110">
<template #default="{ row }">{{ appointmentTypeDescription(row.appointment_type) }}</template>
</el-table-column>
<el-table-column label="确认诊单" width="90" align="center">
<template #default="{ row }">
@@ -219,8 +221,9 @@
</el-button>
<template v-if="row.status !== 3">
<el-button
v-perms="['tcm.diagnosis/videoQr']"
<el-button
v-if="canAppointmentVideoCall(row.appointment_type)"
v-perms="['tcm.diagnosis/videoQr']"
type="warning"
link
size="small"
@@ -237,7 +240,7 @@
size="small"
@click="handleChat(row)"
>
通话
{{ canAppointmentVideoCall(row.appointment_type) ? '通话' : '图文沟通' }}
</el-button>
<el-button
v-perms="['doctor.appointment/complete']"
@@ -340,8 +343,8 @@
<span class="detail-value">{{ detailData.period === 'morning' ? '上午' : '下午' }}</span>
</div>
<div class="detail-item">
<span class="detail-label">预约类型</span>
<span class="detail-value">{{ detailData.appointment_type_desc }}</span>
<span class="detail-label">面诊类型</span>
<span class="detail-value">{{ appointmentTypeDescription(detailData.appointment_type) }}</span>
</div>
</div>
</div>
@@ -555,7 +558,8 @@
</div>
</template>
<script setup lang="ts">
<script setup lang="ts">
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import { usePaging } from '@/hooks/usePaging'
import { defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
import { appointmentLists, cancelAppointment, completeAppointment, appointmentDetail } from '@/api/doctor'
@@ -1012,7 +1016,8 @@ const handleChat = async (row: any) => {
// 获取聊天签名信息
const res = await getCallSignature({
patient_id: sourcePatientId,
diagnosis_id: diagnosisId
diagnosis_id: diagnosisId,
appointment_id: Number(row.id)
})
console.log('获取聊天签名成功:', res)
@@ -1022,6 +1027,8 @@ const handleChat = async (row: any) => {
patientId: sourcePatientId,
patientName: row.patient_name,
diagnosisId,
appointmentId: Number(row.id),
appointmentType: row.appointment_type,
signatureData: res // 传入签名数据
})
} catch (error: any) {
@@ -1031,7 +1038,11 @@ const handleChat = async (row: any) => {
}
// 生成小程序二维码(跳转小程序路径:pages/login/login)
const handleMiniProgramQRCode = async (row: any) => {
const handleMiniProgramQRCode = async (row: any) => {
if (!canAppointmentVideoCall(row.appointment_type)) {
feedback.msgWarning('仅视频问诊可生成视频二维码')
return
}
if (!row.patient_id) {
feedback.msgWarning('患者信息不完整')
return
+24 -11
View File
@@ -108,8 +108,12 @@
<span class="apt-h5-row-key">预约</span>
<span class="apt-h5-row-val">{{ row.appointment_date || '-' }} {{ row.appointment_time || '' }}</span>
</div>
<div class="apt-h5-row">
<span class="apt-h5-row-key">医生</span>
<div class="apt-h5-row">
<span class="apt-h5-row-key">面诊类型</span>
<span class="apt-h5-row-val">{{ appointmentTypeDescription(row.appointment_type) }}</span>
</div>
<div class="apt-h5-row">
<span class="apt-h5-row-key">医生</span>
<span class="apt-h5-row-val">{{ row.doctor_name || '-' }}</span>
</div>
<div class="apt-h5-row">
@@ -147,7 +151,7 @@
:icon="Phone"
@click="handleChat(row)"
>
通话
{{ canAppointmentVideoCall(row.appointment_type) ? '通话' : '图文沟通' }}
</el-button>
<el-button
v-if="hasPermission(['tcm.diagnosis/kaifang'])"
@@ -179,7 +183,7 @@
>
<div v-if="moreSheetRow" class="apt-h5-actions">
<button
v-if="moreSheetRow.status !== 3 && hasPermission(['tcm.diagnosis/videoQr'])"
v-if="moreSheetRow.status !== 3 && canAppointmentVideoCall(moreSheetRow.appointment_type) && hasPermission(['tcm.diagnosis/videoQr'])"
class="apt-h5-action"
@click="runAction('videoQr')"
>
@@ -236,7 +240,7 @@
<div><span>医生</span><strong>{{ detailData.doctor_name || '-' }}</strong></div>
<div><span>预约时间</span><strong>{{ detailData.appointment_date || '-' }} {{ detailData.appointment_time || '' }}</strong></div>
<div><span>时段</span><strong>{{ detailData.period === 'morning' ? '上午' : detailData.period === 'afternoon' ? '下午' : '-' }}</strong></div>
<div><span>预约类型</span><strong>{{ detailData.appointment_type_desc || '-' }}</strong></div>
<div><span>面诊类型</span><strong>{{ appointmentTypeDescription(detailData.appointment_type) }}</strong></div>
</div>
</section>
@@ -336,7 +340,7 @@
plain
@click="handleChat(detailActionRow)"
>
通话
{{ canAppointmentVideoCall(detailActionRow.appointment_type) ? '通话' : '图文沟通' }}
</el-button>
<el-button
v-if="detailActionRow.status !== 3 && hasPermission(['doctor.appointment/complete'])"
@@ -407,7 +411,8 @@
</div>
</template>
<script setup lang="ts" name="tcmAppointmentH5">
<script setup lang="ts" name="tcmAppointmentH5">
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import { appointmentDetail, appointmentLists, cancelAppointment, completeAppointment } from '@/api/doctor'
import { getWeappConfig } from '@/api/channel/weapp'
import {
@@ -656,12 +661,15 @@ const handleChat = async (row: any) => {
try {
const res = await getCallSignature({
patient_id: sourcePatientId,
diagnosis_id: diagnosisId
diagnosis_id: diagnosisId,
appointment_id: Number(row.id)
})
chatDialogRef.value?.open({
patientId: sourcePatientId,
patientName: row.patient_name,
diagnosisId,
appointmentId: Number(row.id),
appointmentType: row.appointment_type,
signatureData: res
})
} catch (e: any) {
@@ -776,7 +784,11 @@ const qrcodeDialogVisible = ref(false)
const qrcodeLoading = ref(false)
const qrcodeUrl = ref('')
const currentQRCodeRow = ref<any>(null)
const handleMiniProgramQRCode = async (row: any) => {
const handleMiniProgramQRCode = async (row: any) => {
if (!canAppointmentVideoCall(row.appointment_type)) {
feedback.msgWarning('仅视频问诊可生成视频二维码')
return
}
if (!row.patient_id) {
feedback.msgWarning('患者信息不完整')
return
@@ -1183,8 +1195,9 @@ onUnmounted(() => {
line-height: 20px;
}
.apt-h5-row-key {
flex: 0 0 38px;
.apt-h5-row-key {
flex: 0 0 60px;
white-space: nowrap;
color: #8a94a6;
}
@@ -30,10 +30,11 @@
</el-radio-group>
</el-form-item>
<!-- 预约类型 -->
<el-form-item label="预约类型:">
<el-radio-group v-model="form.appointmentType">
<el-radio value="video">视频问诊</el-radio>
<!-- 挂号类型 -->
<el-form-item label="挂号类型:">
<el-radio-group v-model="form.appointmentType">
<el-radio value="video">视频问诊</el-radio>
<el-radio value="text">图文问诊</el-radio>
</el-radio-group>
</el-form-item>
@@ -2,29 +2,47 @@
<div class="im-chat-record-panel">
<el-alert type="info" show-icon :closable="false" class="mb-4" title="说明">
<p class="panel-tip">
展示单聊记录:已合并患者 与
展示患者所有诊单中与
<strong>所有医生 / 医助账号</strong>分别产生的会话,按时间排序。
数据由后台定时任务从腾讯云 IM 漫游消息同步至本地归档;点击下方按钮可立即触发后台同步。
打开页面后自动加载并同步最新消息,页面可见期间每 30 秒继续检查更新。
</p>
</el-alert>
<div class="toolbar mb-3">
<el-button type="primary" link :loading="syncing" @click="triggerSync">
<el-icon class="mr-1"><Promotion /></el-icon>
同步最新(后台异步)
同步最新
</el-button>
<el-button type="primary" link :loading="loading" @click="reloadArchived">
<el-icon class="mr-1"><Refresh /></el-icon>
重新加载已归档
</el-button>
</div>
<div v-loading="loading" class="chat-wrap">
<template v-if="!loading && rows.length">
</div>
<p v-if="syncing" class="sync-status" role="status" aria-live="polite">
<template v-if="history.phase === 'checking_accounts'">
正在核验聊天账号<span v-if="history.candidateAccounts">,{{ history.checkedAccounts }} / {{ history.candidateAccounts }}</span>
</template>
<template v-else>正在同步聊天记录<span v-if="history.totalPeers">,已处理 {{ history.processedPeers }} / {{ history.totalPeers }} 个会话</span>,新增 {{ history.inserted }} 条</template>
</p>
<p v-else-if="history.lastSyncAt" class="sync-status">上次同步:{{ formatTime(history.lastSyncAt) }}</p>
<p v-if="history.skippedAccounts" class="sync-status">已跳过 {{ history.skippedAccounts }} 个未注册或已失效的聊天账号,已有归档不受影响。</p>
<el-alert v-if="history.readError" type="error" show-icon :closable="false" class="mb-3" :title="`读取聊天记录失败:${history.readError}`" />
<el-alert v-if="history.syncError" type="error" show-icon :closable="false" class="mb-3" :title="`同步失败:${history.syncError}`" />
<el-alert v-if="history.partialErrors.length" type="warning" show-icon :closable="false" class="mb-3" title="聊天记录未完全同步">
<p v-for="error in history.partialErrors.slice(0, 3)" :key="error" class="panel-tip">{{ error }}</p>
<details v-if="history.partialErrors.length > 3">
<summary>查看其余 {{ history.partialErrors.length - 3 }} 项同步问题</summary>
<p v-for="error in history.partialErrors.slice(3)" :key="error" class="panel-tip">{{ error }}</p>
</details>
</el-alert>
<div v-loading="loading && !rows.length" class="chat-wrap">
<template v-if="rows.length">
<div class="chat-list">
<div
v-for="item in rows"
:key="item.raw.msg_id"
:key="`${item.raw.from_account || ''}-${item.raw.to_account || ''}-${item.raw.msg_id}`"
class="chat-row"
:class="item.raw.is_from_doctor ? 'from-doctor' : 'from-patient'"
>
@@ -64,31 +82,40 @@
</div>
</div>
</template>
<el-empty v-else-if="!loading" description="暂无 IM 聊天记录" />
<el-empty v-else-if="!loading" :description="emptyDescription" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, shallowRef, watch, computed } from 'vue'
import { watch, computed, toRefs, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import dayjs from 'dayjs'
import { Refresh, Promotion } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getImChatMessages, triggerImChatSync } from '@/api/tcm'
import type { FriendlyParse } from '@/utils/im-business-message-parse'
import { parseImBusinessPayload } from '@/utils/im-business-message-parse'
import { parseImBusinessPayload } from '@/utils/im-business-message-parse'
import { createImChatHistory } from '@/utils/im-chat-history'
const props = defineProps<{
diagnosisId: number
}>()
const loading = ref(false)
const syncing = ref(false)
const rawRows = shallowRef<any[]>([])
const patientImId = ref('')
const patientName = ref('')
const patientImHint = computed(() => patientImId.value || 'patient_*')
const documentVisible = () => typeof document === 'undefined' || document.visibilityState !== 'hidden'
const controller = createImChatHistory({
load: (diagnosisId) => getImChatMessages({ diagnosis_id: diagnosisId, only_archived: 1 }),
sync: (diagnosisId, syncToken) => triggerImChatSync({ diagnosis_id: diagnosisId, ...(syncToken ? { sync_token: syncToken } : {}) }),
notify: (kind, message) => ElMessage[kind](message),
visible: documentVisible()
})
const history = controller.state
const { loading, syncing, rows: rawRows, patientName } = toRefs(history)
const emptyDescription = computed(() => {
if (history.readError) return '聊天记录读取失败,请重试'
if (history.syncError || history.partialErrors.length) return '暂未读取到聊天记录,请重试同步'
if (syncing.value) return '正在同步聊天记录…'
return history.hasLoaded ? '暂无聊天记录' : '正在加载聊天记录…'
})
interface EnrichedRow {
raw: any
@@ -109,16 +136,21 @@ const MSG_TYPE_LABELS: Record<string, string> = {
}
const rows = computed<EnrichedRow[]>(() =>
rawRows.value.map((row) => {
const fr = parseImFriendly(row)
let tag = ''
if (fr?.tag) {
tag = fr.tag
} else {
tag = MSG_TYPE_LABELS[row.msg_type] || (row.msg_type !== 'other' ? row.msg_type : '')
}
return { raw: row, friendly: fr, tag }
})
rawRows.value.flatMap((row) => {
const messages = row.msg_type === 'composite' && Array.isArray(row.parts)
? row.parts.map((part: any, index: number) => ({ ...row, ...part, msg_id: `${row.msg_id}:${index}` }))
: [row]
return messages.map((row: any) => {
const fr = parseImFriendly(row)
let tag = ''
if (fr?.tag) {
tag = fr.tag
} else {
tag = MSG_TYPE_LABELS[row.msg_type] || (row.msg_type !== 'other' ? row.msg_type : '')
}
return { raw: row, friendly: fr, tag }
})
})
)
function formatTime(ts: number | undefined) {
@@ -145,54 +177,37 @@ function senderLabel(row: any) {
return patientName.value ? `患者(${patientName.value})` : '患者'
}
async function load() {
if (!props.diagnosisId) return
loading.value = true
try {
const res = (await getImChatMessages({
diagnosis_id: props.diagnosisId,
only_archived: 1
})) as {
lists?: any[]
patient_im_id?: string
patient_name?: string
}
rawRows.value = res?.lists || []
patientImId.value = res?.patient_im_id || ''
patientName.value = res?.patient_name || ''
} catch (e) {
console.error(e)
rawRows.value = []
} finally {
loading.value = false
}
}
function reloadArchived() {
load()
}
async function triggerSync() {
if (!props.diagnosisId) return
syncing.value = true
try {
await triggerImChatSync({ diagnosis_id: props.diagnosisId })
ElMessage.success('已发起后台同步,几秒后请点击"重新加载已归档"查看新消息')
} catch (e) {
console.error(e)
ElMessage.error('发起同步失败')
} finally {
syncing.value = false
}
}
function reloadArchived() {
return controller.reload()
}
function triggerSync() {
return controller.sync()
}
watch(
() => props.diagnosisId,
() => {
load()
},
(diagnosisId) => controller.setDiagnosis(diagnosisId),
{ immediate: true }
)
)
let activated = true
function updateVisibility() {
controller.setVisible(activated && documentVisible())
}
onMounted(() => document.addEventListener('visibilitychange', updateVisibility))
onActivated(() => {
activated = true
updateVisibility()
})
onDeactivated(() => {
activated = false
updateVisibility()
})
onBeforeUnmount(() => {
document.removeEventListener('visibilitychange', updateVisibility)
controller.dispose()
})
defineExpose({ refresh: reloadArchived })
</script>
@@ -209,9 +224,15 @@ defineExpose({ refresh: reloadArchived })
font-size: 12px;
}
}
.toolbar {
.toolbar {
display: flex;
align-items: center;
align-items: center;
flex-wrap: wrap;
}
.sync-status {
margin: 0 0 12px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.chat-wrap {
min-height: 120px;
+93 -45
View File
@@ -259,7 +259,20 @@
</div>
</template>
</el-table-column>
<el-table-column label="确认" width="88" align="center">
<el-table-column label="挂号类型" min-width="120">
<template #default="{ row }">
<template v-if="appointmentRows(row).length">
<div v-for="apt in appointmentRows(row)" :key="apt.id || `${apt.doctor_id}-${apt.time_text}`" class="mb-2">
<div>{{ appointmentTypeDescription(apt.appointment_type) }}</div>
<div v-if="appointmentRows(row).length > 1" class="text-xs text-gray-500">
{{ apt.doctor_name || '—' }} · {{ apt.time_text || '—' }}
</div>
</div>
</template>
<span v-else class="apt-none">—</span>
</template>
</el-table-column>
<el-table-column label="确认" width="88" align="center">
<template #default="{ row }">
<span v-if="isDiagnosisConfirmed(row)" class="status-confirmed">已确认</span>
<span v-else class="status-unconfirmed">未确认</span>
@@ -388,7 +401,7 @@
<el-icon><Remove /></el-icon>取消指派
</el-dropdown-item>
<el-dropdown-item v-if="isAppointmentActiveForVideo(row) && hasPermission(['tcm.diagnosis/videoQr'])" command="videoQr"><el-icon><Picture /></el-icon>视频二维码</el-dropdown-item>
<el-dropdown-item v-if="hasPermission(['tcm.diagnosis/guahao']) && isAppointmentActiveForVideo(row)" command="confirmQr"><el-icon><Picture /></el-icon>二维码</el-dropdown-item>
<el-dropdown-item v-if="hasPermission(['tcm.diagnosis/guahao']) && hasActiveAppointment(row)" command="confirmQr"><el-icon><Picture /></el-icon>二维码</el-dropdown-item>
<el-dropdown-item
v-if="canCancelAppointmentFromDropdown(row) && hasPermission(['tcm.diagnosis/guahao'])"
command="cancelApt"
@@ -731,7 +744,8 @@ import { usePaging } from '@/hooks/usePaging'
import { getDictData } from '@/api/app'
import { getWeappConfig } from '@/api/channel/weapp'
import feedback from '@/utils/feedback'
import { hasPermission } from '@/utils/perm'
import { hasPermission } from '@/utils/perm'
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import { Loading, Warning, List, CircleCheck, Clock, ArrowDown, Picture, User, Document, Delete, CircleClose, Remove } from '@element-plus/icons-vue'
import useUserStore from '@/stores/modules/user'
import { useRoute, useRouter } from 'vue-router'
@@ -1377,10 +1391,11 @@ type VideoCallHint = {
end_time?: number
}
const canWatchCallEntry = (row: any) =>
isAssignedAssistant(row) && hasPermission(['tcm.diagnosis/watchCall'])
const canWatchCallEntry = (row: any) =>
isAppointmentActiveForVideo(row) && isAssignedAssistant(row) && hasPermission(['tcm.diagnosis/watchCall'])
const watchCallState = (row: any) => (row.video_call_hint?.state as string) || 'none'
const watchCallState = (row: any) =>
isAppointmentActiveForVideo(row) ? (row.video_call_hint?.state as string) || 'none' : 'none'
const watchCallLiveTooltip = (row: any) => {
const h = row.video_call_hint as VideoCallHint | undefined
@@ -1404,7 +1419,11 @@ const watchCallEnterTooltip = (row: any) => {
return watchCallLiveTooltip(row)
}
const onWatchCallEntryClick = (row: any) => {
const onWatchCallEntryClick = (row: any) => {
if (!canWatchCallEntry(row)) {
feedback.msgWarning('仅已预约的视频问诊可进入视频旁观')
return
}
if (watchCallState(row) !== 'live') {
feedback.msgWarning('医生尚未接通或未同步房间号,请稍后再试')
return
@@ -1716,7 +1735,7 @@ const handleRowAction = (cmd: string, row: any) => {
case 'cancelAssign': handleCancelAssign(row); break
case 'videoQr':
if (!isAppointmentActiveForVideo(row)) {
feedback.msgWarning('仅「已预约」状态可生成视频二维码')
feedback.msgWarning('仅已预约的视频问诊可生成视频二维码')
return
}
handleVideoQRCode(row)
@@ -1753,7 +1772,8 @@ const appointmentRows = (row: any) => {
status: row.appointment_status,
doctor_id: row.appointment_doctor_id,
doctor_name: row.appointment_doctor_name,
time_text: row.appointment_time_text
time_text: row.appointment_time_text,
appointment_type: row.appointment_type
}]
}
@@ -1775,9 +1795,35 @@ const appointmentCellClasses = (row: any) => {
}
}
/** 仅已预约(1)可进视频/小程序码 */
const isAppointmentActiveForVideo = (row: any) =>
row.has_appointment && Number(row.appointment_status) === 1
/**
* 找到当前可用的已预约挂号。
* 同一诊单当天可能先完成一条挂号、随后又新增一条预约,此时行级 appointment_* 仍可能指向旧记录。
*/
const activeAppointment = (row: any, videoOnly = false) =>
appointmentRows(row).find((apt: any) =>
Number(apt?.status) === 1 && (!videoOnly || canAppointmentVideoCall(apt.appointment_type))
) ?? null
/** 二维码必须使用已预约挂号对应的医生和时间,不能继续沿用行级旧挂号字段。 */
const activeAppointmentRow = (row: any, videoOnly = false) => {
const apt = activeAppointment(row, videoOnly)
if (!apt) return null
return {
...row,
has_appointment: 1,
appointment_id: apt.id,
appointment_status: apt.status,
appointment_doctor_id: apt.doctor_id,
appointment_doctor_name: apt.doctor_name,
appointment_time_text: apt.time_text,
appointment_type: apt.appointment_type
}
}
/** 诊单二维码适用于所有已预约挂号;视频入口仅适用于视频问诊。 */
const hasActiveAppointment = (row: any) => !!activeAppointment(row)
const isAppointmentActiveForVideo = (row: any) => !!activeAppointment(row, true)
/** 已预约、已过号可取消(后端同步限制),针对行上主字段 */
const canCancelAppointmentRow = (row: any) => {
@@ -1961,18 +2007,19 @@ const submitFillIdCard = async () => {
}
}
// 生成视频二维码(跳转登录页)- 仅已预约(1)可生成
const handleVideoQRCode = async (row: any) => {
if (!isAppointmentActiveForVideo(row)) {
feedback.msgWarning('仅「已预约」状态可生成视频二维码')
return
}
if (!row.patient_id) {
feedback.msgWarning('患者信息不完整')
return
}
lastQRCodeType.value = 'video'
currentQRCodePatient.value = row
// 生成视频二维码(跳转登录页)- 仅已预约的视频问诊可生成
const handleVideoQRCode = async (row: any) => {
const qrcodeRow = activeAppointmentRow(row, true)
if (!qrcodeRow) {
feedback.msgWarning('仅已预约的视频问诊可生成视频二维码')
return
}
if (!qrcodeRow.patient_id) {
feedback.msgWarning('患者信息不完整')
return
}
lastQRCodeType.value = 'video'
currentQRCodePatient.value = qrcodeRow
qrcodeDialogVisible.value = true
qrcodeLoading.value = true
qrcodeUrl.value = ''
@@ -1983,11 +2030,11 @@ const handleVideoQRCode = async (row: any) => {
feedback.msgError('小程序未配置,请先配置小程序信息')
qrcodeDialogVisible.value = false
return
}
const result = await generateMiniProgramQrcode({
doctor_id: row.appointment_doctor_id,
diagnosis_id: row.appointment_doctor_id,
patient_id: row.patient_id,
}
const result = await generateMiniProgramQrcode({
doctor_id: qrcodeRow.appointment_doctor_id,
diagnosis_id: qrcodeRow.appointment_doctor_id,
patient_id: qrcodeRow.patient_id,
share_user_id: userStore.userInfo?.id || '',
mini_program_path: 'pages/login/login'
})
@@ -2004,17 +2051,18 @@ const handleVideoQRCode = async (row: any) => {
}
// 生成确认诊单二维码
const handleMiniProgramQRCode = async (row: any) => {
if (!isAppointmentActiveForVideo(row)) {
feedback.msgWarning('仅「已预约」状态可使用诊单二维码')
return
}
if (!row.patient_id) {
feedback.msgWarning('患者信息不完整')
return
}
lastQRCodeType.value = 'confirm'
currentQRCodePatient.value = row
const handleMiniProgramQRCode = async (row: any) => {
const qrcodeRow = activeAppointmentRow(row)
if (!qrcodeRow) {
feedback.msgWarning('仅「已预约」状态可使用诊单二维码')
return
}
if (!qrcodeRow.patient_id) {
feedback.msgWarning('患者信息不完整')
return
}
lastQRCodeType.value = 'confirm'
currentQRCodePatient.value = qrcodeRow
qrcodeDialogVisible.value = true
qrcodeLoading.value = true
qrcodeUrl.value = ''
@@ -2033,11 +2081,11 @@ const handleMiniProgramQRCode = async (row: any) => {
// 获取当前登录用户信息
const currentUser = userStore.userInfo
// 调用生成二维码接口
const result = await generateMiniProgramQrcode({
diagnosis_id: row.id,
doctor_id: row.appointment_doctor_id,
patient_id: row.patient_id,
// 调用生成二维码接口
const result = await generateMiniProgramQrcode({
diagnosis_id: qrcodeRow.id,
doctor_id: qrcodeRow.appointment_doctor_id,
patient_id: qrcodeRow.patient_id,
share_user_id: currentUser?.id || ''
})
+83 -41
View File
@@ -155,13 +155,15 @@
>
<span class="dh5-apt-status">{{ appointmentStatusLabelByStatus(apt.status) }}</span>
<span class="dh5-apt-doctor">{{ apt.doctor_name || '-' }}</span>
<span class="dh5-apt-time">{{ apt.time_text || '-' }}</span>
<span class="dh5-apt-time">{{ apt.time_text || '-' }}</span>
<span class="dh5-apt-type">挂号类型:{{ appointmentTypeDescription(apt.appointment_type) }}</span>
</div>
</template>
<template v-else>
<span class="dh5-apt-status">{{ appointmentStatusLabel(row) }}</span>
<span class="dh5-apt-doctor">{{ row.appointment_doctor_name || '-' }}</span>
<span class="dh5-apt-time">{{ row.appointment_time_text || '-' }}</span>
<span class="dh5-apt-time">{{ row.appointment_time_text || '-' }}</span>
<span class="dh5-apt-type">挂号类型:{{ appointmentTypeDescription(row.appointment_type) }}</span>
</template>
</template>
<span v-else class="dh5-apt-none">未挂号</span>
@@ -299,7 +301,7 @@
<span>视频二维码</span>
</button>
<button
v-if="isAppointmentActiveForVideo(moreSheetRow) && hasPermission(['tcm.diagnosis/guahao'])"
v-if="hasActiveAppointment(moreSheetRow) && hasPermission(['tcm.diagnosis/guahao'])"
class="dh5-action"
@click="runAction('confirmQr')"
>
@@ -584,7 +586,8 @@
</div>
</template>
<script setup lang="ts" name="tcmDiagnosisH5">
<script setup lang="ts" name="tcmDiagnosisH5">
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import {
tcmDiagnosisLists,
tcmDiagnosisDelete,
@@ -924,7 +927,8 @@ const appointmentRows = (row: any) => {
status: row.appointment_status,
doctor_id: row.appointment_doctor_id,
doctor_name: row.appointment_doctor_name,
time_text: row.appointment_time_text
time_text: row.appointment_time_text,
appointment_type: row.appointment_type
}]
}
@@ -946,8 +950,32 @@ const appointmentRowClass = (row: any) => {
}
}
const isAppointmentActiveForVideo = (row: any) =>
row.has_appointment && Number(row.appointment_status) === 1
/**
* 同一诊单可能同时有已完成的旧挂号和已预约的新挂号,二维码应使用明细里的有效预约。
*/
const activeAppointment = (row: any, videoOnly = false) =>
appointmentRows(row).find((apt: any) =>
Number(apt?.status) === 1 && (!videoOnly || canAppointmentVideoCall(apt.appointment_type))
) ?? null
const activeAppointmentRow = (row: any, videoOnly = false) => {
const apt = activeAppointment(row, videoOnly)
if (!apt) return null
return {
...row,
has_appointment: 1,
appointment_id: apt.id,
appointment_status: apt.status,
appointment_doctor_id: apt.doctor_id,
appointment_doctor_name: apt.doctor_name,
appointment_time_text: apt.time_text,
appointment_type: apt.appointment_type
}
}
const hasActiveAppointment = (row: any) => !!activeAppointment(row)
const isAppointmentActiveForVideo = (row: any) => !!activeAppointment(row, true)
const canCancelAppointmentRow = (row: any) => {
const s = Number(row.appointment_status)
@@ -961,9 +989,10 @@ const isAssignedAssistant = (row: any) => {
if (aid === null || aid === undefined || aid === '') return false
return Number(aid) === Number(userStore.userInfo?.id)
}
const canWatchCallEntry = (row: any) =>
isAssignedAssistant(row) && hasPermission(['tcm.diagnosis/watchCall'])
const watchCallState = (row: any) => (row.video_call_hint?.state as string) || 'none'
const canWatchCallEntry = (row: any) =>
isAppointmentActiveForVideo(row) && isAssignedAssistant(row) && hasPermission(['tcm.diagnosis/watchCall'])
const watchCallState = (row: any) =>
isAppointmentActiveForVideo(row) ? (row.video_call_hint?.state as string) || 'none' : 'none'
const watchCallShowEnterButton = (row: any) => {
const st = watchCallState(row)
return st === 'live' || st === 'pending_room'
@@ -995,7 +1024,11 @@ const watchCallVisibleForRow = (row: any) => {
}
const watchCallDialogVisible = ref(false)
const watchCallDiagnosisId = ref(0)
const onWatchCallEntryClick = (row: any) => {
const onWatchCallEntryClick = (row: any) => {
if (!canWatchCallEntry(row)) {
feedback.msgWarning('仅已预约的视频问诊可进入视频旁观')
return
}
if (watchCallState(row) !== 'live') {
feedback.msgWarning('医生未接通或未同步房间号,请稍后再试')
return
@@ -1067,7 +1100,7 @@ const runAction = (cmd: string) => {
case 'assign': handleSingleAssign(row); break
case 'videoQr':
if (!isAppointmentActiveForVideo(row)) {
feedback.msgWarning('仅「已预约」状态可生成视频二维码')
feedback.msgWarning('仅已预约的视频问诊可生成视频二维码')
return
}
handleVideoQRCode(row); break
@@ -1241,13 +1274,14 @@ const qrcodeAppointmentTimeText = computed(() => {
return p.appointment_time_text || '—'
})
const handleVideoQRCode = async (row: any) => {
if (!isAppointmentActiveForVideo(row)) {
feedback.msgWarning('仅「已预约」状态可生成视频二维码'); return
}
if (!row.patient_id) { feedback.msgWarning('患者信息不完整'); return }
lastQRCodeType.value = 'video'
currentQRCodePatient.value = row
const handleVideoQRCode = async (row: any) => {
const qrcodeRow = activeAppointmentRow(row, true)
if (!qrcodeRow) {
feedback.msgWarning('仅已预约的视频问诊可生成视频二维码'); return
}
if (!qrcodeRow.patient_id) { feedback.msgWarning('患者信息不完整'); return }
lastQRCodeType.value = 'video'
currentQRCodePatient.value = qrcodeRow
qrcodeDialogVisible.value = true
qrcodeLoading.value = true
qrcodeUrl.value = ''
@@ -1258,11 +1292,11 @@ const handleVideoQRCode = async (row: any) => {
feedback.msgError('小程序未配置')
qrcodeDialogVisible.value = false
return
}
const result = await generateMiniProgramQrcode({
doctor_id: row.appointment_doctor_id,
diagnosis_id: row.appointment_doctor_id,
patient_id: row.patient_id,
}
const result = await generateMiniProgramQrcode({
doctor_id: qrcodeRow.appointment_doctor_id,
diagnosis_id: qrcodeRow.appointment_doctor_id,
patient_id: qrcodeRow.patient_id,
share_user_id: userStore.userInfo?.id || '',
mini_program_path: 'pages/login/login'
})
@@ -1275,13 +1309,14 @@ const handleVideoQRCode = async (row: any) => {
}
}
const handleMiniProgramQRCode = async (row: any) => {
if (!isAppointmentActiveForVideo(row)) {
feedback.msgWarning('仅「已预约」状态可使用诊单二维码'); return
}
if (!row.patient_id) { feedback.msgWarning('患者信息不完整'); return }
lastQRCodeType.value = 'confirm'
currentQRCodePatient.value = row
const handleMiniProgramQRCode = async (row: any) => {
const qrcodeRow = activeAppointmentRow(row)
if (!qrcodeRow) {
feedback.msgWarning('仅「已预约」状态可使用诊单二维码'); return
}
if (!qrcodeRow.patient_id) { feedback.msgWarning('患者信息不完整'); return }
lastQRCodeType.value = 'confirm'
currentQRCodePatient.value = qrcodeRow
qrcodeDialogVisible.value = true
qrcodeLoading.value = true
qrcodeUrl.value = ''
@@ -1292,11 +1327,11 @@ const handleMiniProgramQRCode = async (row: any) => {
feedback.msgError('小程序未配置')
qrcodeDialogVisible.value = false
return
}
const result = await generateMiniProgramQrcode({
diagnosis_id: row.id,
doctor_id: row.appointment_doctor_id,
patient_id: row.patient_id,
}
const result = await generateMiniProgramQrcode({
diagnosis_id: qrcodeRow.id,
doctor_id: qrcodeRow.appointment_doctor_id,
patient_id: qrcodeRow.patient_id,
share_user_id: userStore.userInfo?.id || ''
})
if (result?.qrcode_url) qrcodeUrl.value = result.qrcode_url
@@ -1783,8 +1818,9 @@ $dh5-card-bg: #ffffff;
}
}
.dh5-apt-item {
display: flex;
.dh5-apt-item {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
padding: 4px 8px;
@@ -1808,11 +1844,17 @@ $dh5-card-bg: #ffffff;
font-weight: 500;
}
.dh5-apt-time {
.dh5-apt-time {
color: $dh5-text-mute;
font-size: 12px;
margin-left: auto;
}
margin-left: auto;
}
.dh5-apt-type {
flex-basis: 100%;
color: $dh5-text-mute;
font-size: 12px;
}
.dh5-apt-none {
color: $dh5-warn;
+146
View File
@@ -0,0 +1,146 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { renderToString } = require('@vue/server-renderer')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const src = path.join(__dirname, '../src')
function moduleFrom(source, mockRequire = require, browserWindow = {}) {
const code = ts.transpileModule(source.replaceAll('import.meta.env.DEV', 'false'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', 'window', code)(mockRequire, module, module.exports, browserWindow)
return module.exports
}
const read = (file) => fs.readFileSync(path.join(src, file), 'utf8')
const types = moduleFrom(read('utils/appointment-type.ts'))
const { descriptor } = parse(read('components/chat-dialog/index.vue'))
const script = compileScript(descriptor, { id: 'appointment-call-mode' })
const template = compileTemplate({ source: descriptor.template.content, filename: 'chat-dialog.vue', id: 'appointment-call-mode', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
const passthrough = { setup: (_, { slots }) => () => vue.h('div', [slots.default?.(), slots.headerToolbar?.()]) }
const picker = text => ({ setup: () => () => vue.h('button', text) })
function chat(policy = {}) {
const requests = [], warnings = [], sdkCalls = []
const guard = moduleFrom(read('utils/appointment-call-guard.ts'))
const server = Object.fromEntries(['calls', 'call', 'groupCall'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
const api = { getCallSignature: async params => { requests.push(params); return policy } }
const result = moduleFrom(script.content, name => {
if (name === 'vue') return { ...vue, onMounted() {}, onUnmounted() {} }
if (name === '@/utils/appointment-type') return types
if (name === '@/utils/appointment-call-guard') return guard
if (name === '@/utils/im-chat-archive-trigger') return moduleFrom(read('utils/im-chat-archive-trigger.ts'))
if (name === '@/api/tcm') return api
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
if (name === '@/stores/modules/user') return { default: () => ({ userInfo: {} }) }
if (name === '@/utils/call-local-recorder') return { CallLocalRecorder: class {} }
if (name === '@tencentcloud/chat-uikit-vue3') return {
useLoginState: () => ({}), useConversationListState: () => ({ activeConversation: vue.ref(null) }),
Chat: passthrough, UIKitProvider: passthrough, MessageInput: passthrough, MessageList: passthrough,
EmojiPicker: picker('表情'), ImagePicker: picker('图片'), FilePicker: picker('文件'),
AudioCallPicker: picker('语音拨打'), VideoCallPicker: picker('视频拨打')
}
if (name === '@tencentcloud/call-uikit-vue') return { TUICallKitServer: server, TUICallType: { VIDEO_CALL: 2 }, TUIStore: {}, StoreName: {}, NAME: {} }
return {}
}).default.setup({}, { expose() {} })
result.visible.value = true
result.isReady.value = true
result.isCallReady.value = true
result.patientId.value = 50
result.diagnosisId.value = 70
result.appointmentId.value = 90
result.syncAppointmentCallPolicy(policy)
guard.registerAppointmentCallGuard(result.prepareAppointmentCall)
return { state: result, guard, server, requests, warnings, sdkCalls, api }
}
const policy = type => ({ appointment_id: 90, appointment_type: type, appointment_type_desc: types.appointmentTypeDescription(type), can_video_call: type === 'video', can_audio_call: type === 'video' || type === 'phone', call_disabled_reason: type === 'text' ? '图文问诊不支持音视频通话' : '当前挂号不支持该通话方式' })
test('type labels and video capability preserve legacy video while rejecting text and unknown', () => {
for (const value of ['text', 'phone', 'unknown']) assert.equal(types.canAppointmentVideoCall(value), false)
for (const value of ['video', '', ' ', null, undefined]) assert.equal(types.canAppointmentVideoCall(value), true)
assert.equal(types.appointmentTypeDescription('text'), '图文问诊')
})
test('rendered real chat template keeps text tools while excluding call controls in text mode', async () => {
async function markup(type) {
const { state } = chat(policy(type))
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
app.config.warnHandler = () => {}
for (const name of ['el-tag', 'el-button', 'el-tooltip', 'el-icon', 'el-alert']) app.component(name, passthrough)
const context = {}
await renderToString(app, context)
return context.teleports.body
}
const text = await markup('text')
assert.match(text, /图文问诊/)
for (const tool of ['表情', '图片', '文件']) assert.match(text, new RegExp(tool))
assert.doesNotMatch(text, /视频拨打|语音拨打|群视频/)
const video = await markup('video')
assert.match(video, /视频问诊/)
assert.match(video, /视频拨打/)
assert.match(video, /群视频/)
})
test('text mode hides all live call entries and refuses direct group invocation', async () => {
const { state, requests, sdkCalls } = chat(policy('text'))
assert.equal(state.appointmentTypeLabel.value, '图文问诊')
assert.equal(state.canVideoCall.value, false)
assert.equal(state.canAudioCall.value, false)
await state.startGroupVideoCall()
await assert.rejects(state.prepareAppointmentCall(2), /图文问诊/)
assert.deepEqual(requests, [])
assert.deepEqual(sdkCalls, [])
assert.match(descriptor.template.content, /<VideoCallPicker v-if="isCallReady && canVideoCall"/)
assert.match(descriptor.template.content, /<AudioCallPicker v-if="isCallReady && canAudioCall"/)
})
test('all SDK outgoing paths stop before touching SDK when current appointment is text', async () => {
const { state, server, sdkCalls } = chat(policy('text'))
state.installTUICallKitRoomHooks()
for (const method of ['call', 'calls', 'groupCall']) await assert.rejects(server[method]({ type: 2 }), /图文问诊/)
assert.deepEqual(sdkCalls, [])
})
test('video preflight uses actual appointment and prevents a server-side change to text', async () => {
const { state, requests, api } = chat(policy('video'))
assert.equal(state.canVideoCall.value, true)
await state.prepareAppointmentCall(2)
assert.deepEqual(requests, [{ patient_id: 50, diagnosis_id: 70, appointment_id: 90 }])
api.getCallSignature = async () => policy('text')
await assert.rejects(state.prepareAppointmentCall(2), /图文问诊/)
assert.equal(state.canVideoCall.value, false)
assert.equal(state.appointmentTypeLabel.value, '图文问诊')
})
test('historical phone is audio-only; missing server confirmation never enables video', async () => {
const { state } = chat(policy('phone'))
assert.equal(state.canAudioCall.value, true)
assert.equal(state.canVideoCall.value, false)
await state.prepareAppointmentCall(1)
await assert.rejects(state.prepareAppointmentCall(2))
state.syncAppointmentCallPolicy({ appointment_type: 'video' })
assert.equal(state.canVideoCall.value, false)
state.syncAppointmentCallPolicy({ appointment_type: null, appointment_type_desc: '未挂号', can_video_call: false, can_audio_call: false })
assert.equal(state.appointmentTypeLabel.value, '未挂号')
assert.equal(state.canVideoCall.value, false)
})
test('singleton call guard switches to current chat and cancels a pending old context', async () => {
const guard = moduleFrom(read('utils/appointment-call-guard.ts'))
let resolveOld
const releaseOld = guard.registerAppointmentCallGuard(() => new Promise(resolve => { resolveOld = resolve }))
const pending = guard.checkAppointmentOutgoingCall({ type: 2 })
const releaseNew = guard.registerAppointmentCallGuard(async () => { throw new Error('图文问诊') })
releaseOld()
await assert.rejects(guard.checkAppointmentOutgoingCall({ type: 2 }), /图文问诊/)
resolveOld()
await assert.rejects(pending, /问诊已切换/)
releaseNew()
await assert.rejects(guard.checkAppointmentOutgoingCall({ type: 2 }), /先打开/)
})
@@ -0,0 +1,125 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const { execFileSync } = require('node:child_process')
const { DatabaseSync } = require('node:sqlite')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const root = path.resolve(__dirname, '../..')
const sql = JSON.parse(execFileSync(process.env.PHP_BINARY || 'php', [path.join(root, 'server/tests/AppointmentTypeFilterSqlFixture.php')], { encoding: 'utf8' }))
const db = new DatabaseSync(':memory:')
db.exec(`
CREATE TABLE doctor_appointment (id INTEGER, patient_id INTEGER, doctor_id INTEGER, assistant_id INTEGER, appointment_type TEXT, status INTEGER, appointment_date TEXT, appointment_time TEXT);
CREATE TABLE tcm_diagnosis (id INTEGER, patient_id INTEGER, patient_name TEXT, phone TEXT, gender INTEGER, age INTEGER, weight INTEGER, height INTEGER, assistant_id INTEGER, delete_time INTEGER);
CREATE TABLE admin (id INTEGER, name TEXT);
INSERT INTO tcm_diagnosis VALUES (100, 1000, '患者甲', '', 1, 30, 60, 170, 301, NULL), (101, 1001, '患者乙', '', 1, 31, 61, 171, 302, NULL), (102, 1002, '已删除', '', 1, 30, 60, 170, 301, 1);
INSERT INTO admin VALUES (201, '医生甲'), (202, '医生乙'), (301, '医助甲'), (302, '医助乙');
`)
const add = db.prepare('INSERT INTO doctor_appointment VALUES (?, ?, ?, 301, ?, ?, ?, ?)')
const fixtures = [
[1, 100, 201, 'video', 1],
[2, 100, 201, null, 1],
[3, 100, 201, '', 2],
[4, 101, 202, ' ', 3],
[5, 101, 202, '\t\r\n\v ', 4],
[6, 100, 201, 'text', 1],
[7, 101, 202, 'text', 3],
[8, 100, 201, 'phone', 1],
[9, 100, 201, 'unknown', 1],
[10, 100, 201, 'Video', 1],
[11, 100, 201, 'video ', 1],
[12, 102, 201, null, 1],
[13, 102, 201, 'text', 1]
]
for (const [id, patient, doctor, type, status] of fixtures) add.run(id, patient, doctor, type, status, '2026-09-09', `${String(id).padStart(2, '0')}:00:00`)
// SQLite's explicit BINARY collation has the same exact text comparison semantics used here.
// The remaining statements are the SQL emitted by the real ThinkPHP list/count/tab paths.
const execute = statement => db.prepare(statement.replace(/BINARY a\.appointment_type/g, 'a.appointment_type COLLATE BINARY')).all()
const result = name => ({
ids: execute(sql[name].lists).map(row => row.id),
count: execute(sql[name].count)[0].think_count,
tabs: Object.fromEntries(execute(sql[name].tabs).map(row => [row.status, row.cnt]))
})
test('video query includes legacy blanks and keeps list, total and status counts aligned', () => {
assert.deepEqual(result('video'), { ids: [1, 2, 3, 4, 5], count: 5, tabs: { 1: 2, 2: 1, 3: 1, 4: 1 } })
})
test('text query excludes video, unknown and historical phone records', () => {
assert.deepEqual(result('text'), { ids: [6, 7], count: 2, tabs: { 1: 1, 3: 1 } })
})
test('all and omitted filters retain historical types without admitting deleted diagnoses', () => {
for (const name of ['omitted', 'all', 'null']) {
const actual = result(name)
assert.equal(actual.count, 11)
assert.deepEqual(actual.ids.toSorted((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
assert.equal(Object.values(actual.tabs).reduce((sum, count) => sum + count, 0), 11)
}
})
test('type filter composes with status, doctor and patient filters without OR leakage', () => {
assert.deepEqual(result('video_status_1'), { ids: [1, 2], count: 2, tabs: { 1: 2, 2: 1, 3: 1, 4: 1 } })
assert.deepEqual(result('text_doctor'), { ids: [6], count: 1, tabs: { 1: 1 } })
assert.deepEqual(result('video_patient'), { ids: [4, 5], count: 2, tabs: { 3: 1, 4: 1 } })
})
test('pagination limits only visible rows while count and tabs retain the full filtered set', () => {
assert.deepEqual(result('video_page'), { ids: [2, 3], count: 5, tabs: { 1: 2, 2: 1, 3: 1, 4: 1 } })
})
test('unsupported filter values return no rows or counts instead of being converted to video', () => {
for (const name of Object.keys(sql).filter(name => name.startsWith('invalid_'))) {
assert.deepEqual(result(name), { ids: [], count: 0, tabs: {} }, name)
}
})
function moduleFrom(source, dependencies = require, globals = {}) {
const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), compiled)(dependencies, module, module.exports, ...Object.values(globals))
return module.exports
}
const pageFile = path.join(root, 'admin/src/views/consumer/prescription/guahao.vue')
const { descriptor, errors } = parse(fs.readFileSync(pageFile, 'utf8'), { filename: pageFile })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'appointment-type-filter' })
test('actual page and paging hook send type on query and clear it together with all fields on reset', async () => {
const calls = []
const paging = moduleFrom(fs.readFileSync(path.join(root, 'admin/src/hooks/usePaging.ts'), 'utf8'))
const component = moduleFrom(script.content, name => {
if (name === 'vue') return vue
if (name === '@/hooks/usePaging') return paging
if (name === '@/api/doctor') return { appointmentLists: async params => { calls.push({ ...params }); return { lists: [], count: 0 } } }
if (name === '@/utils/appointment-type') return { appointmentTypeDescription: value => value }
return {}
}, { reactive: vue.reactive, ref: vue.ref, computed: vue.computed, onMounted() {}, onActivated() {} })
const page = component.default.setup({}, { expose() {} })
assert.equal(calls[0].appointment_type, '')
page.pager.page = 4
page.queryParams.appointment_type = 'text'
page.queryParams.patient_name = '张'
page.resetPage()
assert.equal(calls.at(-1).page_no, 1)
assert.equal(calls.at(-1).appointment_type, 'text')
assert.equal(calls.at(-1).patient_name, '张')
page.pager.page = 3
page.queryParams.appointment_type = 'video'
page.resetPage()
assert.equal(calls.at(-1).appointment_type, 'video')
page.resetFilter()
assert.equal(calls.at(-1).appointment_type, '')
assert.equal(calls.at(-1).patient_name, '')
assert.equal(calls.at(-1).page_no, 1)
await Promise.resolve()
})
test('updated filter template compiles with existing page bindings', () => {
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: pageFile, id: 'appointment-type-filter', compilerOptions: { bindingMetadata: script.bindings } }).errors, [])
})
@@ -0,0 +1,89 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const source = fs.readFileSync(path.join(__dirname, '../src/utils/im-chat-archive-trigger.ts'), 'utf8')
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
const mod = { exports: {} }
new Function('module', 'exports', compiled)(mod, mod.exports)
const { createImChatArchiveTrigger } = mod.exports
const deferred = () => {
let resolve, reject
const promise = new Promise((a, b) => { resolve = a; reject = b })
return { promise, resolve, reject }
}
test('all pages use server-owned current-doctor scope and carry the continuation token', async () => {
const calls = []
const sync = createImChatArchiveTrigger(async params => {
calls.push(params)
return { completed: calls.length === 3, sync_token: 'next-page' }
})
await sync(12116)
assert.deepEqual(calls, [
{ diagnosis_id: 12116, scope: 'current', sync_token: undefined },
{ diagnosis_id: 12116, scope: 'current', sync_token: 'next-page' },
{ diagnosis_id: 12116, scope: 'current', sync_token: 'next-page' }
])
})
test('many events while syncing coalesce, then perform one catch-up scan for new messages', async () => {
const page = deferred()
let calls = 0
const sync = createImChatArchiveTrigger(() => {
calls++
return calls === 1 ? page.promise : Promise.resolve({ completed: true })
})
const first = sync(10)
assert.equal(sync(10), first)
assert.equal(sync(10), first)
assert.equal(calls, 1)
page.resolve({ completed: true })
await first
assert.equal(calls, 2)
await sync(10)
assert.equal(calls, 3)
})
test('switching patients keeps in-flight requests bound to their original diagnosis', async () => {
const old = deferred(), calls = []
const sync = createImChatArchiveTrigger(params => {
calls.push(params)
if (params.diagnosis_id === 10 && !params.sync_token) return old.promise
return Promise.resolve({ completed: true })
})
const first = sync(10)
await sync(20)
old.resolve({ completed: false, sync_token: 'old-patient' })
await first
assert.deepEqual(calls.map(p => [p.diagnosis_id, p.sync_token]), [[10, undefined], [20, undefined], [10, 'old-patient']])
})
test('partial failure and network failure are reported and do not poison later retries', async () => {
const warnings = []
let count = 0
const sync = createImChatArchiveTrigger(async () => {
count++
if (count === 1) return { completed: true, errors: ['cloud unavailable'] }
if (count === 2) throw new Error('request timeout')
return { completed: true }
}, error => warnings.push(error.message))
await sync(10)
await sync(10)
await sync(10)
assert.deepEqual(warnings, ['cloud unavailable', 'request timeout'])
assert.equal(count, 3)
})
test('invalid IDs never request and missing progress stops a malformed response loop', async () => {
const warnings = []
let count = 0
const sync = createImChatArchiveTrigger(async () => { count++; return { completed: false } }, error => warnings.push(error.message))
for (const id of [0, -1, NaN, 1.5]) await sync(id)
assert.equal(count, 0)
await sync(10)
assert.equal(count, 1)
assert.match(warnings[0], /未返回进度/)
})
+392
View File
@@ -0,0 +1,392 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const { parse, compileScript, compileTemplate, compileStyle } = require('@vue/compiler-sfc')
function loadTs(filename, dependencies = require) {
const source = fs.readFileSync(filename, 'utf8')
const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(dependencies, module, module.exports)
return module.exports
}
const { createImChatHistory } = loadTs(path.join(__dirname, '../src/utils/im-chat-history.ts'))
const archive = (id, text = '已归档消息') => ({ lists: [{ msg_id: id, text }], patient_im_id: `patient_${id}`, patient_name: `患者${id}` })
const progress = (completed, extra = {}) => ({ completed, sync_token: 'session-token', inserted: 2, processed_peers: 1, total_peers: 2, ...extra })
const deferred = () => {
let resolve, reject
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
return { promise, resolve, reject }
}
const settle = async () => { for (let i = 0; i < 50; i++) await Promise.resolve() }
function fixture(overrides = {}) {
let time = 100000, nextTimer = 0
const timers = new Map(), calls = [], notices = []
const controller = createImChatHistory({
load: async (id) => { calls.push(['load', id]); return overrides.load ? overrides.load(id) : archive(id) },
sync: async (id, token) => { calls.push(['sync', id, token]); return overrides.sync ? overrides.sync(id, token) : progress(true) },
notify: (kind, message) => notices.push({ kind, message }),
now: () => time,
setTimer: (callback, delay) => { const id = ++nextTimer; timers.set(id, { callback, at: time + delay }); return id },
clearTimer: (id) => timers.delete(id),
visible: overrides.visible
})
return {
controller, state: controller.state, calls, notices, timers,
setTime(value) { time = value },
advance(ms) {
time += ms
for (const [id, timer] of [...timers]) {
if (timer.at <= time) { timers.delete(id); timer.callback() }
}
}
}
}
test('archive appears immediately while automatic cloud sync is pending, then refreshes on completion', async () => {
const pending = deferred()
let reads = 0
const f = fixture({ load: async () => archive(++reads), sync: () => pending.promise })
f.controller.setDiagnosis(10)
await settle()
assert.equal(f.state.rows[0].msg_id, 1)
assert.equal(f.state.syncing, true)
assert.equal(f.state.loading, false)
assert.equal(f.timers.size, 0)
pending.resolve(progress(true))
await settle()
assert.equal(f.state.rows[0].msg_id, 2)
assert.equal(f.state.syncing, false)
assert.equal(f.timers.size, 1)
assert.deepEqual(f.notices, [])
f.controller.dispose()
})
test('account verification progress and skipped staff are displayed separately from sync failures', async () => {
const checked = deferred(), finished = deferred()
let step = 0
const f = fixture({ sync: async () => {
step++
if (step === 1) return progress(false, { phase: 'checking_accounts', checked_accounts: 100, candidate_accounts: 185, skipped_accounts: 98 })
if (step === 2) return checked.promise
return finished.promise
} })
f.controller.setDiagnosis(1)
await settle()
assert.equal(f.state.phase, 'checking_accounts')
assert.equal(f.state.checkedAccounts, 100)
assert.equal(f.state.candidateAccounts, 185)
assert.deepEqual(f.state.partialErrors, [])
checked.resolve(progress(false, { phase: 'syncing', checked_accounts: 185, candidate_accounts: 185, skipped_accounts: 183, total_peers: 1 }))
await settle()
assert.equal(f.state.totalPeers, 1)
assert.equal(f.state.skippedAccounts, 183)
finished.resolve(progress(true, { phase: 'completed', skipped_accounts: 183, total_peers: 1 }))
await settle()
assert.equal(f.state.syncError, '')
assert.deepEqual(f.state.partialErrors, [])
f.controller.setDiagnosis(2)
assert.equal(f.state.skippedAccounts, 0)
f.controller.dispose()
})
test('completion waits for initial archive read and starts a fresh read after it', async () => {
const initial = deferred()
let reads = 0
const f = fixture({ load: () => ++reads === 1 ? initial.promise : Promise.resolve(archive(2)) })
f.controller.setDiagnosis(10)
await settle()
assert.equal(reads, 1)
initial.resolve(archive(1))
await settle()
assert.equal(reads, 2)
assert.equal(f.state.rows[0].msg_id, 2)
assert.equal(f.timers.size, 1)
f.controller.dispose()
})
test('sync tokens continue across pages and archive refreshes every three pages and on completion', async () => {
const lastPage = deferred()
let pages = 0, reads = 0
const f = fixture({
load: async () => archive(++reads),
sync: async () => ++pages < 4 ? progress(false, { sync_token: `token-${pages}`, inserted: pages }) : lastPage.promise
})
f.controller.setDiagnosis(10)
await settle()
assert.equal(pages, 4)
assert.equal(reads, 2)
assert.deepEqual(f.calls.filter(call => call[0] === 'sync').map(call => call[2]), [undefined, 'token-1', 'token-2', 'token-3'])
assert.equal(f.state.inserted, 3)
lastPage.resolve(progress(true, { inserted: 4, processed_peers: 2 }))
await settle()
assert.equal(reads, 3)
assert.equal(f.state.inserted, 4)
f.controller.dispose()
})
test('a slow page refreshes archive after two seconds even before three pages', async () => {
const lastPage = deferred()
let pages = 0, reads = 0
const f = fixture({
load: async () => archive(++reads),
sync: async () => {
if (++pages === 1) { f.setTime(102100); return progress(false) }
return lastPage.promise
}
})
f.controller.setDiagnosis(10)
await settle()
assert.equal(reads, 2)
assert.equal(f.state.syncing, true)
f.controller.dispose()
lastPage.resolve(progress(true))
await settle()
})
test('switching diagnosis ignores old archive, old sync errors, and old completion timers', async () => {
const oldRead = deferred(), oldSync = deferred()
const f = fixture({ load: (id) => id === 1 ? oldRead.promise : Promise.resolve(archive(id)), sync: (id) => id === 1 ? oldSync.promise : Promise.resolve(progress(true)) })
f.controller.setDiagnosis(1)
await settle()
f.controller.setDiagnosis(2)
await settle()
oldRead.resolve(archive(1))
oldSync.reject(new Error('旧患者同步失败'))
await settle()
assert.equal(f.state.patientName, '患者2')
assert.equal(f.state.rows[0].msg_id, 2)
assert.equal(f.state.syncError, '')
assert.equal(f.timers.size, 1)
assert.equal(f.calls.filter(call => call[0] === 'load' && call[1] === 1).length, 1)
f.controller.dispose()
})
test('dispose invalidates in-flight requests and never refreshes or schedules after completion', async () => {
const pending = deferred()
const f = fixture({ sync: () => pending.promise })
f.controller.setDiagnosis(1)
await settle()
const before = f.calls.length
f.controller.dispose()
pending.resolve(progress(true))
await settle()
assert.equal(f.calls.length, before)
assert.equal(f.timers.size, 0)
assert.equal(f.state.syncing, false)
f.controller.setVisible(true)
f.controller.setDiagnosis(2)
assert.equal(f.calls.length, before)
})
test('read and sync failures preserve existing rows and expose the original errors', async () => {
let readFails = false, syncFails = false
const f = fixture({
load: async () => { if (readFails) throw { response: { data: { msg: '归档服务读取失败' } } }; return archive(1) },
sync: async () => { if (syncFails) throw new Error('腾讯云凭证无效'); return progress(true) }
})
f.controller.setDiagnosis(1)
await settle()
readFails = true
await f.controller.reload()
assert.equal(f.state.rows[0].msg_id, 1)
assert.equal(f.state.readError, '归档服务读取失败')
syncFails = true
await f.controller.sync()
assert.equal(f.state.rows[0].msg_id, 1)
assert.equal(f.state.syncError, '腾讯云凭证无效')
assert.deepEqual(f.notices, [{ kind: 'error', message: '腾讯云凭证无效' }])
assert.equal(f.timers.size, 1)
f.controller.dispose()
})
test('only a manual completed sync emits success; concurrent clicks share the in-flight run', async () => {
let pending
const f = fixture({ sync: () => pending ? pending.promise : Promise.resolve(progress(true)) })
f.controller.setDiagnosis(1)
await settle()
assert.deepEqual(f.notices, [])
pending = deferred()
const manual = f.controller.sync()
const duplicate = f.controller.sync()
await settle()
assert.equal(f.calls.filter(call => call[0] === 'sync').length, 2)
assert.deepEqual(f.notices, [])
pending.resolve(progress(true, { inserted: 7 }))
await Promise.all([manual, duplicate])
assert.deepEqual(f.notices, [{ kind: 'success', message: '聊天记录已更新,本次新增 7 条' }])
assert.equal(f.timers.size, 1)
f.controller.dispose()
})
test('completed partial failure refreshes rows, ends the loop, and never reports full success', async () => {
let partial = false, reads = 0
const f = fixture({ load: async () => archive(++reads), sync: async () => progress(true, partial ? { error: '医生账号失败', errors: ['医生账号失败', '医助账号失败'] } : {}) })
f.controller.setDiagnosis(1)
await settle()
partial = true
await f.controller.sync()
assert.deepEqual([...f.state.partialErrors], ['医生账号失败', '医助账号失败'])
assert.equal(f.state.rows[0].msg_id, 3)
assert.equal(f.state.syncing, false)
assert.equal(f.notices.length, 1)
assert.equal(f.notices[0].kind, 'warning')
assert.match(f.notices[0].message, /医生账号失败;医助账号失败/)
f.controller.dispose()
})
test('missing token and missing completed state stop safely without claiming success', async () => {
for (const response of [{ completed: false }, { inserted: 0 }]) {
const f = fixture({ sync: async () => response })
f.controller.setDiagnosis(1)
await settle()
assert.equal(f.calls.filter(call => call[0] === 'sync').length, 1)
assert.match(f.state.syncError, /同步接口未返回/)
assert.equal(f.state.rows[0].msg_id, 1)
assert.equal(f.notices.length, 0)
f.controller.dispose()
}
})
test('one 30-second timer starts only after completion and never overlaps a pending run', async () => {
let pending
const f = fixture({ sync: () => pending ? pending.promise : Promise.resolve(progress(true)) })
f.controller.setDiagnosis(1)
await settle()
f.advance(29999)
await settle()
assert.equal(f.calls.filter(call => call[0] === 'sync').length, 1)
pending = deferred()
f.advance(1)
await settle()
assert.equal(f.calls.filter(call => call[0] === 'sync').length, 2)
assert.equal(f.timers.size, 0)
f.advance(90000)
await settle()
assert.equal(f.calls.filter(call => call[0] === 'sync').length, 2)
pending.resolve(progress(true))
await settle()
assert.equal(f.timers.size, 1)
f.controller.dispose()
assert.equal(f.timers.size, 0)
})
test('hidden or deactivated panels stop scheduling and resume with existing rows retained', async () => {
const f = fixture({ visible: false })
f.controller.setDiagnosis(1)
await settle()
assert.deepEqual(f.calls, [])
f.controller.setVisible(true)
await settle()
assert.equal(f.state.rows[0].msg_id, 1)
f.controller.setVisible(false)
assert.equal(f.timers.size, 0)
const before = f.calls.length
f.advance(60000)
await settle()
assert.equal(f.calls.length, before)
f.controller.setVisible(true)
assert.equal(f.state.rows[0].msg_id, 1)
await settle()
assert.equal(f.timers.size, 1)
f.controller.dispose()
})
test('IM API functions retain raw backend reasons, send progress tokens, and disable retries', async () => {
const calls = []
let reply = { code: 1, data: progress(true), msg: '不应自动显示的成功提示', show: 1 }
const request = {}
for (const method of ['get', 'post']) request[method] = async (config, options) => { calls.push({ method, config, options }); return reply }
const api = loadTs(path.join(__dirname, '../src/api/tcm.ts'), (name) => {
if (name === '@/utils/request') return { default: request }
throw new Error(`Unexpected import: ${name}`)
})
assert.equal((await api.triggerImChatSync({ diagnosis_id: 2, sync_token: 'resume' })).completed, true)
reply = { code: 1, data: archive(2) }
assert.equal((await api.getImChatMessages({ diagnosis_id: 2, only_archived: 1 })).lists[0].msg_id, 2)
assert.deepEqual(calls[0].config.data, { diagnosis_id: 2, sync_token: 'resume' })
for (const call of calls) {
assert.equal(call.config.timeout, 30000)
assert.deepEqual(call.options, { isTransformResponse: false, ignoreCancelToken: true, isOpenRetry: false, retryCount: 0 })
}
reply = { code: 0, data: [], msg: '腾讯云错误:签名校验失败' }
await assert.rejects(api.triggerImChatSync({ diagnosis_id: 2 }), /腾讯云错误:签名校验失败/)
})
test('chat panel script, template, and scoped styles compile', () => {
const filename = path.join(__dirname, '../src/views/tcm/diagnosis/components/ImChatRecordPanel.vue')
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'im-chat-history' })
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: 'im-chat-history', compilerOptions: { bindingMetadata: script.bindings } }).errors, [])
assert.deepEqual(compileStyle({ source: descriptor.styles[0].content, filename, id: 'im-chat-history', scoped: true, preprocessLang: 'scss' }).errors, [])
})
test('actual panel setup wires archived reads, continued sync, patient switches, and lifecycle cleanup', async () => {
const vue = require('vue')
const hooks = {}, listeners = new Map(), timers = new Map(), apiCalls = []
const pending = deferred()
let timerId = 0
const originalDocument = global.document
global.document = {
visibilityState: 'visible',
addEventListener: (name, callback) => listeners.set(name, callback),
removeEventListener: (name) => listeners.delete(name)
}
const scope = vue.effectScope()
try {
const filename = path.join(__dirname, '../src/views/tcm/diagnosis/components/ImChatRecordPanel.vue')
const { descriptor } = parse(fs.readFileSync(filename, 'utf8'), { filename })
const script = compileScript(descriptor, { id: 'im-chat-panel-setup' })
const compiled = ts.transpileModule(script.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)((name) => {
if (name === 'vue') return { ...vue, ...Object.fromEntries(['onMounted', 'onBeforeUnmount', 'onActivated', 'onDeactivated'].map(hook => [hook, callback => { hooks[hook] = callback }])) }
if (name === 'dayjs') return { default: require('dayjs') }
if (name === '@element-plus/icons-vue') return {}
if (name === 'element-plus') return { ElMessage: { success() {}, warning() {}, error() {} } }
if (name === '@/utils/im-business-message-parse') return { parseImBusinessPayload: () => null }
if (name === '@/utils/im-chat-history') return { createImChatHistory: (deps) => createImChatHistory({ ...deps, setTimer: callback => { const id = ++timerId; timers.set(id, callback); return id }, clearTimer: id => timers.delete(id) }) }
if (name === '@/api/tcm') return {
getImChatMessages: async params => { apiCalls.push(['read', params]); return archive(params.diagnosis_id) },
triggerImChatSync: async params => { apiCalls.push(['sync', params]); return params.diagnosis_id === 1 ? pending.promise : progress(true) }
}
throw new Error(`Unexpected panel import: ${name}`)
}, module, module.exports)
const props = vue.reactive({ diagnosisId: 1 })
const panel = scope.run(() => module.exports.default.setup(props, { expose() {} }))
hooks.onMounted()
await settle()
assert.equal(panel.rows.value[0].raw.msg_id, 1)
assert.deepEqual(apiCalls[0], ['read', { diagnosis_id: 1, only_archived: 1 }])
assert.deepEqual(apiCalls[1], ['sync', { diagnosis_id: 1 }])
props.diagnosisId = 2
await settle()
assert.equal(panel.rows.value[0].raw.msg_id, 2)
pending.resolve(progress(true))
await settle()
assert.equal(panel.rows.value[0].raw.msg_id, 2)
assert.equal(timers.size, 1)
panel.history.rows = [{
msg_id: 'multi-part', msg_type: 'composite', from_account: 'doctor_20', to_account: 'patient_2', time: 1700000000,
parts: [{ msg_type: 'text', text: '第一段' }, { msg_type: 'image', image_url: 'https://example.invalid/chat.png' }, { msg_type: 'text', text: '第三段' }]
}]
assert.deepEqual(panel.rows.value.map(item => [item.raw.msg_id, item.raw.msg_type]), [
['multi-part:0', 'text'], ['multi-part:1', 'image'], ['multi-part:2', 'text']
])
assert.equal(panel.rows.value[2].raw.text, '第三段')
assert.ok(panel.rows.value.every(item => item.raw.to_account === 'patient_2'))
global.document.visibilityState = 'hidden'
listeners.get('visibilitychange')()
assert.equal(timers.size, 0)
hooks.onBeforeUnmount()
assert.equal(listeners.size, 0)
} finally {
scope.stop()
global.document = originalDocument
}
})
@@ -0,0 +1,102 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const ts = require('typescript')
const vue = require('vue')
const filename = path.join(__dirname, '../src/views/consumer/prescription/components/PrescriptionOrderTimeDialog.vue')
const source = fs.readFileSync(filename, 'utf8')
const { descriptor, errors } = parse(source, { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'order-time-test' })
const template = compileTemplate({
source: descriptor.template.content,
filename,
id: 'order-time-test',
compilerOptions: { bindingMetadata: script.bindings }
})
assert.deepEqual(template.errors, [])
const compiled = ts.transpileModule(script.content, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
}).outputText
function dialog(save = async () => ({})) {
const calls = []
const events = []
const module = { exports: {} }
const mockRequire = (name) => {
if (name === 'vue') return vue
if (name === '@/api/tcm') return {
prescriptionOrderEditTime: async (payload) => {
calls.push(payload)
return save(payload)
}
}
if (name === '@/utils/feedback') return { default: { msgSuccess() {} } }
throw new Error(`Unexpected dependency: ${name}`)
}
new Function('require', 'module', 'exports', compiled)(mockRequire, module, module.exports)
const state = module.exports.default.setup({}, {
expose() {},
emit: (...event) => events.push(event)
})
state.formRef.value = { validate: async () => true, clearValidate() {} }
return { state, calls, events }
}
test('opening and saving preserves creation time seconds and submits only the selected order', async () => {
const { state, calls, events } = dialog()
state.open({ id: 42, order_no: 'RX42', create_time: '2026-09-09 11:12:37' })
assert.equal(state.form.create_time, '2026-09-09 11:12:37')
state.form.create_time = '2026-08-31 09:08:07'
await state.submit()
assert.deepEqual(calls, [{ id: 42, create_time: '2026-08-31 09:08:07' }])
assert.deepEqual(events, [['saved', 42]])
assert.equal(state.visible.value, false)
})
test('legacy seconds, milliseconds and strings populate the same local picker time', () => {
const { state } = dialog()
const date = new Date(2026, 8, 9, 11, 12, 37)
for (const value of [date.getTime() / 1000, String(date.getTime() / 1000), date.getTime(), '2026-09-09T11:12:37']) {
state.open({ id: 1, create_time: value })
assert.equal(state.form.create_time, '2026-09-09 11:12:37')
}
state.open({ id: 1, create_time: '2026-09-09 11:12' })
assert.equal(state.form.create_time, '2026-09-09 11:12:00')
state.open({ id: 1, create_time: 0 })
assert.equal(state.form.create_time, '')
})
test('validation failures do not send requests, and failed saves retain editable input', async () => {
const { state, calls, events } = dialog(async () => { throw new Error('denied') })
state.open({ id: 9, create_time: '2026-09-09 11:12:37' })
state.formRef.value.validate = async () => { throw new Error('required') }
await state.submit()
assert.equal(calls.length, 0)
state.formRef.value.validate = async () => true
await state.submit()
assert.equal(state.visible.value, true)
assert.equal(state.submitting.value, false)
assert.equal(state.form.create_time, '2026-09-09 11:12:37')
assert.deepEqual(events, [])
})
test('a pending request cannot submit twice or switch its target order', async () => {
let finish
const pending = new Promise((resolve) => { finish = resolve })
const { state, calls, events } = dialog(() => pending)
state.open({ id: 7, create_time: '2026-09-09 11:12:37' })
const saving = state.submit()
await state.submit()
await new Promise((resolve) => setImmediate(resolve))
state.open({ id: 8, create_time: '2026-09-08 00:00:00' })
await state.submit()
assert.equal(calls.length, 1)
assert.equal(state.form.id, 7)
finish({})
await saving
assert.deepEqual(events, [['saved', 7]])
})
@@ -0,0 +1,156 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const handlers = [
'isDualAuditPassed', 'canQuickTrackRow', 'canShipRow', 'openQuickTrack',
'submitQuickTrack', 'openShip', 'openEdit', 'submitEdit', 'resetEditOrderDialog'
]
const stateNames = [
'quickTrackVisible', 'quickTrackSaving', 'quickTrackRowId', 'quickTrackForm',
'shipVisible', 'shipRowId', 'shipForm', 'editVisible', 'editDialogLoading',
'editSaving', 'editOrderStep', 'editOrderPrescription',
'editFormRef', 'editForm', 'editDepositMin'
]
for (const page of ['order_list.vue', 'order_list_h5.vue']) {
const filename = path.join(__dirname, '../src/views/consumer/prescription', page)
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: page })
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
// Execute the actual order handlers with only network and unrelated UI dependencies stubbed.
const declarations = new Map()
for (const node of ast.statements) {
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
if (ts.isVariableStatement(node)) {
for (const declaration of node.declarationList.declarations) {
declarations.set(declaration.name.getText(ast), `const ${declaration.getText(ast)}`)
}
}
}
const selected = [...handlers, ...stateNames]
for (const name of selected) assert.ok(declarations.has(name), `${page}: missing ${name}`)
const compiled = ts.transpileModule(selected.map(name => declarations.get(name)).join('\n'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
function instance(detail = {}, saveTracking = async () => {}) {
const warnings = []
const errors = []
const edits = []
const tracks = []
const globals = {
ref: vue.ref, reactive: vue.reactive, nextTick: vue.nextTick,
feedback: { msgWarning: message => warnings.push(message), msgError: message => errors.push(message), msgSuccess() {} },
prescriptionOrderDetail: async () => ({ data: detail }),
prescriptionOrderEdit: async payload => edits.push(payload),
prescriptionOrderDdcode: async payload => { tracks.push(payload); await saveTracking(payload) },
canEditRow: () => true,
parseServicePackageValues: () => [],
loadEditPaidOrders: async () => {},
resolveShipModeForRow: row => row.ship_mode || 'gancao',
editGancaoLogisticsOnlyMode: vue.ref(false),
editGancaoDisplayNo: vue.ref(''),
detailDrawerRef: vue.ref(null),
detailVisible: vue.ref(false),
getLists() {}
}
const state = new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
state.editFormRef.value = { validate: async () => {}, clearValidate() {} }
return { state, warnings, errors, edits, tracks }
}
test(`${page}: only two approved audits unlock tracking, including legacy string statuses`, () => {
const { state } = instance()
for (const rx of [undefined, null, 0, 1, 2, '0', '1', '2']) {
for (const pay of [undefined, null, 0, 1, 2, '0', '1', '2']) {
const row = { prescription_audit_status: rx, payment_slip_audit_status: pay, fulfillment_status: 2 }
const allowed = [1, '1'].includes(rx) && [1, '1'].includes(pay)
assert.equal(state.canQuickTrackRow(row), allowed, `tracking: ${rx}/${pay}`)
assert.equal(state.canShipRow(row), allowed, `shipping: ${rx}/${pay}`)
}
}
for (const status of [1, 3, 4, 5, 6, 9]) {
assert.equal(state.canShipRow({ prescription_audit_status: 1, payment_slip_audit_status: 1, fulfillment_status: status }), false)
}
})
test(`${page}: direct handler calls cannot open tracking or shipping before both approvals`, () => {
for (const [rx, pay] of [[0, 0], [1, 0], [0, 1], [2, 1], [1, 2]]) {
const { state, warnings } = instance()
const row = { id: 42, prescription_audit_status: rx, payment_slip_audit_status: pay, fulfillment_status: 2 }
state.openQuickTrack(row)
state.openShip(row)
assert.equal(state.quickTrackVisible.value, false)
assert.equal(state.shipVisible.value, false)
assert.equal(state.quickTrackRowId.value, 0)
assert.equal(state.shipRowId.value, 0)
assert.equal(warnings.length, 2)
}
})
test(`${page}: approved orders can fill or replace the number and preserve the carrier`, async () => {
for (const oldNumber of ['', 'SF-OLD']) {
const { state, tracks } = instance()
const row = { id: 42, prescription_audit_status: 1, payment_slip_audit_status: 1, fulfillment_status: 2, express_company: 'sf', tracking_number: oldNumber }
state.openQuickTrack(row)
assert.equal(state.quickTrackVisible.value, true)
assert.equal(state.quickTrackForm.tracking_number, oldNumber)
state.quickTrackForm.tracking_number = ' SF-NEW '
await state.submitQuickTrack()
assert.deepEqual(tracks, [{ id: 42, express_company: 'sf', tracking_number: 'SF-NEW' }])
assert.equal(state.quickTrackVisible.value, false)
state.openShip(row)
assert.equal(state.shipVisible.value, true)
}
})
test(`${page}: a server rejection after audit revocation retains the dialog and entered number`, async () => {
const { state } = instance({}, async () => { throw new Error('audit revoked') })
state.openQuickTrack({ id: 42, prescription_audit_status: 1, payment_slip_audit_status: 1 })
state.quickTrackForm.tracking_number = 'SF-NEW'
await state.submitQuickTrack()
assert.equal(state.quickTrackVisible.value, true)
assert.equal(state.quickTrackSaving.value, false)
assert.equal(state.quickTrackForm.tracking_number, 'SF-NEW')
})
test(`${page}: editing preserves the existing number while saving other fields before approval`, async () => {
const { state, edits, errors } = instance({ id: 42, prescription_audit_status: 1, payment_slip_audit_status: 0, tracking_number: 'SF-EXISTING' })
await state.openEdit({ id: 42, prescription_audit_status: 1, payment_slip_audit_status: 1 })
assert.deepEqual(errors, [])
assert.equal(state.editForm.tracking_number, 'SF-EXISTING')
state.editForm.tracking_number = 'FORGED'
state.editForm.recipient_name = '修改后的收货人'
state.editOrderStep.value = 2
await state.submitEdit()
assert.equal(edits.length, 1)
assert.equal(edits[0].recipient_name, '修改后的收货人')
assert.equal(Object.hasOwn(edits[0], 'tracking_number'), false)
})
test(`${page}: ordinary editing cannot change tracking while resetting an approved payment audit`, async () => {
const { state, edits, errors } = instance({ id: 42, prescription_audit_status: '1', payment_slip_audit_status: '1' })
await state.openEdit({ id: 42 })
assert.deepEqual(errors, [])
state.editForm.tracking_number = 'SF-NEW'
state.editOrderStep.value = 2
await state.submitEdit()
assert.equal(edits.length, 1)
assert.equal(Object.hasOwn(edits[0], 'tracking_number'), false)
})
test(`${page}: template compiles with tracking controls bound to audit restrictions`, () => {
const template = compileTemplate({ source: descriptor.template.content, filename, id: page, compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const inputs = [...descriptor.template.content.matchAll(/<el-input\b[^>]*v-model="editForm\.tracking_number"[^>]*>/g)]
assert.equal(inputs.length, page === 'order_list.vue' ? 2 : 1)
for (const [input] of inputs) assert.match(input, /\sdisabled(?:\s|\/?>)/)
assert.match(descriptor.template.content, /v-if="canQuickTrackRow\(row\)"/)
})
}
@@ -0,0 +1,362 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const { parse, compileScript, compileTemplate, compileStyle } = require('@vue/compiler-sfc')
const ts = require('typescript')
const vue = require('vue')
const filename = path.join(__dirname, '../src/views/first_visit/wecom_promotion/index.vue')
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'member-sync-test' })
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'member-sync-test', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
assert.deepEqual(compileStyle({ source: descriptor.styles[0].content, filename, id: 'member-sync-test', scoped: true, preprocessLang: 'scss' }).errors, [])
function loadModule(source, mockRequire) {
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(mockRequire, module, module.exports)
return module.exports
}
const automation = loadModule(fs.readFileSync(path.join(path.dirname(filename), 'components/promotion-automation.ts'), 'utf8'), require)
const member = (id, enabled = 1) => ({ id, admin_id: id, userid: `member-${id}`, name: `医助 ${id}`, enabled, reception_available: enabled === 1, is_in_remote_range: true })
const pool = (id = 1) => ({ id, name: `方案 ${id}`, status: 1, can_operate: true, can_manage_access: true, member_admin_ids: [1, 2], member_rules: [member(1), member(2, 0)], official_link: { range_userids: ['member-1', 'member-2'] }, dispatch_sync: { status: 1 } })
function page(api = {}, pools = [pool()]) {
const messages = []
const emitMessage = (type, value) => messages.push({ type, message: typeof value === 'string' ? value : value.message })
const ElMessage = (value) => emitMessage(value.type, value)
for (const type of ['success', 'warning', 'error']) ElMessage[type] = (value) => emitMessage(type, value)
const instance = loadModule(script.content, (name) => {
if (name === 'vue') return { ...vue, onMounted() {} }
if (name === 'element-plus') return { ElMessage, ElMessageBox: {} }
if (name === '@element-plus/icons-vue') return {}
if (name === '@/api/first_visit') return { wecomPromotionOverview: async () => ({ pools }), ...api }
if (name.endsWith('.vue')) return {}
if (name === './components/promotion-automation') return automation
throw new Error(`Unexpected dependency: ${name}`)
}).default.setup({}, { expose() {} })
Object.assign(instance.overview, { pools })
instance.selectedPoolId.value = pools[0]?.id
return { state: instance, messages }
}
test('disabled local member still in remote snapshot is explicitly pending removal', () => {
const { state } = page()
assert.equal(state.routeStatus(member(2, 0)).label, '待移出(仍在企微)')
assert.equal(state.routeStatus({ ...member(1), is_in_remote_range: '0' }).label, '待加入企微')
assert.match(state.selectedSyncState.value.description, /当前计划:医助 1;上次企微确认:医助 1、医助 2/)
state.overview.pools[0].dispatch_sync = { status: 3, last_error: '可信 IP 校验失败' }
assert.match(state.selectedSyncState.value.description, /可信 IP 校验失败/)
})
test('single toggles never infer remote success from an empty error or planned dispatch', async () => {
const calls = []
const { state, messages } = page({ wecomPromotionToggleMember: async (payload) => { calls.push(payload); return { sync_error: '', dispatch: { queued: true } } } })
await state.handleMemberToggle(member(2), false)
assert.deepEqual(calls, [{ id: 2, status: 0 }])
assert.equal(messages.at(-1).type, 'warning')
assert.match(messages.at(-1).message, /尚未确认同步/)
assert.doesNotMatch(messages.at(-1).message, /已确认同步|已重新计算/)
assert.match(state.operationResultText(state.operationResults.value[0]), /尚未确认同步/)
})
test('single rule save reports explicit remote confirmation and preserves precise failures', async () => {
const { state, messages } = page({ wecomPromotionSaveMember: async () => ({ sync_status: 'failed', sync_error: '企微成员范围不一致' }) })
Object.assign(state.memberForm, { id: 2, active_range: [] })
await state.saveMemberRule()
assert.equal(messages.at(-1).type, 'warning')
assert.match(messages.at(-1).message, /企微成员范围不一致/)
state.notifySavedResult('本地已保存', { sync_status: 'synced' })
assert.equal(messages.at(-1).type, 'success')
assert.match(messages.at(-1).message, /企微成员范围已确认同步/)
})
test('pool saves with queued work retain a warning instead of implying official link completion', async () => {
const { state, messages } = page({ wecomPromotionSavePool: async () => ({ id: 1, sync_status: 'pending', sync_queued: true, sync_error: '' }) })
Object.assign(state.poolForm, { id: 1, name: '方案 1', member_admin_ids: [1] })
await state.savePool()
assert.equal(state.poolDialogVisible.value, false)
assert.equal(messages.at(-1).type, 'warning')
assert.match(messages.at(-1).message, /尚未确认同步/)
assert.equal(state.operationResults.value[0].sync_queued, true)
})
test('manual retry targets only its pool and does not import remote links', async () => {
const calls = []
const { state, messages } = page({ wecomPromotionSyncMemberRange: async (payload) => { calls.push(payload); return { pool_id: 1, sync_status: 'synced', sync_error: '', sync_queued: false } } })
await state.syncMemberRange(1)
assert.deepEqual(calls, [{ pool_id: 1 }])
assert.equal(state.operationResults.value[0].sync_status, 'synced')
assert.equal(state.syncingPoolId.value, 0)
assert.equal(messages.at(-1).type, 'success')
state.overview.pools[0].can_operate = false
await state.syncMemberRange(1)
assert.equal(calls.length, 1)
})
test('batch sync awaits all queued successful pools with at most two concurrent requests', async () => {
const pending = []
let active = 0
let maximum = 0
const { state } = page({ wecomPromotionSyncMemberRange: ({ pool_id }) => new Promise((resolve) => {
active++
maximum = Math.max(maximum, active)
pending.push({ id: pool_id, finish: (result) => { active--; resolve({ pool_id, ...result }) } })
}) })
const results = [1, 2, 3].map((id) => ({ id, name: `方案 ${id}`, success: true, sync_queued: true }))
results.push({ id: 4, name: '保存失败方案', success: false, sync_queued: true, error: '无权限' })
const saving = state.syncBatchResults(results)
assert.deepEqual(pending.map((item) => item.id), [1, 2])
pending[0].finish({ sync_status: 'synced', sync_error: '' })
await new Promise((resolve) => setImmediate(resolve))
assert.deepEqual(pending.map((item) => item.id), [1, 2, 3])
assert.equal(state.batchSyncProgress.completed, 1)
pending[1].finish({ sync_status: 'failed', sync_error: '范围校验失败' })
pending[2].finish({ sync_status: 'pending', sync_error: '' })
await saving
assert.equal(maximum, 2)
assert.equal(state.batchSyncProgress.completed, 3)
assert.deepEqual(state.operationResults.value.map((item) => item.sync_status), ['synced', 'failed', 'pending', undefined])
assert.match(state.operationResultText(state.operationResults.value[1]), /范围校验失败/)
assert.match(state.operationResultText(state.operationResults.value[3]), /本地保存失败:无权限/)
})
test('batch save retains partial failures and never reports queued work as remote success', async () => {
const pools = [pool(1), pool(2), pool(3)]
const syncedIds = []
const { state, messages } = page({
wecomPromotionBatchUpdatePools: async () => ({ updated: 2, failed: 1, member_updated: 2, results: [
{ id: 1, name: '方案 1', success: true, sync_queued: true },
{ id: 2, name: '方案 2', success: true, sync_queued: true },
{ id: 3, name: '方案 3', success: false, error: '保存失败' }
] }),
wecomPromotionSyncMemberRange: async ({ pool_id }) => {
syncedIds.push(pool_id)
if (pool_id === 2) throw '企微请求超时'
return { pool_id, sync_status: 'synced', sync_error: '', sync_queued: false }
}
}, pools)
Object.assign(state.batchConfigApply, { member_status: true })
Object.assign(state.batchConfigForm, { pool_ids: [1, 2, 3], member_admin_ids: [2], member_status: 0 })
state.batchConfigDialogVisible.value = true
await state.saveBatchConfig()
assert.deepEqual(syncedIds, [1, 2])
assert.equal(state.savingBatchConfig.value, false)
assert.equal(state.batchConfigDialogVisible.value, false)
assert.deepEqual(state.selectedPoolIds.value, [2, 3])
assert.match(messages.at(-1).message, /企微已确认同步 1 个,1 个尚未确认同步;1 个本地保存失败/)
assert.equal(messages.at(-1).type, 'warning')
assert.match(state.operationResults.value[1].sync_error, /企微请求超时/)
})
test('direct batch sync snapshots and deduplicates selection, limits concurrency, and waits for refresh', async () => {
const pools = [pool(1), pool(2), pool(3), pool(4)]
const pending = []
const unrelatedCalls = []
let active = 0
let maximum = 0
let refreshCount = 0
let finishRefresh
const api = Object.fromEntries([
'wecomPromotionBatchUpdatePools', 'wecomPromotionSavePool', 'wecomPromotionSaveMember',
'wecomPromotionBatchSetOperators', 'wecomPromotionSyncCustomers', 'wecomPromotionToggleMember'
].map((name) => [name, async (payload) => { unrelatedCalls.push({ name, payload }); return {} }]))
const { state, messages } = page({
...api,
wecomPromotionOverview: () => {
refreshCount++
return new Promise((resolve) => { finishRefresh = () => resolve({ pools }) })
},
wecomPromotionSyncMemberRange: ({ pool_id }) => new Promise((resolve) => {
active++
maximum = Math.max(maximum, active)
pending.push({ id: pool_id, finish: () => {
active--
resolve({ pool_id, sync_status: 'synced', sync_error: '', sync_queued: false })
} })
})
}, pools)
state.selectedPoolIds.value = [1, 1, 2, 3]
let completed = false
const syncing = state.syncSelectedMemberRanges().then(() => { completed = true })
assert.equal(state.syncingBatchMembers.value, true)
assert.deepEqual(pending.map((item) => item.id), [1, 2])
assert.deepEqual({ ...state.batchSyncProgress }, { completed: 0, total: 3 })
// A changed ref must not alter the already-dispatched batch's work list.
state.selectedPoolIds.value = [4]
pending[0].finish()
await new Promise((resolve) => setImmediate(resolve))
assert.deepEqual(pending.map((item) => item.id), [1, 2, 3])
assert.equal(state.batchSyncProgress.completed, 1)
assert.equal(refreshCount, 0)
pending[1].finish()
await new Promise((resolve) => setImmediate(resolve))
assert.equal(state.batchSyncProgress.completed, 2)
assert.equal(completed, false)
assert.equal(refreshCount, 0)
pending[2].finish()
await new Promise((resolve) => setImmediate(resolve))
assert.equal(maximum, 2)
assert.equal(refreshCount, 1)
assert.equal(state.syncingBatchMembers.value, true)
assert.equal(state.batchSyncProgress.completed, 3)
assert.equal(completed, false)
finishRefresh()
await syncing
assert.equal(state.syncingBatchMembers.value, false)
assert.deepEqual({ ...state.batchSyncProgress }, { completed: 0, total: 0 })
assert.deepEqual(state.selectedPoolIds.value, [])
assert.deepEqual(state.operationResults.value.map((item) => item.id), [1, 2, 3])
assert.ok(state.operationResults.value.every((item) => item.sync_only && item.sync_status === 'synced'))
assert.deepEqual(unrelatedCalls, [])
assert.equal(messages.at(-1).type, 'success')
assert.match(messages.at(-1).message, /已确认同步 3 个/)
assert.doesNotMatch(messages.at(-1).message, /本地.*保存/)
for (const result of state.operationResults.value) {
assert.match(state.operationResultText(result), /已确认同步/)
assert.doesNotMatch(state.operationResultText(result), /本地.*保存/)
}
})
test('direct batch sync keeps failed, pending and blocked pools selected with precise results', async () => {
const pools = [pool(1), pool(2), pool(3), { ...pool(4), official_link: null }, { ...pool(5), can_operate: false }]
const calls = []
let refreshCount = 0
const { state, messages } = page({
wecomPromotionOverview: async () => { refreshCount++; return { pools } },
wecomPromotionSyncMemberRange: async ({ pool_id }) => {
calls.push(pool_id)
if (pool_id === 2) throw new Error('企微请求超时,请检查网络')
return { pool_id, sync_status: pool_id === 1 ? 'synced' : 'pending', sync_queued: pool_id === 3, sync_error: '' }
}
}, pools)
state.selectedPoolIds.value = [1, 2, 3, 4, 5]
await state.syncSelectedMemberRanges()
assert.deepEqual(calls, [1, 2, 3])
assert.equal(refreshCount, 1)
assert.deepEqual(state.selectedPoolIds.value, [2, 3, 4, 5])
assert.deepEqual(state.operationResults.value.map((item) => item.sync_status), ['synced', 'failed', 'pending', 'blocked', 'blocked'])
assert.ok(state.operationResults.value.every((item) => item.sync_only))
assert.match(state.operationResults.value[1].sync_error, /企微请求超时,请检查网络/)
assert.equal(state.operationResults.value[2].sync_queued, true)
assert.match(state.operationResultText(state.operationResults.value[3]), /链接/)
assert.match(state.operationResultText(state.operationResults.value[4]), /权限|无权/)
for (const result of state.operationResults.value) assert.doesNotMatch(state.operationResultText(result), /本地.*保存/)
assert.equal(messages.at(-1).type, 'warning')
assert.match(messages.at(-1).message, /已确认同步 1 个/)
assert.match(messages.at(-1).message, /4 个尚未确认同步/)
assert.doesNotMatch(messages.at(-1).message, /本地.*保存/)
assert.equal(state.syncingBatchMembers.value, false)
assert.deepEqual({ ...state.batchSyncProgress }, { completed: 0, total: 0 })
})
test('direct batch sync prevents duplicate requests and freezes member and selection changes while busy', async () => {
const pools = [pool(1), pool(2)]
const calls = []
const toggles = []
let finish
const { state } = page({
wecomPromotionSyncMemberRange: ({ pool_id }) => {
calls.push(pool_id)
return new Promise((resolve) => { finish = () => resolve({ pool_id, sync_status: 'synced' }) })
},
wecomPromotionToggleMember: async (payload) => { toggles.push(payload); return { sync_status: 'synced' } }
}, pools)
state.selectedPoolIds.value = [1]
const syncing = state.syncSelectedMemberRanges()
await state.syncSelectedMemberRanges()
await state.syncMemberRange(2)
await state.handleMemberToggle(member(2), false)
state.togglePoolSelection(pools[0], false)
state.togglePoolSelection(pools[1], true)
assert.deepEqual(state.selectedPoolIds.value, [1])
state.toggleAllPoolSelection(false)
assert.deepEqual(state.selectedPoolIds.value, [1])
state.toggleAllPoolSelection(true)
assert.deepEqual(state.selectedPoolIds.value, [1])
assert.deepEqual(calls, [1])
assert.deepEqual(toggles, [])
finish()
await syncing
assert.equal(state.syncingBatchMembers.value, false)
})
test('direct batch sync cannot begin while a single sync, member toggle or batch save is active', async () => {
const calls = []
const { state } = page({ wecomPromotionSyncMemberRange: async (payload) => { calls.push(payload); return { sync_status: 'synced' } } })
state.selectedPoolIds.value = [1]
for (const [busy, value] of [[state.syncingPoolId, 1], [state.togglingMemberId, 2], [state.savingBatchConfig, true]]) {
busy.value = value
await state.syncSelectedMemberRanges()
assert.deepEqual(calls, [])
assert.equal(state.syncingBatchMembers.value, false)
busy.value = typeof value === 'boolean' ? false : 0
}
})
test('direct batch sync rejects empty and oversized selections but accepts 100 unique pools', async () => {
const pools = Array.from({ length: 101 }, (_, index) => pool(index + 1))
const calls = []
const { state, messages } = page({ wecomPromotionSyncMemberRange: async ({ pool_id }) => {
calls.push(pool_id)
return { pool_id, sync_status: 'synced' }
} }, pools)
await state.syncSelectedMemberRanges()
assert.equal(messages.at(-1).type, 'warning')
assert.match(messages.at(-1).message, /选择|勾选/)
assert.deepEqual(calls, [])
state.selectedPoolIds.value = pools.map((item) => item.id)
await state.syncSelectedMemberRanges()
assert.equal(messages.at(-1).type, 'warning')
assert.match(messages.at(-1).message, /100/)
assert.deepEqual(calls, [])
assert.equal(state.syncingBatchMembers.value, false)
state.selectedPoolIds.value = [...pools.slice(0, 100).map((item) => item.id), 1]
await state.syncSelectedMemberRanges()
assert.deepEqual(calls, pools.slice(0, 100).map((item) => item.id))
assert.equal(messages.at(-1).type, 'success')
})
test('shared operators can select and sync pools while access and configuration stay manager-only', async () => {
const pools = [
{ ...pool(1), can_manage_access: false },
{ ...pool(2), can_operate: false },
{ ...pool(3), can_operate: false, can_manage_access: false },
pool(4)
]
const calls = []
const { state, messages } = page({ wecomPromotionSyncMemberRange: async ({ pool_id }) => {
calls.push(pool_id)
return { pool_id, sync_status: 'synced' }
} }, pools)
assert.deepEqual(state.selectablePoolIds.value, [1, 2, 4])
state.togglePoolSelection(pools[0], true)
state.togglePoolSelection(pools[2], true)
await vue.nextTick()
assert.deepEqual(state.selectedPoolIds.value, [1])
state.openAccessDialog()
assert.equal(state.accessDialogVisible.value, false)
assert.equal(messages.at(-1).type, 'warning')
state.openBatchConfigDialog()
assert.equal(state.batchConfigDialogVisible.value, false)
assert.equal(messages.at(-1).type, 'warning')
await state.syncSelectedMemberRanges()
assert.deepEqual(calls, [1])
state.toggleAllPoolSelection(true)
assert.deepEqual(state.selectedPoolIds.value, [1, 2, 4])
state.openAccessDialog()
assert.deepEqual(state.accessForm.pool_ids, [2, 4])
state.openBatchConfigDialog()
assert.deepEqual(state.batchConfigForm.pool_ids, [2, 4])
state.overview.pools[0].can_operate = false
await vue.nextTick()
assert.deepEqual(state.selectedPoolIds.value, [2, 4])
})
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 73 KiB

+40 -2
View File
@@ -11,6 +11,7 @@ their platform media backends.
"""
import os
import re
import sys
from pathlib import Path
@@ -23,9 +24,46 @@ RESOURCES = PROJECT_ROOT / "resources"
WINDOWS_ICON = RESOURCES / "branding" / "app-icon.ico"
MACOS_ICON = RESOURCES / "branding" / "app-icon.icns"
ENTITLEMENTS = PROJECT_ROOT / "packaging" / "macos" / "entitlements.plist"
VERSION_FILE = PROJECT_ROOT / "packaging" / "windows" / "version_info.txt"
VERSION_SOURCE = SOURCE_ROOT / "doctor_workstation" / "__init__.py"
VERSION_TEMPLATE = PROJECT_ROOT / "packaging" / "windows" / "version_info.template.txt"
MEDIA_SMOKE_HOOK = PROJECT_ROOT / "packaging" / "runtime_media_smoke.py"
def read_application_version():
source = VERSION_SOURCE.read_text(encoding="utf-8")
match = re.search(r'^__version__\s*=\s*["\']([^"\']+)["\']', source, re.MULTILINE)
if not match:
raise SystemExit(f"Application version is missing from {VERSION_SOURCE}")
return match.group(1)
def windows_version_tuple(version):
match = re.match(r"^(\d+(?:\.\d+){0,3})", version)
if not match:
raise SystemExit(f"Application version is invalid for Windows resources: {version}")
parts = [int(part) for part in match.group(1).split(".")]
return tuple((parts + [0, 0, 0, 0])[:4])
def generate_windows_version_file(version):
template = VERSION_TEMPLATE.read_text(encoding="utf-8")
version_tuple = ", ".join(str(part) for part in windows_version_tuple(version))
rendered = template.replace("@VERSION_TUPLE@", version_tuple)
rendered = rendered.replace("@VERSION_STRING@", version)
output = PROJECT_ROOT / "build" / "generated" / "version_info.txt"
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(rendered, encoding="utf-8")
return output
APP_VERSION = read_application_version()
if sys.platform == "win32":
if not VERSION_TEMPLATE.is_file():
raise SystemExit(f"Windows version template is missing: {VERSION_TEMPLATE}")
VERSION_FILE = generate_windows_version_file(APP_VERSION)
else:
VERSION_FILE = None
if not ENTRY_POINT.is_file():
raise SystemExit(f"Application entry point is missing: {ENTRY_POINT}")
if not (VIDEO_DIST / "index.html").is_file():
@@ -107,7 +145,7 @@ exe = EXE(
icon=str(WINDOWS_ICON) if sys.platform == "win32" else None,
codesign_identity=os.environ.get("MACOS_CODESIGN_IDENTITY") if is_macos else None,
entitlements_file=str(ENTITLEMENTS) if is_macos else None,
version=str(VERSION_FILE) if sys.platform == "win32" else None,
version=str(VERSION_FILE) if VERSION_FILE else None,
)
collection = COLLECT(
@@ -1,9 +1,10 @@
# UTF-8
# Example PyInstaller version resource. Update all four version tuples together.
# PyInstaller version resource template. Values are generated from
# doctor_workstation.__version__ by packaging/doctor_workstation.spec.
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(0, 1, 0, 0),
prodvers=(0, 1, 0, 0),
filevers=(@VERSION_TUPLE@),
prodvers=(@VERSION_TUPLE@),
mask=0x3f,
flags=0x0,
OS=0x40004,
@@ -18,11 +19,11 @@ VSVersionInfo(
[
StringStruct('CompanyName', 'ZYT'),
StringStruct('FileDescription', '医生工作台'),
StringStruct('FileVersion', '0.1.0.0'),
StringStruct('FileVersion', '@VERSION_STRING@'),
StringStruct('InternalName', 'DoctorWorkstation'),
StringStruct('OriginalFilename', 'DoctorWorkstation.exe'),
StringStruct('ProductName', '医生工作台'),
StringStruct('ProductVersion', '0.1.0.0')
StringStruct('ProductVersion', '@VERSION_STRING@')
]
)
]),
+4 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "zhenyang-doctor-workstation"
version = "1.0.0"
dynamic = ["version"]
description = "Cross-platform doctor consultation workstation for Windows and macOS"
readme = "README.md"
requires-python = ">=3.11"
@@ -31,6 +31,9 @@ build = [
[project.scripts]
doctor-workstation = "doctor_workstation.app:main"
[tool.hatch.version]
path = "src/doctor_workstation/__init__.py"
[tool.hatch.build.targets.wheel]
packages = ["src/doctor_workstation"]
@@ -46,4 +49,3 @@ target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]
ignore = ["E501"]
+158
View File
@@ -0,0 +1,158 @@
# Windows x64 客户端更新 `can_install=False` 诊断
## 结论
“已识别最新版本,但按钮显示「暂不可安装」并提示后台尚未配置安装包”并不等价于只有一种后台配置错误。当前链路把多种拒绝原因压缩为同一个 `UpdateOffer.can_install=False`,而对话框的兜底文案统一归因为“后台未配置”。
对标准 Windows x64 客户端,最值得按以下顺序检查:
1. **服务端没有在 `packages.windows_x64` 取到同时非空的 `url` 和 `sha256`。** 最新版本是全局字段,安装包是按平台另行选择,因此完全可能 `has_update=True` 但 `can_install=False`。
2. **Windows Inno Setup 包使用了 HTTP(非 localhost)地址,或本机关闭了 HTTPS 证书校验。** 前者会被解析器拒绝;后者会在 UI session 中把一个原本可安装的 offer 二次降级为不可安装。
3. **服务端返回了非 64 位十六进制 SHA-256。** 当前 PHP evaluate 只检查 SHA 是否非空,Python 客户端则做严格格式校验,两端判定可能不一致。
4. **`package` 结构或 `package.type` 不符合客户端契约。** 客户端只接受对象形式的 `package`,类型只接受 `archive` / `inno_setup`;不过当前第一方 PHP 后端会把未知类型归一为 `archive`,当前管理端也只提供这两个选项,所以这通常只发生在旧服务、手工响应或绕过当前保存链路的配置中。
如果更新对话框确实已经出现,则单纯的版本、`enabled`、响应平台/架构不匹配通常可以排除:`AppUpdateSession._on_offer()` 在 `offer.has_update=False` 时直接返回,不会展示更新对话框(`app/src/doctor_workstation/ui/dialogs/app_update.py:360-368`)。
## 端到端链路与证据
### 1. 客户端发送的身份
- Windows 被映射为 `windows`(`app/src/doctor_workstation/services/app_update.py:78-83`)。
- `AMD64`、`x86_64`、`x64` 都被映射为 `x64`(`app/src/doctor_workstation/services/app_update.py:86-92`)。
- 检查请求固定发往 `setting.desktop_workstation/check`,携带 `current_version`、`platform`、`arch`(`app/src/doctor_workstation/services/app_update.py:218-243`)。
- `ApiClient` 会解开 `{code, data}` 信封,`code == 1` 时把 `data` 直接交给更新解析器(`app/src/doctor_workstation/services/api_client.py:515-542`)。
因此标准 64 位 Windows 的请求应为:
```text
GET /adminapi/setting.desktop_workstation/check
?current_version=<当前版本>&platform=windows&arch=x64
```
### 2. 服务端先决定是否有对应平台安装包
- 服务端只声明三个包槽位:`windows_x64`、`macos_arm64`、`macos_x64`(`server/app/adminapi/logic/setting/DesktopWorkstationLogic.php:28-32`)。
- `windows`/`win32`/`win64` 会归一为 `windows`,`x64`/`amd64`/`x86_64` 会归一为 `x64`,然后拼成 `windows_x64`(同文件 `:125-153`)。
- evaluate 从 `config.packages[windows_x64]` 取包;服务端 `canInstall` 只要求 `url !== '' && sha256 !== ''`(同文件 `:75-86`)。
- `hasUpdate` 独立由启用状态和版本比较决定(`:86-88`),响应中只有 `canInstall` 为真才返回 `package`,最终 `can_install = hasUpdate && canInstall`(`:90-103`)。
这直接解释了核心现象:`latest_version` 配置正确会让客户端看到新版本,但 `packages.windows_x64.url` 或 `packages.windows_x64.sha256` 任一为空,响应仍会是 `has_update: true`、`package: null`、`can_install: false`。
管理端保存的真实字段是嵌套结构 `packages.windows_x64.{url,sha256,size,filename,type}`(`admin/src/api/setting/desktop_workstation.ts:5-24`、`admin/src/views/setting/desktop_workstation/index.vue:330-344`),而不是把 Windows 包放在 macOS 槽位或任意自定义键下。管理页默认 Windows 类型为 `inno_setup`(Vue 文件 `:198-218`),上传 `.exe` 也会设置为 `inno_setup` 并在浏览器计算 SHA-256(`:292-315`)。
当前服务端校验允许整行安装包为空:空值/空行会继续通过(`server/app/adminapi/validate/setting/DesktopWorkstationValidate.php:83-110`),所以“自动检测已启用、最新版本有效、Windows 包未完整配置”是被允许保存的状态。外部 URL 缺 SHA 会被拒绝,但站内相对 URL 对应文件不存在且 SHA 为空的情形仍可能保存;服务端只会在本地文件确实存在时自动补 SHA、大小和文件名(`DesktopWorkstationLogic.php:309-331`)。
### 3. Python 客户端会再做一轮更严格的判定
`parse_update_offer()` 的规则位于 `app/src/doctor_workstation/services/app_update.py:140-215`:
- `package` 必须是字典;`url` 必须非空(`:152-167`)。
- `type` 缺省为 `archive`,只接受 `archive` / `inno_setup`;`inno_setup` 只允许 Windows(`:158-167`)。
- 响应平台、架构必须与请求时的期望值完全一致;同时必须满足服务端 `has_update`、`enabled`、合法且更高的版本(`:175-184`)。
- SHA-256 必须恰好 64 个十六进制字符(`:185-189`)。
- `inno_setup` URL 必须是 HTTPS,唯一例外是 HTTP localhost/loopback(`:190-194`,具体 URL 规则在 `:371-376`)。
- 最终 `can_install` 是服务端 `can_install`、有效 package、有效 SHA、安全安装器传输、`has_update` 五者的合取(`:195-201`)。判失败后返回对象会清除 `package`,并把 `force` 一并降为 false(`:202-215`)。
因此若原始 API 返回 `can_install: true`,客户端仍可能因以下字段得到 false:
| 字段/状态 | 拒绝条件 | Windows x64 症状是否吻合 |
|---|---|---|
| `package` | `null`、数组、字符串等非对象 | 是 |
| `package.url` | 空字符串 | 是 |
| `package.sha256` | 空、长度不是 64、包含非十六进制字符 | 是 |
| `package.type` | 非 `archive` / `inno_setup` | 是,但当前第一方后端通常会归一为 `archive` |
| `package.type=inno_setup` + URL | 非 localhost 的 `http://` 或相对 URL | 是 |
| `package.filename` | 空或扩展名不匹配 | **不会在 offer 阶段令 `can_install=False`**;可能在下载/应用阶段失败 |
| `package.size` | 空、0、不可转整数 | **不会在 offer 阶段令 `can_install=False`**;解析为 0 |
| 缺少 `package.type` | 默认 `archive` | **不会单独导致 false**;EXE 被误当 archive 会在稍后解压失败 |
一个重要的不一致是:PHP evaluate 目前只检查 SHA 非空(`DesktopWorkstationLogic.php:85`),Python 检查完整格式(`app_update.py:185-189`)。管理端正常保存会校验 64 位十六进制(`DesktopWorkstationValidate.php:147-151`),但旧数据、直接写配置或绕过校验的导入仍可能造成“后端说可安装、客户端说不可安装”。
### 4. UI session 还会因本机 TLS 设置二次降级
即使 `fetch_update_offer()` 返回的 Inno Setup offer 已经 `can_install=True`,`AppUpdateSession._on_offer()` 仍会以本机 `config.verify_ssl` 调用安装器下载策略;失败时把 `force=False`、`package=None`、`can_install=False`(`app/src/doctor_workstation/ui/dialogs/app_update.py:371-392`)。
本机配置默认 `verify_ssl=True`(`app/src/doctor_workstation/config.py:88-97`、`:124-130`),但登录页勾选“信任自签名证书(仅内网调试)”会把它反转为 false(`app/src/doctor_workstation/ui/login.py:831-844`、`:937-944`、`:1041-1053`)。`validate_installer_download_policy()` 明确拒绝 `verify_ssl=False`,也拒绝非安全的 Inno Setup URL(`app/src/doctor_workstation/services/app_update.py:379-385`)。
这是最容易被误判为“后台没包”的非后台原因。诊断时应比较两个时点:
1. `fetch_update_offer()` 刚返回时是否 `can_install=True`;
2. `_on_offer()` 传给 `_present()` 时是否已经变成 false。
若只有第 2 个时点为 false,按当前代码唯一的正常降级入口就是 Inno Setup 下载策略,优先检查 `verify_ssl`。
审阅时工作树中已存在一项并非本文创建的未提交改善:`UpdateOffer` 增加 `install_unavailable_reason`,TLS 策略降级时生成具体原因,对话框优先展示该原因(`app_update.py` service `:53-67`;UI `:200-206`、`:379-391`)。兜底文案仍用于服务端/解析阶段没有原因的 `can_install=False`,所以根因判别和补测仍有必要。
### 5. 为什么平台或版本通常不是这个弹窗的根因
- 客户端要求响应 `platform`/`arch` 与请求期望值精确相等,错配会让 `has_update=False`(`app_update.py:175-184`)。
- session 对 `has_update=False` 直接显示“当前已是最新版本”或静默返回,不创建更新对话框(UI `:360-368`)。
- 当前第一方后端会把 Windows/x64 常见别名归一为响应中的 `windows`/`x64`(`DesktopWorkstationLogic.php:125-153`)。
所以对于已经出现该对话框的标准 Windows x64 客户端,优先查 `packages.windows_x64`,而不是先怀疑 `AMD64` 与 `x64` 名称差异。例外是非标准/旧后端没有按当前契约归一,或实际机器是 Windows ARM64;服务端没有 `windows_arm64` 包槽位,后者会天然没有对应包。
同理,`enabled=false`、最新版本无效、当前版本不低于最新版本都会使 `has_update=False`,与“更新弹窗出现但不可安装”不吻合。源码运行也不是该兜底文案的成因:源码模式只会取消强制属性,点击安装后才显示“当前为源码运行”(UI `:393-394`、`:401-410`)。
## 最短现场排查路径
1. 用发生问题的当前版本请求实际 API,并保留解包后的 `data`:
```text
/adminapi/setting.desktop_workstation/check?current_version=<version>&platform=windows&arch=x64
```
2. 若响应已经是 `can_install:false` 且 `package:null`,读取管理端配置并核对 `packages.windows_x64.url` 与 `.sha256` 是否同时非空;确认包没有误填到 `macos_x64`,也没有只保存最新版本而未保存包。
3. 若响应是 `can_install:true`,核对 `package` 是否为对象、SHA 是否 64 位十六进制、`type` 是否精确为 `archive` 或 `inno_setup`。若为 Inno Setup,URL 应为 HTTPS。
4. 若解析后 offer 为 true、弹窗前变成 false,检查客户端 `preferences.json` 中的 `verify_ssl`,以及登录页“信任自签名证书”是否被勾选。
5. 对 Windows 安装程序,期望响应至少应类似:
```json
{
"has_update": true,
"enabled": true,
"platform": "windows",
"arch": "x64",
"can_install": true,
"package": {
"url": "https://cdn.example.com/DoctorWorkstation-Setup-Windows-x64-0.2.0.exe",
"sha256": "<64 lowercase hex chars>",
"size": 123456789,
"filename": "DoctorWorkstation-Setup-Windows-x64-0.2.0.exe",
"type": "inno_setup"
}
}
```
## 现有测试覆盖与缺口
已有客户端测试覆盖:
- 缺 SHA 会拒绝安装(`app/tests/test_app_update.py:43-63`)。
- 合法 HTTPS Inno Setup 会接受(`:66-89`)。
- HTTP Inno Setup 会拒绝(`:92-115`)。
- 未知类型会拒绝(`:118-139`)。
- 旧版本/错误平台响应不会成为 update(`:142-163`)。
- 检查接口会发送 `platform=windows`、`arch=x64`(`:166-208`)。
- UI 的可选/强制升级基本行为,以及“给定 policy reason 时展示该 reason”(`app/tests/test_app_update_ui.py:49-96`)。
已有 PHP 契约测试覆盖 `win32 + amd64 -> windows_x64`,以及完整 Windows Inno 包可安装(`server/tests/DesktopWorkstationUpdateContractTest.php:17-62`);缺包测试只覆盖 macOS 槽位(`:74-77`)。
建议新增以下测试:
1. **Windows x64 服务端缺字段矩阵(最高优先级)**:分别让 `packages.windows_x64.url` 为空、`sha256` 为空、整个键缺失;断言 `has_update=true`、`package=null`、`can_install=false`。这会直接固化本次症状。
2. **服务端/客户端 SHA 契约一致性**:给 evaluate 一个“非空但不是 64 位十六进制”的 SHA。期望服务端也返回不可安装,或至少用共享 fixture 明确当前由客户端拒绝;避免两端一个 true、一个 false。
3. **`AppUpdateSession` TLS 二次降级**:构造合法 HTTPS `inno_setup` offer,分别设置 `verify_ssl=True/False`,截获 `_present()`;true 时保持可安装,false 时断言 `can_install=False` 且原因明确指向证书策略而非后台缺包。
4. **UI 兜底分支**:构造 `can_install=False` 且无 reason 的 offer,断言按钮禁用并展示后台/平台包缺失文案;与已有“注入 policy reason”的测试形成两条独立路径。
5. **解析字段矩阵**:补充 `package=null`、非对象、空 URL、63 位 SHA、含非 hex SHA、缺少 type 默认 archive、Windows archive 使用 HTTP 仍可解析等边界测试。现有测试覆盖了部分,但没有把每个判定条件与原因一一锁定。
6. **跨层契约 fixture**:把 PHP `check` 的 Windows x64 JSON 响应作为 Python `parse_update_offer()` 输入,验证 canonical `windows/x64`、包类型、SHA 和 `can_install` 不发生语义漂移。
7. **管理端 payload 测试**:确认保存时始终发送 `packages.windows_x64` 嵌套对象,上传 `.exe` 后 `type=inno_setup` 且 URL、SHA、文件名、大小均落在同一槽位。
长期看,最稳妥的可观测性是让 `can_install=False` 同时带结构化原因(例如 `missing_package`、`invalid_digest`、`unsupported_type`、`insecure_installer_url`、`tls_verification_disabled`),并在客户端保留原因而不是立即清除所有包信息。这样 UI 不必用一个“后台未配置”文案覆盖所有安全门禁。
## 验证记录
- 根目录 `.trellis/` 不存在;本次按根 `AGENTS.md` 执行,只读检查生产代码,仅新增本文档。
- `app/.venv/Scripts/python.exe -m pytest tests/test_app_update.py tests/test_app_update_ui.py -q`:通过。
- 收集结果:`test_app_update.py` 21 项、`test_app_update_ui.py` 3 项,共 24 项。
- `php tests/DesktopWorkstationUpdateContractTest.php`(工作目录 `server/`):`Desktop workstation update contract: OK`。
+171
View File
@@ -0,0 +1,171 @@
# DEBUG_MODE 与线上 API 固定策略分析
## 结论
当前启动配置不是单一的“环境变量 -> `AppConfig`”链路,而是四层覆盖:
1. `python-dotenv` 先加载 `.env`,且 `override=False`,所以进程环境变量优先于 `.env`(`app/src/doctor_workstation/config.py:113-118`)。
2. `DOCTOR_API_BASE_URL` 被规范化并传入 `AppConfig`(`config.py:118-132`)。
3. 用户目录中的 `preferences.json` 再覆盖环境配置,因此当前实际上是 `进程环境/.env < preferences.json`(`config.py:133-153`)。
4. 登录页另有一套 Qt `QSettings`:`server/base_url` 会覆盖已经合并好的 `config.api_base_url`,保存或正式登录时再通过 `config_changed` 写回 `AppConfig`,控制器随后保存 `preferences.json` 并重建远端仓库(`app/src/doctor_workstation/ui/login.py:917-927, 1026-1054, 1067-1077, 1079-1103`;`app/src/doctor_workstation/app.py:438-504`)。
所以,只在 `AppConfig.load()` 里把环境变量替换成线上域名是不完整的。`DEBUG_MODE=False` 时必须同时封住:
- 环境变量 / `.env`;
- `preferences.json`;
- Qt `QSettings` 的 `server/base_url`;
- 登录页运行期 `with_updates(api_base_url=...)`。
建议目标契约为:
| 模式 | 最终 `AppConfig.api_base_url` | 本地地址设置 |
| --- | --- | --- |
| `DEBUG_MODE=False` | 始终为 `https://admin.zhenyangtang.com.cn/adminapi` | 环境、JSON preference、Qt `QSettings`、登录页编辑均不得改变 |
| `DEBUG_MODE=True` | 保留当前规则:环境/.env 初始化,`preferences.json` 覆盖,登录页可再次编辑 | 完全保留现有可配置行为 |
仓库内线上地址最直接的证据是 `admin/.env.production:1-3`,生产管理端使用 `https://admin.zhenyangtang.com.cn/`;`admin/vite.config.ts:54-64` 的开发代理也指向同一主机。桌面端的 `normalize_api_base_url()` 会追加 `/adminapi`(`config.py:67-85`),因此建议常量保存主机根地址,最终有效地址由同一个规范化函数产生。`TongjiUniApp/main.js:3` 当前使用的是 `https://xt.zhenyangtang.com.cn/`,它属于另一客户端,不能替代管理 API 地址。
## 精确修改建议
### 1. 包级发布策略常量
在 `app/src/doctor_workstation/__init__.py:1-6` 添加两个普通源码常量,并更新 `__all__`。当前该文件已有未提交的版本升级 `1.1.0 -> 1.2.0`,实现时必须保留它,只做增量编辑。
建议名称和取值:
```python
DEBUG_MODE = False
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
__all__ = ["__version__", "DEBUG_MODE", "ONLINE_API_BASE_URL"]
```
`DEBUG_MODE` 不应来自 `DOCTOR_DEBUG_MODE` 或其他环境变量,否则已安装程序仍可被本地环境切回调试地址,直接违反需求。它应是发布代码/构建产物内的策略开关。线上常量不要带查询参数、凭据或 fragment;是否在常量里带 `/adminapi` 均可,但建议只放域名根地址,让 `normalize_api_base_url()` 保持路径的唯一规范化入口。
`config.py` 从包根导入这两个常量不会形成循环:包 `__init__.py` 不导入 `config.py`;现有 `services/app_update.py:21` 也已经用相同方式从包根导入 `__version__`。
### 2. 在 AppConfig 的两个入口执行同一发布策略
涉及 `app/src/doctor_workstation/config.py:17-30, 67-85, 113-153, 167-176`。
建议在 `normalize_api_base_url()` 之后增加一个小型策略函数(名称可调整):
```python
def effective_api_base_url(candidate: str) -> str:
if not DEBUG_MODE:
# 源码常量无效属于发布错误,应显式失败,不要静默退回空地址。
return normalize_api_base_url(ONLINE_API_BASE_URL)
try:
return normalize_api_base_url(candidate)
except ValueError:
return ""
```
然后在两个入口复用:
1. `AppConfig.load()` 的 `api_url` 必须由该函数生成。这样进程环境和 `.env` 在 release 模式下即使含 `http://127.0.0.1` 也只会被读取而不会成为有效 API 地址。
2. `_merge_preferences()` 在 `DEBUG_MODE=False` 时必须忽略 JSON 中的 `api_base_url`;也可以允许读取后在 `replace()` 前强制写回 `effective_api_base_url(...)`。关键是**发布策略必须在 preference 合并之后生效**。
3. `with_updates()` 在 `DEBUG_MODE=False` 时必须把任何传入的 `api_base_url` 强制改为线上值,而不是仅做 URL 规范化。登录页运行期正是通过此入口更新配置。
实现上可选择“每个入口调用 `effective_api_base_url()`”,也可选择一个 `_apply_runtime_policy()` 在 `_merge_preferences()` 和 `with_updates()` 的 `replace()` 之后统一执行。后者更不容易遗漏,但需要保证两条返回路径都调用它。
不建议用 `AppConfig.__post_init__()` 强制改写所有直接构造的实例。仓库中大量单元/UI 测试直接构造带 `.test` 域名的 `AppConfig`(例如 `app/tests/test_ui_contract.py:408-412`);发布要求针对真实运行配置入口,没必要破坏依赖注入式测试。若希望更强的防御,可提供显式 `apply_runtime_policy()`,由 `load()`、`with_updates()` 和控制器接收外部 `AppConfig` 时调用。
### 3. 封住 Qt QSettings 的第二套本地 preference
涉及 `app/src/doctor_workstation/ui/login.py:451-468, 788-851, 917-950, 956-969, 1026-1054`。
这是满足“本地 preference 不应把它改回调试地址”的必需修改,不是纯 UI 优化:
- `_restore_settings()`:`DEBUG_MODE=False` 时,`server_url_edit` 只能显示 `config.api_base_url`,不得读取 `self.settings.value("server/base_url", ...)`;`DEBUG_MODE=True` 时保持现有读取逻辑。
- `_apply_server_settings()`:`DEBUG_MODE=False` 时使用 `config.api_base_url` 作为 `base_url`,不得信任编辑框或旧 QSettings;也不要把旧调试地址重新写入 `server/base_url`。`DEBUG_MODE=True` 时保持现状。
- 发布模式下至少将 `server_url_edit` 设为只读。也可隐藏地址编辑入口,但不要无意中一起删除超时设置;是否同时禁止“信任自签名证书”属于另一项发布安全策略。
- `_credential_scope()` 当前优先使用地址编辑框(`login.py:956-969`)。因此必须先确保发布模式下编辑框显示线上地址,否则实际请求虽已被 `with_updates()` 锁到线上,密码却可能错误地按旧调试地址做凭据 scope,造成跨环境凭据恢复混乱。
不建议启动时删除旧的 `server/base_url` QSettings。发布模式忽略它即可,这样将来显式切到 `DEBUG_MODE=True` 时仍能保留既有调试配置,也避免无必要的数据清理。
### 4. bootstrap / repository 侧无需另建域名来源
实际启动入口是 `app/src/doctor_workstation/__main__.py:5-19 -> app.py:1166-1182`。`main()` 只调用一次 `AppConfig.load()`,随后 `ApplicationController.__init__()` 立即执行 `_rebuild_remote_repository()`(`app.py:402-424`);后者把 `self.config.api_base_url` 原样传给 `build_repository()`(`app.py:513-525`),再由 `ApiClient` 规范化为带结尾斜杠的 `/adminapi/` 地址(`services/factory.py:13-45`;`services/api_client.py:133-148`)。
因此 `app.py`、`factory.py`、`api_client.py` 不应复制线上域名常量。只要 `AppConfig` 在完成所有合并后保持不变量,这一段无需修改。
可选的纵深防御:`ApplicationController._on_config_changed()` 在收到一个完整 `AppConfig` payload 时目前直接接受(`app.py:460-489`),只有 dict payload 才经过 `self.config.with_updates()`。若未来可能有第二个发信者,建议让完整 `AppConfig` 同样经过显式 runtime policy;当前唯一连接来自 `LoginWindow`(`app.py:447`),且其正常路径会先调用 `with_updates()`,所以这不是本次最小改动的阻塞项。
## 当前覆盖顺序与修改后顺序
当前:
```text
.env --(override=False)--> os.environ
|
v
AppConfig(env)
|
v
preferences.json 覆盖 env
|
v
LoginWindow 的 QSettings/server/base_url 覆盖 config
|
v
with_updates -> save_preferences -> rebuild repository
```
建议修改后:
```text
DEBUG_MODE=True : 保持上面的完整可配置链路
DEBUG_MODE=False:
env/.env ----------- ignored for api_base_url ---+
preferences.json --- ignored for api_base_url ---+--> ONLINE_API_BASE_URL
QSettings ---------- ignored for api_base_url ---+ |
runtime update ------ clamped for api_base_url ---+ v
build_repository
```
## 兼容风险与边界
1. **Demo 模式仍可覆盖“是否使用远端仓库”。** 当前 `demo_mode` 默认 `True`,且仍可被环境和 `preferences.json` 覆盖(`config.py:93, 126, 140-153`);登录页也会保存它(`login.py:1002-1006`)。本需求只要求固定 API 域名,所以不应顺手强制 `demo_mode=False`。如果产品语义其实是“发布版必须始终连接线上、不能进入 Demo”,需要单独明确并给 `demo_mode` 增加相同发布策略。
2. **TLS 校验仍可被本地 preference 关闭。** `verify_ssl` 当前可由环境、JSON preference 和 QSettings 改为 `False`(`config.py:129, 151-152, 174-175`;`login.py:937-944, 1038-1048`)。固定线上域名但允许关闭证书校验仍有中间人风险。建议产品确认是否在 `DEBUG_MODE=False` 时也强制 `verify_ssl=True`,但它超出“域名不可改”的最小范围。
3. **调试启动脚本不会自动打开源码 DEBUG_MODE。** `app/Debug_DoctorWorkstation.bat:16-23` 只设置独立配置目录、Demo 和日志级别,没有能力改变源码布尔常量。若常量提交为 `False`,脚本仍能跑 Demo,但不能用本地 URL。不要为方便而从环境读取 `DEBUG_MODE`;更安全的方案是开发者本地改为 `True`(不提交),或由明确区分的 debug 构建生成非发布模块。
4. **已有 preference 不需要迁移或删除。** 发布模式会忽略旧调试 URL;切回 debug 后仍按现有优先级恢复。`save_preferences()` 当前把完整 dataclass 写入 JSON(`config.py:155-165`),发布运行后可能把线上 URL写回文件,这是可接受的,但测试应覆盖“旧文件存在时首次启动仍直接得到线上 URL”。
5. **凭据按 URL scope 隔离。** `LoginWindow._credential_scope()` 和 `TokenStore` 使用 API scope。切到线上后旧调试 token/password 不应被用于线上,这是正确行为;但若只锁 `AppConfig` 而不锁登录页 QSettings,可能出现“请求发往线上、密码却按调试 URL scope 保存/恢复”的错配,因此第 3 节不能省略。
6. **构建 smoke 环境目前注入 loopback API。** Windows/macOS 构建与安装 smoke 分别在 `app/scripts/build_windows.ps1:28-47`、`build_macos.sh:105-123`、`smoke_windows_installer.ps1:101-109` 注入 `https://127.0.0.1:9`。发布策略生效后该变量会被忽略。正常 smoke 不应访问线上:更新检查被 `DOCTOR_SMOKE_TEST`/`--smoke-test` 阻断(`ui/dialogs/app_update.py:332-340`),且这些脚本设置 `DOCTOR_DEMO_MODE=true`,会阻断 session restore(`app.py:530-540`)。仍建议增加“smoke 期间没有发起线上请求”的断言,避免未来启动流程变化造成生产流量。
7. **不要把线上常量的错误静默转为空地址。** 调试环境输入无效时保持当前的空地址降级合理;源码内线上常量无效则应让测试/构建立即失败,否则发布包只会落入 `_UnconfiguredRepository`(`app.py:435-436, 513-525`),错误会拖到登录时才暴露。
8. **版本读取兼容。** PyInstaller spec 用正则只读取 `__version__` 行(`app/packaging/doctor_workstation.spec:27-37`)。只要保留当前独立的 `__version__ = "1.2.0"` 赋值,新增常量与 `__all__` 不影响版本生成。
## 建议测试
优先在 `app/tests/test_config.py` 增加以下矩阵:
1. `DEBUG_MODE=False`,环境 `DOCTOR_API_BASE_URL=http://127.0.0.1:8000`,无 preference:`AppConfig.load().api_base_url == "https://admin.zhenyangtang.com.cn/adminapi"`。
2. `DEBUG_MODE=False`,环境为线上、`preferences.json` 保存调试 URL:最终仍为线上。
3. `DEBUG_MODE=False`,先 `AppConfig.load()`,再 `with_updates(api_base_url="http://localhost:8000")`:最终仍为线上。
4. `DEBUG_MODE=True`,环境提供 A、preference 提供 B:最终仍为 B,证明现有“preference 覆盖 env”行为未回归。
5. `DEBUG_MODE=True`,无 preference,仅环境提供 URL:继续规范化并自动追加 `/adminapi`。
6. 将 `ONLINE_API_BASE_URL` 临时 monkeypatch 为非法值且 `DEBUG_MODE=False`:应显式抛错,避免发布误配置静默降级。
在 `app/tests/test_ui_contract.py` 增加:
1. 发布模式的 QSettings 预置 `server/base_url=http://127.0.0.1:8000`,创建 `LoginWindow` 后地址框显示线上 URL且不可编辑。
2. 发布模式调用 `_save_server_settings()` / 非 Demo `submit()`,`config_changed` payload 的 `api_base_url` 仍为线上,远端仓库不会以 QSettings 地址重建。
3. 上述场景下 `_credential_scope()` 返回线上 scope,防止凭据落在旧调试 scope。
4. `DEBUG_MODE=True` 重跑同类场景,确认地址框仍从 QSettings 恢复、保存后仍能切换服务器。
在 bootstrap/构建层增加或保留以下回归:
1. `ApplicationController` 用 `AppConfig.load()` 启动时,传给 `build_repository()` 的 release base URL 精确为 `https://admin.zhenyangtang.com.cn/adminapi`。
2. `--smoke-test` 和 `DOCTOR_SMOKE_TEST=1` 下,无论 release URL 是否存在,都不执行更新请求或 token restore 网络调用。
3. 冻结包 smoke 继续通过;原 smoke 脚本中的 loopback `DOCTOR_API_BASE_URL` 被忽略是预期行为,不应把断言写成“最终 URL 等于 127.0.0.1”。
建议验证命令:
```powershell
Set-Location D:\web\zyt\app
uv run pytest tests/test_config.py tests/test_ui_contract.py -q
uv run ruff check src/doctor_workstation/__init__.py src/doctor_workstation/config.py src/doctor_workstation/ui/login.py tests/test_config.py tests/test_ui_contract.py
```
若还修改了 bootstrap 防御或 smoke 契约,再运行相关完整测试和冻结构建门禁;仅本分析任务未修改生产代码、也未执行会连接线上环境的测试。
+143
View File
@@ -0,0 +1,143 @@
# 登录页 DEBUG_MODE 门禁分析
## 结论
当前实现不存在 `DEBUG_MODE`(项目内唯一含 `debug_mode` 的命中只是一个测试函数名)。登录页始终创建并展示“演示模式”和“服务器设置”入口;`AppConfig.demo_mode` 默认又是 `True`,且 `preferences.json` 会覆盖环境配置。因此,仅对两个控件调用 `hide()` 不能满足目标:隐藏的 checkbox 仍可能保持 checked,普通登录仍会自动读取/写回残留 `QSettings`,控制器也会接受伪造或残留的 demo 状态。
建议把 `DEBUG_MODE` 设计成**非用户偏好、不可由 `QSettings` 或 `preferences.json` 覆盖的单一运行时门禁**,并在配置加载、LoginWindow 行为和 ApplicationController 三层同时收口:
- `DEBUG_MODE=True`:显示且允许演示仓库切换和登录页服务器设置,保留现有调试行为。
- `DEBUG_MODE=False`:隐藏完整 UI 区块,强制 effective demo 为 `False`,忽略残留服务器 QSettings,登录只能使用 composition root 提供的远程仓库;直接调用槽函数、设置隐藏 checkbox、发信号或构造 demo payload 也不能绕过。
`demo_mode` 只能表示 DEBUG 模式下的默认选择/当前选择,不能再充当“是否有权使用 demo”的授权位。
## 当前实现与风险点
### 1. 配置与持久化
| 位置 | 当前行为 | DEBUG_MODE=False 的风险 |
| --- | --- | --- |
| `src/doctor_workstation/config.py:88-99` | `AppConfig.demo_mode` 默认 `True`,没有 debug gate | 直接构造 `AppConfig()` 就默认允许 demo |
| `config.py:113-133` | `DOCTOR_DEMO_MODE` 未设置时也按 `True` 加载,然后调用 `_merge_preferences()` | 生产未显式注入环境变量时默认 demo;即使环境设为 false,后续偏好仍可覆盖 |
| `config.py:135-153` | `preferences.json` 中所有 dataclass 字段均会合并,包括 `demo_mode`、`api_base_url`、`request_timeout`、`verify_ssl` | 旧 debug profile 的 demo/server 值可覆盖本次受控配置 |
| `config.py:155-165` | `save_preferences()` 用 `asdict(self)` 保存完整配置 | demo 切换和服务器设置会持续残留在 JSON 中 |
| `config.py:167-176` | `with_updates()` 可随时把 demo/服务器字段改回调试值 | UI 隐藏后仍可从信号/直接调用修改 |
需要特别区分两套持久化:demo 当前**不写 QSettings**,它通过 `config_changed -> ApplicationController._on_config_changed -> save_preferences()` 写入 `preferences.json`;服务器地址、超时和证书校验先写 `QSettings`,随后同一信号链又写入 `preferences.json`。相关位置是 `ui/login.py:1038-1054` 和 `app.py:460-491`。
当前 `Debug_DoctorWorkstation.bat:16-24` 只是设置 `DOCTOR_DEMO_MODE=true` 和 `DOCTOR_LOG_LEVEL=DEBUG`,没有提供独立 debug capability。若新门禁来自环境,调试启动器应显式设置专用值(例如 `DOCTOR_DEBUG_MODE=true`);普通/冻结启动不得设置。若门禁是构建期常量,则无需让用户偏好或 `.env` 参与。无论采用哪种来源,都不要把它作为普通 `AppConfig` dataclass 字段写入 `preferences.json`。
### 2. LoginWindow 组件和信号
| 位置 | 组件/信号链 | 当前行为与缺口 |
| --- | --- | --- |
| `ui/login.py:444-449` | `server_settings_changed(dict)`、`config_changed(object)`、`demo_mode_changed(bool)` | `server_settings_changed` 目前仅测试监听;另外两个信号由 controller 监听。所有发射点都无 debug gate |
| `login.py:451-468` | 构造参数、`demo_repository`、`active_repository` | 只要传入 demo repository 就保留可切换能力;controller 当前总会传入 |
| `login.py:739-755` | “记住密码”行和 `demo_check` | checkbox 始终加入布局;只有 repository 为空时 disabled,不会隐藏 |
| `login.py:770-855` | “或”分隔线、`server_toggle`、`server_panel` 及 URL/timeout/self-signed/save 子控件 | toggle 始终显示,panel 只是在初始时折叠。若只隐藏 toggle,“或”分隔线和固定 spacing 仍会残留 |
| `login.py:917-948` | `_restore_settings()` | 始终从 QSettings 恢复三项 server 值;只看 `config.demo_mode` 就勾选 demo。`setChecked(True)` 会触发已连接的 `_on_demo_toggled()` |
| `login.py:956-969` | `_credential_scope()` | 优先读取 `server_url_edit`;即便控件隐藏,残留 QSettings URL 仍可改变凭据读取/保存 scope |
| `login.py:1002-1013` | `demo_check.toggled -> _on_demo_toggled()` | 切换 `active_repository`,发射 `demo_mode_changed`,再经 `_emit_config_update` 发射 `config_changed`;没有权限判断 |
| `login.py:1015-1027` | `server_toggle.clicked`、save button | 方法可被直接调用,隐藏控件并不能阻止 panel 展开或保存 |
| `login.py:1029-1054` | `_apply_server_settings()` | 会持久化 QSettings、发射两个配置相关信号;没有权限判断 |
| `login.py:1079-1126` | `submit()` | 直接以隐藏 checkbox 的 checked 状态决定 demo;非 demo 登录会**无条件自动应用服务器控件当前值**,所以旧 QSettings 即便不展开 panel 也会生效 |
| `login.py:1140-1159` | `_set_loading()` | loading 结束会按 `demo_repository is not None` 重新 enable demo,并重新 enable server 子控件;需把 debug gate 合入 enable 条件 |
| `login.py:1177-1216` | 登录成功与凭据保存 | `payload["demo_mode"]` 决定是否保存密码;凭据 scope 又可能来自隐藏的 server edit |
| `login.py:1224-1234` | 证书错误 | 会直接勾选 toggle 并展开 panel;生产隐藏后仍可被错误路径重新显示 |
证书错误文案还在 `ui/widgets.py:376-383` 明确引导用户展开服务器设置、关闭证书校验。非 debug 模式必须改为不引用隐藏入口的运维提示,否则 UI 和文案契约矛盾。
### 3. ApplicationController 与登录可信边界
| 位置 | 当前行为 | 需要的防线 |
| --- | --- | --- |
| `app.py:402-423` | 总是实例化 `DemoDoctorRepository()`;`current_demo_mode=config.demo_mode` | 非 debug 不创建/不暴露 demo repository,并强制 current demo false |
| `app.py:438-455` | 总把 demo repository 传给 LoginWindow;复用窗口时信任 `demo_check` | 传递显式 gate;非 debug 复用时重置 checkbox/active repository |
| `app.py:460-506` | 接受 `demo_mode` 及全部 server 字段,保存 preferences 并重建 repository | 非 debug 拒绝 debug-only changes,避免伪造 `config_changed` 绕过 UI |
| `app.py:508-511` | 任意 `demo_mode_changed(True)` 都会设置 current demo 并取消 session restore | 非 debug 忽略/纠正 true |
| `app.py:530-540` | `config.demo_mode=True` 会跳过生产 token restore | 必须基于经过门禁归一化的 effective demo;残留 preference 不能阻止 restore |
| `app.py:653-681` | 信任成功 payload 中的 `demo_mode` 与 repository | 非 debug 必须拒绝 demo payload/repository,或无条件把 effective demo 归零;这是 UI 之外的最后可信边界 |
| `app.py:782-792` | `current_demo_mode` 决定是否打开离线 demo 视频窗 | 前述边界不收口时,伪造状态还会扩散到登录后的功能 |
## 精确修改建议
### A. 建立单一、不可持久化的 capability
在 `src/doctor_workstation/config.py` 定义唯一 `DEBUG_MODE`(或等价只读函数),由受控构建/专用调试启动器决定。不要从 `QSettings` 读取,不要让 `preferences.json` 覆盖,也不要随 `asdict(AppConfig)` 保存。
配置加载完成后必须做一次最终归一化:`effective_demo_mode = DEBUG_MODE and requested_demo_mode`。在 `DEBUG_MODE=False` 时,`_merge_preferences()` 至少忽略 `demo_mode`;若“服务器设置不可用”意味着生产连接完全由受控环境提供,还应同时忽略偏好中的 `api_base_url`、`request_timeout`、`verify_ssl`,否则旧登录页设置虽然 UI 不可见,仍会从 JSON 生效。`with_updates()` 也应拒绝或丢弃非 debug 下对这些 debug-only 字段的修改。
推荐把 debug capability 显式传给 `ApplicationController`/`LoginWindow` 或保存为只读实例属性,便于测试 True/False 两条路径。不要在多个模块各自复制一个可 monkeypatch 的常量,否则测试或运行时可能出现 config 判 false、UI 判 true 的分裂状态。
### B. LoginWindow:可见性和行为同时门禁
在 `ui/login.py:451-468` 记录 `self.debug_mode`,并把 `self.demo_repository` 设为 `demo_repository if debug_mode else None`。建议仍构造具名控件以保持测试和代码引用稳定,但所有状态转换都使用 `self.debug_mode` 判断。
UI 结构建议:
1. `demo_check` 仅在 debug 时 visible,并且 enabled 条件为 `debug_mode and demo_repository is not None and not loading`。
2. 把 `login.py:770-855` 的“或”分隔线、server toggle、panel 和上下 spacing 包进一个 `self.debug_server_section` QWidget;整个 section 仅在 debug 时 visible。单独隐藏 `server_toggle` 会留下“或”和空白。
3. panel 初始仍折叠;debug true 时保持现有 toggle 行为。
行为防线建议:
1. `_restore_settings()`:非 debug 不读取 `server/*` QSettings,不恢复 demo,明确令 demo unchecked、active repository 为 production repository;服务器控件若仍构造,只从受控 `config` 填充。是否删除旧键是迁移策略,**忽略它们才是安全要求**。
2. `_credential_scope()`:非 debug 始终从受控 config URL 取 scope,不读取隐藏的 `server_url_edit`。
3. `_on_demo_toggled(True)`:非 debug 立即用 signal blocker 恢复 unchecked/production repository,然后 return;不得发 `demo_mode_changed` 或 `config_changed`。
4. `_toggle_server_panel()`、`_save_server_settings()`、`_apply_server_settings()`:非 debug 强制 panel 关闭且不写 QSettings、不发 `server_settings_changed/config_changed`。直接调用也必须无效。
5. `submit()`:用 `demo_mode = self.debug_mode and self.demo_check.isChecked()`,并从这个 effective 值选择 repository。非 debug 跳过 `_apply_server_settings()`,只使用 composition root 已构造的 remote repository;否则会再次应用隐藏控件中的旧值。
6. `_set_loading()`:所有 demo/server enabled 状态与 `self.debug_mode` 做 AND,防止 loading 完成后重新激活。
7. `_on_login_error()`:仅 debug 时自动展开 certificate panel;非 debug 保持 section 隐藏,并显示“请联系管理员检查受控服务器/证书配置”之类不提供绕过证书校验的文案。
### C. Controller:不要信任 UI 状态或 payload
在 `app.py:402-423` 以同一 capability 计算 effective state;非 debug 最好根本不实例化 `DemoDoctorRepository`。`_show_login()` 显式传 gate,窗口复用时不要读取隐藏 checkbox 决定 repository。
`_on_config_changed()` 必须再次过滤 demo/server debug-only 字段;`_on_demo_mode_changed()` 非 debug 不接受 true;`_begin_session_restore()` 不得因未经门禁的旧 `config.demo_mode` 跳过;`_on_login_succeeded()` 应把 demo capability 作为可信边界,非 debug 收到 `demo_mode=True` 或 demo repository 时拒绝进入 shell并清理 session,而不是静默接受 payload。这样即使未来有其他代码直接调用槽函数,也不能重新开启演示路径。
## `tests/test_ui_contract.py` 现状与调整
实际文件是 `app/tests/test_ui_contract.py`,`app/tests` 下没有 `conftest.py`;这里使用的 `tmp_path`/`monkeypatch` 是 pytest 内置 fixture,相关 helper 都定义在测试函数内。
现有相关契约:
- `test_ui_contract.py:230-273`:真实 demo 登录,证明 `config.demo_mode=True` 会勾选 checkbox、使用空账号密码登录 demo,并发出 demo payload;未覆盖 debug capability。
- `test_ui_contract.py:276-337`:同一 QSettings 跨窗口恢复账号/密码;不涉及 demo。
- `test_ui_contract.py:340-375`:服务器 panel 在最小窗口的布局。
- `test_ui_contract.py:378-399`:函数名虽含 `debug_mode`,实际仅验证 self-signed 值写入 QSettings,没有任何 `DEBUG_MODE` 判断。
- `test_ui_contract.py:402-455`:普通登录前自动应用 server 值、经 `config_changed` 换成新 repository。
- `test_ui_contract.py:458-463`:证书错误文案指向服务器设置。
- `test_ui_contract.py:495-513`:证书错误会自动展开服务器 panel;这个契约只应在 debug true 成立。
引入 gate 后,`230`、`340`、`378`、`402`、`495` 这几组依赖 demo/server 的测试都应显式运行在 `DEBUG_MODE=True`,避免它们因测试默认值偶然通过。不要新增“把 demo 写入 QSettings”的契约;当前 demo 的持久化源是 AppConfig/preferences,目标反而要求非 debug 忽略该残留值。
## 建议回归测试矩阵
### `tests/test_ui_contract.py`
1. **debug true 可见且可用**:show 窗口后断言 demo checkbox、完整 server section/toggle 可见;原 demo 登录、panel 几何、自签名保存、登录前应用服务器设置均继续通过。
2. **debug false 无视觉残件**:断言 demo checkbox、`debug_server_section`(包括“或”分隔线)、toggle、panel 都不可见;demo unchecked,`active_repository is remote_repository`。
3. **残留 QSettings 不生效**:预写 `server/base_url=旧地址`、`server/read_timeout`、`server/verify_ssl=false`,用 debug false 构造窗口;断言 credential scope/实际登录 repository 使用受控 config,QSettings 值未被 `_apply_server_settings()` 写回或发射成配置更新。
4. **直接调用不能绕过**:debug false 下程序化 `demo_check.setChecked(True)`、`_on_demo_toggled(True)`、`_toggle_server_panel(True)`、`_save_server_settings()`;断言仍 unchecked、production repository、panel hidden,`demo_mode_changed`、`server_settings_changed`、`config_changed` 均无 debug 更新。
5. **提交强制 production**:给 debug false 窗口同时传 remote 和 demo repository,并让 stale config 的 `demo_mode=True`;输入账号密码后立即执行 worker,断言只有 remote `login()` 被调用,payload `demo_mode=False`。
6. **证书错误分模式**:debug true 仍自动展开并给出 self-signed 指引;debug false 不展开/不显示 section,错误文案不再提隐藏的“服务器设置”或关闭证书校验。
7. **loading 不重启入口**:debug false 执行 `_set_loading(True)` 再 `_set_loading(False)`,断言 demo/server 控件持续 hidden + disabled。
### `tests/test_config.py`
1. 在隔离 `DOCTOR_CONFIG_DIR` 写入旧 `preferences.json`(至少 `demo_mode:true`);DEBUG false 加载后必须 `demo_mode is False`,即使 `DOCTOR_DEMO_MODE=true` 也不能越权。
2. DEBUG true 时确认 `DOCTOR_DEMO_MODE`/允许的 demo preference 仍能选择默认 demo 状态。
3. 若生产服务器配置要求环境权威,再写入旧 JSON server 字段,断言 DEBUG false 仍采用环境的 URL/timeout/verify_ssl。
4. `with_updates(demo_mode=True)` 在 DEBUG false 下不能产生 effective demo true;同理覆盖 server debug-only 更新的策略。
### `tests/test_ui_contract.py` 中的 controller 边界(或拆到 controller 专属测试)
1. DEBUG false 时 `_begin_session_restore()` 不因 stale `config.demo_mode=True` 而跳过远程恢复。
2. DEBUG false 时直接调用 `_on_demo_mode_changed(True)` 不改变 `current_demo_mode`。
3. DEBUG false 时把 `demo_mode=True`/demo repository 的伪造 payload 传给 `_on_login_succeeded()`,断言不能创建 ShellWindow。
若采用专用 `DOCTOR_DEBUG_MODE` 环境变量,还应在 `tests/test_one_click_entrypoints.py:102-108` 增加调试启动器显式开启、普通启动器/打包入口不开启的静态契约,并同步 `.env.example:8-17` 与 `README.md:56-72`,避免继续把 `DOCTOR_DEMO_MODE=true` 描述成足以启用演示能力。
## 最小验收标准
非 debug 模式应同时满足以下可观察结果:登录页看不到 demo、服务器入口、“或”分隔线或相关空白;旧 demo preference 不能阻止远程 token restore;旧 server QSettings 不能改变 URL、timeout、TLS 校验或凭据 scope;程序化调用隐藏控件/槽函数/信号也不能切换仓库或进入 demo shell。只有这四层都成立,才不是单纯的视觉隐藏。
+79
View File
@@ -0,0 +1,79 @@
# Windows 1.2.0 正式包重建结果(DEBUG_MODE=False)
- 执行日期:2026-08-28(Asia/Shanghai)
- 工作目录:`D:\web\zyt\app`
- 总体结果:成功
- 生产源码修改:无(本次仅重建产物并新增本记录)
## 发布配置核对
打包前解析 `src/doctor_workstation/__init__.py`,确认:
- `__version__ = "1.2.0"`
- `DEBUG_MODE = False`
- `ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"`
打包完成后,使用 PyInstaller 的归档读取器打开
`dist/DoctorWorkstation/DoctorWorkstation.exe` 内嵌的 `PYZ.pyz`,提取
`doctor_workstation` 模块并检查其顶层字节码常量,得到:
- `STORE_NAME __version__` 前的常量为 `"1.2.0"`
- `STORE_NAME DEBUG_MODE` 前的常量为 `False`
- `STORE_NAME ONLINE_API_BASE_URL` 前的常量为
`"https://admin.zhenyangtang.com.cn"`
因此本次重建的 EXE 已包含正式模式和线上 API 域名配置。
Windows 版本资源也核对为:应用 EXE 的 `FileVersion` / `ProductVersion`
均为 `1.2.0`,安装器的 `ProductVersion` 为 `1.2.0`。
## 打包
执行命令:
```powershell
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File scripts\package_windows.ps1
```
- 退出码:`0`
- Vue/Vite 前端构建:通过(43 个模块)
- PyInstaller 6.22.0 / Python 3.12.12:通过
- Frozen Qt multimedia file gate:通过
- Frozen Qt multimedia smoke gate:通过
- Frozen application entry smoke gate:通过
- 7-Zip ZIP 创建:通过(`Everything is Ok`)
- Inno Setup 6.7.3:通过(`Successful compile (175.078 sec)`)
构建过程出现 Vite 大 chunk 提示、一个可选 Qt QML 插件缺失提示以及
Windows 系统 DLL 解析警告;它们均未阻断构建,且上述冻结产物门禁全部通过。
## 安装器烟测
执行命令:
```powershell
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File scripts\smoke_windows_installer.ps1 -Installer dist\DoctorWorkstation-Setup-Windows-x64-1.2.0.exe
```
- 退出码:`0`
- 结果:`Installer icon/install/start/uninstall smoke test passed.`
- 隔离测试目录:
`C:\Users\pc\AppData\Local\Temp\doctor-workstation-installer-smoke-4988cc3cc71346e49925445b9ae57fb9`
- 覆盖项:安装器图标、静默安装、已安装 EXE 启动、静默卸载及卸载残留检查
## 产物与校验
| 文件 | 大小(字节) | 大小(MiB) | SHA-256 |
| --- | ---: | ---: | --- |
| `dist/DoctorWorkstation-Setup-Windows-x64-1.2.0.exe` | 162,912,808 | 155.366 | `D0A9EED88F42F7FBBF31920D7B1ED82BD241481E98964F42313DF386CB746C0A` |
| `dist/DoctorWorkstation-Windows-x64-1.2.0.zip` | 230,810,092 | 220.118 | `9FAA8596AE0D233626B3D44676C51E6DB0BA3496B12D2EE6C984ABC0E51EB01B` |
| `dist/SHA256SUMS.txt` | 220 | 0.000 | `2DA56F76458ACE040597916C68B265C737D270B335EA73F21C4A248A2FA41B78` |
`dist/SHA256SUMS.txt` 内容:
```text
D0A9EED88F42F7FBBF31920D7B1ED82BD241481E98964F42313DF386CB746C0A DoctorWorkstation-Setup-Windows-x64-1.2.0.exe
9FAA8596AE0D233626B3D44676C51E6DB0BA3496B12D2EE6C984ABC0E51EB01B DoctorWorkstation-Windows-x64-1.2.0.zip
```
独立使用 `Get-FileHash -Algorithm SHA256` 重算 EXE 和 ZIP 后,两项均与
`SHA256SUMS.txt` 逐字符匹配;清单恰好包含两条记录。
+57
View File
@@ -0,0 +1,57 @@
# Debug mode full-suite verification
Verification date: 2026-08-28 (Asia/Shanghai)
Scope: read-only verification of the current shared worktree under `D:\web\zyt\app`. No production source was modified.
## Pytest
Command:
```powershell
.venv\Scripts\python.exe -m pytest
```
- Exit code: `1`
- Result: `2 failed, 684 passed`
- Total collected/executed: `686`
- Duration: `3195.85s` (`0:53:15`)
Failures:
1. `tests/test_diagnosis_order_video_visual.py::test_video_table_embeds_player_and_preserves_row_bound_upload`
- Assertion location: `tests/test_diagnosis_order_video_visual.py:429`
- Assertion: `table.rowHeight(0) >= playback.required_table_row_height()`
- Actual: row height `246`; required row height `250`.
2. `tests/test_reception_parity_ui.py::test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geometry`
- Assertion location: `tests/test_reception_parity_ui.py:1575`
- Assertion: `expand_button.size().width() == expand_button.size().height() == 28`
- Actual: `QSize(28, 34)`; expected `QSize(28, 28)`.
## Ruff
Command:
```powershell
.venv\Scripts\python.exe -m ruff check src tests
```
- Exit code: `1`
- Result: `9` errors, all `F401` unused imports and all reported as fixable with `--fix`.
Findings:
1. `src/doctor_workstation/ui/diagnosis_index_widgets.py:37:5` - unused `PySide6.QtGui.QPixmap`.
2. `src/doctor_workstation/ui/dialogs/ai_consult.py:18:5` - unused `PySide6.QtGui.QFont`.
3. `src/doctor_workstation/ui/dialogs/ai_consult.py:24:5` - unused `PySide6.QtGui.QPixmap`.
4. `src/doctor_workstation/ui/dialogs/ai_consult.py:26:5` - unused `PySide6.QtGui.QTextBlockFormat`.
5. `src/doctor_workstation/ui/dialogs/ai_consult.py:27:5` - unused `PySide6.QtGui.QTextCharFormat`.
6. `src/doctor_workstation/ui/dialogs/ai_consult.py:28:5` - unused `PySide6.QtGui.QTextCursor`.
7. `src/doctor_workstation/ui/dialogs/prescription.py:19:28` - unused `datetime.datetime`.
8. `src/doctor_workstation/ui/pages/patients.py:11:75` - unused `PySide6.QtGui.QPixmap`.
9. `src/doctor_workstation/ui/pages/prescriptions.py:10:65` - unused `PySide6.QtGui.QPixmap`.
## Overall result
The full verification gate is failing: both pytest and ruff returned exit code `1`.
+166
View File
@@ -0,0 +1,166 @@
# 强制更新对话框“退出软件”安全实现分析
## 结论
强制更新对话框可以提供“退出软件”,但不能把按钮直接连接到 `dialog.close()`、`reject()` 或 `QApplication.quit()`。当前更新下载由全局 `QThreadPool` 中的 `QRunnable` 执行,退出应用不会自动取消或等待该任务;安全的最小方案应是两阶段退出:
1. GUI 线程记录“退出已请求”,禁止再提交安装,并用线程安全的取消事件通知下载任务;
2. 更新任务通过既有 `finished` 信号确认已结束后,再由 `ApplicationController` 调用 `application.quit()`;
3. `aboutToQuit` 中的 `ApplicationController.shutdown()` 只做最终、幂等的资源清理,不能承担异步等待任务结束的职责。
这条顺序保证:用户选择“退出软件”后不会又启动更新助手;`.part` 文件能走现有异常清理;Qt 事件循环在工作线程仍可能发信号时不会提前消失。
## 当前实现与证据
### 1. 强制对话框目前没有退出路径
- `AppUpdateDialog` 对强制更新移除关闭按钮并设为应用级模态(`app/src/doctor_workstation/ui/dialogs/app_update.py:112-121`)。
- 按钮区只有“稍后提醒”“取消下载”“立即更新”;“稍后提醒”在强制更新时隐藏(`:179-197`)。
- `set_busy()` 只在“忙且非强制”时显示取消下载,所以强制更新下载过程中没有任何停止入口(`:208-213`)。
- 强制更新或任意下载忙状态都会忽略窗口关闭事件,强制更新还会忽略 Escape(`:265-275`)。
因此新增能力应是独立的 `exit_requested` 语义,而不是复用 `download_cancelled`。后者当前在 session 中明确拒绝强制更新(`:411-415`),且它的既有语义只是“取消后留在应用内”。
### 2. session 没有“请求取消 -> 已经停稳”的闭环
- `_TaskSignals` 已声明 `finished`,`_Task.run()` 也一定会在 `finally` 发出它(`app_update.py:67-90`),但 `AppUpdateSession` 没有连接该信号。
- session 只保留一个跨线程共享的 `_cancel: bool` 和最近一次 `_signals`,没有活动 worker/token、退出状态或完成回调(`:285-292`)。
- 检查任务和安装准备任务均直接提交到 `QThreadPool.globalInstance()`(`:316-330`、`:467-472`);局部 `worker` 没被 session 用来跟踪生命周期。
- 安装准备任务直接把进度/状态连到 dialog,把结果连到 `_finish_install()`(`:467-471`)。关闭事件循环前没有撤销或门控这些回调。
- 新 offer 到达时,session 会对旧 dialog 调用 `close()` 后立刻 `deleteLater()`(`:397-405`)。如果旧 dialog 正在强制更新/下载,它的 `closeEvent()` 会拒绝关闭,但 `deleteLater()` 仍会排队;与此同时旧 worker 仍持有连接和捕获该 dialog 的 lambda。这也是需要用“活动操作 token”阻止重入/替换的理由。
### 3. 当前取消只能在收到下载分块以后生效
- `download_package()` 把 HTTP read timeout 设为 `None`(`app/src/doctor_workstation/services/app_update.py:311`)。服务器建立连接后若不再发送数据,worker 可以无限阻塞在读取中,GUI 写入 `_cancel=True` 也不能唤醒 socket。
- 取消回调只在 `iter_bytes()` 产出一个 chunk 后检查(`:334-337`)。取消被观察到时会抛出 `AppUpdateError`,现有异常分支会删除 `.part` 文件(`:349-351`),这一清理机制可以继续复用。
- 下载返回以后没有再次检查取消状态;job 会继续校验安装器,或调用不可取消的 `safe_extract_zip()`(UI `app_update.py:439-465`;service `app_update.py:247-260`)。
- 下载全部完成后,文件在 `os.replace()` 前也没有最后一次取消检查(service `app_update.py:358-367`)。即使退出请求恰好到达末尾,job 仍可能返回 `_PreparedUpdate`。
- 工作目录在下一次同版本尝试开始时会整体删除重建(service `app_update.py:722-727`),所以取消发生在下载完成或解压阶段时,保留完整 zip/部分解压目录不会污染下一次尝试;关键仍是不能继续提交安装。
### 4. 直接 `quit()` 存在安装竞态
当前 `_finish_install()` 收到任何合法 `_PreparedUpdate` 就先启动外部更新助手,再用 300 ms 定时器调用 `application.quit()`(UI `app_update.py:483-503`)。更新助手按设计等待当前 PID 消失后才覆盖/安装并重启:archive 路径见 service `app_update.py:517-525`,Inno Setup 路径见 `:594-625`。
若下载中“退出软件”直接调用 `quit()`,存在以下时序:
1. worker 已完成最后一个 chunk,并已把 `result` 排进 GUI 事件队列;
2. 用户的退出点击与该 queued result 先后到达 GUI 线程;
3. 若 result 仍被处理,当前 `_finish_install()` 没有“退出已请求”门禁,会启动更新助手;
4. 应用随后退出,于是用户选择的“只退出”实际变成“退出并安装”。
反向时序也不安全:如果 `quit()` 先结束事件循环,worker 仍可能在独立 `httpx.Client` 中写 `.part`、解压或发射 Qt 信号。`QApplication.quit()` 是退出事件循环的请求,不是 `QRunnable` 的 cancel/join。进程最终可能等待 Qt 线程池析构、遗留中间文件,或丢弃已经排队的结果;不能把这些析构时机当成生命周期协议。
### 5. `ApplicationController.shutdown()` 目前不管理 updater
- `aboutToQuit` 在控制器构造时连接到 `shutdown()`(`app/src/doctor_workstation/app.py:402-427`)。
- `shutdown()` 只置 `_shutting_down`、失效 session restore、关闭视频和远端 API client;没有调用 `self.app_updater.shutdown()`(`:1081-1097`)。
- Qt 配置了 `setQuitOnLastWindowClosed(True)`(`:1147-1162`),因此单纯关闭/拒绝 dialog 也不是统一的退出协议:父 login/shell 仍存在时未必退出,最后窗口意外关闭时又会绕过 updater 的准备阶段。
- `ApiClient.close()` 会无超时地等待所有活跃短请求归还连接(`app/src/doctor_workstation/services/api_client.py:414-450`,尤其 `:427-432`)。更新检查使用的正是共享 remote client(UI `app_update.py:310-330`),所以若退出恰逢检查请求,`aboutToQuit -> shutdown -> client.close()` 可能在 GUI 线程等待请求超时/重试结束。强制对话框的原始检查通常已经返回,但 session 仍应在最终 shutdown 时先递增 generation,使迟到的检查结果绝不能再创建窗口。
`aboutToQuit` 已经处于事件循环退出阶段,不适合再启动“取消后等 finished signal”的异步流程;finished queued signal 可能已没有下一轮事件可处理。因此必须在点击“退出软件”时先完成 quiesce,再真正调用 `quit()`。
## 建议的最小实现
### A. 对话框只发意图,不自行退出
在 `AppUpdateDialog` 增加独立信号 `exit_requested = Signal()` 和按钮:
- 文案为“退出软件”,仅 `offer.force` 时显示;非强制更新继续使用“稍后提醒/取消下载”。
- 强制更新即使 `_busy=True` 也保持该按钮可用,因为这正是下载中唯一的离开路径。
- 点击后只 emit;session 接管状态转换。对话框增加 `set_exiting()`,禁用所有按钮、显示“正在停止更新并退出…”,防止双击。
- `closeEvent()` 和 Escape 的现有强制拦截继续保留。不要让窗口标题栏关闭绕开协调器。
- 一旦外部安装助手已经成功启动,进入不可逆的 `APPLY_COMMITTED` 状态,禁用“退出软件”;此后退出必然表示“退出并安装”。
### B. 用 `threading.Event` 和活动操作身份建立闭环
`AppUpdateSession` 最少需要以下 GUI 线程状态:
```python
self._cancel_event = Event()
self._active_install_signals: _TaskSignals | None = None
self._exit_requested = False
self._quit_when_idle: Callable[[], None] | None = None
self._apply_committed = False
```
开始安装准备时 `clear()` event,保存本次 `signals`,并把 `signals.finished` 连到带 `signals` 身份参数的 `_on_install_finished()`。进度、状态、result、error 也不要再直接连接 dialog 方法;统一经过 session handler,并同时验证:
- `signals is self._active_install_signals`;
- dialog 仍是 `self.dialog`;
- 未处于 `_exit_requested`(finished handler 除外)。
这会同时解决迟到回调、旧 dialog 被替换、以及上一次任务影响下一次 `_cancel` 状态的问题。活动安装存在时,`check()`/`_present()` 应拒绝再替换 dialog,避免两个 job 同时删除和使用同一版本 workspace。
退出请求的最小状态机是:
```text
IDLE/PREPARING --点击退出--> EXIT_PENDING
EXIT_PENDING --cancel_event.set()--> 等待当前 install signals.finished
无活动任务或 finished 到达 --> ApplicationController.request_quit()
aboutToQuit --> ApplicationController.shutdown() 最终幂等清理
```
`_finish_install()` 的第一条业务门禁必须是“如果退出已请求、event 已 set、或 signals 已不是当前操作,则直接返回,不调用 `apply_downloaded_update()`”。这是防止“退出反而安装”的关键断言。
### C. 让 job 在阶段边界观察取消,并给网络读取有限上界
现有 `download_package(cancelled=...)` 接口无需改变,改传 `self._cancel_event.is_set`。job 至少在以下边界调用统一的 `_raise_if_cancelled()`:
1. 创建 workspace 前;
2. `download_package()` 返回后;
3. 安装器校验/zip 解压前;
4. 校验/解压后、构造 `_PreparedUpdate` 前。
同时把 `download_package()` 的 `read=None` 改成有限的“单次读空闲超时”,建议沿用配置的 `request_timeout` 或默认 30 秒。这个 timeout 不是总下载时长:只要持续收到 chunk,大文件仍可继续;服务器停止发数据后,退出等待则有确定上界。
如果希望解压中点击退出也能很快响应,可把 `safe_extract_zip()` 从一次性 `extractall()` 改为逐 member 提取并在每个 member 前检查同一个 cancel callback。若坚持最小改动,也可以让退出等待当前 `extractall()` 完成,但必须保持 event loop 和 dialog 存活,并在解压后门禁掉安装,不能先 `quit()`。
### D. 由控制器统一发起真正退出
在 `ApplicationController` 增加与 `_shutting_down` 分离的 `_quit_requested`,以及幂等 `request_quit()`:
1. 首次调用时设置 `_quit_requested`;
2. 调用 `app_updater.prepare_to_quit(self.application.quit)`;
3. updater 无活动安装时立即以 `QTimer.singleShot(0, callback)` 完成;有任务时保存 callback,待该任务 `finished` 后完成;
4. 重复调用不做任何事。
不要提前设置 `_shutting_down`,否则真正触发 `aboutToQuit` 时现有 `shutdown()` 会在 `:1084-1086` 直接返回,跳过资源释放。
`ApplicationController.shutdown()` 中应在 `_cancel_session_restore()` 之后、关闭视频和 remote client 之前调用幂等的 `self.app_updater.shutdown()`。该方法应:递增 `_generation`、设置 cancel event、清除退出 callback、使所有迟到 callback 失效;它是兜底,不再等待 worker。正常的强制对话框退出路径到这里时,安装准备 worker 已经 finished。
成功更新也应复用同一完成门:`_finish_install()` 成功启动 helper 后只记录 `_apply_committed=True` 和“任务结束后退出”;由本次 `signals.finished` 再调用控制器的 `request_quit()`。这样可以删除当前依赖经验值的 300 ms 定时退出(UI `app_update.py:501-503`),并明确保证 worker 已离开 `run()`。
### E. 不建议的实现
- 不要在退出按钮中调用 `os._exit()`、`terminate()` 或强杀线程;这会绕过 controller 的视频/API 清理,并可能截断 `.part`/日志写入。
- 不要在 `aboutToQuit` 中调用 `QThreadPool.globalInstance().waitForDone()`;它会等待整个应用的全局线程池,而不只是更新任务,当前无限 read timeout 还可能让 GUI 永久卡住。
- 不要用循环 `processEvents()` 等待 worker;这会允许更新按钮、窗口关闭和 queued result 重入。
- 不要只设置现有 `_cancel=True` 后立即 `quit()`;设置取消只是请求,`finished` 才是可退出的确认。
## 建议补测
在 `app/tests/test_app_update_ui.py` 现有强制对话框测试(`:68-83`)基础上补:
1. 强制更新显示“退出软件”,不显示“稍后提醒”,关闭按钮/Escape 仍不能绕过;非强制更新不显示该退出按钮。
2. 空闲时点击退出只调用一次 controller `request_quit()`。
3. 下载中点击退出会 set event、保持应用运行且不立即调用 `application.quit()`;手工 emit 当前 signals 的 `finished` 后才调用一次。
4. 退出请求后再投递 `progress/status/result/error` 均不更新旧 dialog;特别断言 `_finish_install()` 不调用 `apply_downloaded_update()`。
5. 模拟“result 已排队但退出点击先处理”的边界,断言不会启动 helper;模拟 result 已先完成 helper 提交,则退出按钮已禁用且最终走“安装后退出”。
6. 新 offer 在活动安装期间不会 `deleteLater()` 当前 dialog,也不会启动第二个 workspace job。
7. `ApplicationController.shutdown()` 调用 updater shutdown 早于 `remote_repository.client.close()`,并保持二次调用幂等。
在 `app/tests/test_app_update.py` 的下载测试(现有 `:235-293`)基础上补:
8. 流式响应在若干 chunk 后设置 `Event`,断言抛取消错误、目标文件和 `.part` 都不存在。
9. 下载最后一个 chunk 后、`os.replace()`/job 返回前取消,断言 session 的阶段门禁不会产出可安装结果。
10. 读空闲超时为有限值,并被转换为 `AppUpdateError`;避免退出永久等待。
## 实施顺序
最小、低风险的提交顺序是:先加入 session 的 operation token、`Event`、finished 门和 controller `request_quit()`;再加对话框按钮;最后把 read timeout 改为有限值并补阶段取消检查。只有当“退出后 result 绝不会进入 `apply_downloaded_update()`”和“quit 只发生在 finished 以后”两条测试通过,才应开放强制更新下载中的退出按钮。
## 审阅说明
- 本次依据工作树当前内容只读分析;生产代码与现有测试均未修改。
- 根目录 `AGENTS.md` 已读取;仓库当前不存在其中提到的 `.trellis/` 目录,因此没有额外的 workflow/spec 文件可读。
- 工作树原本已有多项未提交修改;本次只新增本研究文档,没有覆盖或回退任何现有改动。
@@ -0,0 +1,87 @@
# 强制更新“退出软件”Windows 正式包重建与验证结果
- 执行日期:2026-08-28(Asia/Shanghai)
- 工作目录:`D:\web\zyt\app`
- 总体结果:成功
- 生产源码/测试修改:无(本次仅重建发布产物并新增本报告)
- 工作树说明:执行前 `src/doctor_workstation/__init__.py` 及其他生产/测试文件已有用户修改;本次全部保留,未覆盖或回退
- Trellis:仓库根目录不存在 `.trellis/`,因此无 Trellis 工作流文件可继续读取
## 发布配置核对
重建前后均读取 `src/doctor_workstation/__init__.py`,确认:
```powershell
rg -n "(__version__|DEBUG_MODE)" src/doctor_workstation/__init__.py
```
- 退出码:`0`
- 输出:`6:__version__ = "1.2.0"`、`10:DEBUG_MODE = False`
- `__version__ = "1.2.0"`
- `DEBUG_MODE = False`
最终 frozen 主程序的 Windows 版本资源也复核为:
- `FileVersion = 1.2.0`
- `ProductVersion = 1.2.0`
最终安装器的 `ProductVersion = 1.2.0`。
## 正式包重建
执行命令:
```powershell
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File scripts\package_windows.ps1
```
- 退出码:`0`
- 结果:`Windows package complete.`
- Python 构建环境:PyInstaller 6.22.0 / Python 3.12.12
- 视频伴侣构建:通过,Vite 转换 43 个模块
- frozen Qt 多媒体文件门禁:通过
- frozen Qt 多媒体 smoke(`--media-smoke-test`,隔离 offscreen 环境):通过
- frozen 应用入口 smoke(`--smoke-test`,隔离 offscreen 环境):通过
- ZIP:7-Zip 报告 `Everything is Ok`
- 安装器:Inno Setup 6.7.3 编译成功,`Successful compile (140.609 sec)`
构建期间有非阻断警告:Vite 报告单个压缩后 chunk 超过 500 kB;PyInstaller 报告一个 Qt QML 插件二进制缺失及若干 Windows 系统 DLL 解析警告。脚本内置的 frozen 文件门禁与两个 smoke gate 均通过,构建最终退出码为 `0`。
## 最终安装器冒烟验证
执行命令:
```powershell
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File scripts\smoke_windows_installer.ps1 -Installer 'D:\web\zyt\app\dist\DoctorWorkstation-Setup-Windows-x64-1.2.0.exe'
```
- 退出码:`0`
- 结果:`Installer icon/install/start/uninstall smoke test passed.`
- 隔离验证目录:`C:\Users\pc\AppData\Local\Temp\doctor-workstation-installer-smoke-55b6feebaa134d21ba0637549d55355b`
- 覆盖范围:安装器品牌图标、静默安装、已安装 EXE 存在性与启动 smoke、静默卸载、卸载后主程序残留检查
## 产物与独立校验
使用以下命令模式逐项独立复核,退出码为 `0`:
```powershell
Get-Item -LiteralPath <产物绝对路径>
Get-FileHash -LiteralPath <产物绝对路径> -Algorithm SHA256
```
| 产物 | 绝对路径 | 字节数 | SHA-256 |
| --- | --- | ---: | --- |
| 正式安装器 EXE | `D:\web\zyt\app\dist\DoctorWorkstation-Setup-Windows-x64-1.2.0.exe` | 162,907,874 | `71B4ADF7B431A3BBC53818AA2D68089977D777D18F0969C930A0A6B1777F2BA9` |
| 发布 ZIP | `D:\web\zyt\app\dist\DoctorWorkstation-Windows-x64-1.2.0.zip` | 230,817,779 | `D41C0794568A59FB57A083425750F4A2CDBED9962B13D9EBBD42FC2EEF374604` |
| frozen 主程序 EXE | `D:\web\zyt\app\dist\DoctorWorkstation\DoctorWorkstation.exe` | 6,300,842 | `550BF4434C6B2BEEB9DDA5A78107FB392C4FF442A6D62D01803A51197E59A893` |
| 校验清单 | `D:\web\zyt\app\dist\SHA256SUMS.txt` | 220 | `9BD4CB7CD0A1FA7FBBED0E6D38BE2A4F98898224A6B97E0E38F35701CB8B8A20` |
`dist\SHA256SUMS.txt` 内容:
```text
71B4ADF7B431A3BBC53818AA2D68089977D777D18F0969C930A0A6B1777F2BA9 DoctorWorkstation-Setup-Windows-x64-1.2.0.exe
D41C0794568A59FB57A083425750F4A2CDBED9962B13D9EBBD42FC2EEF374604 DoctorWorkstation-Windows-x64-1.2.0.zip
```
独立复算的安装器与 ZIP 哈希均与脚本末尾输出及 `SHA256SUMS.txt` 逐字符一致。
+182
View File
@@ -0,0 +1,182 @@
# 强制更新“退出软件”回归测试设计
## 结论
建议在 `app/tests/test_app_update_ui.py` 把“退出软件”作为强制更新对话框的独立显式动作测试,不把它等同于关闭窗口或 `reject()`:
- 强制更新在初始状态和下载中状态都显示且启用“退出软件”。
- 点击只发出一次专用信号(下文假定为 `exit_requested`);对话框自身不静默 `reject()`。
- 普通更新仍显示“稍后提醒”,不显示“退出软件”,原有 `update_deferred` + `reject()` 行为不变。
- 强制更新无论初始还是下载中,标题栏关闭和 Escape 都继续被拦截;用户只能通过明确的“退出软件”动作退出。
生产实现若采用独立控件,建议公开 `exit_button`;这比把强制退出语义塞进现有 `later_button` 更容易测试,也避免 `_defer()` 同时承担“稍后”和“退出”两种相反行为。若实现选择复用 `later_button`,下述断言可把 `exit_button` 替换为该控件,但至少应保留独立的 `exit_requested` 信号。
## 当前覆盖缺口
当前 `test_app_update_ui.py` 有以下相关覆盖:
- `test_optional_update_dialog_allows_later` 只断言普通更新的稍后按钮可见和更新文案,未点击按钮,也未验证 `update_deferred`。
- `test_forced_update_dialog_hides_defer_and_blocks_escape` 断言稍后按钮隐藏,并用 `dialog.close()` 验证强更无法关闭;尽管测试名写有 `blocks_escape`,测试体没有发送 Escape。
- 没有覆盖 `set_busy(True)`。当前 `set_busy()` 会禁用 `later_button`,因此若复用该按钮显示“退出软件”,下载中会直接回归为不可退出。
- 没有覆盖退出信号的次数,也没有证明显式退出动作不会被当成普通 `reject()`。
现有 service 测试 `app/tests/test_app_update.py` 主要覆盖 offer 解析、下载、校验与更新应用,不适合承载 Qt 按钮和键盘行为;这些回归应继续留在 `test_app_update_ui.py`。
## 建议测试矩阵
| offer | 对话框状态 | 稍后按钮 | 退出按钮 | 更新按钮 | 取消下载 | 关闭 / Escape |
|---|---|---|---|---|---|---|
| 强制 | 初始 | 隐藏 | 显示、启用 | 启用 | 隐藏 | 均拦截 |
| 强制 | 下载中 | 隐藏 | 显示、启用 | 禁用 | 隐藏 | 均拦截 |
| 普通 | 初始 | 显示、启用,文案“稍后提醒” | 隐藏 | 启用 | 隐藏 | 允许 |
| 普通 | 下载中 | 保持现有禁用语义 | 隐藏 | 禁用 | 显示 | `closeEvent` 目前拦截;本次不要顺带定义 Escape 新语义 |
最后一格存在现有 Qt 行为不对称:普通更新下载中时 `closeEvent()` 会拦截标题栏关闭,但 `keyPressEvent()` 仅专门拦截强制更新的 Escape。除非产品需求明确要求调整普通更新下载中的 Escape,否则本次回归不要无意固化或改变该行为。
## 推荐测试拆分
测试文件增加:
```python
import pytest
from PySide6.QtCore import Qt
from PySide6.QtTest import QTest
```
### 1. 强制更新在初始和下载中均可显式退出
用参数化覆盖两个状态,避免只测初始渲染:
```python
@pytest.mark.parametrize("busy", [False, True], ids=["initial", "downloading"])
def test_forced_update_exit_action_stays_available(
busy: bool,
application: QApplication | None = None,
) -> None:
app = application or QApplication.instance() or QApplication([])
apply_theme(app)
dialog = AppUpdateDialog(_offer(force=True))
dialog.show()
if busy:
dialog.set_busy(True)
dialog.show_download_progress(256, 1024)
app.processEvents()
assert not dialog.later_button.isVisible()
assert dialog.exit_button.isVisible()
assert dialog.exit_button.isEnabled()
assert dialog.exit_button.text() == "退出软件"
assert dialog.update_button.isEnabled() is (not busy)
assert not dialog.cancel_button.isVisible()
dialog.hide()
dialog.deleteLater()
app.processEvents()
```
这里必须在 `set_busy(True)` 后断言,才能捕获“统一禁用底部按钮”导致强制更新无法退出的回归。调用 `show_download_progress()` 同时让测试更贴近真实 `_start_install()` 顺序:先 `set_busy(True)`,再进入下载进度态。
### 2. 点击退出按钮只发一次专用信号
```python
def test_forced_update_exit_button_emits_request(
application: QApplication | None = None,
) -> None:
app = application or QApplication.instance() or QApplication([])
dialog = AppUpdateDialog(_offer(force=True))
requested: list[bool] = []
dialog.exit_requested.connect(lambda: requested.append(True))
dialog.show()
app.processEvents()
dialog.exit_button.click()
assert requested == [True]
assert dialog.isVisible()
dialog.hide()
dialog.deleteLater()
app.processEvents()
```
`assert dialog.isVisible()` 有意证明按钮在 dialog 层只表达“请求退出软件”,而不是绕开应用级清理流程直接 `reject()`。真正退出应由 `AppUpdateSession`/应用层的 slot 完成。若最终设计明确由 dialog 自身关闭,则删除这一条,但仍要保留信号次数断言。
还可把该测试参数化为初始/下载中并在两种状态点击;若测试数量需要控制,则第一个参数化测试负责可用性,第二个测试负责一次信号已足够定位大部分回归。
### 3. 普通更新仍是“稍后提醒”
建议增强现有 optional 测试,而不是只检查可见性:
```python
def test_optional_update_dialog_keeps_defer_action(
application: QApplication | None = None,
) -> None:
app = application or QApplication.instance() or QApplication([])
dialog = AppUpdateDialog(_offer(force=False))
deferred: list[bool] = []
dialog.update_deferred.connect(lambda: deferred.append(True))
dialog.show()
app.processEvents()
assert dialog.later_button.isVisible()
assert dialog.later_button.isEnabled()
assert dialog.later_button.text() == "稍后提醒"
assert not dialog.exit_button.isVisible()
dialog.later_button.click()
assert deferred == [True]
assert not dialog.isVisible()
dialog.deleteLater()
app.processEvents()
```
这条会防止实现“退出软件”时误把普通更新的次按钮文案、信号或关闭行为一起改掉。
### 4. 强制更新明确拦截关闭与 Escape
把当前名不副实的测试改成真实事件测试,并参数化初始/下载中:
```python
@pytest.mark.parametrize("busy", [False, True], ids=["initial", "downloading"])
def test_forced_update_only_allows_explicit_exit(
busy: bool,
application: QApplication | None = None,
) -> None:
app = application or QApplication.instance() or QApplication([])
dialog = AppUpdateDialog(_offer(force=True))
dialog.show()
if busy:
dialog.set_busy(True)
dialog.show_download_progress(256, 1024)
app.processEvents()
dialog.close()
app.processEvents()
assert dialog.isVisible()
QTest.keyClick(dialog, Qt.Key.Key_Escape)
app.processEvents()
assert dialog.isVisible()
dialog.hide()
dialog.deleteLater()
app.processEvents()
```
行为断言比检查 window flags 更稳定:不同平台可能规范化窗口标志,但 `closeEvent()`/`keyPressEvent()` 是否真正保留对话框才是用户可观察契约。
## 会话层边界
dialog 信号测试只能证明点击请求已发出,不能证明应用最终退出。生产接线还应满足:
- `AppUpdateSession._present()` 连接 `exit_requested` 到一个应用级退出入口。
- 下载中退出时先设置取消标志,使 `download_package(..., cancelled=...)` 尽快结束并清理 `.part` 文件,再请求 `QApplication.quit()`;否则全局线程池任务可能拖延进程退出。
- 应用级退出必须走既有 `QApplication.aboutToQuit -> ApplicationController.shutdown`,不要从 dialog 直接调用 `sys.exit()` 或跳过资源清理。
若实现为可替换的 session 方法(例如 `_request_exit()`),可另补一个 session 单测,mock/monkeypatch 该方法后验证 dialog 信号接线;不要在 pytest 共享的真实 `QApplication` 上直接调用 `quit()`,以免污染同进程后续 UI 测试。本次题目明确要求的四项回归,以上 dialog 测试已经可以独立、稳定覆盖。
## 验证记录
- 已读取根 `AGENTS.md`;工作树中不存在 `.trellis/workflow.md` 和 `.trellis/spec/`,因此无法应用额外 Trellis 分层规范。
- 只读运行现有基线:`app/.venv/Scripts/python.exe -m pytest tests/test_app_update_ui.py -q`,结果 `4 passed`。
- 本文之外未修改生产代码或测试代码;工作树中原有的 `app_update.py` 与 `test_app_update_ui.py` 未提交改动均已保留。
@@ -0,0 +1,26 @@
# 已开处方 → AI 界面改造
## 功能分析
这是基于已保存资料快照的双模型分析与医生复核工作台。主流程是确认患者和批次、查看模型完成情况、对照原方差异、核查资料缺口、记录所选模型的复核意见。
保留六个入口:对比总览、完整报告、候选与逐味、资料与缺口、处理进度、历史与趋势。历史批次切换、刷新、重新分析、单模型重试、独立复核草稿及保存继续使用现有服务和权限逻辑。医生原方及支持报告仍可访问。
## 设计决定
- 主程序 `shell.py` 将 prescriptions 等业务页列为科技蓝页面。因此继续复用 `reception_style.TECH_BLUE`:主色 #1769E8,背景 #F3F7FD,白色面板,分割线 #DBE5F2。没有采用主程序其他页面的靛蓝令牌,也没有修改全局主题。
- 深蓝渐变横幅改为白色标题工具栏。批次状态放在顶行,患者及原方信息单独成行,当前导航用浅蓝背景与蓝色底线标识。
- 缩小一致度圆环和数字,保留共同药味、候选药味与药味重合的计算依据;修复指标区样式误把分隔线应用到每个子标签的问题。
- 总览由三栏改成剂量差异主区与固定复核侧栏。三方交集和附件覆盖改为可展开的摘要,减少初始屏幕空白和对主图的挤压。
- 复核模型和复核状态并排显示,意见输入和保存按钮放在一起。顶部保存动作显示当前模型名,切换时同步更新。
- 短窗口收起次要信息,保留剂量主图和复核输入;展开图表时剂量滚动区域可让出高度。列表内容保持最小高度,避免刷新后条目重叠。
- 保留未知值与零值区分、不可比/历史状态处理、模型各自失败重试以及现有一致度说明。
## 验证
- 处方 AI 五组回归测试覆盖数据处理、权限、异步读取、逐味比较、页面、模型复核与布局。
- 新增八种窗口/展开状态组合的控件边界检查,以及展开/收起不改变比较数据和复核清单的检查。
- 离线模拟数据预览覆盖 1440×940、1280×860、1024×700、940×640,各内容页面、展开图表、运行中、失败、历史及统计窗口。
- 预览输出:`app/artifacts/issued_prescription_redesign/`。模拟数据仅供 UI 验证,不对应真实患者。
本次改动在现有未提交工作区基础上完成,仅调整桌面呈现与相关回归检查;没有重新打包或发布桌面安装程序。
+52
View File
@@ -0,0 +1,52 @@
# Windows 1.2.0 正式打包结果
- 打包日期:2026-08-28(Asia/Shanghai)
- 工作目录:`D:\web\zyt\app`
- 版本源:`src/doctor_workstation/__init__.py`
- 确认版本:`1.2.0`
- 执行命令:`powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File scripts\package_windows.ps1`
- 脚本退出码:`0`
- 总体结果:成功
## 发布产物核对
| 文件 | 大小(字节) | 大小(MiB) | SHA-256 |
| --- | ---: | ---: | --- |
| `dist/DoctorWorkstation-Setup-Windows-x64-1.2.0.exe` | 162,914,042 | 155.367 | `1D74966B73005B30ECB4EB7E2101BECB57BB8C91D0981392ACD00F6800D37E7D` |
| `dist/DoctorWorkstation-Windows-x64-1.2.0.zip` | 230,810,707 | 220.118 | `A56057D95EFCE70E58FA54264CAC17A16E2F5BDB842FE515A5A153B073A4AFE9` |
| `dist/SHA256SUMS.txt` | 220 | 0.000 | `08BD69A21BACEC86B8269ED665C50CDAF4D3ED6D252CEC4DD7BEE30E73573175` |
以上三个文件均存在。独立使用 `Get-FileHash -Algorithm SHA256` 重新计算 EXE 和 ZIP 哈希,结果与打包脚本末尾输出及 `SHA256SUMS.txt` 中的两条记录逐项一致。
## 脚本验证结果
- 锁定的 Python 构建依赖检查通过。
- 视频伴侣依赖安装成功,`vue-tsc --noEmit && vite build` 成功;Vite 共转换 43 个模块。
- PyInstaller 6.22.0 / Python 3.12.12 构建成功,输出 `dist/DoctorWorkstation`。
- `Frozen Qt multimedia file gate passed.`
- `Frozen Qt multimedia smoke gate passed (--media-smoke-test, isolated offscreen mode).`
- `Frozen application entry smoke gate passed (--smoke-test, isolated offscreen mode).`
- 7-Zip 创建 ZIP 成功,输出 `Everything is Ok`;归档包含 180 个目录、3,011 个文件。
- Inno Setup 6.7.3 编译成功,输出 `Successful compile (165.062 sec)`。
- 正式安装包、ZIP 和校验清单均生成,脚本最终退出码为 0。
## 非阻断警告
- Vite 报告单个压缩后 chunk 超过 500 kB,仅为体积优化提示。
- PyInstaller 报告一个 Qt QML 插件二进制缺失,以及若干 Windows 系统 DLL 解析警告;这些警告未阻断构建,且脚本内置的多媒体文件门禁、多媒体离屏 smoke test 和应用入口 smoke test 全部通过。
## 真实安装器冒烟测试
- 执行命令:`powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File scripts\smoke_windows_installer.ps1 -Installer 'D:\web\zyt\app\dist\DoctorWorkstation-Setup-Windows-x64-1.2.0.exe'`
- 脚本退出码:`0`
- 脚本最终结果:`Installer icon/install/start/uninstall smoke test passed.`
- 隔离测试目录:`C:\Users\pc\AppData\Local\Temp\doctor-workstation-installer-smoke-ac84581babe94e28a0d0ffab63dd0b5f`
### 分阶段核对
- 静默安装:通过。安装器以 `/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /CURRENTUSER` 运行到隔离目录;`setup.log` 记录 `Installation process succeeded.` 和 `Need to restart Windows? No`。
- 安装内容:通过。脚本在启动前确认 `DoctorWorkstation.exe` 与 `unins000.exe` 均存在。
- 图标:通过。脚本分别提取安装器、已安装主程序及卸载器的 32×32 关联图标并计算 SHA-256;主程序与卸载器图标均和安装器品牌图标一致,否则脚本会失败。
- 启动 smoke:通过。已安装主程序在隔离配置、日志目录与 `QT_QPA_PLATFORM=offscreen` 环境下执行 `--smoke-test`,退出码为 0;应用日志记录 `doctor workstation starting`,未记录异常堆栈。
- 静默卸载:通过。卸载器以 `/VERYSILENT /SUPPRESSMSGBOXES /NORESTART` 运行,退出码为 0;`uninstall.log` 记录 `Uninstallation process succeeded.`、`Removed all? Yes` 和 `Need to restart Windows? No`。
- 残留检查:通过。卸载完成后独立确认隔离安装目录、`DoctorWorkstation.exe`、`unins000.exe`、当前用户开始菜单快捷方式及本次当前用户卸载注册表键均不存在。隔离测试根目录按设计保留,仅包含安装/卸载日志和隔离应用日志,便于审计。
+233
View File
@@ -0,0 +1,233 @@
# 医生工作站版本发布配置与更新 API 诊断
## 结论
当前仓库中,admin、server、app 三端的**现行契约是一致的**,但字段名不是扁平的
`package_type` / `download_url`。正式 wire contract 是:
```json
{
"code": 1,
"data": {
"has_update": true,
"force": false,
"enabled": true,
"current_version": "1.1.0",
"latest_version": "1.2.0",
"min_version": "",
"title": "...",
"notes": "...",
"platform": "windows",
"arch": "x64",
"package": {
"url": "https://.../DoctorWorkstation-Setup-Windows-x64-1.2.0.exe",
"sha256": "64 位十六进制值",
"size": 123,
"filename": "DoctorWorkstation-Setup-Windows-x64-1.2.0.exe",
"type": "inno_setup"
},
"can_install": true
}
}
```
因此:
- `latest_version` 是 `data` 下的顶层字段。
- `platform`、`arch` 是检测请求参数,同时在 `data` 下回显规范化后的值;它们不保存在发布配置中。
- 安装包对象叫 `package`。
- 安装包类型叫 `package.type`,不是顶层或同级的 `package_type`。
- 下载地址叫 `package.url`,不是 `download_url`。
- 哈希叫 `package.sha256`。
- 如果截图或线上响应实际出现的是扁平 `package_type`、`download_url`,当前 app 不会读取这些别名。这不是当前仓库 server 的输出,优先怀疑线上后端/代理为另一版本或只部署了部分提交。
当前工作区还存在一个已确认的发布物版本风险:运行时版本源已经是 `1.2.0`(`app/src/doctor_workstation/__init__.py:5-6`),但 `app/dist/SHA256SUMS.txt:1-2` 只登记了 `1.1.0` 的 EXE/ZIP,且本地 `DoctorWorkstation.exe` 文件版本也是 `1.1.0`。如果管理端把 `latest_version` 设为 `1.2.0`,却填入当前 `1.1.0` 安装包,客户端安装后仍会报告 `1.1.0`,下次启动会再次发现 `1.2.0`,形成重复升级提示。打包脚本明确从同一个 `__version__` 读取版本(`app/scripts/package_windows.ps1:68-76`),并用它生成 EXE/ZIP 名称(`:169-174`)及两者哈希(`:234-244`);发布前必须重新生成 `1.2.0` 产物。
> 本轮只读诊断没有修改生产代码。根目录 `AGENTS.md` 已读取;仓库中没有 `.trellis/` 目录。
## 1. Windows 64 位安装包字段如何进入保存请求
管理端类型定义把 Windows 包放在 `packages.windows_x64`,每个包固定包含
`url`、`sha256`、`size`、`filename`、`type`;其中 `type` 只允许
`archive | inno_setup`(`admin/src/api/setting/desktop_workstation.ts:3-24`)。保存接口是
`POST /setting.desktop_workstation/setConfig`(同文件 `:27-34`)。
页面的 Windows 区块来自平台键 `windows_x64`(`admin/src/views/setting/desktop_workstation/index.vue:196-224`),默认类型是 `inno_setup`(`:198-218`)。UI 字段与请求体的对应关系如下:
| 截图/UI 字段 | 保存请求字段 | 证据 |
|---|---|---|
| Windows 64 位安装包 | `packages.windows_x64` | `index.vue:221-224, 339-343` |
| 安装包类型 | `packages.windows_x64.type`,EXE 为 `inno_setup` | `index.vue:96-104, 305-309` |
| 安装包地址 | `packages.windows_x64.url` | `index.vue:113-123, 318-324` |
| SHA-256 | `packages.windows_x64.sha256` | `index.vue:144-150, 292-315` |
| 文件名 | `packages.windows_x64.filename` | `index.vue:152-162, 300-304` |
| 文件大小(字节) | `packages.windows_x64.size` | `index.vue:164-174, 300-304` |
| 最新版本号 | 顶层 `latest_version` | `index.vue:34-42, 330-344` |
选择文件后,页面在浏览器本地读取原始文件名和字节数,`.exe` 自动切换为
`inno_setup`,并用 Web Crypto 计算 SHA-256(`index.vue:292-315`)。上传成功后只把上传接口返回的 `data.uri`(次选 `data.url`)写入包的 `url`(`:318-328`)。最终点击保存时,页面显式组装三个平台的完整 `packages` 对象,而不是上传后自动发布(`:330-345`)。
虽然 API 封装调用写成 `request.post({ params })`,拦截器会在 POST 且没有 `data` 时把
`params` 移入 JSON body(`admin/src/utils/request/index.ts:20-38`),所以 PHP 收到的是上述嵌套 JSON,而不是查询字符串。
## 2. 后端如何校验和持久化
控制器用 POST 校验器接收请求,再交给逻辑层保存(`server/app/adminapi/controller/setting/DesktopWorkstationController.php:38-46`)。
正常管理端保存时的关键约束:
- 版本号需是纯数字分段格式(`server/app/adminapi/validate/setting/DesktopWorkstationValidate.php:48-57`)。
- 包类型只允许 `archive` / `inno_setup`,且 `inno_setup` 只允许 Windows x64(`:118-137`)。
- Inno Setup 若填写文件名,必须以 `.exe` 结尾(`:138-140`)。
- 显式 `http://` 的 Inno Setup 地址会被拒绝(`:141-143`)。
- 外部 http(s) 地址必须带 SHA-256,SHA-256 若非空必须是 64 位十六进制(`:144-152`)。
- 文件名最长 180 字节,size 必须是非负数(`:153-158`)。
逻辑层将标量分别保存为配置项,把所有平台包作为一个 `packages` 配置项保存:
- `enabled`
- `latest_version`
- `min_version`
- `force_update`
- `title`
- `notes`
- `packages`
证据为 `server/app/adminapi/logic/setting/DesktopWorkstationLogic.php:45-55`。其中
`latest_version` / `min_version` 会被正规化为三段版本,包则逐平台正规化
`url/sha256/size/filename/type`(`:180-205, 226-254`)。
`ConfigService::set()` 对数组执行 `json_encode(..., JSON_UNESCAPED_UNICODE)` 后写入 Config 模型的 `value` 字段;标量直接写入(`server/app/common/service/ConfigService.php:32-50`)。因此数据库中的逻辑形态是:
```text
type = desktop_workstation, name = latest_version, value = "1.2.0"
type = desktop_workstation, name = packages, value =
{"windows_x64":{"url":"...","sha256":"...","size":...,"filename":"...","type":"inno_setup"},...}
```
读取时,`ConfigService::get()` 会对合法 JSON 自动 `json_decode(..., true)`(同文件
`:65-85`),所以 `packages` 回到 PHP 数组。保存 URL 时会去掉当前站点/当前存储域名,读取给 API 时再补回绝对域名(`DesktopWorkstationLogic.php:231-252, 261-280`;`server/app/common/service/FileService.php:42-59, 69-78`)。本地 `uploads/...` 文件还会在缺失/无效时由 server 计算哈希、大小和文件名(`DesktopWorkstationLogic.php:309-331`)。
## 3. 检测 API 如何选择包和序列化响应
app 请求的端点是 `setting.desktop_workstation/check`(`app/src/doctor_workstation/services/app_update.py:29-35`)。控制器把 `check` 放进免登录列表(`server/app/adminapi/controller/setting/DesktopWorkstationController.php:26-29`),并把 GET 参数直接交给逻辑层(`:48-55`)。
客户端发送:
```text
current_version=<当前运行时版本>&platform=windows&arch=x64
```
证据为 `app_update.py:217-243`。server 将 `windows/win/win32/win64` 统一成
`windows`,把 `amd64/x86_64/x64` 统一成 `x64`,拼成配置键
`windows_x64`(`DesktopWorkstationLogic.php:125-153`)。也就是说,`platform` / `arch`
不是管理端发布字段,而是由客户端运行环境发给检测接口、用于选择
`packages.windows_x64` 的请求维度。
server 的检测响应由 `evaluate()` 直接组成(`DesktopWorkstationLogic.php:75-103`):
- `latest_version` 来自已保存的配置并正规化。
- `platform`、`arch` 是请求值正规化后的回显。
- `package` 是匹配平台的单个包,只有 `url` 和 `sha256` 都非空才返回,否则为 `null`。
- 包对象的键为 `url/sha256/size/filename/type`(`:272-280`)。
- `can_install = has_update && url 非空 && sha256 非空`。
- `force` 只有存在更新、命中强制策略并且有可安装包时才为 true。
控制器的 `data()` 最终封装为 `{code, show, msg, data}`(`server/app/common/controller/BaseLikeAdminController.php:50-60`;`server/app/common/service/JsonService.php:71-91`)。app 的 `ApiClient` 对 `code == 1` 返回 envelope 中的 `data`(`app/src/doctor_workstation/services/api_client.py:504-542`),因此 `parse_update_offer()` 收到的就是上面列出的 `data` 对象,而不是整个 envelope。
## 4. 与 app 客户端契约逐字段对照
| 语义 | server 实际输出 | app 实际读取 | 是否一致 |
|---|---|---|---|
| 最新版本 | `latest_version` | `data.get("latest_version")` | 一致(`DesktopWorkstationLogic.php:95`; `app_update.py:174-181`) |
| 平台 | `platform` | `data.get("platform")` | 一致(server `:99`; app `:147-150, 176-183`) |
| 架构 | `arch` | `data.get("arch")` | 一致(server `:100`; app `:147-150, 176-183`) |
| 安装包 | `package` object/null | `data.get("package")` | 一致(server `:101`; app `:151-153`) |
| 下载地址 | `package.url` | `package_payload.get("url")` | 一致(server `:275`; app `:154, 166-173`) |
| SHA-256 | `package.sha256` | `package_payload.get("sha256")` | 一致(server `:276`; app `:155, 184-188`) |
| 包类型 | `package.type` | `package_payload.get("type")` | 一致(server `:279`; app `:157-173`) |
| 文件大小 | `package.size` | `package_payload.get("size")` | 一致(server `:277`; app `:158-173`) |
| 文件名 | `package.filename` | `package_payload.get("filename")` | 一致(server `:278`; app `:156-173`) |
| 可安装 | `can_install` | `data.get("can_install")` + 客户端二次校验 | 一致但客户端更严格(server `:85-102`; app `:184-200`) |
客户端只认可 `archive` / `inno_setup`,且 Inno 只允许 Windows;它还要求 SHA-256
严格为 64 位小写十六进制、响应平台/架构必须与请求一致(`app_update.py:162-200`)。对于
`inno_setup`,下载 URL 还必须是 HTTPS(localhost 调试例外),随后下载内容要通过 SHA-256、size、`.exe` 后缀和 PE `MZ` 头校验(`:287-300, 360-397`)。UI 根据 `package.type` 分流:`inno_setup` 直接走 Windows 安装器,`archive` 则按 ZIP 解压(`app/src/doctor_workstation/ui/dialogs/app_update.py:423-449`)。
现有自动化也明确锁定了这个嵌套契约:server contract test 要求 Windows 包返回
`package.type == inno_setup`(`server/tests/DesktopWorkstationUpdateContractTest.php:34-62`);app test 用
`package.{url,sha256,size,filename,type}` 构造响应并验证接收(`app/tests/test_app_update.py:66-90`)。本轮实跑:
```text
php server/tests/DesktopWorkstationUpdateContractTest.php PASS
uv run pytest app/tests/test_app_update.py -q PASS (21 tests)
```
## 5. 根因候选(按优先级)
### A. `latest_version` 与实际安装包版本不一致(当前工作区已有直接证据)
当前版本源是 `1.2.0`,但现有 EXE/ZIP、SHA256SUMS 和冻结 exe 都是 `1.1.0`。如果截图中的管理端配置已经把最新版本发布为 `1.2.0`,当前 `1.1.0` 包不能作为它的安装包。表现为下载、安装可能成功,但应用重启后仍是旧版本并再次提示更新。
### B. 线上响应使用 `package_type` / `download_url` 扁平字段
当前 app 没有这两个 wire key 的兼容读取,仓库内也没有生成它们的 server 代码。如果截图中的实际网络响应是例如:
```json
{"latest_version":"1.2.0","package_type":"inno_setup","download_url":"...","sha256":"..."}
```
app 会因为没有 `package.url` 而得到 `package=None`,最终 `can_install=false`;即使把包放在
`package` 中但只给 `package_type`,客户端也会默认当成 `archive`,对 EXE 执行 ZIP 解压并失败。该情形应视为明确的协议不一致。
### C. admin / server / app 部署版本分叉,或 PHP OPcache 未刷新
Git 历史显示提交 `43e5411b6a8d2e625140c5dca8ddeb8492ba7daa` 才同步把
`type=inno_setup` 加入 admin、server 和 app。它之前的 server 会在保存/读取包时丢掉 `type`。
因此“管理页面已有 Inno Setup 下拉框,但 check 响应没有 `package.type`”最符合部分部署或旧 PHP 代码仍在运行,而不是当前源码的逻辑错误。
### D. SHA-256 非空但无效,server 与 app 的可安装判定强度不同
`evaluate()` 只检查 URL/哈希非空;app 要求恰好 64 位十六进制。通过正常管理端保存不会发生,因为 validator 会拦截;但旧数据、手工改库、另一服务写入配置时,可能出现 server 返回 `can_install=true`、app 最终降级为不可安装。
### E. 相对上传路径在 server 输出时被扩成 HTTP
validator 只对输入字符串显式以 `http://` 开头的 Inno URL 拒绝;`uploads/...` 相对路径可通过。响应时 `FileService::getFileUrl()` 按 `request()->domain()` 补域名。如果生产位于 HTTPS 反向代理后但 PHP 未正确识别代理协议,响应可能变成 `http://...`。app 会安全地拒绝自动执行这个 EXE。若截图中的 `package.url` 为 HTTP,应核对反向代理的 forwarded proto / trusted proxy 配置,而不是放宽客户端安全校验。
## 6. 建议修复与验证顺序
1. **先重新打 1.2.0 正式包再发布。** 保持 `app/src/doctor_workstation/__init__.py`、EXE 的 FileVersion/ProductVersion、安装包文件名、管理端 `latest_version` 四者全部为 `1.2.0`;从新生成的 `SHA256SUMS.txt` 复制 EXE 对应哈希,不要复用 1.1.0 的值。
2. **直接抓线上 check 响应。** 用与 app 一样的参数请求:
`GET /adminapi/setting.desktop_workstation/check?current_version=1.1.0&platform=windows&arch=x64`。确认有效数据位于 `data`,并且字段精确为 `data.package.url/type/sha256`。
3. **如果看到 `download_url/package_type`,统一契约。** 首选修 server 采用当前仓库的嵌套结构并整体部署;若必须兼容历史服务,可在 app 解析层短期接受别名,但 canonical 输出仍应只有 `package.{url,type,...}`,并补契约测试。
4. **如果 `package.type` 缺失,做完整部署并清 OPcache。** 同时部署 admin 静态资源、PHP controller/logic/validator 和新 app;不要只替换管理页面。
5. **核验 URL 与哈希。** `package.url` 必须是客户端可达的 HTTPS 绝对地址;下载文件 SHA-256 必须与 `package.sha256` 完全一致,size 若填写也必须一致。
6. **补一条跨端端到端 fixture。** 固化一个 Windows `inno_setup` 响应,既让 PHP `evaluate()` 产出 JSON,也让 Python `parse_update_offer()` 消费同一 fixture;另外增加扁平别名必须被拒绝(或在决定兼容后明确接受)的测试,避免字段名再次漂移。
## 最小正确发布样例
管理端保存体中的 Windows 部分:
```json
{
"enabled": 1,
"latest_version": "1.2.0",
"min_version": "",
"force_update": 0,
"title": "医生工作站 1.2.0",
"notes": "...",
"packages": {
"windows_x64": {
"url": "https://cdn.example.com/DoctorWorkstation-Setup-Windows-x64-1.2.0.exe",
"sha256": "<新 1.2.0 EXE 的 64 位 SHA-256>",
"size": 0,
"filename": "DoctorWorkstation-Setup-Windows-x64-1.2.0.exe",
"type": "inno_setup"
},
"macos_arm64": {"url":"","sha256":"","size":0,"filename":"","type":"archive"},
"macos_x64": {"url":"","sha256":"","size":0,"filename":"","type":"archive"}
}
}
```
不要把同一内容改名为顶层 `download_url` / `package_type`;当前 app 不消费该形态。
+447
View File
@@ -0,0 +1,447 @@
"""Read-only-ish timing probe for the desktop update commit sequence.
The probe imports production code and replaces only its external download/apply
edges in memory. It does not modify production sources or existing tests.
"""
from __future__ import annotations
import gc
import json
import os
import subprocess
import sys
import tempfile
import threading
import time
import weakref
from pathlib import Path
from types import SimpleNamespace
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import QCoreApplication, QEvent, QObject, QThreadPool, QTimer
from PySide6.QtWidgets import QApplication
from doctor_workstation.services import app_update as update_service
from doctor_workstation.services.app_update import (
PACKAGE_TYPE_INNO_SETUP,
UpdateOffer,
UpdatePackage,
)
from doctor_workstation.ui.dialogs import app_update as update_ui
def _record(events: list[dict[str, Any]], name: str, started: float) -> None:
events.append(
{
"event": name,
"elapsed_ms": round((time.perf_counter() - started) * 1000, 3),
"thread_id": threading.get_ident(),
}
)
def exercise_session(iterations: int = 25) -> dict[str, Any]:
app = QApplication.instance() or QApplication([])
main_thread = threading.get_ident()
original_edges = {
"is_frozen_install": update_ui.is_frozen_install,
"frozen_install_root": update_ui.frozen_install_root,
"download_package": update_ui.download_package,
"apply_downloaded_update": update_ui.apply_downloaded_update,
}
failures: list[dict[str, Any]] = []
samples: list[list[dict[str, Any]]] = []
collected_signals = 0
try:
with tempfile.TemporaryDirectory(prefix="zyt-update-commit-") as raw_tmp:
temp_root = Path(raw_tmp)
install_root = temp_root / "installed"
install_root.mkdir()
(install_root / "DoctorWorkstation.exe").write_bytes(b"MZ")
update_ui.is_frozen_install = lambda: True
update_ui.frozen_install_root = lambda: install_root
for index in range(iterations):
run_root = temp_root / f"run-{index}"
run_root.mkdir()
events: list[dict[str, Any]] = []
started = time.perf_counter()
def fake_download(
_url: str,
destination: Path,
*,
_events: list[dict[str, Any]] = events,
_started: float = started,
**kwargs: Any,
) -> Path:
_record(_events, "download_enter", _started)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(b"MZ" + b"probe")
progress = kwargs.get("progress")
if callable(progress):
progress(7, 7)
_record(_events, "download_return", _started)
return destination
def fake_apply(
_payload: Path,
*,
package_type: str,
_events: list[dict[str, Any]] = events,
_started: float = started,
) -> None:
assert package_type == PACKAGE_TYPE_INNO_SETUP
_record(_events, "apply_enter", _started)
_record(_events, "apply_return", _started)
update_ui.download_package = fake_download
update_ui.apply_downloaded_update = fake_apply
host = QObject()
host.config = SimpleNamespace( # type: ignore[attr-defined]
config_dir=run_root,
verify_ssl=True,
)
def request_quit(
_events: list[dict[str, Any]] = events,
_started: float = started,
) -> None:
_record(_events, "request_quit", _started)
host.request_quit = request_quit # type: ignore[attr-defined]
session = update_ui.AppUpdateSession(host)
offer = UpdateOffer(
has_update=True,
force=True,
enabled=True,
current_version="1.0.0",
latest_version=f"1.0.{index + 1}",
min_version="",
title="probe",
notes="probe",
platform="windows",
arch="x64",
package=UpdatePackage(
url="https://example.invalid/DoctorWorkstation-Setup.exe",
sha256="a" * 64,
size=7,
filename="DoctorWorkstation-Setup.exe",
type=PACKAGE_TYPE_INNO_SETUP,
),
can_install=True,
)
dialog = update_ui.AppUpdateDialog(offer)
session.dialog = dialog
original_finish = session._finish_install
original_finished = session._on_install_finished
def finish_probe(
*args: Any,
_events: list[dict[str, Any]] = events,
_started: float = started,
_original: Any = original_finish,
**kwargs: Any,
) -> None:
_record(_events, "result_slot_enter", _started)
_original(*args, **kwargs)
_record(_events, "result_slot_return", _started)
def finished_probe(
*args: Any,
_events: list[dict[str, Any]] = events,
_started: float = started,
_original: Any = original_finished,
**kwargs: Any,
) -> None:
_record(_events, "finished_slot_enter", _started)
_original(*args, **kwargs)
_record(_events, "finished_slot_return", _started)
session._finish_install = finish_probe # type: ignore[method-assign]
session._on_install_finished = finished_probe # type: ignore[method-assign]
session._start_install(dialog, offer)
signal_ref = weakref.ref(session._active_install_signals)
deadline = time.perf_counter() + 3.0
while time.perf_counter() < deadline:
app.processEvents()
if any(item["event"] == "request_quit" for item in events):
break
time.sleep(0.001)
QThreadPool.globalInstance().waitForDone(3000)
app.processEvents()
names = [item["event"] for item in events]
expected = [
"download_enter",
"download_return",
"result_slot_enter",
"apply_enter",
"apply_return",
"result_slot_return",
"finished_slot_enter",
"request_quit",
"finished_slot_return",
]
slot_threads = {
item["thread_id"]
for item in events
if item["event"] in {"result_slot_enter", "finished_slot_enter", "request_quit"}
}
if names != expected or slot_threads != {main_thread}:
failures.append(
{
"iteration": index,
"events": events,
"main_thread_id": main_thread,
}
)
if index < 3:
samples.append(events)
session.deleteLater()
dialog.deleteLater()
del session, dialog, host
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
app.processEvents()
gc.collect()
app.processEvents()
if signal_ref() is None:
collected_signals += 1
finally:
update_ui.is_frozen_install = original_edges["is_frozen_install"]
update_ui.frozen_install_root = original_edges["frozen_install_root"]
update_ui.download_package = original_edges["download_package"]
update_ui.apply_downloaded_update = original_edges["apply_downloaded_update"]
return {
"iterations": iterations,
"failures": failures,
"signals_collected_after_iteration": collected_signals,
"main_thread_id": main_thread,
"samples": samples,
}
def exercise_real_popen() -> dict[str, Any]:
if sys.platform != "win32":
return {"skipped": f"requires win32, got {sys.platform}"}
with tempfile.TemporaryDirectory(prefix="zyt-update-helper-") as raw_tmp:
temp_root = Path(raw_tmp)
script = temp_root / "probe_helper.ps1"
script.write_text(
"\n".join(
[
"param(",
" [int]$TargetPid, [string]$Installer, [string]$RestartExe,",
" [string]$HelperLogFile, [string]$InstallerLogFile",
")",
"Set-Content -LiteralPath $HelperLogFile -Value 'child-started'",
"Start-Sleep -Milliseconds 1200",
"Set-Content -LiteralPath $HelperLogFile -Value 'child-complete'",
]
),
encoding="utf-8-sig",
)
installer = temp_root / "Setup.exe"
installer.write_bytes(b"MZ")
restart = temp_root / "DoctorWorkstation.exe"
restart.write_bytes(b"MZ")
helper_log = temp_root / "helper.log"
fixed_log = temp_root / "fixed.log"
installer_log = temp_root / "installer.log"
original_script = script.read_text(encoding="utf-8-sig")
fixed_log_literal = str(fixed_log).replace("'", "''")
script.write_text(
original_script.replace(
"Set-Content -LiteralPath $HelperLogFile -Value 'child-started'",
"Set-Content -LiteralPath '"
+ fixed_log_literal
+ "' -Value (\"helper=<{0}> args=<{1}>\" -f $HelperLogFile, ($args -join '|'))\n"
+ "Set-Content -LiteralPath $HelperLogFile -Value 'child-started'",
),
encoding="utf-8-sig",
)
captured: list[subprocess.Popen[Any]] = []
captured_calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
real_popen = update_service.subprocess.Popen
def capture_popen(*args: Any, **kwargs: Any) -> subprocess.Popen[Any]:
captured_calls.append((args, kwargs.copy()))
process = real_popen(*args, **kwargs)
captured.append(process)
return process
update_service.subprocess.Popen = capture_popen
try:
started = time.perf_counter()
update_service._spawn_inno_setup_applier(
script,
installer=installer,
restart_exe=restart,
helper_log_file=helper_log,
installer_log_file=installer_log,
)
returned_ms = round((time.perf_counter() - started) * 1000, 3)
finally:
update_service.subprocess.Popen = real_popen
deadline = time.perf_counter() + 2.5
child_log = ""
while time.perf_counter() < deadline:
if helper_log.exists():
child_log = helper_log.read_text(encoding="utf-8").strip()
if child_log == "child-complete":
break
time.sleep(0.05)
return_code = captured[0].poll() if captured else None
if captured and return_code is None:
return_code = captured[0].wait(timeout=2.0)
matrix: dict[str, Any] = {}
if captured_calls:
command = list(captured_calls[0][0][0])
flag_cases = {
"zero": 0,
"detached": getattr(subprocess, "DETACHED_PROCESS", 0),
"new_process_group": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
"no_window": getattr(subprocess, "CREATE_NO_WINDOW", 0),
"detached_new_group": getattr(subprocess, "DETACHED_PROCESS", 0)
| getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
"detached_no_window": getattr(subprocess, "DETACHED_PROCESS", 0)
| getattr(subprocess, "CREATE_NO_WINDOW", 0),
"new_group_no_window": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
| getattr(subprocess, "CREATE_NO_WINDOW", 0),
"production_all": getattr(subprocess, "DETACHED_PROCESS", 0)
| getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
| getattr(subprocess, "CREATE_NO_WINDOW", 0),
}
running: dict[str, tuple[subprocess.Popen[Any], Path]] = {}
helper_parameter = command.index("-HelperLogFile") + 1
for name, flags in flag_cases.items():
case_command = command.copy()
case_log = temp_root / f"matrix-{name}.log"
case_command[helper_parameter] = str(case_log)
process = real_popen(
case_command,
close_fds=True,
creationflags=flags,
cwd=str(temp_root),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
running[name] = (process, case_log)
production_flags = flag_cases["production_all"]
detached_flags = flag_cases["detached"]
extra_cases = {
"production_close_false": (production_flags, False, False),
"production_all_devnull": (production_flags, True, True),
"detached_close_false": (detached_flags, False, False),
"detached_all_devnull": (detached_flags, True, True),
}
for name, (flags, close_fds, all_devnull) in extra_cases.items():
case_command = command.copy()
case_log = temp_root / f"matrix-{name}.log"
case_command[helper_parameter] = str(case_log)
stream_kwargs = (
{
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
}
if all_devnull
else {}
)
process = real_popen(
case_command,
close_fds=close_fds,
creationflags=flags,
cwd=str(temp_root),
**stream_kwargs,
)
flag_cases[name] = flags
running[name] = (process, case_log)
matrix_deadline = time.perf_counter() + 3.0
while time.perf_counter() < matrix_deadline:
if all(case_log.exists() for _, case_log in running.values()):
break
time.sleep(0.05)
for name, (process, case_log) in running.items():
matrix[name] = {
"flags": flag_cases[name],
"log_created": case_log.exists(),
"return_code": process.poll(),
}
control_return_code = None
control_stdout = ""
control_stderr = ""
if not fixed_log.exists() and captured_calls:
call_args, call_kwargs = captured_calls[0]
call_kwargs.update(
creationflags=0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
control = real_popen(*call_args, **call_kwargs)
control_stdout, control_stderr = control.communicate(timeout=5.0)
control_return_code = control.returncode
return {
"command": captured_calls[0][0][0] if captured_calls else [],
"spawn_returned_ms": returned_ms,
"child_completed": child_log == "child-complete",
"child_log": child_log,
"fixed_log": fixed_log.read_text(encoding="utf-8").strip()
if fixed_log.exists()
else "",
"child_return_code": return_code,
"flag_matrix": matrix,
"control_return_code": control_return_code,
"control_stdout": control_stdout,
"control_stderr": control_stderr,
}
def exercise_controller_quit() -> dict[str, Any]:
"""Run the production request_quit method against a real Qt event loop."""
from doctor_workstation.app import ApplicationController
app = QApplication.instance() or QApplication([])
events: list[str] = []
holder = SimpleNamespace(application=app, _shutting_down=False)
app.aboutToQuit.connect(lambda: events.append("aboutToQuit"))
QTimer.singleShot(
0,
lambda: (
events.append("request_quit_enter"),
ApplicationController.request_quit(holder),
events.append("request_quit_return"),
),
)
watchdog = QTimer()
watchdog.setSingleShot(True)
watchdog.timeout.connect(lambda: (events.append("watchdog"), app.quit()))
watchdog.start(1000)
started = time.perf_counter()
return_code = app.exec()
return {
"events": events,
"return_code": return_code,
"returned_ms": round((time.perf_counter() - started) * 1000, 3),
}
if __name__ == "__main__":
iteration_count = int(sys.argv[1]) if len(sys.argv) > 1 else 25
output = {
"session": exercise_session(iteration_count),
"real_popen": exercise_real_popen(),
"controller_quit": exercise_controller_quit(),
}
print(json.dumps(output, ensure_ascii=False, indent=2))
+200
View File
@@ -0,0 +1,200 @@
# AppUpdateSession 更新提交时序复现报告
日期:2026-08-28
环境:Windows、Python 3.12.13、PySide6 6.11.1、uv 0.11.8
范围:只读检查生产源码和现有测试;新增的唯一测试资产是
`app/research/update_commit_repro.py`,未修改生产源码和既有测试。
## 结论
1. **当前工作树中的 `result -> finished -> request_quit` 时序可以稳定复现为正确。**
100 次真实 `QThreadPool` 跨线程循环没有一次乱序或丢失:下载/prepare 在 worker
线程,`_finish_install()`、`_on_install_finished()` 和 `request_quit()` 都在 GUI 主线程。
2. **`_TaskSignals` 不会因局部变量释放而提前消失。** 安装期间它同时被 `_Task`、
`AppUpdateSession._signals` 和 `_active_install_signals` 强引用;`finished` 到达后才清空
session 引用。探针在主动 `gc.collect()` 后仍观察到 wrapper 存活,风险方向是残留/泄漏,
不是过早 GC 导致信号丢失。
3. **`ApplicationController.request_quit()` 本身有效。** 在真实 Qt 事件循环里,调用顺序是
`request_quit_enter -> request_quit_return -> aboutToQuit`,没有触发 1 秒 watchdog;本次
测量从进入事件循环到退出约 0.1 ms。
4. **`apply_downloaded_update()` 的 `Popen` 调用不阻塞 GUI。** 生产参数下
`_spawn_inno_setup_applier()` 约 2.7--4.7 ms 返回。
5. **真正可复现的安装失败位于 Windows helper 启动。** 当前代码组合
`DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW` 启动 Windows
PowerShell。调用会快速返回,PowerShell 进程退出码甚至是 0,但脚本没有执行第一条写日志
命令。标志矩阵表明:本机上任何包含 `DETACHED_PROCESS` 的组合都失败;去掉它后,
`CREATE_NEW_PROCESS_GROUP`、`CREATE_NO_WINDOW` 以及两者组合均能执行脚本。
6. **本机真实 18:08 更新尝试与复现完全一致。** 安装包和 `install_update.ps1` 都在
18:08:37 生成,证明 Qt `result` 已投递且 `_finish_install()` 已进入
`apply_downloaded_update()`;但同目录没有 `update_helper.log` 和 `inno_setup.log`,说明
helper 没有运行到脚本第 20 行的第一条 `Write-Log`。
因此,“下载完成后没有进入安装”的首要根因不是 `finished` 信号丢失,也不是
`request_quit()` 失效,而是 **`DETACHED_PROCESS` 令 PowerShell helper 静默不执行**。
当前源码仍会在 `finished` 后请求退出,所以如果现场描述为“窗口也一直不关闭”,这部分在当前
工作树中未能复现;现有日志更符合“应用已走到提交/退出路径,但安装器从未启动,因此没有安装
和重启”的用户观感。成功路径没有阶段日志,无法仅凭旧日志证明窗口具体关闭时刻。
## 源码时序
相关位置:
- `app/src/doctor_workstation/ui/dialogs/app_update.py:68-91`:`_Task.run()` 在同一个
`try/else/finally` 中先 `result.emit(result)`,再 `finished.emit()`。
- `app/src/doctor_workstation/ui/dialogs/app_update.py:503-555`:安装任务创建
`_TaskSignals`,保存到 `_signals` 和 `_active_install_signals`,然后连接
`progress/status/result/error/finished`。
- `app/src/doctor_workstation/ui/dialogs/app_update.py:601-641`:`result` 槽先设置
`_apply_committed=True` 并同步调用 `apply_downloaded_update()`;`finished` 槽随后清理活动
signals,并在 `_apply_committed` 或 `_exit_requested` 时调用 `_complete_quit()`。
- `app/src/doctor_workstation/app.py:1081-1086`:controller 通过
`QTimer.singleShot(0, application.quit)` 请求正常退出。
- `app/src/doctor_workstation/app.py:427,1088-1105`:`aboutToQuit` 同步进入幂等
`shutdown()`,更新 session 先被 invalidated,再清理视频和 remote client。
- `app/src/doctor_workstation/services/app_update.py:637-672`:Inno helper 的 Windows
`Popen` 和三个 creation flags。
必须注意一个 Qt 细节:worker 发出 `result` 后不会等待 GUI 槽执行,紧接着就发出
`finished`;两者作为同一 sender 的跨线程事件按连接顺序排入 GUI 队列。本次 100 次实测均为:
```text
worker: download/prepare return
-> GUI: result slot enter
-> GUI: apply_downloaded_update enter/return
-> GUI: result slot return
-> GUI: finished slot enter
-> GUI: request_quit
```
这也意味着:如果 `apply_downloaded_update()` 真正阻塞,排在它后面的 `finished` 和 quit 会一起
延迟。但本机真实 `Popen` 返回只需数毫秒,未观察到阻塞。
## 复现结果
### 1. 现有测试
```powershell
$env:QT_QPA_PLATFORM='offscreen'
uv run --project app pytest app/tests/test_app_update_ui.py app/tests/test_app_update.py -q
```
结果:`28 passed`。
现有 `test_session_waits_for_update_worker_before_quitting` 是直接调用私有槽的同步单元测试,能够
检查状态门禁,但没有经过 `QThreadPool`/Qt queued delivery;这正是独立探针需要补足的部分。
### 2. 独立跨线程与 helper 探针
```powershell
$env:QT_QPA_PLATFORM='offscreen'
uv run --project app python app/research/update_commit_repro.py 100
```
关键结果:
```text
session.iterations = 100
session.failures = []
worker thread != GUI thread
result_slot_enter.thread_id == finished_slot_enter.thread_id
request_quit.thread_id == GUI main thread
_spawn_inno_setup_applier return = 约 3 ms
production flags script log created = false
production PowerShell return code = 0
controller quit events =
request_quit_enter, request_quit_return, aboutToQuit
```
Windows 创建标志矩阵:
| creation flags | 脚本是否执行 |
|---|---:|
| `0` | 是 |
| `CREATE_NEW_PROCESS_GROUP` | 是 |
| `CREATE_NO_WINDOW` | 是 |
| `CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW` | 是 |
| `DETACHED_PROCESS` | 否 |
| `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` | 否 |
| `DETACHED_PROCESS | CREATE_NO_WINDOW` | 否 |
| 当前生产三标志组合 | 否 |
将 `close_fds` 改为 false,或给 stdin/stdout/stderr 全部接 `DEVNULL`,均不能挽救包含
`DETACHED_PROCESS` 的组合。
### 3. 真实运行残留
本机目录:
```text
C:\Users\pc\AppData\Local\ZhenYangTang\ZhenyangDoctor\updates\1_3_0\
```
18:08:37 已有:
- `DoctorWorkstation-Setup-Windows-x64-1.1.0.exe`
- `install_update.ps1`
不存在:
- `update_helper.log`
- `inno_setup.log`
`install_update.ps1` 只会在 `_finish_install() -> apply_downloaded_update() ->
apply_inno_setup_update()` 中生成,所以这组残留直接排除了“result 未投递”和
“`_TaskSignals` 被提前回收”。脚本第一项业务动作就是写 `waiting for pid ...`;没有 helper log
则失败发生在脚本业务逻辑之前。
另有一个独立的发布数据风险:workspace 名为 `1_3_0`,下载文件名却是 `1.1.0`,而请求中的
当前版本是 `1.2.0`。即使 helper 启动成功,也可能尝试降级安装。服务端 offer 的
`latest_version`、package filename、安装器 FileVersion/产品版本需要在发布端和客户端都做一致性
校验。这不是本次 helper 不启动的直接原因,但上线前必须处理。
## 建议修复方向
1. Windows helper 不使用 `DETACHED_PROCESS`;先验证保留
`CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW` 时,父进程结束后 helper 仍能存活并运行。
2. 不把 `Popen()` 成功等同于 helper 已启动。让 helper 在等待目标 PID 前先原子写一个
`ready`/`waiting` 标记,应用收到握手后才设置最终 commit 并退出;握手超时则留在应用内显示
明确错误。
3. 给成功路径补结构化日志:`prepare_result_received`、`helper_spawn_requested`、
`helper_ready`、`worker_finished`、`request_quit`、`about_to_quit`。当前只有异常日志,现场无法
区分“100% 后仍在 fsync/校验”“helper 启动失败”和“quit 清理较慢”。
4. 对 package 声明版本和安装器版本做一致性校验,拒绝低于当前版本或不同于
`latest_version` 的安装器。
## 建议回归测试
### Qt/session 测试
1. **真实 queued delivery 成功路径**:用 `QThreadPool` 启动 `_Task`,以 event loop 等待,断言
`result slot -> apply return -> finished slot -> request_quit` 严格顺序,并断言所有 UI/controller
槽都在 GUI 线程。
2. **signals 生命周期**:启动任务后删除局部 worker/signals 引用并强制 GC,仍应收到 result 和
finished;finished 后断开连接并 `deleteLater()`,最终 weakref 应释放,避免长期检查导致残留。
3. **apply 门控**:用 `Event` 暂停 fake apply,断言暂停期间不会调用 quit;释放后 finished 只触发
一次 quit。
4. **apply 失败**:`apply_downloaded_update()` 抛 `AppUpdateError` 时不 quit、
`_apply_committed` 恢复 false;另外补非 `AppUpdateError` 异常,避免意外异常留下 commit=true 后
仍被 finished 退出。
5. **controller 集成**:在真实 `QApplication.exec()` 中调用 controller `request_quit()`,spy
`aboutToQuit`、`app_updater.shutdown()` 和远程 client close,断言各一次且总时长有上界。
### Windows helper 测试
1. **sentinel 启动测试(当前代码应失败)**:生成只写 sentinel 的 PowerShell 文件,使用生产
`_spawn_inno_setup_applier()` 启动,2 秒内必须看到 sentinel;不能只断言 `Popen` 被调用。
2. **父进程退出测试**:子 Python 进程启动 helper 后立即退出;helper 应先记录 waiting/ready,
再观察父 PID 消失并写第二个 sentinel,证明去掉 `DETACHED_PROCESS` 后不会被父退出连带杀死。
3. **完整握手测试**:应用只有在 helper ready 后才调用 quit;helper 未 ready、提前退出或无法写
日志时,应用保留并展示可重试错误。
4. **打包 smoke**:从实际 PyInstaller onedir/installer 环境执行上述测试,不能只在源码虚拟环境
mock `subprocess.Popen`。
## 仓库说明
根 `AGENTS.md` 声明项目由 Trellis 管理,但当前工作区没有 `.trellis/` 目录,因而无法读取
`.trellis/workflow.md` 或 layer spec;本次按根指令执行并在此记录。工作树原本已有大量未提交
修改,本次没有改动其中任何生产源码或既有测试。
@@ -0,0 +1,134 @@
# Doctor Workstation 1.3.0 Windows 正式包构建与安全验证结果
- 执行日期:2026-08-28(Asia/Shanghai)
- 工作目录:`D:\web\zyt\app`
- 结论:通过。1.3.0 Windows 安装器与 ZIP 已重新构建;冻结媒体/入口门禁、隔离安装/启动/卸载冒烟和真实 Windows helper bootstrap 专项测试全部通过。
- 安全边界:未修改生产源码或既有测试,未执行 reset/checkout,未访问现场服务端,也未用 `dist` 中旧的 1.1.0 安装器覆盖真实安装。安装器冒烟显式指定 1.3.0 文件并仅安装到随机临时目录。
## 最终产物
| 产物 | 字节数 | SHA-256 |
| --- | ---: | --- |
| `D:\web\zyt\app\dist\DoctorWorkstation-Setup-Windows-x64-1.3.0.exe` | 162917310 | `E1734C7B5E1619951AF81082FC4578D50BD881B5CD8C7AC7F4E658E8E28B74A7` |
| `D:\web\zyt\app\dist\DoctorWorkstation-Windows-x64-1.3.0.zip` | 230820285 | `FAF2D4A68065C1ED528A1D887B5210B44FACBEBBC1CB89729FA3B690D7995CEF` |
`dist\SHA256SUMS.txt` 与重新计算的两个 SHA-256 完全一致。
## 命令、退出码与结果
以下命令均从 PowerShell 执行;未特别注明时工作目录为 `D:\web\zyt\app`。
### 1. 项目约束与 Trellis 检查
```powershell
Get-Content -LiteralPath 'D:\web\zyt\AGENTS.md' -Raw
if (Test-Path -LiteralPath 'D:\web\zyt\.trellis') { Get-ChildItem ... } else { 'NO_TRELLIS' }
```
- 退出码:`0`
- 结果:根 `AGENTS.md` 已完整读取;`D:\web\zyt\.trellis` 不存在,因此没有可继续读取的 `.trellis/workflow.md` 或分层 spec。
### 2. 初始共享工作树与构建输入只读检查
```powershell
git status --short
Get-Content src\doctor_workstation\__init__.py
Get-Content scripts\package_windows.ps1
Get-Content scripts\smoke_windows_installer.ps1
rg -n "bootstrap|ready|helper|windows" tests\test_app_update.py
Get-ChildItem dist -File
```
- 退出码:`0`
- 结果:开始时共享工作树已有大量未提交源码/测试变更和研究文件,均视为他人工作并保留;确认构建、安装器冒烟与 helper 测试入口存在。`dist` 内旧 1.1.0/1.2.0 包仅被列出,没有被安装或复制到真实安装位置。
### 3. 版本源逐行及实际导入检查
```powershell
[System.IO.File]::ReadAllLines((Resolve-Path 'src\doctor_workstation\__init__.py'))
.\.venv\Scripts\python.exe -c "import doctor_workstation; print(repr(doctor_workstation.__version__)); print(repr(doctor_workstation.DEBUG_MODE)); print(repr(doctor_workstation.ONLINE_API_BASE_URL))"
```
- 退出码:`0`
- 结果:`__version__ == '1.3.0'`;`DEBUG_MODE is False`;线上 API 基址为 `https://admin.zhenyangtang.com.cn`。
### 4. 打包脚本内置冻结门禁确认
```powershell
rg -n "runtime_media_smoke|smoke|entry|frozen|media|DoctorWorkstation.exe|--smoke" scripts\package_windows.ps1 scripts\build_windows.ps1 packaging\runtime_media_smoke.py
```
- 退出码:`0`
- 结果:确认 `build_windows.ps1` 在构建后依次执行冻结 Qt 多媒体文件门禁、`--media-smoke-test` 冻结进程门禁和 `--smoke-test` 应用入口门禁。
### 5. 1.3.0 Windows 正式包重建
```powershell
& .\scripts\package_windows.ps1
```
- 退出码:`0`
- 关键结果:
- `uv sync --frozen --extra build` 成功;构建环境使用 Python 3.12.12、PyInstaller 6.22.0。
- `npm ci` 成功,视频伴侣生产构建成功(Vite 6.1.1,43 modules transformed)。
- PyInstaller onedir 冻结成功,输出 `dist\DoctorWorkstation\DoctorWorkstation.exe`。
- `Frozen Qt multimedia file gate passed.`
- `Frozen Qt multimedia smoke gate passed (--media-smoke-test, isolated offscreen mode).`
- `Frozen application entry smoke gate passed (--smoke-test, isolated offscreen mode).`
- 7-Zip 创建 1.3.0 ZIP 成功;Inno Setup 6.7.3 编译 1.3.0 安装器成功。
- 脚本打印的最终哈希与本报告“最终产物”一致。
- 非阻塞警告:Vite 报告单个 JS chunk 大于 500 kB;PyInstaller 报告一个可选 QML asset downloader 插件二进制不存在及若干 Windows 系统 DLL 静态解析警告。它们未阻断构建,且后续冻结媒体实际进程、应用入口及安装后启动门禁全部通过。
### 6. 新安装器隔离安装/启动/卸载冒烟
```powershell
& .\scripts\smoke_windows_installer.ps1 -Installer (Resolve-Path -LiteralPath '.\dist\DoctorWorkstation-Setup-Windows-x64-1.3.0.exe').Path
```
- 退出码:`0`(PowerShell 进程退出码)
- 结果:`Installer icon/install/start/uninstall smoke test passed.`
- 隔离目录:`C:\Users\pc\AppData\Local\Temp\doctor-workstation-installer-smoke-14b72f4137814eea8ede6bc48920f5f5`
- 覆盖项:安装器/主程序/卸载器图标一致;安装目录内主程序和卸载器存在;安装后主程序 `--smoke-test` 返回 0;卸载返回 0;卸载后主程序不再存在。
- 安全说明:脚本使用随机 `%LOCALAPPDATA%\Temp\doctor-workstation-installer-smoke-*\install`,环境变量、配置与日志均隔离;命令显式锁定 1.3.0 安装器,没有调用 1.1.0 包或现场服务端。
### 7. 真实 Windows helper bootstrap 专项测试
```powershell
.\.venv\Scripts\python.exe -m pytest 'tests\test_app_update.py::test_inno_helper_executes_bootstrap_with_production_flags' -q
```
- 退出码:`0`
- 结果:`1 passed`(单点输出为 `.`)。该测试未 mock `subprocess.Popen`,会真实启动 PowerShell helper,并由测试生成的 helper 脚本在收到生产参数集后写入 ready 文件;最后断言 ready 文件内容为 `ready`,因此确认生产 flags 下 ready 握手实际产生。
### 8. 最终版本/生产 flag 复核及独立哈希核验
```powershell
.\.venv\Scripts\python.exe -c "import doctor_workstation; assert doctor_workstation.__version__ == '1.3.0'; assert doctor_workstation.DEBUG_MODE is False"
Get-Item .\dist\DoctorWorkstation-Setup-Windows-x64-1.3.0.exe
Get-FileHash .\dist\DoctorWorkstation-Setup-Windows-x64-1.3.0.exe -Algorithm SHA256
Get-Item .\dist\DoctorWorkstation-Windows-x64-1.3.0.zip
Get-FileHash .\dist\DoctorWorkstation-Windows-x64-1.3.0.zip -Algorithm SHA256
Compare-Object <重新计算的两行> (Get-Content .\dist\SHA256SUMS.txt)
```
- 退出码:`0`
- 结果:版本和 `DEBUG_MODE` 断言通过;EXE/ZIP 字节数和哈希如“最终产物”所列;`Compare-Object` 无差异。
### 9. 完成前共享工作树/产物复查
```powershell
git status --short
Get-ChildItem .\dist -File | Where-Object { $_.Name -match '1\.3\.0|SHA256SUMS' } | Select-Object Name,Length,LastWriteTime
```
- 退出码:`0`
- 结果:1.3.0 EXE、ZIP 和新 `SHA256SUMS.txt` 均存在;本任务未编辑生产源码或测试。完成复查时仍可见共享工作树中的既有 `src/doctor_workstation/services/app_update.py` 修改,未回退或覆盖。
## 验收结论
1. 版本/发布开关正确:`1.3.0`、`DEBUG_MODE=False`。
2. 正式 EXE/ZIP 重建成功,内置三项冻结门禁全部通过。
3. 1.3.0 安装器隔离安装、启动、卸载和残留检查通过。
4. 真实 Windows helper bootstrap 在生产 flags 下成功生成 ready 文件。
5. 最终大小与 SHA-256 已独立复核,且与 `SHA256SUMS.txt` 一致。
6. 未触碰真实安装或现场服务端 1.1.0 包。
@@ -0,0 +1,115 @@
# Windows 更新安装交接故障诊断
## 结论
“下载完成后显示即将关闭,但程序不退出/不安装”不是下载失败。当前现场同时存在三个问题,其中第 1 项能够确定性复现用户看到的主症状,第 2 项是本次现场已经发生但被代码吞掉的 helper 启动失败,第 3 项是必须立即纠正的发布配置错误。
1. **确定性根因:强制更新对话框拒绝了 `QApplication.quit()` 触发的关闭事件。** 下载 job 完成后,session 启动 helper、设置 `_apply_committed=True`,随后在 `finished` 回调中调用应用级 `request_quit()`;但对话框此时仍是 `offer.force=True` 且 `_busy=True`,其 `closeEvent()` 无条件 `ignore()`。Qt 明确允许窗口通过 Close event 阻止 `quit()`,所以事件循环不退出,`aboutToQuit`/`ApplicationController.shutdown()` 也不会发生。helper 又先等待当前 PID 消失,于是交接形成闭环等待。
2. **独立的已确认问题:PowerShell helper 进程被创建后,在执行脚本首条日志之前就退出了,而父进程把“CreateProcess 成功”误判成“helper 已接管”。** 现场有精确的 PowerShell 启动事件,但没有 `update_helper.log`、没有 `inno_setup.log`、没有存活 helper/installer 进程。代码丢弃 `Popen` 句柄、不检查早退、也没有 ready handshake,因此 UI 仍停在“即将关闭”。现有证据不足以还原该次子进程的退出码;这正是当前可观测性缺口。
3. **发布配置错误:服务端宣称最新/最低版本为 `1.3.0`,实际下发的安装器却是 `1.1.0`。** 本机当前运行 `1.2.0`,所以即使退出与 helper 均修复,也会尝试降级安装,而不是升级到 `1.3.0`。修复客户端前应先停止这条强制更新配置。
## 代码交接链路与根因证据
### 1. UI 已经请求退出,但强制对话框否决退出
当前交接顺序是:
1. `_start_install()` 设置 busy、启动 QThreadPool 下载 job(`app/src/doctor_workstation/ui/dialogs/app_update.py:481-555`)。
2. job 下载并校验 Inno Setup EXE,返回 `_PreparedUpdate`(`:511-545`)。
3. `_finish_install()` 先显示“即将关闭程序并自动安装”,再调用 `dialog.set_apply_committed()`;该方法把 `_busy` 保持为 true(`:616-628`、`:275-283`)。
4. `apply_downloaded_update()` 进入 `apply_inno_setup_update()`,写脚本并 `Popen` PowerShell helper(`app/src/doctor_workstation/services/app_update.py:429-472`)。
5. QRunnable 随后发送 `finished`,`_on_install_finished()` 清理 active signals 并调用 `_complete_quit()`(UI `:634-641`)。
6. `_complete_quit()` 调用 controller `request_quit()`;controller 用 `QTimer.singleShot(0, self.application.quit)` 请求正常退出(UI `:472-479`;`app/src/doctor_workstation/app.py:1081-1086`)。
7. 但是更新对话框的 `closeEvent()` 在 `offer.force` **或** `_busy` 为真时执行 `event.ignore()`(UI `:296-300`)。此时两个条件都为真。
使用当前 PySide6 做了不改文件的最小事件循环复现:显示一个 modal dialog,其 `closeEvent()` 执行 `ignore()`,50 ms 后调用 `QApplication.quit()`,并设置 2 秒进程级 watchdog。输出为:
```text
calling quit
closeEvent ignored
CODE=9
```
也就是 `quit()` 确实到达了窗口,但被 Close event 否决,事件循环直到 watchdog 才终止。Qt 官方文档同样说明 `QCoreApplication.quit()` 可能被仍未关闭的窗口或被忽略的 Quit/Close event 阻止:<https://doc.qt.io/qt-6/qcoreapplication.html#quit>。
这也解释了为何 controller 的 `aboutToQuit -> shutdown()` 接线本身没有帮助:`aboutToQuit` 只有在退出请求未被阻止时才会发出(`app.py:425-427`、`:1088-1105`)。
### 2. Inno helper 的等待设计放大了 UI 退出缺陷
生成的 `install_update.ps1` 首先写 `waiting for pid ...`,然后无限轮询 `Get-Process -Id $TargetPid`;只有目标 PID 消失后才启动安装器(service `:566-627`)。父进程传入的是 `os.getpid()`(`:637-672`)。因此,只要 Qt 主进程被对话框留下,安装器就不可能启动。
安装器参数本身与 Inno 静默更新意图一致:`/VERYSILENT`、`/SUPPRESSMSGBOXES`、`/NORESTART`、`/CLOSEAPPLICATIONS`、`/NOFORCECLOSEAPPLICATIONS`、`/NORESTARTAPPLICATIONS`、`/LOG=...`;返回 `0`/`3010` 后才重启已安装的 `DoctorWorkstation.exe`,其他返回码重启旧程序(`:599-627`)。`powershell.exe -File <script> <script args>` 的排列也符合 Windows PowerShell 5.1 的 `-File` 契约:<https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1>。
不过当前等待还有两个健壮性问题:
- 循环无超时、只按整数 PID 查询;极端情况下 PID 被复用会继续等待无关进程。更安全的是先取得特定 `Process` 对象/句柄,再等待该对象退出,而不是每 400 ms 重新按 ID 查找。
- helper 的成功标准只是 `subprocess.Popen(...)` 没有同步抛出 `OSError`。`Popen` 返回后句柄立即丢失,没有 child PID 日志、早退检测、stderr 捕获或 ready handshake(`:637-672`)。
当前还同时设置 `DETACHED_PROCESS`、`CREATE_NEW_PROCESS_GROUP`、`CREATE_NO_WINDOW`(`:645-670`)。Microsoft 文档指出 `CREATE_NO_WINDOW` 与 `DETACHED_PROCESS` 同用时会被忽略,因此这组 flag 至少是冗余且不能证明 helper 已进入脚本:<https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags>。本次现场只能确认 PowerShell 在脚本体前早退,不能仅凭事件日志断言具体是 flag、stdio、执行策略还是主机初始化中的哪一个原因;修复应以“可确认接管”为契约,而不是猜一个退出原因。
### 3. `apply_downloaded_update()` 的路由本身正确
`package_type=inno_setup` 会进入 `apply_inno_setup_update()`;后者要求 Windows、可解析的 frozen install root、存在的已安装 EXE,以及扩展名为 `.exe` 且 DOS header 为 `MZ` 的安装器(service `:390-401`、`:429-483`)。现场已经生成 `install_update.ps1`,证明路由、install root、EXE/PE 基本校验均已通过;故障发生在 helper 启动及应用退出交接之后。
## 本机现场证据(2026-08-28,Asia/Shanghai)
- 运行进程:PID `36304`,`C:\Program Files\ZYT\DoctorWorkstation\DoctorWorkstation.exe`,启动于 `18:08:13`;检查时仍 `Responding=True`、主窗口可见,文件 `ProductVersion=1.2.0`。
- 应用日志:`C:\Users\pc\AppData\Local\Zhenyangtang\ZhenyangDoctor\Logs\doctor-workstation.log`。
- `18:08:13`:应用启动。
- `18:08:15`:以 `current_version=1.2.0&platform=windows&arch=x64` 检查更新成功。
- `18:08:32`:下载 `DoctorWorkstation-Setup-Windows-x64-1.1.0.exe` 返回 HTTP 200。
- 此后没有安装/helper/退出阶段日志,也没有 Python 异常。
- 工作区:`C:\Users\pc\AppData\Local\Zhenyangtang\ZhenyangDoctor\updates\1_3_0`。
- 安装器大小 `162,873,123` 字节,SHA-256 `0CDD38DB6EEF5E7B7380FFAE3FBC407B602EB916C68AE4C8F29496B621F50789`,`ProductVersion=1.1.0`,未签名。
- `install_update.ps1` 在 `18:08:37` 生成,PowerShell AST 解析无语法错误。
- `update_helper.log` 不存在;`inno_setup.log` 不存在。
- Windows PowerShell Operational 日志:`18:08:37.828` 有 Event `40961`“Powershell 控制台正在启动”,没有配对的 ready `40962`;检查时也没有命令行指向 `install_update.ps1` 的 PowerShell 或 Inno Setup 进程。这证明子进程被创建过,但没有进入脚本首条 `Write-Log`。
- crash log 只有各次进程启动标记,本次没有崩溃堆栈。
- 实时只读请求更新接口得到:`latest_version=1.3.0`、`min_version=1.3.0`、`force=true`,但 URL、filename、size、sha256 全都对应上述 `1.1.0` 安装器。本机实测文件 hash 与接口 SHA 一致,说明下载正确,错误在发布元数据/产物绑定。
## 最小安全修复
### P0:先修发布配置
在正确的 `1.3.0` 安装器上传并核对 `ProductVersion`、filename、size、SHA-256 前,立即关闭这条强制更新或将其设为不可安装。不要让 `latest_version=1.3.0` 继续绑定 `1.1.0` 安装器。客户端后续应增加“offer 版本与包版本”的发布门禁;仅校验 HTTPS、SHA 和 `MZ` 不能防止签名正确的旧包被错误发布。
### P0:让应用级退出能够越过“用户不可关闭”的对话框门禁
不要把“禁止用户关闭强制更新弹窗”和“禁止应用已提交后的受控退出”共用同一个 `closeEvent` 条件。建议增加明确的 `_allow_application_exit` 状态:
- 用户点击标题栏关闭/Escape 时仍然拒绝;
- helper 已确认接管,或用户点击专用“退出软件”且更新 worker 已安全结束时,session 先设置 allow 状态并关闭/隐藏该 dialog,再调用 controller `request_quit()`;
- `closeEvent()` 仅在 `not _allow_application_exit and (offer.force or _busy)` 时 ignore。
直接在主线程调用 `QCoreApplication.exit(0)`也能绕过 Close event,但会绕过其他窗口的正常 close 协议;相比之下,显式放行本更新对话框后继续走既有 `QApplication.quit -> aboutToQuit -> shutdown` 更小、更安全。
### P0:把 helper“已接管”变成可验证状态
`_spawn_inno_setup_applier()` 应返回并保留 `Popen`/child PID,且 helper 在做任何 PID 等待前原子写入 ready 标记(或首条结构化 bootstrap log)。父进程应异步等待一个很短且有界的 ready 窗口:
- ready 到达且 child 仍存活后,才设置 `_apply_committed=True`、放行 dialog close、请求主程序退出;
- child 在 ready 前退出时,读取退出码/bootstrap stderr,留在当前 UI 显示错误,不退出主程序;
- 使用 `-NonInteractive`,明确重定向 stdin/stdout/stderr 到日志或 `DEVNULL`;规范化 creation flags,不同时依赖会被忽略的 `DETACHED_PROCESS + CREATE_NO_WINDOW`;
- helper 顶层捕获脚本初始化、首条日志、PID wait、安装器启动等所有异常,并写明阶段和退出码。
这样即使本次 PowerShell 早退的底层原因在另一台机器上不同,也不会再出现“UI 已锁死并宣称即将关闭,但其实无人接管”的假成功。
## 建议测试
现有 `app/tests/test_app_update.py` 与 `app/tests/test_app_update_ui.py` 共 `28 passed`,但没有覆盖真实交接:service 测试只截获 `_spawn_inno_setup_applier` 并检查脚本文本;UI 测试只断言 mock `host.request_quit` 被调用,没有运行 `QApplication` 事件循环,也没有验证强制 dialog 是否会否决 quit。现有 installer smoke 直接执行安装器,也绕过了应用退出与 helper。
建议至少增加:
1. **Qt 子进程回归(必须)**:显示 `force=True` 且 busy/apply committed 的真实 `AppUpdateDialog`,触发 session 完成退出,以 watchdog 保底;断言事件循环正常返回 `0`、`aboutToQuit` 发生,而不是被 `closeEvent` 卡住。
2. **显式退出路径**:强制更新下载中点击“退出软件”,worker `finished` 后同样能退出;result 已排队但退出先处理时不得启动 helper。
3. **helper ready 成功**:使用临时 noop PowerShell fixture 和真实生产 creation flags,断言 child PID、ready、等待目标进程退出、后续阶段按顺序发生,并覆盖路径含空格。
4. **helper 早退**:脚本缺失/解析失败/首条日志失败时,断言父进程取得非零退出码、不设置 committed、不退出、UI 可重试且有明确日志路径。
5. **PID 身份**:目标进程退出后即使整数 PID 被模拟复用,也不会等待或误伤新进程;等待有诊断超时但绝不在无法确认旧进程退出时启动安装。
6. **隔离端到端 Inno 更新**:从一个测试 frozen app 发起 handoff,确认旧 PID 消失、helper log 产生、安装器 log 产生、目标版本真正安装、只重启一次。不要只测试安装器单独运行。
7. **发布契约**:服务端 `latest_version`、package filename/manifest `ProductVersion`、SHA/size 必须属于同一版本;构造 `latest=1.3.0 + package=1.1.0` 时发布或客户端安装必须失败。
## 审阅边界
- 已读取根 `AGENTS.md`;仓库不存在 `.trellis/`,因此没有额外 workflow/spec 可读取。
- 工作树原本已有大量未提交改动,包括本报告涉及的生产文件和测试;本次未修改、覆盖或回退它们。
- 除新增本文档外,没有修改生产代码或测试。
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+29
View File
@@ -0,0 +1,29 @@
# Bundled Noto Sans SC
`NotoSansSC-VF.ttf` is the unmodified Google Fonts distribution of
`NotoSansSC[wght].ttf`, stored under a filename without brackets for simpler
resource lookup. No font bytes were changed or subsetted locally.
- Qt family: `Noto Sans SC`
- Font version: `Version 2.004-H2;hotconv 1.0.118;makeotfexe 2.5.65603`
- Variable axis: `wght`, 100–900; named instances at every 100, including 600.
- Size: 17,772,300 bytes.
- SHA-256: `a3041811a78c361b1de50f953c805e0244951c21c5bd412f7232ef0d899af0da`
- Official repository revision: `google/fonts@5e35378e6bda803962ee6fd257e444a7d459660d`.
- [Pinned font source](https://github.com/google/fonts/blob/5e35378e6bda803962ee6fd257e444a7d459660d/ofl/notosanssc/NotoSansSC%5Bwght%5D.ttf).
- [Pinned license source](https://github.com/google/fonts/blob/5e35378e6bda803962ee6fd257e444a7d459660d/ofl/notosanssc/OFL.txt).
The font is distributed under the SIL Open Font License 1.1. Retain
`OFL-NotoSansSC.txt`, including its copyright notice, when redistributing the
font with the application. The license applies to the font, independently of
the application's license.
Load this local resource through `QFontDatabase.addApplicationFont` after
creating `QApplication`, then use the returned family name. The application
must not fetch fonts at runtime. The PyInstaller spec already copies the
entire `resources` directory, including this directory and its license.
Google Fonts supplies explicit Regular (400), Medium (500), and SemiBold (600)
instances. The Noto CJK upstream 2.004 file lacks a named 600 instance and Qt
may select Medium for a plain `font-weight: 600` request; this distribution
preserves distinct results with the application's normal QSS font weights.
+24 -2
View File
@@ -169,8 +169,30 @@ try {
& $Npm run build --prefix $CompanionRoot
if ($LASTEXITCODE -ne 0) { throw "video companion build failed" }
& $Python -m PyInstaller --noconfirm --clean $Spec
if ($LASTEXITCODE -ne 0) { throw "PyInstaller build failed" }
$BuildPythonBase = (& $Python -c "import sys; print(sys.base_prefix)").Trim()
if ($LASTEXITCODE -ne 0 -or -not $BuildPythonBase) {
throw "Unable to resolve the build Python runtime directory"
}
# Dependency scanning must not collect unrelated ICU/OpenSSL libraries from
# an editor's helper tools (for example Poppler) ahead of Windows libraries.
$PreviousBuildPath = $env:PATH
$BuildRuntimePaths = @(
(Split-Path -Parent $Python),
$BuildPythonBase,
(Join-Path $BuildPythonBase "DLLs"),
(Join-Path $env:SystemRoot "System32"),
$env:SystemRoot,
(Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0")
)
try {
$env:PATH = ($BuildRuntimePaths | Select-Object -Unique) -join [System.IO.Path]::PathSeparator
& $Python -m PyInstaller --noconfirm --clean $Spec
$PyInstallerExitCode = $LASTEXITCODE
}
finally {
$env:PATH = $PreviousBuildPath
}
if ($PyInstallerExitCode -ne 0) { throw "PyInstaller build failed" }
$Artifact = Join-Path $ProjectRoot "dist\DoctorWorkstation"
$Helper = Get-ChildItem -LiteralPath $Artifact -Recurse -Filter "QtWebEngineProcess.exe" -File | Select-Object -First 1
+3 -3
View File
@@ -131,9 +131,9 @@ PYINSTALLER_PYTHON="$python_bin" SKIP_FRONTEND_INSTALL=1 \
/bin/bash "$script_dir/build_macos.sh"
artifact="$project_root/dist/DoctorWorkstation.app"
project_version="$(/usr/bin/awk -F '"' '/^version = "/ { print $2; exit }' \
"$project_root/pyproject.toml")"
[[ -n "$project_version" ]] || macos_die "无法从 pyproject.toml 读取版本号。"
project_version="$(/usr/bin/awk -F '"' '/^__version__ = "/ { print $2; exit }' \
"$project_root/src/doctor_workstation/__init__.py")"
[[ -n "$project_version" ]] || macos_die "无法从 doctor_workstation.__version__ 读取版本号。"
case "$(uname -m)" in
arm64) release_arch="arm64" ;;
x86_64) release_arch="x64" ;;
+12 -11
View File
@@ -20,7 +20,7 @@ $ReleaseLauncher = Join-Path $DistributionRoot "Start_DoctorWorkstation.bat"
$InstallerDefinition = Join-Path $ProjectRoot "packaging\windows\doctor_workstation.iss"
$EnsureInstallerCompiler = Join-Path $PSScriptRoot "ensure_inno_setup.ps1"
$InstallerMessagesFile = Join-Path $ProjectRoot ".build-tools\inno-languages\ChineseSimplified.isl"
$ProjectMetadata = Join-Path $ProjectRoot "pyproject.toml"
$VersionSource = Join-Path $ProjectRoot "src\doctor_workstation\__init__.py"
$MediaSmokeHook = Join-Path $ProjectRoot "packaging\runtime_media_smoke.py"
$WindowsIcon = Join-Path $ProjectRoot "resources\branding\app-icon.ico"
@@ -53,7 +53,7 @@ try {
$BuildScript,
$PackageLock,
(Join-Path $ProjectRoot "uv.lock"),
$ProjectMetadata,
$VersionSource,
$MediaSmokeHook,
$WindowsIcon,
$ReleaseLauncherTemplate,
@@ -65,6 +65,16 @@ try {
}
}
$VersionText = [System.IO.File]::ReadAllText($VersionSource)
$VersionMatch = [regex]::Match(
$VersionText,
'(?m)^\s*__version__\s*=\s*"([^"]+)"'
)
if (-not $VersionMatch.Success) {
throw "Unable to read the application version from $VersionSource"
}
$ProjectVersion = $VersionMatch.Groups[1].Value
$Npm = Find-Application -Name "npm.cmd"
$Node = Find-Application -Name "node.exe"
if (-not $Npm -or -not $Node) {
@@ -156,15 +166,6 @@ try {
throw "Build completed without the expected executable: $Executable"
}
$ProjectText = [System.IO.File]::ReadAllText($ProjectMetadata)
$VersionMatch = [regex]::Match(
$ProjectText,
'(?m)^\s*version\s*=\s*"([^"]+)"'
)
if (-not $VersionMatch.Success) {
throw "Unable to read the project version from $ProjectMetadata"
}
$ProjectVersion = $VersionMatch.Groups[1].Value
$ReleaseZip = Join-Path $DistributionRoot (
"DoctorWorkstation-Windows-x64-$ProjectVersion.zip"
)
@@ -8,10 +8,10 @@ from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtGui import QFont, QFontDatabase
from PySide6.QtWidgets import QApplication
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui import apply_theme
from doctor_workstation.ui.diagnosis_editors import DailyRecordEditorDialog
from doctor_workstation.ui.diagnosis_media import RecordingPlayerDialog
from doctor_workstation.ui.dialogs import diagnosis as diagnosis_module
@@ -480,12 +480,7 @@ def _run_immediately(
def render() -> list[Path]:
app = QApplication.instance() or QApplication([])
font_path = Path("C:/Windows/Fonts/msyh.ttc")
if font_path.is_file():
font_id = QFontDatabase.addApplicationFont(str(font_path))
families = QFontDatabase.applicationFontFamilies(font_id)
if families:
app.setFont(QFont(families[0], 9))
apply_theme(app)
diagnosis_module.run_async = _run_immediately
root = Path(__file__).resolve().parents[1]
output = root / "artifacts" / "diagnosis_visual"
@@ -8,7 +8,6 @@ from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import QThreadPool
from PySide6.QtGui import QFont, QFontDatabase
from PySide6.QtWidgets import QApplication
from doctor_workstation.services import DemoDoctorRepository
@@ -19,13 +18,6 @@ def render() -> list[Path]:
app = QApplication.instance() or QApplication([])
apply_theme(app)
font_path = Path("C:/Windows/Fonts/msyh.ttc")
if font_path.is_file():
font_id = QFontDatabase.addApplicationFont(str(font_path))
families = QFontDatabase.applicationFontFamilies(font_id)
if families:
app.setFont(QFont(families[0], 9))
root = Path(__file__).resolve().parents[1]
output = root / "artifacts" / "diagnosis_visual"
output.mkdir(parents=True, exist_ok=True)
+3 -9
View File
@@ -9,10 +9,11 @@ from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import Qt, QThreadPool, Signal
from PySide6.QtGui import QColor, QFont, QFontDatabase, QImage, QPainter, QPixmap
from PySide6.QtGui import QColor, QImage, QPainter, QPixmap
from PySide6.QtWidgets import QApplication, QToolButton, QWidget
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui import apply_theme
from doctor_workstation.ui.pages import consultations as consultations_module
from doctor_workstation.ui.pages.consultations import ConsultationsPage
@@ -339,14 +340,7 @@ def _save_with_payment_qr(
def _application() -> QApplication:
app = QApplication.instance() or QApplication([])
# The offscreen Windows plugin does not enumerate system fonts. Register
# the same CJK face used by the production QSS when it is available.
font_path = Path("C:/Windows/Fonts/msyh.ttc")
if font_path.is_file():
font_id = QFontDatabase.addApplicationFont(str(font_path))
families = QFontDatabase.applicationFontFamilies(font_id)
if families:
app.setFont(QFont(families[0], 9))
apply_theme(app)
return app
@@ -0,0 +1,281 @@
"""Render the prescription comparison window with synthetic, offline data."""
from __future__ import annotations
import os
from copy import deepcopy
from pathlib import Path
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
from doctor_workstation.ui.dialogs import issued_prescription_ai as ai
from doctor_workstation.ui.theme import apply_theme
def example_batch() -> dict[str, Any]:
"""Three prescriptions that actually differ, so every state of the page has something to draw."""
doctor = {"生地黄": 16, "天花粉": 15, "干石斛": 20, "醋五味子": 6,
"生麦冬": 12, "茯苓": 10, "红参片": 6, "生牡丹皮": 10}
candidates = {
"qwen": {"生地黄": 15, "干石斛": 12, "醋五味子": 6, "生麦冬": 12, "茯苓": 15, "麸炒白术": 12, "丹参": 15},
"openai": {"生地黄": 12, "醋五味子": 6, "生麦冬": 10, "茯苓": 12, "生白芍": 5, "炒酸枣仁": 6},
}
reports = {
"qwen": {"summary": "界面演示数据:对照药味组成、剂量及用法,辅助医生逐项复核。",
"diagnosis": "消渴病,气阴两虚兼血热。兼证需结合舌脉资料核实。",
"analysis": "阅读药方对比页,查看同名药材的剂量差异、仅医生方药味与仅候选方药味。",
"risk_assessment": [{"level": "high", "label": "血压数据缺失,影响补气药安全性评估"},
{"level": "medium", "label": "肝肾功能具体指标未提供"}],
"missing_information": ["甲状腺功能及眼底检查报告缺失", "舌象与脉诊仅有附件,无文本记录"]},
"openai": {"summary": "界面演示数据:两份候选方独立生成,引用编号可回查原始资料。",
"diagnosis": "已记录气阴两虚证;辨证依据需补充。",
"analysis": "候选方以益气养阴为主,安神药味为本模型新增,需要医师确认。",
"risk_assessment": [{"level": "high", "label": "缺少当前用药记录,无法排除配伍风险"}],
"missing_information": ["舌象与脉诊仅有附件,无文本记录", "近期体重变化及 BMI 数据缺失"]},
}
models = {}
for key, doses in candidates.items():
herbs, rows = [], []
for name in sorted(set(doctor) | set(doses), key=lambda item: (item not in doses, item)):
common = {"name": name, "unit": "g", "dose_basis": "per_dose", "formula_type": "主方"}
left, right = doctor.get(name), doses.get(name)
if right is not None:
herbs.append({**common, "dosage": right})
rows.append({
**common, "key": name,
"doctor": {**common, "dosage": left} if left is not None else None,
"candidate": {**common, "dosage": right, "source_rows": [len(herbs) - 1]} if right is not None else None,
"doctor_dosage": left, "candidate_dosage": right,
"match_type": "candidate_only" if left is None else "doctor_only" if right is None else "matched",
"contribution": min(left, right) / max(left, right) if left and right else None,
})
matched = sum(row["match_type"] == "matched" for row in rows)
denominator = len(doctor) + len(herbs)
models[key] = {
"status": "success", "report_id": 10 if key == "qwen" else 11,
"candidate": {"status": "available_for_review", "prescription_name": "候选药方 · 界面示例",
"herbs": herbs, "dose_basis": "per_dose", "prescription_type": "浓缩水丸",
"usage_instruction": "服法由医生复核后确认。", "usage_days": 7, "times_per_day": 2,
"rationale": "这是用于检查界面排版的模拟药方,不对应真实患者。",
"risk_warnings": ["药味与剂量差异需要逐项复核。"]},
"comparison": {"status": "comparable",
"score": 200 * sum(row["contribution"] or 0 for row in rows) / denominator,
"herb_score": 200 * matched / denominator, "matched_count": matched,
"doctor_count": len(doctor), "candidate_count": len(herbs), "rows": rows,
"reason": "药味与剂量可比;服法与疗程需单独复核。", "usage_differences": []},
"report": reports[key],
"coverage": {"status": "incomplete", "complete": False,
"files": [{"file_id": f"a{index:04d}", "type": "image" if index % 3 else "document",
"status": "processed", "transmitted": True, "version_verified": True}
for index in range(20 if key == "qwen" else 17)]
+ [{"file_id": f"z{index:04d}", "type": "document", "status": "restricted",
"transmitted": False, "version_verified": False,
"reason": "FILE_UNAVAILABLE_OR_UNSUPPORTED"} for index in range(2)]},
"progress": {"stage_label": "处理完成", "elapsed_seconds": 135 if key == "qwen" else 591,
"attempt": 1},
"usage": {"total_calls": 3, "calls": [
{"stage": "text:0", "ok": True, "latency_ms": 3120, "file_count": 0,
"usage": {"completion_tokens": 980}, "error_code": ""},
{"stage": "files:0", "ok": True, "latency_ms": 22400,
"file_count": 20 if key == "qwen" else 17,
"usage": {"completion_tokens": 2140}, "error_code": ""},
{"stage": "final", "ok": True, "latency_ms": 18800, "file_count": 0,
"usage": {"completion_tokens": 5617}, "error_code": ""}]},
"review": {"status": "viewed", "comment": ""},
"algorithm_version": "prescription-soft-dice-v1.1.0",
"prompt_version": "manual-prescription-required-candidate-v4",
}
return {"id": 40, "prescription_id": 7556, "patient_id": 1391, "diagnosis_id": 1391,
"prescription_revision": 1, "status": "success", "validity": "current",
"comparison_type": "non_independent", "models": models, "coverage_status": "partial",
"created_at": "2026-09-10 15:29:00", "cutoff_at": "2026-09-10 15:29:00",
"source_summary": {"diagnoses_count": 2, "attachment_count": 22, "video_calls_count": 4,
"chat_messages_count": 137, "source_record_count": 31},
"doctor_snapshot": {"patient": {"name": "张卫君", "gender": 2, "gender_label": "女", "age": 58},
"diagnosis": {"clinical_diagnosis": "2型糖尿病 消渴病 · 气阴两虚兼血热",
"chief_complaint": "咳嗽反复1月余"},
"prescription": {"herbs": [{"name": name, "dosage": dose, "unit": "g",
"dose_basis": "per_dose", "formula_type": "主方"}
for name, dose in doctor.items()],
"prescription_type": "浓缩水丸", "dose_count": 1,
"usage_instruction": "每日1剂,水煎分服。"}},
"missing": [{"code": "TRANSCRIPT_NOT_VERIFIED_COMPLETE", "critical": True},
{"code": "TRANSCRIPT_NOT_VERIFIED_COMPLETE", "critical": True},
{"code": "ARCHIVE_SYNC_WATERMARK_UNAVAILABLE", "critical": False}]}
def example_statistics() -> dict[str, Any]:
"""Doctor-level shape the statistics window renders; synthetic, but structurally complete."""
def doctor(identifier: int, name: str, totals: tuple[int, int, int],
qwen: tuple[int, float | None], openai: tuple[int, float | None],
review: tuple[int, int]) -> dict[str, Any]:
total, patients, paired = totals
models = {}
for key, (eligible, mean) in (("qwen", qwen), ("openai", openai)):
share = (0.34, 0.38, 0.18, 0.07, 0.03)
models[key] = {"eligible_count": eligible, "mean": mean,
"median": None if mean is None else round(mean - 1.4, 1),
"excluded_reasons": {"SOURCE_HISTORY_VERSIONS_UNAVAILABLE": max(0, total - eligible - 2),
"incomplete_coverage": min(2, max(0, total - eligible))},
"distribution": {name: round(eligible * fraction)
for name, fraction in zip(
("[0,20)", "[20,40)", "[40,60)", "[60,80)", "[80,100]"),
share, strict=True)}}
evaluated, qualified = review
return {"doctor_id": identifier, "doctor_name": name, "total_count": total,
"patient_count": patients, "paired_count": paired, "models": models,
"review": {"evaluated_count": evaluated, "qualified_count": qualified,
"qualified_rate": None if not evaluated else round(100 * qualified / evaluated, 1)}}
doctors = [doctor(26, "何医生", (18, 14, 9), (12, 21.4), (9, 18.9), (6, 4)),
doctor(31, "李医生", (11, 9, 4), (7, 26.8), (5, 24.1), (3, 1)),
doctor(44, "王医生", (6, 5, 1), (2, 15.2), (0, None), (0, 0))]
return {"total_count": sum(item["total_count"] for item in doctors),
"patient_count": sum(item["patient_count"] for item in doctors), "doctors": doctors}
class PreviewRepository:
def __init__(self) -> None:
self.batch = example_batch()
def list_prescription_ai_reports(self, **_params: Any) -> dict[str, Any]:
return {"enabled": True, "lists": deepcopy(self.history()), "count": len(self.history())}
def history(self) -> list[dict[str, Any]]:
"""The current batch plus the earlier ones it supersedes, newest first."""
older = [
{"id": 39, "created_at": "2026-09-10 15:18:00", "status": "success", "validity": "superseded",
"comparison_type": "non_independent",
"models": {"qwen": {"comparison": {"status": "comparable", "score": 48.9},
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"},
"openai": {"comparison": {"status": "comparable", "score": 41.7},
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"}}},
{"id": 38, "created_at": "2026-09-10 14:05:00", "status": "success", "validity": "superseded",
"models": {"qwen": {"comparison": {"status": "comparable", "score": 33.4},
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"},
"openai": {"comparison": {"status": "comparable", "score": 31.1},
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"}}},
{"id": 37, "created_at": "2026-09-10 13:25:00", "status": "failed", "validity": "superseded",
"models": {"qwen": {"error_message": "模型返回未通过校验",
"algorithm_version": "prescription-soft-dice-v1.0.1"},
"openai": {"comparison": {"status": "not_comparable"}}}},
{"id": 36, "created_at": "2026-09-10 12:34:00", "status": "success", "validity": "superseded",
"models": {"qwen": {"comparison": {"status": "not_comparable"},
"algorithm_version": "prescription-soft-dice-v1.0.0"},
"openai": {"comparison": {"status": "not_comparable"}}}},
]
return [self.batch, *older]
def get_prescription_ai_report(self, _batch_id: int) -> dict[str, Any]:
return deepcopy(self.batch)
def prescription_ai_statistics(self, *_args: Any, **_params: Any) -> dict[str, Any]:
return deepcopy(example_statistics())
def main() -> None:
application = QApplication.instance() or QApplication([])
apply_theme(application)
output = Path(__file__).resolve().parents[1] / "artifacts" / "issued_prescription_redesign"
output.mkdir(parents=True, exist_ok=True)
def immediate(function: Any, **callbacks: Any) -> None:
result = function()
if callbacks.get("on_success"):
callbacks["on_success"](result)
if callbacks.get("on_finished"):
callbacks["on_finished"]()
ai.run_async = immediate
repository = PreviewRepository()
dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=7556,
current_user={"name": "张医生"})
dialog.show()
names = {dialog.tabs.tabText(index): index for index in range(dialog.tabs.count())}
for filename, width, height, tab in (
("prescription-1440.png", 1440, 940, "对比总览"),
("prescription-1280.png", 1280, 860, "对比总览"),
("prescription-1024.png", 1024, 700, "对比总览"),
("prescription-940.png", 940, 640, "对比总览"),
("original-1280.png", 1280, 860, "原方记录"),
("analysis-1280.png", 1280, 860, "完整报告"),
("candidate-1280.png", 1280, 860, "方义与用法"),
("per-herb-1440.png", 1440, 940, "候选与逐味"),
("sources-1440.png", 1440, 940, "资料与缺口"),
("history-1440.png", 1440, 940, "历史与趋势"),
("pipeline-1440.png", 1440, 940, "处理进度"),
):
dialog.resize(width, height)
dialog.tabs.setCurrentIndex(names[tab])
for _ in range(4):
application.processEvents()
assert (dialog.width(), dialog.height()) == (width, height), (filename, dialog.size())
assert dialog.grab().save(str(output / filename))
print(filename, "window", width, height, "workspace", dialog.tabs.width(), dialog.tabs.height())
dialog.tabs.setCurrentIndex(names["完整报告"])
dialog._set_report_mode("differences")
application.processEvents()
assert dialog.grab().save(str(output / "report-differences-1440.png"))
dialog._set_report_mode("both")
dialog.tabs.setCurrentIndex(names["对比总览"])
dialog.resize(1280, 860)
for _ in range(4):
application.processEvents()
dialog.review_model.setCurrentIndex(1)
application.processEvents()
assert dialog.grab().save(str(output / "openai-1280.png"))
dialog.review_model.setCurrentIndex(0)
repository.batch["status"] = "running"
repository.batch["models"]["openai"].update(status="running", candidate=None, comparison=None, report=None)
dialog.refresh()
application.processEvents()
assert dialog.grab().save(str(output / "partial-1280.png"))
repository.batch.update(validity="superseded", status="success")
dialog.refresh()
application.processEvents()
assert dialog.grab().save(str(output / "historical-1280.png"))
repository.batch.update(validity="current", status="running")
repository.batch["models"]["qwen"].update(status="running", candidate=None, comparison=None, report=None)
dialog.refresh()
application.processEvents()
assert dialog.grab().save(str(output / "pending-1280.png"))
# A failed model must state the reason and offer its own retry on the card itself.
repository.batch.update(validity="current", status="partial")
repository.batch["models"]["qwen"].update(
status="failed", error_code="upstream_timeout", error_message="上游模型超时,未返回结果",
candidate=None, comparison=None, report=None, retry_count=1, max_retry=3)
repository.batch["models"]["openai"] = deepcopy(example_batch()["models"]["openai"])
dialog.refresh()
application.processEvents()
assert dialog.grab().save(str(output / "failed-1280.png"))
# The light theme is the same window with the other palette; capture it once.
dialog.resize(1440, 940)
dialog._switch_theme()
for _ in range(12):
application.processEvents()
dialog.repaint()
assert dialog.grab().save(str(output / "light-1440.png"))
dialog._switch_theme()
for _ in range(4):
application.processEvents()
dialog.close()
statistics = ai.PrescriptionAiStatisticsDialog(repository, ["*"])
statistics.resize(1240, 880)
statistics.show()
for _ in range(4):
application.processEvents()
assert statistics.grab().save(str(output / "statistics-1240.png"))
statistics.close()
print("statistics-1240.png", statistics.panel.doctors.rowCount(), "doctors")
print(output)
if __name__ == "__main__":
main()
@@ -9,7 +9,6 @@ from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtGui import QFont, QFontDatabase
from PySide6.QtWidgets import QApplication, QWidget
from doctor_workstation.core.permissions import PermissionSet
@@ -136,12 +135,6 @@ def _settle(app: QApplication, rounds: int = 8) -> None:
def render() -> list[Path]:
app = QApplication.instance() or QApplication([])
apply_theme(app)
font_path = Path("C:/Windows/Fonts/msyh.ttc")
if font_path.is_file():
font_id = QFontDatabase.addApplicationFont(str(font_path))
families = QFontDatabase.applicationFontFamilies(font_id)
if families:
app.setFont(QFont(families[0], 9))
output = Path(__file__).resolve().parents[1] / "artifacts" / "subwindow_exact"
output.mkdir(parents=True, exist_ok=True)
@@ -8,7 +8,6 @@ from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import QThreadPool
from PySide6.QtGui import QFontDatabase
from PySide6.QtWidgets import QApplication
from doctor_workstation.services.mock_repository import DemoDoctorRepository
@@ -19,9 +18,6 @@ from doctor_workstation.ui.theme import apply_theme
def main() -> int:
application = QApplication.instance() or QApplication([])
apply_theme(application)
font_path = Path(r"C:\Windows\Fonts\msyh.ttc")
if font_path.is_file():
QFontDatabase.addApplicationFont(str(font_path))
repository = DemoDoctorRepository()
session = repository.login("doctor", "doctor123")
+93
View File
@@ -0,0 +1,93 @@
"""Render the clinical reading surfaces with demo data and production fonts."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import Qt, QThreadPool
from PySide6.QtGui import QFontInfo, QGuiApplication, QPalette
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui import ShellWindow, apply_theme
def _settle(app: QApplication) -> None:
for _ in range(4):
QThreadPool.globalInstance().waitForDone(3000)
app.processEvents()
QTest.qWait(100)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=Path("artifacts/ui_comfort"))
parser.add_argument("--width", type=int, default=1536)
parser.add_argument("--height", type=int, default=912)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
)
app = QApplication.instance() or QApplication([])
apply_theme(app)
repo = DemoDoctorRepository()
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
shell = ShellWindow(
repo, {"session": session, "demo_mode": True}, permissions=session.permissions
)
shell.resize(args.width, args.height)
shell.show()
try:
shell.navigate("reception")
_settle(app)
page = shell.pages["reception"]
page._set_queue_filter(None)
_settle(app)
# A synthetic multiline case tests paragraph rhythm without capturing
# a live patient or connecting to a production service.
page.case_labels["present"].setText(
"患者自述近期口干,睡眠较浅,日常饮食与作息较规律。\n"
"近一周已记录空腹血糖,复诊时携带记录与既往检查报告。\n"
"问诊记录包含当前不适、变化时间、生活习惯与既往用药,供医生核对。"
)
app.processEvents()
if not shell.grab().save(str(args.output / "reception.png")):
raise RuntimeError("Could not save reception preview")
daily = next(
index
for index in range(page.detail_tabs.count())
if page.detail_tabs.tabText(index) == "日常记录"
)
page.detail_tabs.setCurrentIndex(daily)
_settle(app)
if not shell.grab().save(str(args.output / "daily_records.png")):
raise RuntimeError("Could not save daily-record preview")
metrics = {
"family": QFontInfo(app.font()).family(),
"pixel_size": app.font().pixelSize(),
"font_strategy": app.font().styleStrategy().value,
"font_hinting": app.font().hintingPreference().name,
"text_color": app.palette().color(QPalette.ColorRole.Text).name(),
"device_pixel_ratio": shell.devicePixelRatioF(),
"window": [shell.width(), shell.height()],
"daily_table_font": QFontInfo(page.daily_panel.matrix.font()).family(),
"daily_table_size": page.daily_panel.matrix.font().pixelSize(),
}
(args.output / "render.json").write_text(
json.dumps(metrics, ensure_ascii=False, indent=2), encoding="utf-8"
)
print(args.output)
finally:
_settle(app)
shell.close()
if __name__ == "__main__":
main()
+8 -2
View File
@@ -1,5 +1,11 @@
"""Zhenyang doctor workstation."""
__all__ = ["__version__"]
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
__version__ = "0.1.0"
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.4.5"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
DEBUG_MODE = False
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
+360 -31
View File
@@ -6,6 +6,7 @@ import logging
import os
import sys
import time
from collections.abc import Mapping, Sequence
from contextlib import suppress
from typing import Any
@@ -26,7 +27,7 @@ from doctor_workstation.config import AppConfig
from doctor_workstation.core import Session
from doctor_workstation.core.errors import AuthenticationExpiredError
from doctor_workstation.logging_setup import configure_logging
from doctor_workstation.resources import app_icon_path, video_dist_path
from doctor_workstation.resources import app_icon_path, video_dist_path
from doctor_workstation.services import (
DemoDoctorRepository,
RemoteDoctorRepository,
@@ -36,7 +37,10 @@ from doctor_workstation.services import (
from doctor_workstation.ui import LoginWindow, ShellWindow, apply_theme
from doctor_workstation.ui.dialogs.app_update import AppUpdateSession
from doctor_workstation.ui.widgets import (
first_value,
friendly_error,
gender_text,
get_value,
run_async,
set_authentication_expired_handler,
show_toast,
@@ -47,6 +51,165 @@ from doctor_workstation.video.window import WEBENGINE_AVAILABLE
LOGGER = logging.getLogger(__name__)
def _video_case_text(value: Any, *, limit: int = 2000) -> str:
"""Render a bounded, JSON-safe clinical value for the trusted call rail."""
if value in (None, "", [], {}):
return ""
if isinstance(value, Mapping):
parts = [
f"{key}:{_video_case_text(item, limit=limit)}"
for key, item in value.items()
if item not in (None, "", [], {})
]
return ";".join(part for part in parts if not part.endswith(":"))[:limit]
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return "、".join(
part
for item in value
if (part := _video_case_text(item, limit=limit))
)[:limit]
return str(value).strip()[:limit]
def _video_identity(value: Any) -> str:
if value in (None, "") or isinstance(value, bool):
return ""
text = str(value).strip()
if not text:
return ""
with suppress(ValueError, TypeError):
return str(int(text))
return text
def _video_identity_matches(expected: Any, actual: Any) -> bool:
normalized_actual = _video_identity(actual)
return not normalized_actual or normalized_actual == _video_identity(expected)
def _build_video_patient_case(
detail: Any,
fallback_record: Any,
*,
diagnosis_id: Any,
patient_id: Any,
patient_name: str,
) -> dict[str, str]:
"""Reduce the readonly diagnosis aggregate to the fields needed in-call."""
if isinstance(detail, Mapping) and not get_value(detail, "diagnosis", None):
nested = get_value(detail, "data", None)
if isinstance(nested, Mapping):
detail = nested
diagnosis = get_value(detail, "diagnosis", None)
if not diagnosis and isinstance(detail, Mapping):
diagnosis = detail
diagnosis = diagnosis or {}
patient = get_value(detail, "patient", None) or {}
appointment = get_value(detail, "appointment", None) or {}
detail_diagnosis_id = first_value(diagnosis, "id", "diagnosis_id", default=None)
detail_patient_id = first_value(
diagnosis,
"source_patient_id",
default=first_value(
patient,
"source_patient_id",
default=None,
),
)
if not _video_identity_matches(
diagnosis_id,
detail_diagnosis_id,
) or not _video_identity_matches(patient_id, detail_patient_id):
detail = diagnosis = patient = appointment = {}
fallback_diagnosis_id = first_value(
fallback_record,
"diagnosis_id",
"id",
default=None,
)
fallback_patient_id = first_value(
fallback_record,
"source_patient_id",
"patient_id",
default=None,
)
if not _video_identity_matches(
diagnosis_id,
fallback_diagnosis_id,
) or not _video_identity_matches(patient_id, fallback_patient_id):
fallback_record = {}
sources = (diagnosis, patient, appointment, fallback_record)
def pick(*keys: str, limit: int = 2000) -> str:
for source in sources:
value = first_value(source, *keys, default=None)
text = _video_case_text(value, limit=limit)
if text:
return text
return ""
raw_gender = next(
(
first_value(source, "gender_desc", "gender", default=None)
for source in sources
if first_value(source, "gender_desc", "gender", default=None) not in (None, "")
),
None,
)
return {
"diagnosisId": _video_case_text(diagnosis_id, limit=80),
"name": pick("patient_name", "name", limit=120)
or _video_case_text(patient_name, limit=120)
or "患者",
"gender": "" if raw_gender in (None, "") else gender_text(raw_gender),
"age": pick("age", limit=20),
"height": pick("height", limit=20),
"weight": pick("weight", limit=20),
"diagnosisDate": pick("diagnosis_date", "diagnosis_date_text", limit=80),
"appointmentDate": pick(
"appointment_date",
"latest_appointment_date",
limit=80,
),
"clinicalDiagnosis": pick(
"clinical_diagnosis",
"diagnosis_name",
"disease_name",
),
"chiefComplaint": pick("chief_complaint", "complaint"),
"presentIllness": pick("present_illness", "present_illness_history", "symptoms"),
"pastHistory": pick("past_history_text", "past_history_desc", "past_history"),
"allergyHistory": pick(
"allergy_history_text",
"allergy_history_desc",
"allergy_history",
),
"personalHistory": pick(
"personal_history_text",
"personal_history_desc",
"personal_history",
),
"familyHistory": pick(
"family_history_text",
"family_history_desc",
"family_history",
),
"currentMedication": pick(
"current_medications",
"current_medicine",
"current_medication",
),
"tongue": pick("tongue", "tongue_coating"),
"pulse": pick("pulse", "pulse_condition"),
"prescriptionOpinion": pick("prescription_opinion", "prescription_advice"),
"remark": pick("remark"),
}
class _ChineseQtTranslator(QTranslator):
"""Guarantee Chinese labels for common Qt standard buttons.
@@ -150,7 +313,7 @@ class DemoVideoDialog(QDialog):
"background:#FFFFFF;color:#3F4E75;border:1px solid #E6EAF5;font-weight:600;}"
"QPushButton:hover{color:#4451E2;background:#F0F2FF;border-color:#5761F4;}"
"QPushButton:checked{color:#FFFFFF;background:#5761F4;border-color:#5761F4;}"
"QPushButton#Hangup{color:#FFFFFF;background:#F15B67;border-color:#F15B67;}"
"QPushButton#Hangup{color:#FFFFFF;background:#C23D4E;border-color:#C23D4E;}"
"QPushButton#Hangup:hover{background:#D94857;border-color:#D94857;}"
)
@@ -163,7 +326,7 @@ class DemoVideoDialog(QDialog):
header.addWidget(title)
header.addStretch(1)
demo = QLabel("● 演示模式 · 未连接腾讯云")
demo.setStyleSheet("color:#7886AA;font-size:12px;")
demo.setStyleSheet("color:#707584;font-size:12px;")
header.addWidget(demo)
self.duration_label = QLabel("00:00")
self.duration_label.setStyleSheet("font-weight:700;")
@@ -240,16 +403,20 @@ class ApplicationController(QObject):
super().__init__()
self.application = application
self.config = config
self.debug_mode = bool(getattr(config, "debug_mode", False))
self.token_store = TokenStore(config.config_dir / "credentials.json")
self.demo_repository = DemoDoctorRepository()
self.demo_repository = DemoDoctorRepository() if self.debug_mode else None
self.remote_repository: RemoteDoctorRepository | None = None
self.login_window: LoginWindow | None = None
self.shell_window: ShellWindow | None = None
self.current_repository: Any = None
self.current_demo_mode = config.demo_mode
self.current_demo_mode = self.debug_mode and config.demo_mode
self.video_calls: dict[str, Any] = {}
self.video_pending: dict[str, object] = {}
self.video_pending: dict[str, object] = {}
self._pending_im_request: tuple[str, object] | None = None
self.demo_video_dialogs: dict[str, DemoVideoDialog] = {}
self._video_preview_state: dict[str, Any] | None = None
self._video_preview_generation = 0
self._restore_generation = 0
self._restore_in_progress = False
self._restore_worker: Any = None
@@ -341,8 +508,9 @@ class ApplicationController(QObject):
self.login_window.config = self.config
def _on_demo_mode_changed(self, enabled: bool) -> None:
self.current_demo_mode = enabled
if enabled:
allowed = self.debug_mode and enabled
self.current_demo_mode = allowed
if allowed:
self._cancel_session_restore()
def _rebuild_remote_repository(self) -> None:
@@ -503,7 +671,8 @@ class ApplicationController(QObject):
self._login_guard_error("该账号需要先绑定企业微信,请在管理后台完成绑定后重新登录。")
return
demo_mode = bool(payload.get("demo_mode"))
demo_mode = self.debug_mode and bool(payload.get("demo_mode"))
payload["demo_mode"] = demo_mode
if not demo_mode and not session.menu:
with suppress(Exception):
repository.logout()
@@ -550,13 +719,15 @@ class ApplicationController(QObject):
def _logout(self, *, message: str = "") -> None:
"""Clear authenticated resources and return to the login window."""
self._restore_video_preview(activate=False)
calls = tuple(self.video_calls.values())
for call in calls:
with suppress(Exception):
call.close()
self._wait_for_video_lifecycle(calls, timeout=1.25)
self.video_calls.clear()
self.video_pending.clear()
self.video_pending.clear()
self._pending_im_request = None
for dialog in self.demo_video_dialogs.values():
dialog.close()
self.demo_video_dialogs.clear()
@@ -577,15 +748,25 @@ class ApplicationController(QObject):
if parent is None or self.current_repository is None:
return
patient_id = payload.get("patient_id")
diagnosis_id = payload.get("diagnosis_id")
diagnosis_id = payload.get("diagnosis_id")
appointment_id = int(payload.get("appointment_id") or 0)
patient_name = str(payload.get("patient_name") or "患者")
open_im = str(payload.get("mode") or "video").lower() == "im"
fallback_record = payload.get("record")
if patient_id in (None, "") or diagnosis_id in (None, ""):
show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200)
return
call_key = str(diagnosis_id)
existing_call = self.video_calls.get(call_key)
call_key = f"{diagnosis_id}:{appointment_id}"
if open_im and self._pending_im_request is not None:
pending_key, pending_marker = self._pending_im_request
if pending_key != call_key:
# Retire a previous selection before any early return, including
# when the selected IM window is already open.
if self.video_pending.get(pending_key) is pending_marker:
self.video_pending.pop(pending_key, None)
self._pending_im_request = None
existing_call = self.video_calls.get(call_key)
if open_im and existing_call is not None and getattr(existing_call, "open_im", False):
qt_window = getattr(existing_call, "qt_window", None)
if qt_window is not None:
@@ -631,21 +812,47 @@ class ApplicationController(QObject):
)
repository = self.current_repository
marker = object()
self.video_pending[call_key] = marker
self.video_pending[call_key] = marker
if open_im:
self._pending_im_request = (call_key, marker)
def get_ticket() -> Any:
return repository.get_call_ticket(
def get_video_context() -> tuple[Any, dict[str, str]]:
ticket = repository.get_call_ticket(
patient_id=int(patient_id),
diagnosis_id=int(diagnosis_id),
diagnosis_id=int(diagnosis_id),
appointment_id=appointment_id,
)
if appointment_id and int(ticket.raw.get("appointment_id") or 0) != appointment_id:
raise ValueError("通话凭证与本次挂号不匹配,请重新打开聊天窗口。")
detail: Any = {}
detail_loader = getattr(repository, "patient_detail", None)
if callable(detail_loader):
try:
detail = detail_loader(int(diagnosis_id))
except Exception as error:
LOGGER.warning(
"patient detail could not be loaded for video call",
extra={
"diagnosis_id": diagnosis_id,
"error_type": type(error).__name__,
},
)
patient_case = _build_video_patient_case(
detail,
fallback_record,
diagnosis_id=diagnosis_id,
patient_id=patient_id,
patient_name=patient_name,
)
return ticket, patient_case
def request_ticket() -> None:
if self.video_pending.get(call_key) is not marker:
return
run_async(
get_ticket,
on_success=lambda ticket: self._launch_video(
ticket,
get_video_context,
on_success=lambda context: self._launch_video(
context[0],
diagnosis_id=diagnosis_id,
patient_id=patient_id,
repository=repository,
@@ -653,6 +860,7 @@ class ApplicationController(QObject):
marker=marker,
open_im=open_im,
patient_name=patient_name,
patient_case=context[1],
),
on_error=lambda error: self._video_ticket_error(
call_key,
@@ -676,10 +884,12 @@ class ApplicationController(QObject):
parent: QWidget,
error: Exception,
) -> None:
if self.video_pending.get(call_key) is not marker:
return
self.video_pending.pop(call_key, None)
if self.shell_window is parent:
if self.video_pending.get(call_key) is not marker:
return
self.video_pending.pop(call_key, None)
if self._pending_im_request == (call_key, marker):
self._pending_im_request = None
if self.shell_window is parent:
show_toast(
parent,
f"视频准备失败:{friendly_error(error)}",
@@ -698,10 +908,13 @@ class ApplicationController(QObject):
marker: object,
open_im: bool = False,
patient_name: str = "患者",
patient_case: Mapping[str, Any] | None = None,
) -> None:
if self.video_pending.get(call_key) is not marker:
return
self.video_pending.pop(call_key, None)
if self.video_pending.get(call_key) is not marker:
return
self.video_pending.pop(call_key, None)
if self._pending_im_request == (call_key, marker):
self._pending_im_request = None
if (
self.shell_window is None
or self.current_repository is not repository
@@ -725,6 +938,10 @@ class ApplicationController(QObject):
logger=logging.getLogger("doctor_workstation.video"),
open_im=open_im,
patient_name=patient_name,
patient_case=patient_case,
on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: (
self._open_video_diagnosis(current_id, call_key=current_key)
),
)
except Exception as error:
LOGGER.exception("video call could not be launched")
@@ -745,7 +962,110 @@ class ApplicationController(QObject):
)
)
def _open_video_diagnosis(self, diagnosis_id: Any, *, call_key: str) -> None:
"""Open the diagnosis while keeping its live video visible as a preview."""
shell = self.shell_window
if shell is None or self.current_repository is None:
return
dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True)
if dialog is None:
return
call = self.video_calls.get(call_key)
video_window = getattr(call, "qt_window", None)
if video_window is not None:
self._show_video_preview(video_window, dialog)
def _show_video_preview(self, video_window: Any, dialog: QDialog) -> None:
"""Pin a compact call window above the modeless diagnosis drawer."""
current = self._video_preview_state
if current is not None and current.get("window") is not video_window:
self._restore_video_preview(activate=False)
self._video_preview_generation += 1
generation = self._video_preview_generation
if current is None or current.get("window") is not video_window:
try:
state = {
"window": video_window,
"geometry": video_window.geometry(),
"minimum_size": video_window.minimumSize(),
"maximized": video_window.isMaximized(),
"full_screen": video_window.isFullScreen(),
"stays_on_top": bool(
video_window.windowFlags()
& Qt.WindowType.WindowStaysOnTopHint
),
}
screen = video_window.screen() or QGuiApplication.primaryScreen()
available = screen.availableGeometry()
preview_width = min(540, max(460, round(available.width() * 0.29)))
preview_height = min(380, max(320, round(preview_width * 0.66)))
margin = 18
video_window.showNormal()
video_window.setMinimumSize(440, 300)
video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
video_window.resize(preview_width, preview_height)
video_window.move(
available.x() + available.width() - preview_width - margin,
available.y() + margin,
)
video_window.show()
self._video_preview_state = state
except RuntimeError:
self._video_preview_state = None
return
dialog.finished.connect(
lambda _result, expected=generation: self._restore_video_preview(expected)
)
try:
video_window.raise_()
dialog.raise_()
dialog.activateWindow()
except RuntimeError:
self._video_preview_state = None
def _restore_video_preview(
self,
generation: int | None = None,
*,
activate: bool = True,
) -> None:
if generation is not None and generation != self._video_preview_generation:
return
state = self._video_preview_state
if state is None:
return
self._video_preview_state = None
self._video_preview_generation += 1
window = state.get("window")
try:
window.setWindowFlag(
Qt.WindowType.WindowStaysOnTopHint,
bool(state.get("stays_on_top")),
)
window.setMinimumSize(state["minimum_size"])
window.setGeometry(state["geometry"])
if state.get("full_screen"):
window.showFullScreen()
elif state.get("maximized"):
window.showMaximized()
else:
window.showNormal()
window.raise_()
if activate:
window.activateWindow()
except (AttributeError, RuntimeError):
return
def _release_video_call(self, call_key: str, call: Any) -> None:
preview = self._video_preview_state
if preview is not None and preview.get("window") is getattr(call, "qt_window", None):
self._video_preview_state = None
self._video_preview_generation += 1
if self.video_calls.get(call_key) is call:
self.video_calls.pop(call_key, None)
@@ -772,12 +1092,19 @@ class ApplicationController(QObject):
LOGGER.warning("video lifecycle cleanup exceeded its bounded deadline")
return complete
@staticmethod
def _apply_window_icon(window: QWidget) -> None:
icon_file = app_icon_path()
@staticmethod
def _apply_window_icon(window: QWidget) -> None:
icon_file = app_icon_path()
if icon_file.exists():
window.setWindowIcon(QIcon(str(icon_file)))
def request_quit(self) -> None:
"""Queue a normal application exit so owned resources are released."""
if self._shutting_down:
return
QTimer.singleShot(0, self.application.quit)
def shutdown(self) -> None:
"""Invalidate asynchronous restoration and release owned resources."""
@@ -785,7 +1112,9 @@ class ApplicationController(QObject):
return
self._shutting_down = True
self._cancel_session_restore()
self.app_updater.shutdown()
set_authentication_expired_handler(None)
self._restore_video_preview(activate=False)
calls = tuple(self.video_calls.values())
for call in calls:
with suppress(Exception):
@@ -858,7 +1187,7 @@ def _create_application(argv: list[str]) -> QApplication:
application.setOrganizationName("ZhenYangTang")
application.setOrganizationDomain("zhenyangtang.com")
application.setQuitOnLastWindowClosed(True)
icon_file = app_icon_path()
icon_file = app_icon_path()
if icon_file.exists():
application.setWindowIcon(QIcon(str(icon_file)))
apply_theme(application)
+27 -6
View File
@@ -14,6 +14,8 @@ from pathlib import Path
from typing import Any
from urllib.parse import urlsplit, urlunsplit
from doctor_workstation import DEBUG_MODE, ONLINE_API_BASE_URL
try:
from dotenv import load_dotenv
except ImportError: # pragma: no cover - optional during pure unit tests
@@ -90,7 +92,8 @@ class AppConfig:
"""Runtime configuration loaded from environment and user preferences."""
api_base_url: str = ""
demo_mode: bool = True
demo_mode: bool = False
debug_mode: bool = DEBUG_MODE
video_mode: str = "embedded"
video_web_url: str = ""
verify_ssl: bool = True
@@ -115,18 +118,28 @@ class AppConfig:
if load_dotenv is not None:
load_dotenv(dotenv_path=env_file, override=False)
raw_url = os.getenv("DOCTOR_API_BASE_URL", "")
debug_mode = bool(DEBUG_MODE)
raw_url = (
os.getenv("DOCTOR_API_BASE_URL", "") if debug_mode else ONLINE_API_BASE_URL
)
try:
api_url = normalize_api_base_url(raw_url)
except ValueError:
except ValueError as error:
if not debug_mode:
raise ValueError("ONLINE_API_BASE_URL 必须是有效的 HTTP(S) 域名") from error
api_url = ""
if not debug_mode and not api_url:
raise ValueError("正式模式下 ONLINE_API_BASE_URL 不能为空")
config = cls(
api_base_url=api_url,
demo_mode=_as_bool(os.getenv("DOCTOR_DEMO_MODE"), True),
demo_mode=_as_bool(os.getenv("DOCTOR_DEMO_MODE"), False) if debug_mode else False,
debug_mode=debug_mode,
video_mode=os.getenv("DOCTOR_VIDEO_MODE", "embedded").strip().lower(),
video_web_url=os.getenv("DOCTOR_VIDEO_WEB_URL", "").strip(),
verify_ssl=_as_bool(os.getenv("DOCTOR_VERIFY_SSL"), True),
verify_ssl=(
_as_bool(os.getenv("DOCTOR_VERIFY_SSL"), True) if debug_mode else True
),
request_timeout=_safe_timeout(os.getenv("DOCTOR_REQUEST_TIMEOUT")),
log_level=os.getenv("DOCTOR_LOG_LEVEL", "INFO").strip().upper(),
)
@@ -137,7 +150,9 @@ class AppConfig:
payload = json.loads(self.preferences_file.read_text(encoding="utf-8"))
except (OSError, ValueError, TypeError):
return self
allowed = {item.name for item in fields(self)}
allowed = {item.name for item in fields(self)} - {"debug_mode"}
if not self.debug_mode:
allowed -= {"api_base_url", "demo_mode", "verify_ssl"}
clean: dict[str, Any] = {key: value for key, value in payload.items() if key in allowed}
if "api_base_url" in clean:
try:
@@ -159,12 +174,18 @@ class AppConfig:
target = self.preferences_file
temporary = target.with_suffix(".tmp")
payload = asdict(self)
payload.pop("debug_mode", None)
temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
with suppress(OSError):
os.chmod(temporary, 0o600)
temporary.replace(target)
def with_updates(self, **changes: Any) -> AppConfig:
changes.pop("debug_mode", None)
if not self.debug_mode:
changes.pop("api_base_url", None)
changes.pop("demo_mode", None)
changes.pop("verify_ssl", None)
if "api_base_url" in changes:
changes["api_base_url"] = normalize_api_base_url(str(changes["api_base_url"]))
if "video_mode" in changes and changes["video_mode"] not in {"embedded", "browser"}:
@@ -0,0 +1,48 @@
"""Appointment medium labels, separate from first-visit/follow-up diagnosis type."""
from collections.abc import Mapping
from typing import Any
APPOINTMENT_MODES = (("视频问诊", "video"), ("图文问诊", "text"))
def appointment_type_description(value: Any) -> str:
if value is None or isinstance(value, str) and not value.strip():
return "视频问诊"
return {"video": "视频问诊", "text": "图文问诊", "phone": "电话问诊"}.get(str(value), "未知")
def can_appointment_video(value: Any) -> bool:
"""UI hint only; actual call permission must come from the server ticket."""
return value is None or isinstance(value, str) and (not value.strip() or value == "video")
def appointment_type_value(record: Any) -> Any:
"""Read appointment rows and diagnosis-list projections without visit-type aliases."""
def read(value: Any, key: str) -> Any:
if isinstance(value, Mapping):
return value.get(key)
result = getattr(value, key, None)
raw = getattr(value, "raw", None)
return raw.get(key) if result is None and isinstance(raw, Mapping) else result
appointment_id = read(record, "appointment_id") or read(record, "latest_appointment_id")
rows = read(record, "appointments")
if isinstance(rows, (list, tuple)) and rows:
if appointment_id:
for row in rows:
if str(read(row, "id")) == str(appointment_id):
return read(row, "appointment_type")
elif len(rows) == 1:
return read(rows[0], "appointment_type")
else:
return "unknown"
for key in ("appointment_type", "latest_appointment_type"):
value = read(record, key)
if value is not None and value != "":
return value
for key in ("appointment", "latest_appointment"):
nested = read(record, key)
if nested is not None:
return read(nested, "appointment_type")
return None
File diff suppressed because it is too large Load Diff
@@ -489,7 +489,7 @@ class DemoDoctorRepository:
return detail
raise ApiBusinessError("挂号不存在", code=0)
def list_departments(self) -> list[dict[str, Any]]:
def list_departments(self, *, apply_data_scope: bool = False) -> list[dict[str, Any]]:
"""Return a small demo department tree."""
return [
@@ -1705,6 +1705,24 @@ class DemoDoctorRepository:
}
return deepcopy(dictionaries.get(dictionary_type, []))
def list_chat_notifications(self) -> list[dict[str, Any]]:
"""Demo mode never queues server-side chat notifications."""
return []
def get_dictionaries(
self, dictionary_types: Sequence[str]
) -> dict[str, list[dict[str, Any]]]:
"""Mirror the remote batch dictionary contract used by readonly screens."""
result: dict[str, list[dict[str, Any]]] = {}
for dictionary_type in dictionary_types:
clean = str(dictionary_type or "").strip()
if not clean or clean in result:
continue
result[clean] = self.get_dictionary(clean)
return result
def list_patients(
self, *, page_no: int = 1, page_size: int = 20, **filters: Any
) -> PageResult[Patient]:
@@ -3004,7 +3022,7 @@ class DemoDoctorRepository:
raise ValueError("order_no is required")
return {"qrcode_url": f"https://demo.invalid/qrcode/order/{clean}.png"}
def get_call_ticket(self, patient_id: int, diagnosis_id: int) -> CallTicket:
def get_call_ticket(self, patient_id: int, diagnosis_id: int, *, appointment_id: int = 0) -> CallTicket:
"""Return non-production placeholder credentials for UI demonstration."""
with self._lock:
@@ -3018,21 +3036,22 @@ class DemoDoctorRepository:
assistant_id="assistant_2001",
diagnosis_id=diagnosis_id,
is_lochost_vod=False,
raw={"demo": True},
raw={"demo": True, "appointment_id": appointment_id},
)
def start_call(
self, diagnosis_id: int, patient_id: int, *, call_type: int = 2
self, diagnosis_id: int, patient_id: int, *, call_type: int = 2, appointment_id: int = 0
) -> dict[str, Any]:
"""Create a mutable demo call record."""
with self._lock:
self.get_call_ticket(patient_id, diagnosis_id)
self.get_call_ticket(patient_id, diagnosis_id, appointment_id=appointment_id)
record = {
"id": self._next_call_id,
"diagnosis_id": diagnosis_id,
"patient_id": patient_id,
"call_type": call_type,
"call_type": call_type,
"appointment_id": appointment_id,
"status": "ringing",
"room_id": "",
}
+170 -30
View File
@@ -233,8 +233,29 @@ class DoctorRepository(Protocol):
) -> dict[str, Any]:
"""Append one model-specific AI diagnosis snapshot for one patient."""
def get_prescription(self, prescription_id: int) -> Prescription:
"""Return one issued prescription."""
def get_prescription(self, prescription_id: int) -> Prescription:
"""Return one issued prescription."""
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
"""Read cached dual-model states for up to 100 prescriptions."""
def list_prescription_ai_reports(self, *, prescription_id: int = 0, diagnosis_id: int = 0, page_no: int = 1, page_size: int = 20) -> dict[str, Any]:
"""Read immutable analysis batch history in the authorized scope."""
def get_prescription_ai_report(self, batch_id: int) -> dict[str, Any]:
"""Read one analysis batch without starting model work."""
def regenerate_prescription_ai(self, prescription_id: int, reason: str) -> dict[str, Any]:
"""Explicitly request a new analysis batch with a reason."""
def retry_prescription_ai(self, batch_id: int, model_key: str) -> dict[str, Any]:
"""Retry only the requested failed model."""
def review_prescription_ai(self, batch_id: int, model_key: str, status: str, comment: str) -> dict[str, Any]:
"""Save a doctor's review separately from immutable AI output."""
def prescription_ai_statistics(self, date_from: str, date_to: str, doctor_id: int | None = None) -> dict[str, Any]:
"""Read baseline agreement statistics, never diagnostic accuracy."""
def create_prescription(
self,
@@ -335,8 +356,8 @@ class DoctorRepository(Protocol):
def get_appointment_detail(self, appointment_id: int) -> dict[str, Any]:
"""Return one appointment detail from ``doctor.appointment/detail``."""
def list_departments(self) -> list[dict[str, Any]]:
"""Return the department tree used by appointment list filters."""
def list_departments(self, *, apply_data_scope: bool = False) -> list[dict[str, Any]]:
"""Return a department tree, optionally scoped to the account's data permissions."""
def get_diagnosis_detail(self, diagnosis_id: int, *, readonly: bool = False) -> dict[str, Any]:
"""Return an editable or permission-aware readonly diagnosis detail."""
@@ -455,6 +476,14 @@ class DoctorRepository(Protocol):
def get_dictionary(self, dictionary_type: str) -> list[dict[str, Any]]:
"""Return one configuration dictionary."""
def get_dictionaries(
self, dictionary_types: Sequence[str]
) -> dict[str, list[dict[str, Any]]]:
"""Return several configuration dictionaries in one call."""
def list_chat_notifications(self) -> list[dict[str, Any]]:
"""Consume this account's queued chat notifications."""
def get_patient_order(self, order_id: int) -> dict[str, Any]:
"""Return a patient-scoped order detail."""
@@ -704,10 +733,10 @@ class DoctorRepository(Protocol):
def generate_order_qrcode(self, order_no: str) -> dict[str, Any]:
"""Generate the payment mini-program QR code for a generic order."""
def get_call_ticket(self, patient_id: int, diagnosis_id: int) -> CallTicket:
def get_call_ticket(self, patient_id: int, diagnosis_id: int, *, appointment_id: int = 0) -> CallTicket:
"""Return short-lived call credentials."""
def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int = 2) -> Any:
def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int = 2, appointment_id: int = 0) -> Any:
"""Create a call record."""
def end_call(
@@ -968,17 +997,20 @@ class RemoteDoctorRepository:
payload = self.client.get("doctor.appointment/detail", {"id": appointment_id})
return dict(_require_mapping(payload, "doctor.appointment/detail"))
def list_departments(self) -> list[dict[str, Any]]:
"""Load the department tree through ``dept.dept/all``."""
def list_departments(self, *, apply_data_scope: bool = False) -> list[dict[str, Any]]:
"""Load ``dept.dept/all`` with optional server-enforced role data scope."""
payload = self.client.get("dept.dept/all")
if isinstance(payload, list):
return [dict(row) for row in payload if isinstance(row, Mapping)]
if isinstance(payload, Mapping):
rows = payload.get("lists", payload.get("data", payload.get("tree")))
if isinstance(rows, list):
return [dict(row) for row in rows if isinstance(row, Mapping)]
return []
payload = self.client.get(
"dept.dept/all", {"apply_data_scope": 1} if apply_data_scope else None
)
for _depth in range(5):
if isinstance(payload, list):
return [dict(row) for row in payload if isinstance(row, Mapping)]
if isinstance(payload, Mapping):
payload = payload.get("lists", payload.get("data", payload.get("tree")))
else:
break
raise ApiProtocolError("部门数据格式异常,请重试")
def list_reception_queue(
self,
@@ -1563,14 +1595,55 @@ class RemoteDoctorRepository:
payload, Prescription.from_dict, page_no=page_no, page_size=page_size
)
def get_prescription(self, prescription_id: int) -> Prescription:
"""Load one issued prescription using ``tcm.prescription/detail``."""
def get_prescription(self, prescription_id: int) -> Prescription:
"""Load one issued prescription using ``tcm.prescription/detail``."""
result = _require_mapping(
self.client.get("tcm.prescription/detail", {"id": prescription_id}),
"tcm.prescription/detail",
)
return Prescription.from_dict(result)
return Prescription.from_dict(result)
def _prescription_ai_request(self, action: str, params: dict[str, Any], *, mutation: bool = False) -> dict[str, Any]:
endpoint = f"tcm.prescriptionAi/{action}"
payload = _client_request(self.client, "post" if mutation else "get", endpoint, params, timeout=30.0)
return dict(_require_mapping(payload, endpoint))
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
if len(ids) > 100 or any(int(value) <= 0 for value in ids):
raise ValueError("statuses requires at most 100 positive prescription IDs")
return self._prescription_ai_request("statuses", {"ids": ",".join(str(int(value)) for value in dict.fromkeys(ids))})
def list_prescription_ai_reports(self, *, prescription_id: int = 0, diagnosis_id: int = 0, page_no: int = 1, page_size: int = 20) -> dict[str, Any]:
if bool(prescription_id) == bool(diagnosis_id):
raise ValueError("Exactly one prescription_id or diagnosis_id is required")
params = {"prescription_id": prescription_id} if prescription_id else {"diagnosis_id": diagnosis_id}
params.update(page_no=page_no, page_size=page_size)
return self._prescription_ai_request("reports", params)
def get_prescription_ai_report(self, batch_id: int) -> dict[str, Any]:
return self._prescription_ai_request("detail", {"batch_id": batch_id})
def regenerate_prescription_ai(self, prescription_id: int, reason: str) -> dict[str, Any]:
if not reason.strip():
raise ValueError("重新分析需要填写原因")
return self._prescription_ai_request("regenerate", {"prescription_id": prescription_id, "reason": reason.strip()}, mutation=True)
def retry_prescription_ai(self, batch_id: int, model_key: str) -> dict[str, Any]:
if model_key not in {"qwen", "openai"}:
raise ValueError("Unknown model_key")
return self._prescription_ai_request("retry", {"batch_id": batch_id, "model_key": model_key}, mutation=True)
def review_prescription_ai(self, batch_id: int, model_key: str, status: str, comment: str) -> dict[str, Any]:
if model_key not in {"qwen", "openai"} or status not in {"viewed", "needs_information", "not_adopted", "reviewed"}:
raise ValueError("Invalid review state")
return self._prescription_ai_request("review", {"batch_id": batch_id, "model_key": model_key, "status": status, "comment": comment}, mutation=True)
def prescription_ai_statistics(self, date_from: str, date_to: str, doctor_id: int | None = None) -> dict[str, Any]:
params: dict[str, Any] = {"date_from": date_from, "date_to": date_to}
if doctor_id is not None:
params["doctor_id"] = doctor_id
return self._prescription_ai_request("statistics", params)
def create_prescription(
self,
@@ -1761,6 +1834,40 @@ class RemoteDoctorRepository:
payload = self.client.get("config/dict", {"type": clean})
return _dictionary_rows(payload, clean)
def get_dictionaries(
self, dictionary_types: Sequence[str]
) -> dict[str, list[dict[str, Any]]]:
"""Load several dictionaries with one request.
``ConfigLogic::getDictByType`` splits ``type`` on commas and answers
``{type_value: [rows...]}``, so readonly screens can translate every
dictionary field without one round trip per type.
"""
wanted = [
str(dictionary_type or "").strip()
for dictionary_type in dictionary_types
if str(dictionary_type or "").strip()
]
ordered = list(dict.fromkeys(wanted))
if not ordered:
return {}
payload = self.client.get("config/dict", {"type": ",".join(ordered)})
return {
dictionary_type: _dictionary_rows(payload, dictionary_type)
for dictionary_type in ordered
}
def list_chat_notifications(self) -> list[dict[str, Any]]:
"""Consume the queued chat notifications for the signed-in account.
与后台一致:``ChatController::notifications`` 取一次即消费(服务端删除缓存),
所以每条通知只会被送到一个已登录的客户端一次,不能重复轮询后再补偿。
"""
payload = self.client.get("chat/notifications")
return _mapping_rows(payload)
def list_patients(
self, *, page_no: int = 1, page_size: int = 20, **filters: Any
) -> PageResult[Patient]:
@@ -2014,7 +2121,10 @@ class RemoteDoctorRepository:
) -> PageResult[Consultation]:
"""List diagnosis records using ``tcm.diagnosis/lists``."""
request_filters = dict(filters)
request_filters = dict(filters)
department_id = request_filters.pop("department_id", None)
if department_id not in (None, ""):
request_filters.setdefault("assistant_dept_id", department_id)
start_date = str(request_filters.pop("start_date", "") or "").strip()
end_date = str(request_filters.pop("end_date", "") or "").strip()
if start_date and start_date == end_date:
@@ -2581,22 +2691,51 @@ class RemoteDoctorRepository:
)
return result
def get_call_ticket(self, patient_id: int, diagnosis_id: int) -> CallTicket:
def get_call_ticket(self, patient_id: int, diagnosis_id: int, *, appointment_id: int = 0) -> CallTicket:
"""Obtain short-lived Tencent credentials for a consultation call."""
result = _require_mapping(
self.client.post(
"tcm.diagnosis/getCallSignature",
{"patient_id": patient_id, "diagnosis_id": diagnosis_id},
result = _require_mapping(
self.client.post(
"tcm.diagnosis/getCallSignature",
{"patient_id": patient_id, "diagnosis_id": diagnosis_id, "appointment_id": appointment_id},
),
"tcm.diagnosis/getCallSignature",
)
ticket = CallTicket.from_dict(result)
"tcm.diagnosis/getCallSignature",
)
policy_fields = {
"appointment_id", "appointmentId", "appointment_type", "appointment_type_desc",
"can_video_call", "can_audio_call", "call_disabled_reason",
}
if appointment_id > 0 and not policy_fields.intersection(result):
# Older signature endpoints authenticate the patient/diagnosis but
# do not echo the appointment. Keep the requested chat context;
# never treat it as server authorization for an audio/video call.
if (
str(result.get("diagnosis_id", "")).strip() != str(diagnosis_id)
or str(result.get("patient_id", "")).strip() != str(patient_id)
or result.get("patientUserId") != f"patient_{patient_id}"
):
raise ValueError("聊天凭证与当前患者或诊单不匹配,请重新打开聊天窗口。")
result = dict(result)
result.update(
appointment_id=appointment_id,
can_video_call=False,
can_audio_call=False,
call_disabled_reason="暂未获取到本次挂号的通话权限,仍可图文聊天",
)
if appointment_id > 0:
returned_id = result.get("appointment_id")
if (
isinstance(returned_id, bool)
or not isinstance(returned_id, (int, str))
or str(returned_id).strip() != str(appointment_id)
):
raise ValueError("通话凭证与本次挂号不匹配,请重新打开聊天窗口。")
ticket = CallTicket.from_dict(result)
if ticket.diagnosis_id is None:
ticket.diagnosis_id = diagnosis_id
return ticket
def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int = 2) -> Any:
def start_call(self, diagnosis_id: int, patient_id: int, *, call_type: int = 2, appointment_id: int = 0) -> Any:
"""Create the server-side call record before ringing participants."""
payload = self.client.post(
@@ -2604,7 +2743,8 @@ class RemoteDoctorRepository:
{
"diagnosis_id": diagnosis_id,
"patient_id": patient_id,
"call_type": call_type,
"call_type": call_type,
"appointment_id": appointment_id,
},
)
if not isinstance(payload, Mapping):
@@ -42,7 +42,8 @@ from PySide6.QtWidgets import (
QWidget,
)
from .widgets import (
from ..core.appointment_modes import APPOINTMENT_MODES
from .widgets import (
display_text,
first_value,
friendly_error,
@@ -55,26 +56,25 @@ from .widgets import (
APPOINTMENT_DRAWER_QSS = r"""
QDialog#AppointmentDrawerOverlay {
background-color: transparent;
color: #111F46;
font-family: "Microsoft YaHei UI", "PingFang SC", "Noto Sans CJK SC", sans-serif;
font-size: 13px;
color: #1A1C1F;
font-size: 14px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerPanel {
background-color: #FFFFFF;
border-left: 1px solid #E6EAF5;
border-left: 1px solid #EDEDEE;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerHeader {
background-color: #FFFFFF;
border: 0;
border-bottom: 1px solid #E6EAF5;
border-bottom: 1px solid #EDEDEE;
}
QDialog#AppointmentDrawerOverlay QLabel#AppointmentDrawerTitle {
color: #111F46;
color: #1A1C1F;
font-size: 18px;
font-weight: 700;
font-weight: 600;
}
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
@@ -86,14 +86,14 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
border: 0;
border-radius: 4px;
background-color: transparent;
color: #7886AA;
color: #606163;
font-size: 22px;
font-weight: 400;
}
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:hover {
color: #4451E2;
background-color: #F0F2FF;
color: #1A1C1F;
background-color: #F0F0F0;
}
QDialog#AppointmentDrawerOverlay QScrollArea#AppointmentDrawerBody,
@@ -109,13 +109,13 @@ QDialog#AppointmentDrawerOverlay QWidget#AppointmentDrawerBodyContent {
}
QDialog#AppointmentDrawerOverlay QLabel[appointmentLabel="true"] {
color: #3F4E75;
color: #1A1C1F;
font-size: 14px;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QLabel[appointmentMuted="true"] {
color: #7886AA;
color: #606163; font-size: 13px;
}
QDialog#AppointmentDrawerOverlay QComboBox,
@@ -123,28 +123,28 @@ QDialog#AppointmentDrawerOverlay QLineEdit,
QDialog#AppointmentDrawerOverlay QPlainTextEdit {
min-height: 30px;
padding: 0 11px;
border: 1px solid #E6EAF5;
border: 1px solid #EDEDEE;
border-radius: 9px;
background-color: #FFFFFF;
color: #111F46;
selection-background-color: #5761F4;
selection-color: #FFFFFF;
color: #1A1C1F;
selection-background-color: #EEF1FA;
selection-color: #1A1C1F; font-size: 14px;
}
QDialog#AppointmentDrawerOverlay QPlainTextEdit {
padding: 7px 11px;
padding: 7px 11px; font-size: 14px;
}
QDialog#AppointmentDrawerOverlay QComboBox:hover,
QDialog#AppointmentDrawerOverlay QLineEdit:hover,
QDialog#AppointmentDrawerOverlay QPlainTextEdit:hover {
border-color: #5761F4;
border-color: #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QComboBox:focus,
QDialog#AppointmentDrawerOverlay QLineEdit:focus,
QDialog#AppointmentDrawerOverlay QPlainTextEdit:focus {
border: 2px solid #8D9BFF;
border: 2px solid #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QComboBox::drop-down {
@@ -154,81 +154,81 @@ QDialog#AppointmentDrawerOverlay QComboBox::drop-down {
QDialog#AppointmentDrawerOverlay QComboBox QAbstractItemView {
background-color: #FFFFFF;
color: #111F46;
border: 1px solid #E6EAF5;
selection-background-color: #5761F4;
selection-color: #FFFFFF;
outline: 0;
color: #1A1C1F;
border: 1px solid #EDEDEE;
selection-background-color: #EEF1FA;
selection-color: #1A1C1F;
outline: 0; font-size: 14px;
}
QDialog#AppointmentDrawerOverlay QRadioButton {
min-height: 24px;
spacing: 8px;
color: #3F4E75;
color: #1A1C1F;
}
QDialog#AppointmentDrawerOverlay QRadioButton::indicator {
width: 12px;
height: 12px;
border-radius: 7px;
border: 1px solid #E6EAF5;
border: 1px solid #EDEDEE;
background-color: #FFFFFF;
}
QDialog#AppointmentDrawerOverlay QRadioButton::indicator:hover {
border-color: #5761F4;
border-color: #4156C4;
}
QDialog#AppointmentDrawerOverlay QRadioButton::indicator:checked {
width: 4px;
height: 4px;
border: 5px solid #5761F4;
border: 5px solid #4F63D9;
border-radius: 7px;
background-color: #FFFFFF;
}
QDialog#AppointmentDrawerOverlay QRadioButton:focus {
color: #4451E2;
color: #4F63D9;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"] {
min-height: 38px;
max-height: 38px;
padding: 0;
border: 1px solid #E6EAF5;
border: 1px solid #EDEDEE;
border-radius: 8px;
background-color: #FFFFFF;
color: #3F4E75;
color: #1A1C1F;
font-size: 14px;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:hover {
color: #4451E2;
border-color: #5761F4;
background-color: #F0F2FF;
color: #4156C4;
border-color: #4156C4;
background-color: #EEF1FA;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:focus {
border-color: #8D9BFF;
border-color: #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:checked {
color: #FFFFFF;
border-color: #5761F4;
background-color: #5761F4;
border-color: #4F63D9;
background-color: #4F63D9;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentSlotsPanel {
background-color: #F7F9FE;
background-color: #F7F7F7;
border: 0;
border-radius: 8px;
}
QDialog#AppointmentDrawerOverlay QLabel#AppointmentSlotsTitle {
color: #111F46;
color: #1A1C1F;
font-size: 15px;
font-weight: 600;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
@@ -238,87 +238,83 @@ QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
border: 0;
border-radius: 4px;
background-color: transparent;
color: #4451E2;
color: #4F63D9;
font-size: 13px;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:hover {
background-color: #F0F2FF;
background-color: #EEF1FA;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] {
min-width: 110px;
min-height: 70px;
padding: 0 8px;
border: 2px solid #E6EAF5;
border: 2px solid #EDEDEE;
border-radius: 8px;
background-color: #FFFFFF;
color: #111F46;
color: #1A1C1F;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotTime {
color: #111F46;
color: #1A1C1F;
font-size: 15px;
font-weight: 600;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotStatus {
padding: 0 8px;
border-radius: 4px;
background-color: #F4F4F5;
color: #7886AA;
font-size: 12px;
background-color: #F7F7F7;
color: #606163;
font-size: 13px;
font-weight: 400;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"][availability="available"] QLabel#AppointmentSlotStatus {
color: #17A77D;
color: #287B65;
background-color: #EAF9F3;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:hover:enabled {
color: #4451E2;
border-color: #5761F4;
background-color: #F0F2FF;
color: #4156C4;
border-color: #4156C4;
background-color: #EEF1FA;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:focus:enabled {
border-color: #8D9BFF;
border-color: #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:checked {
color: #FFFFFF;
border-color: #5761F4;
background: qlineargradient(
x1:0, y1:0, x2:1, y2:1,
stop:0 #5761F4,
stop:1 #7769F7
);
border-color: #4F63D9;
background: #4F63D9;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:checked QLabel#AppointmentSlotTime,
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:checked QLabel#AppointmentSlotStatus {
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotTime[slotSelected="true"],
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotStatus[slotSelected="true"] {
color: #FFFFFF;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:checked QLabel#AppointmentSlotStatus {
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotStatus[slotSelected="true"] {
background-color: rgba(255, 255, 255, 46);
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:disabled {
color: #A4ADC3;
border-color: #E6EAF5;
background-color: #F0F2F8;
color: #8E8F90;
border-color: #EDEDEE;
background-color: #F7F7F7;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:disabled QLabel#AppointmentSlotTime,
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:disabled QLabel#AppointmentSlotStatus {
color: #A4ADC3;
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotTime:disabled,
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotStatus:disabled {
color: #8E8F90;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"]:disabled QLabel#AppointmentSlotStatus {
background-color: #F0F2F8;
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] QLabel#AppointmentSlotStatus:disabled {
background-color: #F7F7F7;
}
QDialog#AppointmentDrawerOverlay QWidget#AppointmentInlineEmpty {
@@ -326,13 +322,13 @@ QDialog#AppointmentDrawerOverlay QWidget#AppointmentInlineEmpty {
}
QDialog#AppointmentDrawerOverlay QLabel#AppointmentEmptyText {
color: #7886AA;
color: #606163;
font-size: 14px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] {
background-color: #F0F4FF;
border: 1px solid #DDE5FF;
background-color: #EEF1FA;
border: 1px solid #EDEDEE;
border-radius: 9px;
}
@@ -355,65 +351,65 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="success"] {
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] QLabel {
color: #4D69ED;
color: #4F63D9;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="warning"] QLabel {
color: #D38625;
color: #A9691D;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="danger"] QLabel {
color: #F15B67;
color: #BE4B58;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="success"] QLabel {
color: #17A77D;
color: #287B65;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter {
background-color: #FFFFFF;
border: 0;
border-top: 1px solid #E6EAF5;
border-top: 1px solid #EDEDEE;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton {
min-height: 30px;
max-height: 30px;
padding: 0 15px;
border: 1px solid #E6EAF5;
border: 1px solid #EDEDEE;
border-radius: 9px;
background-color: #FFFFFF;
color: #3F4E75;
color: #1A1C1F;
font-size: 13px;
font-weight: 600;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:hover {
color: #4451E2;
border-color: #5761F4;
background-color: #F0F2FF;
color: #4156C4;
border-color: #4156C4;
background-color: #EEF1FA;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:focus {
border-color: #8D9BFF;
border-color: #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[primary="true"] {
color: #FFFFFF;
border-color: #5761F4;
background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5761F4, stop:1 #7769F7);
border-color: #4F63D9;
background: #4F63D9;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[primary="true"]:hover {
color: #FFFFFF;
border-color: #4C57E9;
background-color: #4C57E9;
border-color: #4156C4;
background-color: #4156C4;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:disabled {
color: #FFFFFF;
border-color: #E6EAF5;
background-color: #A4ADC3;
border-color: #EDEDEE;
background-color: #8E8F90;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay {
@@ -422,7 +418,7 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay {
}
QDialog#AppointmentDrawerOverlay QLabel#AppointmentLoadingText {
color: #7886AA;
color: #606163;
font-size: 14px;
}
@@ -436,11 +432,11 @@ QDialog#AppointmentDrawerOverlay QScrollBar:vertical {
QDialog#AppointmentDrawerOverlay QScrollBar::handle:vertical {
min-height: 30px;
border-radius: 3px;
background-color: #E6EAF5;
background-color: #EDEDEE;
}
QDialog#AppointmentDrawerOverlay QScrollBar::handle:vertical:hover {
background-color: #8D9BFF;
background-color: #E4E4E5;
}
QDialog#AppointmentDrawerOverlay QScrollBar::add-line:vertical,
@@ -722,15 +718,15 @@ class _EmptyIllustration(QWidget):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#EEF2F8"))
painter.setBrush(QColor("#F7F7F7"))
painter.drawEllipse(QRect(9, 48, 62, 8))
painter.setPen(QPen(QColor("#D8DEEA"), 1))
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.setBrush(QColor("#FFFFFF"))
painter.drawRoundedRect(QRect(22, 21, 36, 27), 4, 4)
painter.setBrush(QColor("#E9EDFF"))
painter.setBrush(QColor("#F0F0F0"))
painter.drawRoundedRect(QRect(18, 15, 44, 12), 4, 4)
painter.setPen(QPen(QColor("#667085"), 2))
painter.setPen(QPen(QColor("#606163"), 2))
painter.drawLine(30, 35, 50, 35)
painter.drawLine(34, 41, 46, 41)
painter.end()
@@ -751,7 +747,7 @@ class _HoverLiftButton(QPushButton):
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(12)
shadow.setOffset(0, 4)
shadow.setColor(QColor(102, 117, 245, 72))
shadow.setColor(QColor(26, 28, 31, 72))
self.setGraphicsEffect(shadow)
self._lifted = True
super().enterEvent(event)
@@ -784,6 +780,15 @@ class _SlotCard(_HoverLiftButton):
self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.status_label.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
layout.addWidget(self.status_label)
self.toggled.connect(self._sync_label_selection)
def _sync_label_selection(self, checked: bool) -> None:
# Qt does not reliably resolve ancestor pseudo states for child labels.
for label in (self.time_label, self.status_label):
label.setProperty("slotSelected", checked)
label.style().unpolish(label)
label.style().polish(label)
label.update()
class AppointmentDrawer(QDialog):
@@ -968,13 +973,24 @@ class AppointmentDrawer(QDialog):
type_container = QWidget()
type_layout = QHBoxLayout(type_container)
type_layout.setContentsMargins(0, 0, 0, 0)
self.appointment_type_radio = QRadioButton("视频问诊")
self.appointment_type_radio.setChecked(True)
type_layout.addWidget(self.appointment_type_radio)
self.appointment_type_radio = QRadioButton("视频问诊")
self.appointment_type_radio.setChecked(True)
type_layout.addWidget(self.appointment_type_radio)
self.text_appointment_type_radio = QRadioButton("图文问诊")
type_layout.addWidget(self.text_appointment_type_radio)
self.appointment_type_group = QButtonGroup(self)
self.appointment_type_group.addButton(self.appointment_type_radio, 0)
self.appointment_type_group.addButton(self.text_appointment_type_radio, 1)
type_layout.addStretch(1)
self._add_form_row("预约类型:", type_container)
self.appointment_type = QComboBox(self)
self.appointment_type.addItem("视频问诊", "video")
for label, value in APPOINTMENT_MODES:
self.appointment_type.addItem(label, value)
self.appointment_type_group.idClicked.connect(self.appointment_type.setCurrentIndex)
self.appointment_type.currentIndexChanged.connect(
lambda index: self.appointment_type_group.button(index).setChecked(True)
if self.appointment_type_group.button(index) is not None else None
)
self.appointment_type.hide()
patient_container = QWidget()
@@ -1705,7 +1721,7 @@ class AppointmentDrawer(QDialog):
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(8, 11, 20, 196))
painter.fillRect(self.rect(), QColor(26, 28, 31, 196))
painter.end()
super().paintEvent(event)
@@ -0,0 +1,144 @@
"""Page-scoped palette and compact typography for the approved appointment list."""
from string import Template
from .reception_style import body_family, heading_family
def appointments_stylesheet() -> str:
return Template(_QSS).substitute(body=body_family(), heading=heading_family())
_QSS = """
#AppointmentsPage { background: #F3F7FD; color: #273244; }
#AppointmentsPage QLabel, #AppointmentsPage QPushButton,
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox,
#AppointmentsPage QTabBar, #AppointmentsPage QTableWidget {
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
}
#AppointmentsPage QWidget#PageHeader QLabel[role="pageTitle"] {
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
}
#AppointmentsPage QWidget#PageHeader QLabel[role="muted"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumb"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbSeparator"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbCurrent"] {
color: #5D6B80; font-size: 13px; font-weight: 400;
}
#AppointmentsPage QFrame#AppointmentFilterPanel,
#AppointmentsPage QFrame#AppointmentMainCard {
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
}
#AppointmentsPage QPushButton {
min-height: 30px; padding: 0 12px; border: 1px solid #DBE5F2;
border-radius: 6px; background: #FFFFFF;
}
#AppointmentsPage QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
#AppointmentsPage QPushButton:pressed { background: #DCEAFF; }
#AppointmentsPage QPushButton:focus { border-color: #75A5F0; }
#AppointmentsPage QPushButton[variant="primary"] {
background: #1769E8; color: #FFFFFF; border-color: #1769E8;
}
#AppointmentsPage QPushButton[variant="primary"]:hover { background: #155BCC; }
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: #124EA9; }
#AppointmentsPage QPushButton[variant="danger"] {
color: #B84652; background: #FFFFFF; border-color: #EFC8CE;
}
#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FFF0F2; }
#AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; }
#AppointmentsPage QPushButton:disabled {
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
}
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox {
min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
}
#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: #75A5F0; }
#AppointmentsPage QLineEdit QToolButton {
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
}
#AppointmentsPage QLineEdit QToolButton:focus { background: #EAF2FF; }
#AppointmentsPage QPushButton#AppointmentSearchButton {
min-height: 39px; max-height: 39px; min-width: 52px;
}
#AppointmentsPage QLineEdit#AppointmentPatientSearch { min-height: 39px; max-height: 39px; }
#AppointmentsPage QPushButton[appointmentStat="true"] {
min-height: 34px; max-height: 34px; padding: 0 10px; background: #F4F7FC;
border-color: transparent; color: #5D6B80; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: #1555B6; background: #EAF2FF; }
#AppointmentsPage QPushButton[appointmentStat="true"]:checked {
color: #FFFFFF; background: #1769E8; border-color: #1769E8;
}
#AppointmentsPage QPushButton[appointmentStatKind="warning"][hasPending="true"]:!checked {
color: #9C681F; background: #FFF6E7; border-color: #EEDCBF;
}
#AppointmentsPage QLabel#FilterRowLabel { color: #5D6B80; font-size: 13px; }
#AppointmentsPage QLabel#FilterDivider { color: #DBE5F2; padding: 0 10px; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab {
min-width: 52px; min-height: 32px; padding: 0 12px; color: #5D6B80;
background: transparent; border: 0; border-bottom: 2px solid transparent; font-size: 13px;
}
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: #1555B6; background: #F7FAFE; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:selected {
color: #1769E8; background: transparent; border-bottom-color: #1769E8;
}
#AppointmentsPage QPushButton[filterChoice="true"] {
min-height: 30px; max-height: 30px; padding: 0 12px; color: #5D6B80;
background: transparent; border-color: transparent; font-size: 13px;
}
#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: #1555B6; background: #EAF2FF; }
#AppointmentsPage QFrame#AppointmentToolbar { background: transparent; border: 0; }
#AppointmentsPage QPushButton[compactAction="true"] {
min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px;
}
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled {
color: #1769E8; border-color: #ADC8F0;
}
#AppointmentsPage QTableWidget#AppointmentTable {
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
}
#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid #E6EDF6; }
#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: #EAF2FF; color: #273244; }
#AppointmentsPage QTableWidget#AppointmentTable QHeaderView::section {
min-height: 40px; padding: 0; background: #F5F8FD; color: #5D6B80;
border: 0; border-top: 1px solid #E1E9F4; border-bottom: 1px solid #E1E9F4;
font-family: "$body"; font-size: 13px; font-weight: 400;
}
#AppointmentsPage QWidget[appointmentSelectionHost="true"] {
background: transparent; border-left: 3px solid transparent;
}
#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: #1769E8; }
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator {
width: 16px; height: 16px; background: #FFFFFF; border: 1px solid #C8D5E6; border-radius: 3px;
}
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
#AppointmentsPage QWidget[appointmentInfoHost="true"],
#AppointmentsPage QWidget[appointmentImHost="true"] { background: transparent; }
#AppointmentsPage QLabel[tableAppointmentStatus="true"] {
min-height: 20px; max-height: 20px; padding: 0 6px; color: #1555B6;
background: #EAF2FF; border-radius: 4px; font-size: 13px;
}
#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: #9C681F; background: #FFF3DD; }
#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: #66758A; background: #EEF2F7; }
#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: #5D6B80; font-size: 13px; }
#AppointmentsPage QPushButton[tableCancelAction="true"] {
min-height: 20px; max-height: 20px; padding: 0 5px; color: #B84652;
background: #FFF0F2; border: 0; border-radius: 4px; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentImAction="true"] {
min-width: 62px; min-height: 32px; max-height: 32px; padding: 0 10px;
color: #1555B6; background: #EAF2FF; border-color: #C9DCF7; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: #FFFFFF; background: #1769E8; }
#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: #8A97A9; background: #F3F6FB; border-color: #DFE7F2; }
#AppointmentsPage QWidget#Pager { background: #FFFFFF; border: 0; border-top: 1px solid #E1E9F4; }
#AppointmentsPage QWidget#Pager QLabel { color: #5D6B80; font-size: 13px; border: 0; }
#AppointmentsPage QWidget#Pager QPushButton {
min-width: 30px; max-width: 30px; min-height: 32px; max-height: 32px;
padding: 0; border: 1px solid #DBE5F2; background: #FFFFFF; color: #5D6B80; font-size: 13px;
}
#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
#AppointmentsPage QWidget#Pager QPushButton:disabled { color: #9AA6B7; background: #F7F9FC; }
"""
@@ -0,0 +1,433 @@
"""登录后常驻的聊天通知:患者打开会话、离开会话、面诊结束。
与后台 ``admin/src/components/chat-notify-toast`` 同一套合同:轮询
``chat/notifications``(服务端取一次即消费),把结果堆成右上角卡片,点击卡片进入
对应工作面,关闭按钮单独移除。桌面端额外做了一件网页做不到的事——新通知到达时让
任务栏闪一下,医生切到别的窗口也能看见。
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from PySide6.QtCore import QEvent, QObject, Qt, QTimer, Signal
from PySide6.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QVBoxLayout,
QWidget,
)
from .widgets import display_text, first_value, run_async
# 后台 ChatNotifyLogic 写入的三种 type。
PATIENT_OPENED_CHAT = "patient_opened_chat"
PATIENT_LEFT_CHAT = "patient_left_chat"
CONSULTATION_COMPLETE = "consultation_complete"
_TITLES: dict[str, str] = {
PATIENT_OPENED_CHAT: "患者打开会话",
PATIENT_LEFT_CHAT: "患者离开会话",
CONSULTATION_COMPLETE: "面诊结束",
}
_MAX_CARDS = 5
_POLL_INTERVAL_MS = 5_000
CHAT_NOTIFICATION_QSS = """
QFrame#ChatNotifyCard {
background-color: #FFFFFF;
border: 1px solid #BBF0CE;
border-radius: 12px;
}
QFrame#ChatNotifyCard[kind="left"] { border-color: #E4E4E5; }
QFrame#ChatNotifyCard[kind="complete"] { border-color: #8B9AD9; }
QLabel#ChatNotifyBadge {
min-width: 34px;
max-width: 34px;
min-height: 34px;
max-height: 34px;
color: #FFFFFF;
background-color: #287B65;
border-radius: 9px;
font-size: 15px;
font-weight: 700;
}
QLabel#ChatNotifyBadge[kind="left"] { background-color: #6A6B6D; }
QLabel#ChatNotifyBadge[kind="complete"] { background-color: #4F63D9; }
QLabel#ChatNotifyTitle { color: #1A1C1F; font-size: 13px; font-weight: 700; }
QLabel#ChatNotifyDesc { color: #1A1C1F; font-size: 12px; }
QLabel#ChatNotifyTime { color: #6A6B6D; font-size: 11px; }
QPushButton#ChatNotifyOpen {
min-height: 26px;
padding: 0 10px;
color: #4F63D9;
background-color: #EEF1FA;
border: 1px solid #EDEDEE;
border-radius: 7px;
font-size: 12px;
font-weight: 600;
}
QPushButton#ChatNotifyOpen:hover {
color: #4156C4;
background-color: #EEF1FA;
border-color: #8B9AD9;
}
QPushButton#ChatNotifyClose {
min-width: 22px;
max-width: 22px;
min-height: 22px;
max-height: 22px;
color: #6A6B6D;
background-color: transparent;
border: 0;
border-radius: 6px;
font-size: 14px;
}
QPushButton#ChatNotifyClose:hover { color: #1A1C1F; background-color: #F7F7F7; }
"""
@dataclass(frozen=True)
class ChatNotification:
"""One queued notification, normalised from the admin payload."""
id: str
kind: str
patient_name: str
patient_id: str
doctor_name: str
diagnosis_id: int
created_at: int
@property
def title(self) -> str:
return _TITLES.get(self.kind, "系统通知")
@property
def description(self) -> str:
patient = self.patient_name or "患者"
if self.kind == CONSULTATION_COMPLETE:
doctor = self.doctor_name or "医生"
return f"{patient} 的面诊已由 {doctor} 完成,请及时跟进"
if self.kind == PATIENT_LEFT_CHAT:
return f"{patient} 已离开问诊会话页面"
return f"{patient} 已打开与您的会话,请及时查看"
@property
def action_text(self) -> str:
if self.kind == CONSULTATION_COMPLETE:
return "查看诊单"
if self.kind == PATIENT_OPENED_CHAT:
return "去接诊台"
return ""
def parse_notification(row: Any) -> ChatNotification | None:
"""Normalise one server row; unknown or id-less rows are dropped."""
if not isinstance(row, Mapping):
return None
identifier = str(first_value(row, "id", default="") or "").strip()
kind = str(first_value(row, "type", default=PATIENT_OPENED_CHAT) or "").strip()
if not identifier or kind not in _TITLES:
return None
try:
diagnosis_id = int(first_value(row, "diagnosis_id", default=0) or 0)
except (TypeError, ValueError):
diagnosis_id = 0
try:
created_at = int(first_value(row, "created_at", default=0) or 0)
except (TypeError, ValueError):
created_at = 0
return ChatNotification(
id=identifier,
kind=kind,
patient_name=display_text(first_value(row, "patient_name"), ""),
patient_id=str(first_value(row, "patient_id", default="") or "").strip(),
doctor_name=display_text(first_value(row, "doctor_name"), ""),
diagnosis_id=diagnosis_id,
created_at=created_at,
)
def relative_time(created_at: int, *, now: float | None = None) -> str:
"""Match the admin card's 刚刚 / N 分钟前 wording."""
if not created_at:
return ""
current = datetime.now().timestamp() if now is None else now
delta = max(0, int(current - created_at))
if delta < 60:
return "刚刚"
if delta < 3600:
return f"{delta // 60} 分钟前"
if delta < 86400:
return f"{delta // 3600} 小时前"
return datetime.fromtimestamp(created_at).strftime("%m-%d %H:%M")
class _NotificationCard(QFrame):
"""One dismissible card; the whole surface is a click target."""
opened = Signal(str)
dismissed = Signal(str)
def __init__(self, notification: ChatNotification, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.notification = notification
self.setObjectName("ChatNotifyCard")
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
self.setCursor(Qt.CursorShape.PointingHandCursor)
kind = (
"complete"
if notification.kind == CONSULTATION_COMPLETE
else "left"
if notification.kind == PATIENT_LEFT_CHAT
else "opened"
)
self.setProperty("kind", kind)
root = QHBoxLayout(self)
root.setContentsMargins(13, 11, 10, 12)
root.setSpacing(11)
badge = QLabel("✓" if kind == "complete" else "→" if kind == "left" else "话")
badge.setObjectName("ChatNotifyBadge")
badge.setProperty("kind", kind)
badge.setAlignment(Qt.AlignmentFlag.AlignCenter)
root.addWidget(badge, 0, Qt.AlignmentFlag.AlignTop)
body = QVBoxLayout()
body.setContentsMargins(0, 0, 0, 0)
body.setSpacing(3)
title = QLabel(notification.title)
title.setObjectName("ChatNotifyTitle")
body.addWidget(title)
description = QLabel(notification.description)
description.setObjectName("ChatNotifyDesc")
description.setWordWrap(True)
body.addWidget(description)
self.time_label = QLabel(relative_time(notification.created_at))
self.time_label.setObjectName("ChatNotifyTime")
body.addWidget(self.time_label)
if notification.action_text:
actions = QHBoxLayout()
actions.setContentsMargins(0, 4, 0, 0)
actions.setSpacing(8)
self.open_button = QPushButton(notification.action_text)
self.open_button.setObjectName("ChatNotifyOpen")
self.open_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.open_button.clicked.connect(lambda: self.opened.emit(self.notification.id))
actions.addWidget(self.open_button)
actions.addStretch(1)
body.addLayout(actions)
root.addLayout(body, 1)
self.close_button = QPushButton("×")
self.close_button.setObjectName("ChatNotifyClose")
self.close_button.setCursor(Qt.CursorShape.PointingHandCursor)
self.close_button.setToolTip("忽略这条通知")
self.close_button.clicked.connect(lambda: self.dismissed.emit(self.notification.id))
root.addWidget(self.close_button, 0, Qt.AlignmentFlag.AlignTop)
def refresh_time(self) -> None:
self.time_label.setText(relative_time(self.notification.created_at))
def mouseReleaseEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
if event.button() == Qt.MouseButton.LeftButton:
self.opened.emit(self.notification.id)
super().mouseReleaseEvent(event)
class ChatNotificationCenter(QWidget):
"""Polls the server queue and stacks cards over the shell's top-right corner."""
notification_activated = Signal(object)
def __init__(
self,
repository: Any,
host: QWidget,
*,
interval_ms: int = _POLL_INTERVAL_MS,
) -> None:
super().__init__(host)
self.repository = repository
self.setObjectName("ChatNotifyLayer")
self.setStyleSheet(CHAT_NOTIFICATION_QSS)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False)
self._cards: dict[str, _NotificationCard] = {}
self._pending: list[ChatNotification] = []
self._loading = False
self._generation = 0
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(10)
self._layout = layout
self.hide()
self._timer = QTimer(self)
self._timer.setInterval(max(1_000, int(interval_ms)))
self._timer.timeout.connect(self.poll)
self._clock = QTimer(self)
self._clock.setInterval(30_000)
self._clock.timeout.connect(self._refresh_times)
host.installEventFilter(self)
# ----- polling ------------------------------------------------------
def start(self) -> None:
if not self._timer.isActive():
self._timer.start()
self._clock.start()
self.poll()
def stop(self) -> None:
self._generation += 1
self._timer.stop()
self._clock.stop()
def poll(self) -> None:
"""Ask for queued notifications; overlapping polls are skipped.
服务端取一次即消费,重叠请求会让通知丢在被丢弃的那次响应里。
"""
if self._loading:
return
fetch = getattr(self.repository, "list_chat_notifications", None)
if not callable(fetch):
return
self._loading = True
generation = self._generation
run_async(
fetch,
on_success=lambda rows: self._loaded(generation, rows),
on_error=lambda _error: None, # 静默失败,避免打断问诊
on_finished=self._finished,
)
def _finished(self) -> None:
self._loading = False
def _loaded(self, generation: int, rows: Any) -> None:
if generation != self._generation:
return
self.add_notifications(rows)
# ----- cards --------------------------------------------------------
@property
def pending(self) -> list[ChatNotification]:
return list(self._pending)
def add_notifications(self, rows: Any) -> int:
"""Show new cards; returns how many were actually added."""
if isinstance(rows, Mapping) or not isinstance(rows, Sequence):
candidates: Sequence[Any] = [rows]
else:
candidates = rows
added = 0
for row in candidates:
notification = parse_notification(row)
if notification is None or notification.id in self._cards:
continue
self._add_card(notification)
added += 1
if added:
self._trim()
self._relayout()
self._alert_taskbar()
return added
def _add_card(self, notification: ChatNotification) -> None:
card = _NotificationCard(notification, self)
card.opened.connect(self._activate)
card.dismissed.connect(self.dismiss)
self._cards[notification.id] = card
self._pending.insert(0, notification)
self._layout.insertWidget(0, card)
def _trim(self) -> None:
while len(self._pending) > _MAX_CARDS:
self.dismiss(self._pending[-1].id, relayout=False)
def dismiss(self, notification_id: str, *, relayout: bool = True) -> None:
card = self._cards.pop(str(notification_id), None)
self._pending = [item for item in self._pending if item.id != str(notification_id)]
if card is not None:
self._layout.removeWidget(card)
card.hide()
card.deleteLater()
if relayout:
self._relayout()
def clear(self) -> None:
for notification_id in list(self._cards):
self.dismiss(notification_id, relayout=False)
self._relayout()
def _activate(self, notification_id: str) -> None:
card = self._cards.get(str(notification_id))
if card is None:
return
notification = card.notification
self.dismiss(notification_id)
self.notification_activated.emit(notification)
def _refresh_times(self) -> None:
for card in self._cards.values():
card.refresh_time()
def _alert_taskbar(self) -> None:
"""Flash the taskbar entry when the doctor is working in another window."""
application = QApplication.instance()
window = self.window()
if application is None or window is None or window.isActiveWindow():
return
application.alert(window, 3_000)
# ----- placement ----------------------------------------------------
def _relayout(self) -> None:
if not self._cards:
self.hide()
return
host = self.parentWidget()
if host is None:
return
width = min(360, max(260, host.width() - 48))
self.setFixedWidth(width)
self.adjustSize()
self.move(max(12, host.width() - width - 24), 74)
self.show()
self.raise_()
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt virtual
if watched is self.parentWidget() and event.type() in {
QEvent.Type.Resize,
QEvent.Type.Show,
}:
self._relayout()
return False
__all__ = [
"CHAT_NOTIFICATION_QSS",
"CONSULTATION_COMPLETE",
"PATIENT_LEFT_CHAT",
"PATIENT_OPENED_CHAT",
"ChatNotification",
"ChatNotificationCenter",
"parse_notification",
"relative_time",
]
@@ -0,0 +1,131 @@
"""Scoped colors and compact typography for the approved consultation list."""
from string import Template
from .reception_style import body_family, heading_family
def consultations_stylesheet() -> str:
return Template(_QSS).substitute(body=body_family(), heading=heading_family())
_QSS = """
#DiagnosisIndex, #DiagnosisIndexContent, #DiagnosisPageScroll {
background: #F3F7FD; color: #273244; border: 0;
}
#DiagnosisIndex QLabel, #DiagnosisIndex QPushButton, #DiagnosisIndex QToolButton,
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit,
#DiagnosisIndex QSpinBox, #DiagnosisIndex QTableView {
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
}
#DiagnosisIndex QWidget#PageHeader QLabel[role="pageTitle"] {
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
}
#DiagnosisIndex QLabel[role="muted"], #DiagnosisIndex QLabel[role="breadcrumb"],
#DiagnosisIndex QLabel[role="breadcrumbCurrent"], #DiagnosisIndex QLabel[role="breadcrumbSeparator"],
#DiagnosisIndex QLabel[filterGroup="true"], #DiagnosisIndex QLabel[pagerMuted="true"] {
color: #5D6B80; font-size: 13px;
}
#DiagnosisIndex QFrame#DiagnosisFilterCard, #DiagnosisIndex QFrame#DiagnosisListCard {
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
}
#DiagnosisIndex QFrame#DiagnosisStatusCard, #DiagnosisIndex QFrame#DiagnosisQuickFilters,
#DiagnosisIndex QFrame#DiagnosisListToolbar { background: transparent; border: 0; }
#DiagnosisIndex QFrame#DiagnosisAdvancedFilters {
background: transparent; border: 0; border-top: 1px solid #E6EDF6; border-radius: 0;
}
#DiagnosisIndex QPushButton {
min-height: 34px; padding: 0 13px; border: 1px solid #DBE5F2;
border-radius: 6px; background: #FFFFFF;
}
#DiagnosisIndex QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
#DiagnosisIndex QPushButton:pressed { background: #DCEAFF; }
#DiagnosisIndex QPushButton:focus { border-color: #75A5F0; }
#DiagnosisIndex QPushButton[variant="primary"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
#DiagnosisIndex QPushButton[variant="primary"]:hover { background: #155BCC; }
#DiagnosisIndex QPushButton[consultationTool="true"] { color: #1555B6; border-color: #C2D5EF; }
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: #BE4B58; border-color: #EBCDD2; }
#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled {
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
}
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox {
min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
font-size: 13px;
}
#DiagnosisIndex QLineEdit:focus, #DiagnosisIndex QComboBox:focus,
#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: #75A5F0; }
#DiagnosisIndex QLineEdit QToolButton {
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
}
#DiagnosisIndex QComboBox::drop-down, #DiagnosisIndex QDateEdit::drop-down {
width: 22px; border: 0; background: transparent;
}
#DiagnosisIndex QComboBox QAbstractItemView {
color: #273244; background: #FFFFFF; border: 1px solid #DBE5F2;
selection-background-color: #EAF2FF; selection-color: #1555B6; outline: 0;
}
#DiagnosisIndex QWidget#DiagnosisStatusSearch QLineEdit,
#DiagnosisIndex QWidget#DiagnosisStatusSearch QPushButton { min-height: 39px; max-height: 39px; }
#DiagnosisIndex QToolButton { min-width: 0; min-height: 0; border: 0; padding: 0; background: transparent; }
#DiagnosisIndex QToolButton[diagnosisChip="true"] {
min-height: 32px; max-height: 32px; padding: 0 14px; border: 1px solid transparent;
border-radius: 5px; color: #5D6B80; background: transparent; font-size: 13px;
}
#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: #F2F7FF; color: #1555B6; }
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: #1769E8; color: #FFFFFF; }
#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; border-color: #E1E9F4; }
#DiagnosisIndex QToolButton[dateChoice="true"]:checked { border-color: #1769E8; }
#DiagnosisIndex QToolButton[statusTab="true"] {
min-height: 44px; max-height: 44px; padding: 0 20px; border: 0;
border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
}
#DiagnosisIndex QToolButton[statusTab="true"]:checked {
color: #1769E8; background: transparent; border-bottom-color: #1769E8;
}
#DiagnosisIndex QToolButton#DiagnosisMoreFilter {
min-height: 32px; padding: 0 6px; color: #5D6B80; font-size: 13px;
}
#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: #1769E8; background: #F2F7FF; }
#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: #E1E9F4; border: 0; }
#DiagnosisIndex QFrame#DiagnosisDateRange {
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px;
}
#DiagnosisIndex QDateEdit[diagnosisRangePart="true"] { min-height: 30px; padding: 0 4px; border: 0; }
#DiagnosisIndex QTableView {
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
}
#DiagnosisIndex QTableView QHeaderView::section {
min-height: 41px; padding: 0; background: #F5F8FD; color: #5D6B80;
border: 0; border-bottom: 1px solid #E1E9F4;
font-family: "$body"; font-size: 13px; font-weight: 400;
}
#DiagnosisIndex QToolButton[rowLink], #DiagnosisIndex QToolButton[appointmentCancel="true"] {
color: #1769E8; min-height: 26px; padding: 0 4px; border: 0; background: transparent; font-size: 13px;
}
#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: #BE4B58; }
#DiagnosisIndex QToolButton[rowLink]:hover { color: #1555B6; background: #DCEAFF; border-radius: 4px; }
#DiagnosisIndex QToolButton[rowLink="muted"], #DiagnosisIndex QLabel[fixedMuted="true"] {
color: #5D6B80; font-size: 13px;
}
#DiagnosisIndex QToolButton#DiagnosisRowMore { padding-right: 18px; }
#DiagnosisIndex QWidget#DiagnosisFixedCell { background: transparent; }
#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: #5D6B80; background: #FFFFFF; }
#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: #BE4B58; }
#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid #E1E9F4; }
#DiagnosisIndex QWidget#DiagnosisPager { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
#DiagnosisIndex QToolButton[pagerButton="true"] {
min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px;
border: 1px solid #DBE5F2; border-radius: 5px; color: #5D6B80; background: #FFFFFF;
}
#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: #A4B0C0; background: #F6F8FC; }
#DiagnosisIndex QComboBox#DiagnosisPageSize { min-width: 95px; min-height: 30px; }
#DiagnosisIndex QSpinBox#DiagnosisPageJumper { min-height: 30px; padding: 0 8px; }
#DiagnosisIndex QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
#DiagnosisIndex QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
#DiagnosisIndex QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
#DiagnosisIndex QScrollBar::add-line, #DiagnosisIndex QScrollBar::sub-line { width: 0; height: 0; }
#DiagnosisIndex QScrollBar::add-page, #DiagnosisIndex QScrollBar::sub-page { background: transparent; }
"""
File diff suppressed because it is too large Load Diff

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