Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
691c749f34 | ||
|
|
40319eea41 | ||
|
|
c1f7287331 | ||
|
|
9d91ff90ae | ||
|
|
1b8e166b33 | ||
|
|
0cea43b027 | ||
|
|
d0e2422155 | ||
|
|
9206d5ea62 | ||
|
|
bd0a3d3b96 | ||
|
|
a5f4c4472d | ||
|
|
9ef6eb8d67 | ||
|
|
d5164b7369 | ||
|
|
cf3fbdc5ef | ||
|
|
928f72ec3d | ||
|
|
b4c11881b4 | ||
|
|
58ffde808f | ||
|
|
486acc465d | ||
|
|
398f9f3726 | ||
|
|
5bd5eae62d | ||
|
|
456dd667df | ||
|
|
ed48f8be31 | ||
|
|
5e22d423d4 | ||
|
|
7f1ed49cc8 | ||
|
|
43ad07208f | ||
|
|
4b8b4eb649 | ||
|
|
75e214dc08 | ||
|
|
74ff568ba4 | ||
|
|
2fa8492c56 | ||
|
|
b5b14516a1 | ||
|
|
381fe65367 | ||
|
|
af603a4e9a | ||
|
|
f24afa116f | ||
|
|
b8ccbaf567 | ||
|
|
af1db59c07 |
@@ -32,3 +32,4 @@ app/.test-tmp-stream/
|
||||
/.spool
|
||||
TUICallKit-Vue3/.env
|
||||
/.codegraph
|
||||
app/artifacts/
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
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,/)
|
||||
}
|
||||
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'
|
||||
]
|
||||
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 })
|
||||
@@ -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
|
||||
|
||||
@@ -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,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' })
|
||||
|
||||
@@ -424,6 +424,11 @@ 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
|
||||
@@ -578,6 +583,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 })
|
||||
|
||||
@@ -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>
|
||||
@@ -140,6 +143,7 @@ import {
|
||||
import { CallLocalRecorder } from '@/utils/call-local-recorder'
|
||||
import { captureVideoFrameFromElement } from '@/utils/call-video-screenshot'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { appointmentTypeDescription } from '@/utils/appointment-type'
|
||||
import {
|
||||
formatTUICallUserError,
|
||||
getTUICallPackageArrearsMessage,
|
||||
@@ -180,6 +184,8 @@ const visible = ref(false)
|
||||
const isReady = ref(false)
|
||||
const error = ref('')
|
||||
const patientName = ref('')
|
||||
const appointmentType = ref<string | null | undefined>('video')
|
||||
const appointmentTypeLabel = computed(() => appointmentTypeDescription(appointmentType.value))
|
||||
const patientId = ref<number | null>(null)
|
||||
const diagnosisId = ref<number | null>(null)
|
||||
const loadingText = ref('正在初始化...')
|
||||
@@ -1010,13 +1016,14 @@ 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; appointmentType?: string | null }) => {
|
||||
visible.value = true
|
||||
isMinimized.value = false
|
||||
posX.value = 100
|
||||
posY.value = 80
|
||||
resetCallKitPositionToLeft()
|
||||
patientName.value = data.patientName
|
||||
appointmentType.value = data.appointmentType
|
||||
patientId.value = data.patientId
|
||||
diagnosisId.value = data.diagnosisId || null
|
||||
error.value = ''
|
||||
@@ -1426,6 +1433,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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** 展示当前挂号的问诊方式;旧记录的空值默认视频。 */
|
||||
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 '未知'
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: '手工备注',
|
||||
|
||||
@@ -182,7 +182,6 @@
|
||||
<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>
|
||||
|
||||
@@ -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"
|
||||
@@ -1511,7 +1522,9 @@
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
<!-- 订单退款:须填写原因 -->
|
||||
<prescription-order-time-dialog ref="orderTimeDialogRef" @saved="onOrderTimeSaved" />
|
||||
|
||||
<!-- 订单退款:须填写原因 -->
|
||||
<el-dialog
|
||||
v-model="refundOrderDialogVisible"
|
||||
title="订单退款"
|
||||
@@ -2031,7 +2044,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,
|
||||
@@ -3087,7 +3101,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)
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -2566,12 +2576,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 +2596,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 {
|
||||
@@ -3513,7 +3525,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 +3858,8 @@ function logActionText(act: string) {
|
||||
patch_rx_patient: '处方患者信息',
|
||||
update_amount: '修改订单金额',
|
||||
complete: '完成订单',
|
||||
refund: '退款'
|
||||
refund: '退款',
|
||||
edit_time: '修改创建时间'
|
||||
}
|
||||
return m[act] || act
|
||||
}
|
||||
|
||||
@@ -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,7 +448,7 @@ 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: '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: '业务订单,按创建人归属并过滤无效单' },
|
||||
@@ -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>
|
||||
|
||||
@@ -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 ''
|
||||
}
|
||||
@@ -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
|
||||
@@ -456,6 +457,7 @@ const handleCall = async (row: QueueRow) => {
|
||||
patientId: sourcePatientId,
|
||||
patientName: row.patient_name,
|
||||
diagnosisId,
|
||||
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>
|
||||
|
||||
@@ -1022,6 +1022,7 @@ const handleChat = async (row: any) => {
|
||||
patientId: sourcePatientId,
|
||||
patientName: row.patient_name,
|
||||
diagnosisId,
|
||||
appointmentType: row.appointment_type,
|
||||
signatureData: res // 传入签名数据
|
||||
})
|
||||
} catch (error: any) {
|
||||
|
||||
@@ -662,6 +662,7 @@ const handleChat = async (row: any) => {
|
||||
patientId: sourcePatientId,
|
||||
patientName: row.patient_name,
|
||||
diagnosisId,
|
||||
appointmentType: row.appointment_type,
|
||||
signatureData: res
|
||||
})
|
||||
} catch (e: any) {
|
||||
|
||||
@@ -32,8 +32,9 @@
|
||||
|
||||
<!-- 预约类型 -->
|
||||
<el-form-item label="预约类型:">
|
||||
<el-radio-group v-model="form.appointmentType">
|
||||
<el-radio value="video">视频问诊</el-radio>
|
||||
<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>
|
||||
|
||||
|
||||
@@ -1775,9 +1775,31 @@ const appointmentCellClasses = (row: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅已预约(1)可进视频/小程序码 */
|
||||
const isAppointmentActiveForVideo = (row: any) =>
|
||||
row.has_appointment && Number(row.appointment_status) === 1
|
||||
/**
|
||||
* 找到当前可用的已预约挂号。
|
||||
* 同一诊单当天可能先完成一条挂号、随后又新增一条预约,此时行级 appointment_* 仍可能指向旧记录。
|
||||
*/
|
||||
const activeAppointment = (row: any) =>
|
||||
appointmentRows(row).find((apt: any) => Number(apt?.status) === 1) ?? null
|
||||
|
||||
/** 二维码必须使用已预约挂号对应的医生和时间,不能继续沿用行级旧挂号字段。 */
|
||||
const activeAppointmentRow = (row: any) => {
|
||||
const apt = activeAppointment(row)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/** 任一挂号记录处于已预约(1)即可进视频/小程序码。 */
|
||||
const isAppointmentActiveForVideo = (row: any) => !!activeAppointment(row)
|
||||
|
||||
/** 已预约、已过号可取消(后端同步限制),针对行上主字段 */
|
||||
const canCancelAppointmentRow = (row: any) => {
|
||||
@@ -1962,17 +1984,18 @@ 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)
|
||||
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 +2006,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 +2027,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 +2057,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 || ''
|
||||
})
|
||||
|
||||
|
||||
@@ -946,8 +946,28 @@ const appointmentRowClass = (row: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
const isAppointmentActiveForVideo = (row: any) =>
|
||||
row.has_appointment && Number(row.appointment_status) === 1
|
||||
/**
|
||||
* 同一诊单可能同时有已完成的旧挂号和已预约的新挂号,二维码应使用明细里的有效预约。
|
||||
*/
|
||||
const activeAppointment = (row: any) =>
|
||||
appointmentRows(row).find((apt: any) => Number(apt?.status) === 1) ?? null
|
||||
|
||||
const activeAppointmentRow = (row: any) => {
|
||||
const apt = activeAppointment(row)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
const isAppointmentActiveForVideo = (row: any) => !!activeAppointment(row)
|
||||
|
||||
const canCancelAppointmentRow = (row: any) => {
|
||||
const s = Number(row.appointment_status)
|
||||
@@ -1241,13 +1261,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)
|
||||
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 +1279,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 +1296,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 +1314,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
|
||||
|
||||
@@ -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,154 @@
|
||||
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, /企微请求超时/)
|
||||
})
|
||||
|
After Width: | Height: | Size: 164 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 73 KiB |
@@ -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,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"]
|
||||
|
||||
|
||||
@@ -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`。
|
||||
|
||||
@@ -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 契约,再运行相关完整测试和冻结构建门禁;仅本分析任务未修改生产代码、也未执行会连接线上环境的测试。
|
||||
@@ -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。只有这四层都成立,才不是单纯的视觉隐藏。
|
||||
@@ -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` 逐字符匹配;清单恰好包含两条记录。
|
||||
@@ -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`.
|
||||
@@ -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` 逐字符一致。
|
||||
@@ -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,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`、当前用户开始菜单快捷方式及本次当前用户卸载注册表键均不存在。隔离测试根目录按设计保留,仅包含安装/卸载日志和隔离应用日志,便于审计。
|
||||
@@ -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 不消费该形态。
|
||||
@@ -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))
|
||||
@@ -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 可读取。
|
||||
- 工作树原本已有大量未提交改动,包括本报告涉及的生产文件和测试;本次未修改、覆盖或回退它们。
|
||||
- 除新增本文档外,没有修改生产代码或测试。
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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" ;;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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()
|
||||
@@ -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.2"
|
||||
|
||||
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
||||
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
||||
DEBUG_MODE = False
|
||||
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
|
||||
|
||||
@@ -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,19 @@ 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.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 +507,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 +670,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,6 +718,7 @@ 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):
|
||||
@@ -580,6 +749,7 @@ class ApplicationController(QObject):
|
||||
diagnosis_id = payload.get("diagnosis_id")
|
||||
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
|
||||
@@ -633,19 +803,40 @@ class ApplicationController(QObject):
|
||||
marker = object()
|
||||
self.video_pending[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),
|
||||
)
|
||||
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 +844,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,
|
||||
@@ -698,6 +890,7 @@ 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
|
||||
@@ -725,6 +918,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: (
|
||||
self._open_video_diagnosis(current_id)
|
||||
),
|
||||
)
|
||||
except Exception as error:
|
||||
LOGGER.exception("video call could not be launched")
|
||||
@@ -745,7 +942,110 @@ class ApplicationController(QObject):
|
||||
)
|
||||
)
|
||||
|
||||
def _open_video_diagnosis(self, diagnosis_id: Any) -> 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(str(diagnosis_id))
|
||||
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 +1072,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 +1092,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 +1167,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)
|
||||
|
||||
@@ -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"}:
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -335,8 +335,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 +455,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."""
|
||||
|
||||
@@ -968,17 +976,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,
|
||||
@@ -1761,6 +1772,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 +2059,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:
|
||||
|
||||
@@ -55,26 +55,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 +85,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 +108,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 +122,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 +153,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 +237,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 +321,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 +350,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 +417,7 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay {
|
||||
}
|
||||
|
||||
QDialog#AppointmentDrawerOverlay QLabel#AppointmentLoadingText {
|
||||
color: #7886AA;
|
||||
color: #606163;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@@ -436,11 +431,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 +717,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 +746,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 +779,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):
|
||||
@@ -1705,7 +1709,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; }
|
||||
"""
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Safe in-application replay players for diagnosis call recordings.
|
||||
"""Safe in-application viewers for diagnosis recordings and attachment images.
|
||||
|
||||
The web diagnosis page keeps the preferred recording in the table and lists
|
||||
the remaining sources underneath it. This module mirrors that contract with
|
||||
QtMultimedia while retaining the older standalone dialog as a codec fallback.
|
||||
Attachment images follow the same rule: they are previewed inside the
|
||||
workstation like the admin ``el-image`` viewer, never handed straight to the
|
||||
operating system.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,14 +15,16 @@ import weakref
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import Qt, QUrl, Signal
|
||||
from PySide6.QtGui import QCloseEvent, QDesktopServices
|
||||
from PySide6.QtCore import QCoreApplication, QObject, QSize, Qt, QUrl, Signal
|
||||
from PySide6.QtGui import QCloseEvent, QDesktopServices, QKeyEvent, QPixmap, QResizeEvent
|
||||
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QScrollArea,
|
||||
QSizePolicy,
|
||||
QSlider,
|
||||
QStackedLayout,
|
||||
@@ -129,63 +134,63 @@ def open_safe_http_url(target: str) -> bool:
|
||||
_INLINE_PLAYER_QSS = """
|
||||
QWidget#DiagnosisInlineRecordingPlayer {
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #E6EAF5;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QFrame#DiagnosisInlineRecordingSurface {
|
||||
background: #11182E;
|
||||
background: #1A1C1F;
|
||||
border: 0;
|
||||
border-radius: 8px 8px 0 0;
|
||||
}
|
||||
QLabel#DiagnosisInlineRecordingPlaceholder {
|
||||
color: #C7D0E8;
|
||||
color: #E4E4E5;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
QLabel#DiagnosisInlineRecordingTime {
|
||||
color: #64739A;
|
||||
color: #6A6B6D;
|
||||
font-size: 11px;
|
||||
}
|
||||
QPushButton[recordingControl="true"] {
|
||||
min-height: 24px;
|
||||
max-height: 24px;
|
||||
padding: 0 8px;
|
||||
color: #3F4E75;
|
||||
background: #FAFBFE;
|
||||
border: 1px solid #D8DEEE;
|
||||
color: #1A1C1F;
|
||||
background: #F7F7F7;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QPushButton[recordingControl="true"]:hover,
|
||||
QPushButton[recordingControl="true"]:focus {
|
||||
color: #4451E2;
|
||||
background: #F0F2FF;
|
||||
border-color: #8D9BFF;
|
||||
color: #4156C4;
|
||||
background: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
QPushButton#DiagnosisInlineRecordingPlay {
|
||||
color: #FFFFFF;
|
||||
background: #5761F4;
|
||||
border-color: #5761F4;
|
||||
background: #4F63D9;
|
||||
border-color: #4F63D9;
|
||||
}
|
||||
QPushButton#DiagnosisInlineRecordingPlay:hover,
|
||||
QPushButton#DiagnosisInlineRecordingPlay:focus {
|
||||
color: #FFFFFF;
|
||||
background: #4C57E9;
|
||||
border-color: #4C57E9;
|
||||
background: #4156C4;
|
||||
border-color: #4156C4;
|
||||
}
|
||||
QPushButton[recordingControl="true"]:disabled {
|
||||
color: #A4ADC3;
|
||||
background: #F0F2F8;
|
||||
border-color: #E6EAF5;
|
||||
color: #8E8F90;
|
||||
background: #F7F7F7;
|
||||
border-color: #EDEDEE;
|
||||
}
|
||||
QSlider::groove:horizontal { height: 3px; background: #D8DEEE; border-radius: 1px; }
|
||||
QSlider::sub-page:horizontal { background: #5761F4; border-radius: 1px; }
|
||||
QSlider::groove:horizontal { height: 3px; background: #E4E4E5; border-radius: 1px; }
|
||||
QSlider::sub-page:horizontal { background: #4F63D9; border-radius: 1px; }
|
||||
QSlider::handle:horizontal {
|
||||
width: 10px;
|
||||
margin: -4px 0;
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #5761F4;
|
||||
border: 1px solid #4F63D9;
|
||||
border-radius: 5px;
|
||||
}
|
||||
"""
|
||||
@@ -461,11 +466,11 @@ class RecordingPlaybackCell(QWidget):
|
||||
separator = QFrame()
|
||||
separator.setObjectName("DiagnosisRecordingAlternateSeparator")
|
||||
separator.setFrameShape(QFrame.Shape.HLine)
|
||||
separator.setStyleSheet("color:#E6EAF5;")
|
||||
separator.setStyleSheet("color:#EDEDEE;")
|
||||
layout.addWidget(separator)
|
||||
label = QLabel("备用地址")
|
||||
label.setObjectName("DiagnosisRecordingAlternateLabel")
|
||||
label.setStyleSheet("color:#7886AA; font-size:12px;")
|
||||
label.setStyleSheet("color:#606163; font-size:12px;")
|
||||
layout.addWidget(label)
|
||||
links = QHBoxLayout()
|
||||
links.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -485,7 +490,7 @@ class RecordingPlaybackCell(QWidget):
|
||||
layout.addLayout(links)
|
||||
self.link_status = QLabel("")
|
||||
self.link_status.setObjectName("DiagnosisRecordingLinkStatus")
|
||||
self.link_status.setStyleSheet("color:#D94856; font-size:11px;")
|
||||
self.link_status.setStyleSheet("color:#BE4B58; font-size:11px;")
|
||||
self.link_status.setWordWrap(True)
|
||||
self.link_status.hide()
|
||||
layout.addWidget(self.link_status)
|
||||
@@ -656,6 +661,454 @@ class RecordingPlayerDialog(QDialog):
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
def shared_image_manager(fallback_parent: QObject | None = None) -> QNetworkAccessManager:
|
||||
"""Return the one image download manager owned by the application.
|
||||
|
||||
每个缩略图/预览窗口原来各自持有 ``QNetworkAccessManager``:关闭抽屉或对话框
|
||||
时,网络栈会连同尚未结束的请求一起析构,Windows 上直接以 0xC0000374 结束
|
||||
进程。改为由 QApplication 持有唯一管理器,请求可以比任何控件活得更久。
|
||||
"""
|
||||
|
||||
app = QCoreApplication.instance()
|
||||
if app is None:
|
||||
return QNetworkAccessManager(fallback_parent)
|
||||
manager = getattr(app, "_doctor_image_network_manager", None)
|
||||
if isinstance(manager, QNetworkAccessManager):
|
||||
try:
|
||||
manager.parent()
|
||||
except RuntimeError: # the C++ object was destroyed behind the wrapper
|
||||
manager = None
|
||||
if not isinstance(manager, QNetworkAccessManager):
|
||||
manager = QNetworkAccessManager(app)
|
||||
app._doctor_image_network_manager = manager
|
||||
return manager
|
||||
|
||||
|
||||
_IMAGE_SUFFIX_PATTERN = re.compile(
|
||||
r"\.(?:png|jpe?g|jfif|gif|bmp|webp|tiff?|heic|heif|avif)(?:\?|#|$)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def is_previewable_image(target: str) -> bool:
|
||||
"""Return whether a safe remote source can be decoded as an inline image."""
|
||||
|
||||
url = safe_http_url(target)
|
||||
if url is None:
|
||||
return False
|
||||
return bool(
|
||||
_IMAGE_SUFFIX_PATTERN.search(url.path() or "")
|
||||
or _IMAGE_SUFFIX_PATTERN.search(url.toString())
|
||||
)
|
||||
|
||||
|
||||
def safe_image_sources(sources: Sequence[Any] | Any) -> list[str]:
|
||||
"""Keep the ordered HTTP(S) sources a preview window can actually fetch."""
|
||||
|
||||
return [
|
||||
target
|
||||
for target in normalize_recording_urls(sources)
|
||||
if safe_http_url(target) is not None
|
||||
]
|
||||
|
||||
|
||||
def image_display_name(target: str, ordinal: int) -> str:
|
||||
"""Name an attachment from its own path so previews never invent a title."""
|
||||
|
||||
url = safe_http_url(target)
|
||||
name = ((url.path() if url is not None else "") or "").rsplit("/", 1)[-1].strip()
|
||||
return name or f"图片 {ordinal}"
|
||||
|
||||
|
||||
_IMAGE_PREVIEW_QSS = """
|
||||
QDialog#DiagnosisImagePreview { background: #FFFFFF; }
|
||||
QLabel#DiagnosisImagePreviewName { color: #1A1C1F; font-size: 14px; font-weight: 600; }
|
||||
QLabel#DiagnosisImagePreviewCounter { color: #6A6B6D; font-size: 12px; }
|
||||
QLabel#DiagnosisImagePreviewStatus { color: #6A6B6D; font-size: 12px; }
|
||||
QLabel#DiagnosisImagePreviewStatus[kind="danger"] { color: #BE4B58; }
|
||||
QLabel#DiagnosisImagePreviewStatus[kind="warning"] { color: #A9691D; }
|
||||
QScrollArea#DiagnosisImagePreviewViewport {
|
||||
background: #1A1C1F;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QLabel#DiagnosisImagePreviewCanvas {
|
||||
background: #1A1C1F;
|
||||
color: #E4E4E5;
|
||||
font-size: 12px;
|
||||
}
|
||||
QPushButton[imagePreviewControl="true"] {
|
||||
min-height: 28px;
|
||||
padding: 0 12px;
|
||||
color: #1A1C1F;
|
||||
background: #F7F7F7;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 7px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QPushButton[imagePreviewControl="true"]:hover,
|
||||
QPushButton[imagePreviewControl="true"]:focus {
|
||||
color: #4156C4;
|
||||
background: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
QPushButton[imagePreviewControl="true"]:disabled {
|
||||
color: #8E8F90;
|
||||
background: #F7F7F7;
|
||||
border-color: #EDEDEE;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class ImagePreviewDialog(QDialog):
|
||||
"""In-window lightbox for safe HTTP(S) attachment images.
|
||||
|
||||
后台用 ``el-image`` + ``preview-src-list`` 直接在页面内放大舌象与报告图片,
|
||||
工作站此前只能把地址交给系统浏览器。这里保持同一合同:医生留在工作站内
|
||||
翻看整组附件,必要时才手动安全外部打开。
|
||||
"""
|
||||
|
||||
_MAX_IMAGE_BYTES = 12 * 1024 * 1024
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sources: Sequence[Any] | Any,
|
||||
*,
|
||||
index: int = 0,
|
||||
names: Sequence[Any] | None = None,
|
||||
title: str = "图片预览",
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
if isinstance(sources, (str, bytes, bytearray)) or not isinstance(sources, Sequence):
|
||||
candidates: Sequence[Any] = [sources]
|
||||
else:
|
||||
candidates = sources
|
||||
ordered = [str(candidate or "").strip() for candidate in candidates]
|
||||
labels = [str(label or "").strip() for label in (names or [])]
|
||||
requested = ordered[index] if 0 <= index < len(ordered) else ""
|
||||
self._sources: list[str] = []
|
||||
self._names: list[str] = []
|
||||
for position, target in enumerate(ordered):
|
||||
if not target or target in self._sources or safe_http_url(target) is None:
|
||||
continue
|
||||
label = labels[position] if position < len(labels) else ""
|
||||
self._sources.append(target)
|
||||
self._names.append(label or image_display_name(target, len(self._sources)))
|
||||
self._index = self._sources.index(requested) if requested in self._sources else 0
|
||||
self._cache: dict[str, QPixmap] = {}
|
||||
self._pixmap = QPixmap()
|
||||
self._fit = True
|
||||
self._generation = 0
|
||||
self._reply: QNetworkReply | None = None
|
||||
self._manager = shared_image_manager(self)
|
||||
|
||||
self.setObjectName("DiagnosisImagePreview")
|
||||
self.setWindowTitle(title)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.setStyleSheet(_IMAGE_PREVIEW_QSS)
|
||||
self.resize(880, 660)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(18, 16, 18, 16)
|
||||
root.setSpacing(10)
|
||||
header = QHBoxLayout()
|
||||
header.setSpacing(10)
|
||||
self.name_label = QLabel(title)
|
||||
self.name_label.setObjectName("DiagnosisImagePreviewName")
|
||||
self.name_label.setTextInteractionFlags(
|
||||
Qt.TextInteractionFlag.TextSelectableByMouse
|
||||
)
|
||||
header.addWidget(self.name_label, 1)
|
||||
self.counter = QLabel("")
|
||||
self.counter.setObjectName("DiagnosisImagePreviewCounter")
|
||||
header.addWidget(self.counter, 0, Qt.AlignmentFlag.AlignRight)
|
||||
root.addLayout(header)
|
||||
|
||||
self.viewport = QScrollArea()
|
||||
self.viewport.setObjectName("DiagnosisImagePreviewViewport")
|
||||
self.viewport.setWidgetResizable(True)
|
||||
self.viewport.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.canvas = QLabel("正在加载图片…")
|
||||
self.canvas.setObjectName("DiagnosisImagePreviewCanvas")
|
||||
self.canvas.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.canvas.setSizePolicy(
|
||||
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
|
||||
)
|
||||
self.viewport.setWidget(self.canvas)
|
||||
root.addWidget(self.viewport, 1)
|
||||
|
||||
self.status = QLabel("")
|
||||
self.status.setObjectName("DiagnosisImagePreviewStatus")
|
||||
self.status.setWordWrap(True)
|
||||
self.status.setTextInteractionFlags(
|
||||
Qt.TextInteractionFlag.TextSelectableByMouse
|
||||
)
|
||||
root.addWidget(self.status)
|
||||
|
||||
controls = QHBoxLayout()
|
||||
controls.setSpacing(8)
|
||||
self.previous_button = QPushButton("上一张")
|
||||
self.previous_button.setProperty("imagePreviewControl", True)
|
||||
self.previous_button.clicked.connect(lambda: self.step(-1))
|
||||
controls.addWidget(self.previous_button)
|
||||
self.next_button = QPushButton("下一张")
|
||||
self.next_button.setProperty("imagePreviewControl", True)
|
||||
self.next_button.clicked.connect(lambda: self.step(1))
|
||||
controls.addWidget(self.next_button)
|
||||
controls.addStretch(1)
|
||||
self.zoom_button = QPushButton("原始大小")
|
||||
self.zoom_button.setProperty("imagePreviewControl", True)
|
||||
self.zoom_button.setToolTip("在适应窗口与原始像素之间切换")
|
||||
self.zoom_button.clicked.connect(self.toggle_zoom)
|
||||
controls.addWidget(self.zoom_button)
|
||||
self.reload_button = QPushButton("重新加载")
|
||||
self.reload_button.setProperty("imagePreviewControl", True)
|
||||
self.reload_button.clicked.connect(self.reload_current)
|
||||
controls.addWidget(self.reload_button)
|
||||
self.external_button = QPushButton("安全外部打开")
|
||||
self.external_button.setProperty("imagePreviewControl", True)
|
||||
self.external_button.clicked.connect(self._open_external)
|
||||
controls.addWidget(self.external_button)
|
||||
self.close_button = QPushButton("关闭")
|
||||
self.close_button.setProperty("imagePreviewControl", True)
|
||||
self.close_button.clicked.connect(self.close)
|
||||
controls.addWidget(self.close_button)
|
||||
root.addLayout(controls)
|
||||
|
||||
if not self._sources:
|
||||
self.canvas.setText("附件地址无效:仅支持包含主机名的 HTTP(S) 图片。")
|
||||
self.status.setText("没有可在工作站内预览的图片。")
|
||||
self.status.setProperty("kind", "danger")
|
||||
for button in (
|
||||
self.previous_button,
|
||||
self.next_button,
|
||||
self.zoom_button,
|
||||
self.reload_button,
|
||||
self.external_button,
|
||||
):
|
||||
button.setEnabled(False)
|
||||
return
|
||||
self.show_index(self._index)
|
||||
|
||||
@property
|
||||
def sources(self) -> list[str]:
|
||||
return list(self._sources)
|
||||
|
||||
@property
|
||||
def current_source(self) -> str:
|
||||
return self._sources[self._index] if self._sources else ""
|
||||
|
||||
def has_images(self) -> bool:
|
||||
return bool(self._sources)
|
||||
|
||||
def show_index(self, index: int) -> None:
|
||||
"""Move to one attachment, serving an already decoded image from cache."""
|
||||
|
||||
if not self._sources:
|
||||
return
|
||||
self._index = max(0, min(int(index), len(self._sources) - 1))
|
||||
target = self._sources[self._index]
|
||||
total = len(self._sources)
|
||||
self.name_label.setText(self._names[self._index])
|
||||
self.name_label.setToolTip(target)
|
||||
self.counter.setText(f"第 {self._index + 1} / {total} 张")
|
||||
self.previous_button.setEnabled(total > 1)
|
||||
self.next_button.setEnabled(total > 1)
|
||||
cached = self._cache.get(target)
|
||||
if cached is not None and not cached.isNull():
|
||||
self._invalidate_request()
|
||||
self._pixmap = cached
|
||||
self._set_status(target)
|
||||
self._render()
|
||||
return
|
||||
self._pixmap = QPixmap()
|
||||
self.canvas.setPixmap(QPixmap())
|
||||
self.canvas.setMinimumSize(0, 0)
|
||||
self.canvas.setText("正在加载图片…")
|
||||
self._set_status(target)
|
||||
self._request(target)
|
||||
|
||||
def step(self, delta: int) -> None:
|
||||
if len(self._sources) < 2:
|
||||
return
|
||||
self.show_index((self._index + int(delta)) % len(self._sources))
|
||||
|
||||
def reload_current(self) -> None:
|
||||
target = self.current_source
|
||||
if not target:
|
||||
return
|
||||
self._cache.pop(target, None)
|
||||
self.show_index(self._index)
|
||||
|
||||
def toggle_zoom(self) -> None:
|
||||
self._fit = not self._fit
|
||||
self.zoom_button.setText("原始大小" if self._fit else "适应窗口")
|
||||
self._render()
|
||||
|
||||
def _invalidate_request(self) -> int:
|
||||
self._generation += 1
|
||||
reply, self._reply = self._reply, None
|
||||
if reply is not None:
|
||||
reply.abort()
|
||||
reply.deleteLater()
|
||||
return self._generation
|
||||
|
||||
def _request(self, target: str) -> None:
|
||||
generation = self._invalidate_request()
|
||||
url = safe_http_url(target)
|
||||
if url is None:
|
||||
self._fail("附件地址无效:仅支持包含主机名的 HTTP(S) 图片。")
|
||||
return
|
||||
request = QNetworkRequest(url)
|
||||
request.setTransferTimeout(15_000)
|
||||
request.setMaximumRedirectsAllowed(4)
|
||||
request.setAttribute(
|
||||
QNetworkRequest.Attribute.RedirectPolicyAttribute,
|
||||
QNetworkRequest.RedirectPolicy.SameOriginRedirectPolicy,
|
||||
)
|
||||
reply = self._manager.get(request)
|
||||
self._reply = reply
|
||||
reply.setProperty("imagePreviewGeneration", generation)
|
||||
reply.setProperty("imagePreviewOversize", False)
|
||||
reply.downloadProgress.connect(self._download_progress)
|
||||
reply.finished.connect(self._reply_finished)
|
||||
|
||||
def _download_progress(self, bytes_received: int, bytes_total: int) -> None:
|
||||
"""Abort as soon as a received or declared size exceeds the safety cap."""
|
||||
|
||||
reply = self.sender()
|
||||
if reply is not self._reply:
|
||||
return
|
||||
if bytes_received <= self._MAX_IMAGE_BYTES and (
|
||||
bytes_total < 0 or bytes_total <= self._MAX_IMAGE_BYTES
|
||||
):
|
||||
return
|
||||
reply.setProperty("imagePreviewOversize", True)
|
||||
reply.abort()
|
||||
|
||||
def _reply_finished(self) -> None:
|
||||
"""Use a QObject receiver connection so destruction disconnects this slot."""
|
||||
|
||||
reply = self.sender()
|
||||
if reply is None:
|
||||
return
|
||||
try:
|
||||
generation = int(reply.property("imagePreviewGeneration"))
|
||||
except (TypeError, ValueError):
|
||||
reply.deleteLater()
|
||||
return
|
||||
if reply is not self._reply or generation != self._generation:
|
||||
reply.deleteLater()
|
||||
return
|
||||
self._reply = None
|
||||
oversize = bool(reply.property("imagePreviewOversize"))
|
||||
error = reply.error()
|
||||
payload = b"" if oversize else bytes(reply.readAll())
|
||||
reply.deleteLater()
|
||||
if oversize:
|
||||
self._fail("图片超过 12 MB 安全上限,已停止加载,可安全外部打开。")
|
||||
return
|
||||
if error != QNetworkReply.NetworkError.NoError:
|
||||
self._fail("图片加载失败,可重新加载或安全外部打开。")
|
||||
return
|
||||
self.apply_payload(payload, generation)
|
||||
|
||||
def apply_payload(self, payload: bytes, generation: int | None = None) -> bool:
|
||||
"""Decode one response; kept public so offline tests can exercise rendering."""
|
||||
|
||||
if generation is not None and generation != self._generation:
|
||||
return False
|
||||
pixmap = QPixmap()
|
||||
if (
|
||||
not payload
|
||||
or len(payload) > self._MAX_IMAGE_BYTES
|
||||
or not pixmap.loadFromData(payload)
|
||||
or pixmap.isNull()
|
||||
):
|
||||
self._fail("图片格式不受支持,无法在工作站内预览。")
|
||||
return False
|
||||
self._cache[self.current_source] = pixmap
|
||||
self._pixmap = pixmap
|
||||
self._set_status(self.current_source)
|
||||
self._render()
|
||||
return True
|
||||
|
||||
def _set_status(self, text: str, kind: str = "") -> None:
|
||||
"""Keep the source address visible; tint it only when something failed."""
|
||||
|
||||
self.status.setText(text)
|
||||
self.status.setProperty("kind", kind)
|
||||
self._repolish_status()
|
||||
|
||||
def _fail(self, message: str) -> None:
|
||||
self._pixmap = QPixmap()
|
||||
self.canvas.setPixmap(QPixmap())
|
||||
self.canvas.setMinimumSize(0, 0)
|
||||
self.canvas.setText(message)
|
||||
self._set_status(self.current_source or message, "warning")
|
||||
|
||||
def _repolish_status(self) -> None:
|
||||
style = self.status.style()
|
||||
style.unpolish(self.status)
|
||||
style.polish(self.status)
|
||||
|
||||
def _render(self) -> None:
|
||||
if self._pixmap.isNull():
|
||||
return
|
||||
self.canvas.setText("")
|
||||
available = self.viewport.viewport().size() - QSize(10, 10)
|
||||
if self._fit and (
|
||||
self._pixmap.width() > available.width()
|
||||
or self._pixmap.height() > available.height()
|
||||
):
|
||||
rendered = self._pixmap.scaled(
|
||||
available,
|
||||
Qt.AspectRatioMode.KeepAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
)
|
||||
else:
|
||||
rendered = self._pixmap
|
||||
self.canvas.setMinimumSize(QSize(0, 0) if self._fit else rendered.size())
|
||||
self.canvas.setPixmap(rendered)
|
||||
|
||||
def _open_external(self) -> None:
|
||||
if not open_safe_http_url(self.current_source):
|
||||
self._set_status("系统未能打开该安全外部链接。", "danger")
|
||||
|
||||
def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt virtual
|
||||
super().resizeEvent(event)
|
||||
if self._fit:
|
||||
self._render()
|
||||
|
||||
def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802 - Qt virtual
|
||||
key = event.key()
|
||||
if key in {Qt.Key.Key_Left, Qt.Key.Key_Up, Qt.Key.Key_PageUp}:
|
||||
self.step(-1)
|
||||
event.accept()
|
||||
return
|
||||
if key in {
|
||||
Qt.Key.Key_Right,
|
||||
Qt.Key.Key_Down,
|
||||
Qt.Key.Key_PageDown,
|
||||
Qt.Key.Key_Space,
|
||||
}:
|
||||
self.step(1)
|
||||
event.accept()
|
||||
return
|
||||
super().keyPressEvent(event)
|
||||
|
||||
def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 - Qt virtual
|
||||
self._invalidate_request()
|
||||
super().closeEvent(event)
|
||||
|
||||
def done(self, result: int) -> None:
|
||||
# QDialog.reject() (including Escape) bypasses closeEvent.
|
||||
self._invalidate_request()
|
||||
super().done(result)
|
||||
|
||||
|
||||
def _clock(milliseconds: int) -> str:
|
||||
seconds = max(0, int(milliseconds) // 1000)
|
||||
return f"{seconds // 60:02d}:{seconds % 60:02d}"
|
||||
@@ -663,13 +1116,18 @@ def _clock(milliseconds: int) -> str:
|
||||
|
||||
__all__ = [
|
||||
"MULTIMEDIA_AVAILABLE",
|
||||
"ImagePreviewDialog",
|
||||
"InlineRecordingPlayer",
|
||||
"RecordingPlaybackCell",
|
||||
"RecordingPlayerDialog",
|
||||
"alternate_recording_label",
|
||||
"image_display_name",
|
||||
"is_previewable_image",
|
||||
"normalize_recording_urls",
|
||||
"open_safe_http_url",
|
||||
"preferred_recording_url",
|
||||
"safe_http_url",
|
||||
"safe_image_sources",
|
||||
"shared_image_manager",
|
||||
"should_inline_recording",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,491 @@
|
||||
"""诊单字段的中文翻译:字典项、枚举与时间戳。
|
||||
|
||||
后台 ``AppointmentLogic::enrichDiagnosisLabels`` 会给只读接口补一份
|
||||
``<field>_text``,所以读取时永远优先用它(与 admin 的 ``makeTextOf`` 同一约定)。
|
||||
处方快照一类的历史数据没有这些字段,就按字段所属字典把 code 翻成中文:字典优先
|
||||
取仓储实时下发的 ``config/dict``,缺失时回退到与
|
||||
``server/sql/present_illness_dict_data.sql`` / ``tcm_diagnosis.sql`` 一致的内置种子。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
# 与 AppointmentLogic::enrichDiagnosisLabels 的 $singleDictFields 保持一致。
|
||||
SINGLE_VALUE_DICTIONARIES: dict[str, str] = {
|
||||
"diagnosis_type": "diagnosis_type",
|
||||
"syndrome_type": "syndrome_type",
|
||||
"diabetes_type": "diabetes_type",
|
||||
"water_intake": "water_intake",
|
||||
"weight_change": "weight_change",
|
||||
"fatty_liver_degree": "fatty_liver_degree",
|
||||
}
|
||||
|
||||
# 与 $multiDictFields 保持一致:值是数组或逗号/顿号分隔的字符串。
|
||||
MULTI_VALUE_DICTIONARIES: dict[str, str] = {
|
||||
"past_history": "past_history",
|
||||
"appetite": "appetite",
|
||||
"diet_condition": "diet_condition",
|
||||
"body_feeling": "body_feeling",
|
||||
"sleep_condition": "sleep_condition",
|
||||
"eye_condition": "eye_condition",
|
||||
"head_feeling": "head_feeling",
|
||||
"sweat_condition": "sweat_condition",
|
||||
"skin_condition": "skin_condition",
|
||||
"urine_condition": "urine_condition",
|
||||
"stool_condition": "stool_condition",
|
||||
"kidney_condition": "kidney_condition",
|
||||
}
|
||||
|
||||
FIELD_DICTIONARIES: dict[str, str] = {
|
||||
**SINGLE_VALUE_DICTIONARIES,
|
||||
**MULTI_VALUE_DICTIONARIES,
|
||||
}
|
||||
|
||||
DICTIONARY_TYPES: tuple[str, ...] = tuple(sorted(set(FIELD_DICTIONARIES.values())))
|
||||
|
||||
# 内置种子:与 server/sql/present_illness_dict_data.sql、tcm_diagnosis.sql 的
|
||||
# zyt_dict_data 初始数据一致;线上字典可被管理员改写,所以实时字典优先。
|
||||
SEED_DICTIONARIES: dict[str, dict[str, str]] = {
|
||||
"appetite": {
|
||||
"dry": "干",
|
||||
"bitter": "苦",
|
||||
"greasy": "腻",
|
||||
},
|
||||
"body_feeling": {
|
||||
"numbness": "麻木",
|
||||
"weakness": "乏力",
|
||||
"pain": "疼痛",
|
||||
"cold_aversion": "畏寒",
|
||||
"fever": "烧热",
|
||||
},
|
||||
"diagnosis_type": {
|
||||
"first_visit": "初诊",
|
||||
"follow_up": "复诊",
|
||||
"consultation": "会诊",
|
||||
},
|
||||
"diet_condition": {
|
||||
"overeating": "多食",
|
||||
"poor_appetite": "纳呆",
|
||||
"stomach_bloating": "胃胀",
|
||||
"stomach_pain": "胃痛",
|
||||
"acid_reflux": "反酸",
|
||||
"loss_of_appetite": "食欲减退",
|
||||
},
|
||||
"eye_condition": {
|
||||
"blurred": "模糊",
|
||||
"dry": "干涩",
|
||||
"tearing": "流泪",
|
||||
"floaters": "飞蚊症",
|
||||
"bleeding": "出血",
|
||||
},
|
||||
"fatty_liver_degree": {
|
||||
"mild": "轻度",
|
||||
"moderate": "中度",
|
||||
"severe": "重度",
|
||||
},
|
||||
"head_feeling": {
|
||||
"fatigue": "疲劳困倦",
|
||||
"dizziness": "头晕",
|
||||
"headache": "头痛",
|
||||
"tinnitus": "耳鸣",
|
||||
},
|
||||
"kidney_condition": {
|
||||
"soreness": "酸胀",
|
||||
"pain": "疼痛",
|
||||
"lower_back_pain": "腰痛",
|
||||
"sexual_dysfunction": "性功能下降",
|
||||
},
|
||||
"past_history": {
|
||||
"hypertension": "高血压",
|
||||
"diabetes": "糖尿病",
|
||||
"gastric_ulcer": "胃溃疡",
|
||||
"hyperlipidemia": "高血脂",
|
||||
"thyroid_nodule": "甲状腺结节",
|
||||
"superficial_gastritis": "浅表性胃炎",
|
||||
"stomach_disease": "胃病",
|
||||
"cerebral_infarction": "脑梗",
|
||||
"breast_nodule": "乳腺结节",
|
||||
"atrophic_gastritis": "萎缩性胃炎",
|
||||
"heart_disease": "心脏病",
|
||||
"cerebral_ischemia": "脑缺血",
|
||||
"intestinal_obstruction": "肠梗阻",
|
||||
"hepatitis_a": "甲肝",
|
||||
"hepatitis_b": "乙肝",
|
||||
"hepatitis_c": "丙肝",
|
||||
"big_three_positive": "大三阳",
|
||||
"cerebral_thrombosis": "脑血栓",
|
||||
"coronary_heart_disease": "冠心病",
|
||||
"angina_pectoris": "心绞痛",
|
||||
"palpitation": "心悸",
|
||||
"renal_insufficiency": "肾功能不全",
|
||||
"benign_tumor": "良性肿瘤",
|
||||
"pancreatitis": "胰腺炎",
|
||||
"small_three_positive": "小三阳",
|
||||
"palpitations": "心慌",
|
||||
"edema": "水肿",
|
||||
"infectious_disease": "传染病",
|
||||
"fundus_congestion": "眼底充血",
|
||||
"tuberculosis": "肺结核",
|
||||
"pneumonia": "肺炎",
|
||||
"pulmonary_nodule": "肺结节",
|
||||
"cardiac_stent": "心脏支架",
|
||||
"renal_stent": "肾脏支架",
|
||||
"hepatitis": "肝炎",
|
||||
"tumor": "肿瘤",
|
||||
"emphysema": "肺气肿",
|
||||
"moderate_fatty_liver": "中度脂肪肝",
|
||||
"lacunar_infarction": "腔梗",
|
||||
"alcoholic_liver": "酒精肝",
|
||||
"brain_atrophy": "脑萎缩",
|
||||
"liver_cyst": "肝囊肿",
|
||||
"stroke": "中风",
|
||||
"cerebral_hemorrhage": "脑出血",
|
||||
"hepatic_insufficiency": "肝功能不全",
|
||||
"arterial_plaque": "动脉斑块",
|
||||
"uterine_fibroids": "子宫肌瘤",
|
||||
"splenomegaly": "脾大",
|
||||
"gastric_perforation": "胃穿孔",
|
||||
"gastric_bleeding": "胃出血",
|
||||
},
|
||||
"skin_condition": {
|
||||
"dry": "干燥",
|
||||
"itching": "瘙痒",
|
||||
"peeling": "脱皮",
|
||||
"edema": "水肿",
|
||||
"eczema": "湿疹",
|
||||
},
|
||||
"sleep_condition": {
|
||||
"difficulty_falling_asleep": "入睡难",
|
||||
"easy_to_wake": "容易醒",
|
||||
"early_waking": "早醒",
|
||||
"many_dreams": "多梦",
|
||||
},
|
||||
"stool_condition": {
|
||||
"dry": "干燥",
|
||||
"constipation": "便秘",
|
||||
"sticky": "粘腻",
|
||||
"diarrhea": "腹泻",
|
||||
},
|
||||
"sweat_condition": {
|
||||
"daytime_sweating": "日间出汗",
|
||||
"night_sweating": "夜间出汗",
|
||||
"sticky_sweat": "汗粘",
|
||||
"excessive_sweating": "多汗",
|
||||
},
|
||||
"syndrome_type": {
|
||||
"qi_deficiency": "气虚",
|
||||
"blood_deficiency": "血虚",
|
||||
"yin_deficiency": "阴虚",
|
||||
"yang_deficiency": "阳虚",
|
||||
"qi_stagnation": "气滞",
|
||||
"blood_stasis": "血瘀",
|
||||
"phlegm_dampness": "痰湿",
|
||||
"damp_heat": "湿热",
|
||||
"cold_dampness": "寒湿",
|
||||
"wind_cold": "风寒",
|
||||
"wind_heat": "风热",
|
||||
},
|
||||
"urine_condition": {
|
||||
"urgency": "尿急",
|
||||
"yellow_urine": "尿黄",
|
||||
"foamy": "有泡",
|
||||
"frequency": "尿频",
|
||||
"painful": "尿痛",
|
||||
"nocturia": "夜尿多",
|
||||
},
|
||||
"water_intake": {
|
||||
"one_bottle": "1瓶矿泉水",
|
||||
"one_half_bottle": "1.5瓶矿泉水",
|
||||
"three_bottles": "3瓶矿泉水",
|
||||
"four_bottles": "4瓶矿泉水",
|
||||
},
|
||||
"weight_change": {
|
||||
"lose_5_jin": "瘦5斤",
|
||||
"lose_10_jin": "瘦10斤",
|
||||
"lose_over_10_jin": "瘦10斤以上",
|
||||
},
|
||||
}
|
||||
|
||||
_GENDER_LABELS: dict[str, str] = {
|
||||
"1": "男",
|
||||
"m": "男",
|
||||
"male": "男",
|
||||
"男": "男",
|
||||
"0": "女",
|
||||
"2": "女",
|
||||
"f": "女",
|
||||
"female": "女",
|
||||
"女": "女",
|
||||
}
|
||||
|
||||
_MARITAL_LABELS: dict[str, str] = {"0": "未婚", "1": "已婚", "2": "离异"}
|
||||
|
||||
# 后台 yesNoText:1 有,其余 无。
|
||||
_YES_NO_FIELDS = frozenset(
|
||||
{
|
||||
"trauma_history",
|
||||
"surgery_history",
|
||||
"allergy_history",
|
||||
"family_history",
|
||||
"pregnancy_history",
|
||||
}
|
||||
)
|
||||
|
||||
_CREATE_SOURCE_LABELS: dict[str, str] = {
|
||||
"mnp": "小程序建档",
|
||||
"mnp_daily": "小程序快捷建档",
|
||||
"admin": "后台创建",
|
||||
"doctor": "医生创建",
|
||||
}
|
||||
|
||||
_RECORD_SOURCE_LABELS: dict[str, str] = {"0": "医生录入", "1": "患者自录"}
|
||||
|
||||
# 纯内部列:启停标记、统计端展示位、排班偏移与软删除时间对医生没有意义。
|
||||
INTERNAL_FIELDS = frozenset(
|
||||
{
|
||||
"status",
|
||||
"show_card",
|
||||
"revisit_slot_start_offset",
|
||||
"delete_time",
|
||||
"is_delete",
|
||||
"is_deleted",
|
||||
"sort",
|
||||
"assistant_id",
|
||||
"doctor_id",
|
||||
"admin_id",
|
||||
}
|
||||
)
|
||||
|
||||
# 附件字段单独渲染成缩略图,不再以 URL 文本出现在字段网格里。
|
||||
IMAGE_FIELDS = frozenset(
|
||||
{
|
||||
"tongue_images",
|
||||
"report_files",
|
||||
"images",
|
||||
"breakfast_images",
|
||||
"lunch_images",
|
||||
"dinner_images",
|
||||
}
|
||||
)
|
||||
|
||||
_TIMESTAMP_SUFFIXES = ("_time", "_at", "_date")
|
||||
_TIMESTAMP_MIN = 10**9 # 2001-09-09,早于本项目任何真实数据
|
||||
_TIMESTAMP_MAX = 4 * 10**9 # 2096 年,之后按普通数字显示
|
||||
|
||||
|
||||
# 只读页的单位,与 admin PatientCaseCard / BloodRecordList 一致。
|
||||
_UNIT_SUFFIXES: dict[str, str] = {
|
||||
"height": " cm",
|
||||
"weight": " kg",
|
||||
"systolic_pressure": " mmHg",
|
||||
"diastolic_pressure": " mmHg",
|
||||
"fasting_blood_sugar": " mmol/L",
|
||||
"postprandial_blood_sugar": " mmol/L",
|
||||
"other_blood_sugar": " mmol/L",
|
||||
"blood_sugar": " mmol/L",
|
||||
"duration": " 分钟",
|
||||
"diabetes_discovery_year": "年",
|
||||
}
|
||||
|
||||
|
||||
def unit_suffix(field: str, value: Any) -> str:
|
||||
"""Return the unit a numeric readonly field should carry, if any."""
|
||||
|
||||
suffix = _UNIT_SUFFIXES.get(str(field or "").strip())
|
||||
if not suffix:
|
||||
return ""
|
||||
text = str(value).strip()
|
||||
if not text or text.endswith(suffix.strip()):
|
||||
return ""
|
||||
# 只给纯数字补单位,"17多"、"五年" 这类自由文本保持原样。
|
||||
normalized = text.replace(".", "", 1)
|
||||
return suffix if normalized.isdigit() else ""
|
||||
|
||||
|
||||
def format_timestamp(value: Any, *, with_time: bool = True) -> str | None:
|
||||
"""把后端的 Unix 秒级时间戳转成中文界面用的日期时间。"""
|
||||
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
try:
|
||||
seconds = int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not _TIMESTAMP_MIN <= seconds <= _TIMESTAMP_MAX:
|
||||
return None
|
||||
moment = datetime.fromtimestamp(seconds)
|
||||
return moment.strftime("%Y-%m-%d %H:%M" if with_time else "%Y-%m-%d")
|
||||
|
||||
|
||||
def is_timestamp_field(field: str) -> bool:
|
||||
return str(field or "").endswith(_TIMESTAMP_SUFFIXES)
|
||||
|
||||
|
||||
def gender_label(value: Any) -> str | None:
|
||||
return _GENDER_LABELS.get(str(value or "").strip().lower())
|
||||
|
||||
|
||||
def split_values(value: Any) -> list[str]:
|
||||
"""按后台 enrichDiagnosisLabels 的方式拆多值字段。"""
|
||||
|
||||
if value in (None, "", []):
|
||||
return []
|
||||
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
||||
items = [str(item or "").strip() for item in value]
|
||||
else:
|
||||
items = [part.strip() for part in _split_text(str(value))]
|
||||
return [item for item in items if item]
|
||||
|
||||
|
||||
def _split_text(text: str) -> list[str]:
|
||||
normalized = text.replace(",", ",").replace("、", ",")
|
||||
return normalized.split(",")
|
||||
|
||||
|
||||
class TermIndex:
|
||||
"""字典翻译表:实时字典覆盖内置种子,两者都缺就回显原值。"""
|
||||
|
||||
def __init__(self, dictionaries: Mapping[str, Any] | None = None) -> None:
|
||||
self._dictionaries: dict[str, dict[str, str]] = {
|
||||
dictionary_type: dict(options)
|
||||
for dictionary_type, options in SEED_DICTIONARIES.items()
|
||||
}
|
||||
self.merge(dictionaries)
|
||||
|
||||
def merge(self, dictionaries: Mapping[str, Any] | None) -> None:
|
||||
"""并入 ``config/dict`` 下发的 ``{type: [{name, value}, ...]}``。"""
|
||||
|
||||
if not isinstance(dictionaries, Mapping):
|
||||
return
|
||||
for dictionary_type, rows in dictionaries.items():
|
||||
options = _options_from_rows(rows)
|
||||
if options:
|
||||
self._dictionaries.setdefault(str(dictionary_type), {}).update(options)
|
||||
|
||||
def dictionary(self, dictionary_type: str) -> dict[str, str]:
|
||||
return dict(self._dictionaries.get(str(dictionary_type), {}))
|
||||
|
||||
def dictionary_label(self, field: str, value: Any) -> str | None:
|
||||
"""翻译一个字典字段;不是字典字段或没有可翻译内容时返回 None。"""
|
||||
|
||||
dictionary_type = FIELD_DICTIONARIES.get(str(field or "").strip())
|
||||
if dictionary_type is None:
|
||||
return None
|
||||
options = self._dictionaries.get(dictionary_type, {})
|
||||
items = split_values(value)
|
||||
if not items:
|
||||
return None
|
||||
labels = [options.get(item, item) for item in items]
|
||||
return "、".join(label for label in labels if label) or None
|
||||
|
||||
def value_label(self, field: str, value: Any) -> str | None:
|
||||
"""翻译字典项或枚举;无法翻译时返回 None,由调用方回显原值。"""
|
||||
|
||||
key = str(field or "").strip()
|
||||
if value in (None, "", [], {}):
|
||||
return None
|
||||
dictionary_label = self.dictionary_label(key, value)
|
||||
if dictionary_label is not None:
|
||||
return dictionary_label
|
||||
if key in {"gender", "patient_gender", "sex"}:
|
||||
return gender_label(value)
|
||||
if key in {"marital_status", "marriage"}:
|
||||
return _MARITAL_LABELS.get(str(value).strip())
|
||||
if key in _YES_NO_FIELDS:
|
||||
text = str(value).strip()
|
||||
if text in {"0", "1"}:
|
||||
return "有" if text == "1" else "无"
|
||||
return None
|
||||
if key == "create_source":
|
||||
return _CREATE_SOURCE_LABELS.get(str(value).strip().lower())
|
||||
if key == "source":
|
||||
return _RECORD_SOURCE_LABELS.get(str(value).strip())
|
||||
if is_timestamp_field(key):
|
||||
return format_timestamp(value, with_time=not key.endswith("_date"))
|
||||
return None
|
||||
|
||||
def display(self, source: Any, field: str, *, default: str = "") -> str:
|
||||
"""按 admin ``textOf`` 的口径取值:先 ``<field>_text``,再字典/枚举,最后原值。"""
|
||||
|
||||
mapping = source if isinstance(source, Mapping) else {}
|
||||
key = str(field or "").strip()
|
||||
translated = mapping.get(f"{key}_text")
|
||||
if translated in (None, "", []):
|
||||
translated = mapping.get(f"{key}_desc")
|
||||
if translated not in (None, "", []):
|
||||
return _join(translated) + unit_suffix(key, translated)
|
||||
raw = mapping.get(key)
|
||||
if raw in (None, "", [], {}):
|
||||
return default
|
||||
labelled = self.value_label(key, raw)
|
||||
if labelled is not None:
|
||||
return labelled
|
||||
rendered = _join(raw)
|
||||
return rendered + unit_suffix(key, rendered)
|
||||
|
||||
|
||||
_SHARED_INDEX = TermIndex()
|
||||
|
||||
|
||||
def shared_terms() -> TermIndex:
|
||||
"""The process-wide index every readonly screen renders through.
|
||||
|
||||
只读界面只用它翻译展示文案,所以共享一份即可:任何界面取回实时字典后,
|
||||
处方快照那种拿不到 ``*_text`` 的旧数据也能跟着翻译正确。
|
||||
"""
|
||||
|
||||
return _SHARED_INDEX
|
||||
|
||||
|
||||
def merge_shared_dictionaries(dictionaries: Mapping[str, Any] | None) -> None:
|
||||
_SHARED_INDEX.merge(dictionaries)
|
||||
|
||||
|
||||
def _join(value: Any) -> str:
|
||||
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
||||
return "、".join(str(item).strip() for item in value if str(item).strip())
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _options_from_rows(rows: Any) -> dict[str, str]:
|
||||
"""从 ``config/dict`` 的行里取 ``value -> name``。"""
|
||||
|
||||
options: dict[str, str] = {}
|
||||
if isinstance(rows, Mapping):
|
||||
for value, name in rows.items():
|
||||
code = str(value).strip()
|
||||
label = str(name).strip()
|
||||
if code and label:
|
||||
options[code] = label
|
||||
return options
|
||||
if not isinstance(rows, Sequence) or isinstance(rows, (str, bytes, bytearray)):
|
||||
return options
|
||||
for row in rows:
|
||||
if not isinstance(row, Mapping):
|
||||
continue
|
||||
code = str(row.get("value", "")).strip()
|
||||
label = str(row.get("name", "")).strip()
|
||||
if code and label:
|
||||
options[code] = label
|
||||
return options
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DICTIONARY_TYPES",
|
||||
"FIELD_DICTIONARIES",
|
||||
"IMAGE_FIELDS",
|
||||
"INTERNAL_FIELDS",
|
||||
"MULTI_VALUE_DICTIONARIES",
|
||||
"SEED_DICTIONARIES",
|
||||
"SINGLE_VALUE_DICTIONARIES",
|
||||
"TermIndex",
|
||||
"format_timestamp",
|
||||
"merge_shared_dictionaries",
|
||||
"shared_terms",
|
||||
"gender_label",
|
||||
"is_timestamp_field",
|
||||
"split_values",
|
||||
]
|
||||
@@ -18,13 +18,13 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..theme import mark_business_dialog
|
||||
from ..widgets import (
|
||||
BusyOverlay,
|
||||
EmptyState,
|
||||
MessageBanner,
|
||||
OverlayHost,
|
||||
Pager,
|
||||
SortableTable,
|
||||
TableColumn,
|
||||
first_value,
|
||||
@@ -33,7 +33,6 @@ from ..widgets import (
|
||||
get_value,
|
||||
invoke,
|
||||
page_items,
|
||||
page_total,
|
||||
run_async,
|
||||
)
|
||||
from .ai_consult import can_open_ai_consult, present_ai_consult
|
||||
@@ -220,8 +219,8 @@ class AiConsultTargetDialog(QDialog):
|
||||
self.body.busy_overlay = self.busy_overlay
|
||||
root.addWidget(self.body, 1)
|
||||
|
||||
self.pager = Pager(self.PAGE_SIZE, self)
|
||||
self.pager.page_changed.connect(self._change_page)
|
||||
self.pager = InfiniteList(self.PAGE_SIZE, self)
|
||||
self.pager.bind(self.table)
|
||||
root.addWidget(self.pager)
|
||||
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel, self)
|
||||
@@ -266,42 +265,41 @@ class AiConsultTargetDialog(QDialog):
|
||||
self.load(1)
|
||||
|
||||
def retry(self) -> None:
|
||||
self.load(self._page)
|
||||
|
||||
def _change_page(self, page: int) -> None:
|
||||
self.load(page)
|
||||
self.load(1)
|
||||
|
||||
def load(self, page: int) -> None:
|
||||
if not self._active:
|
||||
return
|
||||
self._page = max(1, int(page))
|
||||
self._generation += 1
|
||||
generation = self._generation
|
||||
page_snapshot = self._page
|
||||
keyword_snapshot = self.search_edit.text().strip()
|
||||
self._invalidate_selection()
|
||||
self._set_loading(True)
|
||||
if keyword_snapshot != getattr(self, "_loaded_keyword", None):
|
||||
self._invalidate_selection()
|
||||
self._loaded_keyword = keyword_snapshot
|
||||
self._set_loading(not self.pager.rows)
|
||||
self.banner.clear()
|
||||
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.pager.reload(
|
||||
lambda requested_page: invoke(
|
||||
self.repository,
|
||||
"list_ai_patient_options",
|
||||
page_no=page_snapshot,
|
||||
page_no=requested_page,
|
||||
page_size=self.PAGE_SIZE,
|
||||
keyword=keyword_snapshot,
|
||||
),
|
||||
on_success=lambda result: self._apply_result(
|
||||
result, generation, page_snapshot, keyword_snapshot
|
||||
apply=lambda result: self._apply_result(
|
||||
result, generation, keyword_snapshot
|
||||
),
|
||||
on_error=lambda error: self._apply_error(error, generation),
|
||||
runner=run_async,
|
||||
query_key=(keyword_snapshot,),
|
||||
on_finished=lambda: self._finish_loading(generation),
|
||||
)
|
||||
|
||||
def _apply_result(
|
||||
self,
|
||||
result: Any,
|
||||
generation: int,
|
||||
page_snapshot: int,
|
||||
keyword_snapshot: str,
|
||||
) -> None:
|
||||
if not self._is_current(generation):
|
||||
@@ -316,36 +314,32 @@ class AiConsultTargetDialog(QDialog):
|
||||
for target in (AiConsultTarget.from_row(row) for row in page_items(result))
|
||||
if target is not None
|
||||
]
|
||||
total = max(0, page_total(result, len(targets)))
|
||||
page_count = max(1, (total + self.PAGE_SIZE - 1) // self.PAGE_SIZE)
|
||||
if page_snapshot > page_count:
|
||||
self.load(page_count)
|
||||
return
|
||||
|
||||
self._page = page_snapshot
|
||||
self.table.set_rows(targets)
|
||||
self.table.setSortingEnabled(False)
|
||||
self.table.clearSelection()
|
||||
self.pager.update_state(page_snapshot, total)
|
||||
self.empty_state.setVisible(not targets)
|
||||
self.table.setVisible(bool(targets))
|
||||
self._page = self.pager.page
|
||||
self.empty_state.setVisible(not targets and not self.pager.has_more)
|
||||
self.table.setVisible(bool(targets) or self.pager.has_more)
|
||||
self.banner.clear()
|
||||
self._set_loading(False)
|
||||
|
||||
def _apply_error(self, error: Exception, generation: int) -> None:
|
||||
if not self._is_current(generation):
|
||||
return
|
||||
self.table.set_rows(())
|
||||
self.table.setSortingEnabled(False)
|
||||
self.table.clearSelection()
|
||||
self.table.hide()
|
||||
self.empty_state.show()
|
||||
self.pager.update_state(1, 0)
|
||||
if not self.pager.rows:
|
||||
self.table.set_rows(())
|
||||
self.table.setSortingEnabled(False)
|
||||
self.table.clearSelection()
|
||||
self.table.hide()
|
||||
self.empty_state.show()
|
||||
self.banner.show_message(
|
||||
f"患者诊单加载失败:{friendly_error(error)}", "danger"
|
||||
)
|
||||
self._set_loading(False)
|
||||
|
||||
def _finish_loading(self, generation: int) -> None:
|
||||
if self._is_current(generation):
|
||||
self._set_loading(False)
|
||||
|
||||
def _is_current(self, generation: int) -> bool:
|
||||
return self._active and generation == self._generation
|
||||
|
||||
@@ -365,7 +359,6 @@ class AiConsultTargetDialog(QDialog):
|
||||
def _set_loading(self, loading: bool) -> None:
|
||||
self._loading = loading
|
||||
self.table.setEnabled(not loading)
|
||||
self.pager.setEnabled(not loading)
|
||||
self.start_button.setEnabled(False if loading else self.table.currentRow() >= 0)
|
||||
self.busy_overlay.setVisible(loading)
|
||||
if loading:
|
||||
@@ -383,6 +376,7 @@ class AiConsultTargetDialog(QDialog):
|
||||
def done(self, result: int) -> None:
|
||||
self._active = False
|
||||
self._generation += 1
|
||||
self.pager.invalidate()
|
||||
self._search_timer.stop()
|
||||
super().done(result)
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Confirmation and optional doctor note for completing an appointment."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
from PySide6.QtGui import QCloseEvent
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QLabel,
|
||||
QPlainTextEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ..theme import mark_business_dialog
|
||||
from ..widgets import MessageBanner
|
||||
|
||||
COMPLETION_NOTE_LIMIT = 500
|
||||
|
||||
|
||||
class AppointmentCompleteDialog(QDialog):
|
||||
"""Keep an unsaved note available if completion or note saving fails."""
|
||||
|
||||
submitted = Signal(str)
|
||||
|
||||
def __init__(self, *, can_note: bool, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self._can_note = can_note
|
||||
self._busy = False
|
||||
self._completed = False
|
||||
self.setWindowTitle("完成问诊")
|
||||
self.resize(460, 350 if can_note else 230)
|
||||
self.setMinimumWidth(420)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(24, 22, 24, 18)
|
||||
layout.setSpacing(10)
|
||||
title = QLabel("完成问诊", self)
|
||||
title.setProperty("dialogRole", "title")
|
||||
layout.addWidget(title)
|
||||
prompt = QLabel("是否添加医生备注?" if can_note else "确认完成该挂号吗?", self)
|
||||
layout.addWidget(prompt)
|
||||
self.note_edit = QPlainTextEdit(self)
|
||||
self.note_edit.setObjectName("AppointmentCompleteNote")
|
||||
self.note_edit.setAccessibleName("完成问诊医生备注")
|
||||
self.note_edit.setPlaceholderText("填写完成备注,将追加到医生备注时间轴")
|
||||
self.note_edit.setMinimumHeight(100)
|
||||
self.note_edit.setVisible(can_note)
|
||||
self.note_edit.textChanged.connect(self._limit_note)
|
||||
layout.addWidget(self.note_edit)
|
||||
self.note_counter = QLabel(f"0 / {COMPLETION_NOTE_LIMIT}", self)
|
||||
self.note_counter.setObjectName("AppointmentCompleteNoteCounter")
|
||||
self.note_counter.setProperty("dialogRole", "subtitle")
|
||||
self.note_counter.setAlignment(Qt.AlignmentFlag.AlignRight)
|
||||
self.note_counter.setVisible(can_note)
|
||||
layout.addWidget(self.note_counter)
|
||||
hint = QLabel("系统会再次核对服务端挂号状态;完成后不可撤销。", self)
|
||||
hint.setProperty("dialogRole", "subtitle")
|
||||
hint.setWordWrap(True)
|
||||
layout.addWidget(hint)
|
||||
self.banner = MessageBanner(parent=self)
|
||||
layout.addWidget(self.banner)
|
||||
self.buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel, self
|
||||
)
|
||||
self.confirm_button = self.buttons.button(QDialogButtonBox.StandardButton.Ok)
|
||||
self.confirm_button.setText("确认完成")
|
||||
self.confirm_button.setProperty("variant", "primary")
|
||||
self.confirm_button.setAutoDefault(False)
|
||||
self.cancel_button = self.buttons.button(QDialogButtonBox.StandardButton.Cancel)
|
||||
self.cancel_button.setText("取消")
|
||||
self.cancel_button.setAutoDefault(False)
|
||||
self.buttons.accepted.connect(self._submit)
|
||||
self.buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(self.buttons)
|
||||
mark_business_dialog(self, "AppointmentCompleteDialog")
|
||||
|
||||
def _limit_note(self) -> None:
|
||||
text = self.note_edit.toPlainText()
|
||||
if len(text) > COMPLETION_NOTE_LIMIT:
|
||||
text = text[:COMPLETION_NOTE_LIMIT]
|
||||
cursor_position = self.note_edit.textCursor().position()
|
||||
self.note_edit.blockSignals(True)
|
||||
self.note_edit.setPlainText(text)
|
||||
cursor = self.note_edit.textCursor()
|
||||
cursor.setPosition(min(cursor_position, self.note_edit.document().characterCount() - 1))
|
||||
self.note_edit.setTextCursor(cursor)
|
||||
self.note_edit.blockSignals(False)
|
||||
self.note_counter.setText(f"{len(text)} / {COMPLETION_NOTE_LIMIT}")
|
||||
|
||||
def _submit(self) -> None:
|
||||
if not self._busy and not self._completed:
|
||||
self.submitted.emit(self.note_edit.toPlainText().strip() if self._can_note else "")
|
||||
|
||||
def set_busy(self, busy: bool) -> None:
|
||||
self._busy = busy
|
||||
self.note_edit.setReadOnly(busy or self._completed)
|
||||
self.confirm_button.setEnabled(not busy and not self._completed)
|
||||
self.confirm_button.setText("正在完成…" if busy else "确认完成")
|
||||
self.cancel_button.setEnabled(not busy)
|
||||
if busy:
|
||||
self.banner.clear()
|
||||
|
||||
def show_error(self, message: str) -> None:
|
||||
self.set_busy(False)
|
||||
self.banner.show_message(message, "danger")
|
||||
|
||||
def show_completed_warning(self, message: str) -> None:
|
||||
self._completed = True
|
||||
self.set_busy(False)
|
||||
self.confirm_button.hide()
|
||||
self.cancel_button.setText("关闭")
|
||||
self.banner.show_message(f"{message}。可复制上方备注,稍后在医生备注中补录。", "warning")
|
||||
|
||||
def reject(self) -> None:
|
||||
if not self._busy:
|
||||
super().reject()
|
||||
|
||||
def closeEvent(self, event: QCloseEvent) -> None: # noqa: N802 - Qt API
|
||||
if self._busy:
|
||||
event.ignore()
|
||||
else:
|
||||
super().closeEvent(event)
|
||||
@@ -46,6 +46,7 @@ from ..diagnosis_drawer import (
|
||||
DiagnosisSwitch,
|
||||
DiagnosisTabWidget,
|
||||
DiagnosisTextEdit,
|
||||
ExpandableDiagnosisTextEdit,
|
||||
LoadingOverlay,
|
||||
MessageStrip,
|
||||
NotesTimeline,
|
||||
@@ -58,7 +59,13 @@ from ..diagnosis_drawer import (
|
||||
set_tag_item,
|
||||
)
|
||||
from ..diagnosis_editors import DailyRecordEditorDialog
|
||||
from ..diagnosis_media import RecordingPlaybackCell, RecordingPlayerDialog
|
||||
from ..diagnosis_media import (
|
||||
ImagePreviewDialog,
|
||||
RecordingPlaybackCell,
|
||||
RecordingPlayerDialog,
|
||||
safe_image_sources,
|
||||
)
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..widgets import (
|
||||
display_text,
|
||||
first_value,
|
||||
@@ -189,74 +196,74 @@ _ORDER_OFFSET_HELP = (
|
||||
|
||||
_ORDER_DETAIL_QSS = """
|
||||
QDialog#DiagnosisOrderDetailOverlay { background: transparent; }
|
||||
QFrame#DiagnosisOrderDetailScrim { background: rgba(30, 64, 175, 0.18); border: 0; }
|
||||
QFrame#DiagnosisOrderDetailScrim { background: rgba(26, 28, 31, 0.18); border: 0; }
|
||||
QFrame#DiagnosisOrderDetailDrawer {
|
||||
background: #F7F9FE;
|
||||
background: #F7F7F7;
|
||||
border: 0;
|
||||
border-left: 1px solid #DDE7FF;
|
||||
border-left: 1px solid #F0F0F0;
|
||||
}
|
||||
QFrame#DiagnosisOrderDetailHeader {
|
||||
background: #FFFFFF;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #DDE7FF;
|
||||
border-bottom: 1px solid #F0F0F0;
|
||||
}
|
||||
QLabel#DiagnosisOrderDetailTitle { color: #15224A; font-size: 19px; font-weight: 650; }
|
||||
QLabel#DiagnosisOrderDetailMeta { color: #7481A3; font-size: 12px; }
|
||||
QLabel#DiagnosisOrderDetailTitle { color: #1A1C1F; font-size: 19px; font-weight: 650; }
|
||||
QLabel#DiagnosisOrderDetailMeta { color: #606163; font-size: 12px; }
|
||||
QLabel#DiagnosisOrderReadonlyBadge {
|
||||
color: #3F4E75;
|
||||
background: #F7F9FE;
|
||||
border: 1px solid #E2E7F4;
|
||||
color: #1A1C1F;
|
||||
background: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 4px;
|
||||
padding: 3px 7px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QScrollArea#DiagnosisOrderDetailScroll { border: 0; background: #F7F9FE; }
|
||||
QScrollArea#DiagnosisOrderDetailScroll > QWidget > QWidget { background: #F7F9FE; }
|
||||
QScrollArea#DiagnosisOrderDetailScroll { border: 0; background: #F7F7F7; }
|
||||
QScrollArea#DiagnosisOrderDetailScroll > QWidget > QWidget { background: #F7F7F7; }
|
||||
QFrame[orderAmountCard="true"] {
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #DDE7FF;
|
||||
border: 1px solid #F0F0F0;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QLabel[orderAmountTitle="true"] { color: #7481A3; font-size: 11px; font-weight: 550; }
|
||||
QLabel[orderAmountTitle="true"] { color: #606163; font-size: 11px; font-weight: 550; }
|
||||
QLabel[orderAmountValue="true"] {
|
||||
color: #15224A;
|
||||
color: #1A1C1F;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
QLabel[orderAmountTone="danger"] { color: #C43E55; }
|
||||
QLabel[orderAmountTone="success"] { color: #16876C; }
|
||||
QLabel[orderAmountTone="warning"] { color: #9A6813; }
|
||||
QLabel[orderAmountTone="danger"] { color: #BE4B58; }
|
||||
QLabel[orderAmountTone="success"] { color: #287B65; }
|
||||
QLabel[orderAmountTone="warning"] { color: #A9691D; }
|
||||
QFrame[orderDetailSection="true"] {
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #E2E7F4;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QLabel[orderSectionTitle="true"] { color: #15224A; font-size: 15px; font-weight: 650; }
|
||||
QLabel[orderSectionHint="true"] { color: #7481A3; font-size: 11px; }
|
||||
QLabel[orderSectionTitle="true"] { color: #1A1C1F; font-size: 15px; font-weight: 650; }
|
||||
QLabel[orderSectionHint="true"] { color: #606163; font-size: 11px; }
|
||||
QFrame[orderField="true"] {
|
||||
background: #F2F6FE;
|
||||
border: 1px solid #E2E7F4;
|
||||
background: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 7px;
|
||||
}
|
||||
QLabel[orderFieldLabel="true"] { color: #7481A3; font-size: 11px; }
|
||||
QLabel[orderFieldValue="true"] { color: #15224A; font-size: 13px; }
|
||||
QLabel[orderFieldLabel="true"] { color: #6A6B6D; font-size: 11px; }
|
||||
QLabel[orderFieldValue="true"] { color: #1A1C1F; font-size: 13px; }
|
||||
QLabel[orderEmptyState="true"] {
|
||||
color: #7481A3;
|
||||
background: #F2F6FE;
|
||||
border: 1px dashed #C9D8F2;
|
||||
color: #606163;
|
||||
background: #F7F7F7;
|
||||
border: 1px dashed #E4E4E5;
|
||||
border-radius: 5px;
|
||||
padding: 18px 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
QFrame#DiagnosisOrderTimelineItem { border: 0; border-left: 2px solid #93B4F4; }
|
||||
QLabel#DiagnosisOrderTimelineTime { color: #7481A3; font-size: 11px; }
|
||||
QLabel#DiagnosisOrderTimelineTitle { color: #15224A; font-size: 12px; font-weight: 600; }
|
||||
QLabel#DiagnosisOrderTimelineBody { color: #7481A3; font-size: 12px; }
|
||||
QFrame#DiagnosisOrderTimelineItem { border: 0; border-left: 2px solid #8B9AD9; }
|
||||
QLabel#DiagnosisOrderTimelineTime { color: #606163; font-size: 11px; }
|
||||
QLabel#DiagnosisOrderTimelineTitle { color: #1A1C1F; font-size: 12px; font-weight: 600; }
|
||||
QLabel#DiagnosisOrderTimelineBody { color: #606163; font-size: 12px; }
|
||||
QFrame#DiagnosisOrderDetailFooter {
|
||||
background: #FFFFFF;
|
||||
border: 0;
|
||||
border-top: 1px solid #DDE7FF;
|
||||
border-top: 1px solid #F0F0F0;
|
||||
}
|
||||
"""
|
||||
|
||||
@@ -300,7 +307,7 @@ _FORM_SECTIONS: tuple[tuple[str, tuple[tuple[tuple[str, str, int, str], ...], ..
|
||||
("渠道", "create_source", 12, "create_source"),
|
||||
),
|
||||
(("统计端就诊卡", "show_card", 12, "show_card"),),
|
||||
(("在用药物", "current_medications", 24, "textarea3"),),
|
||||
(("在用药物", "current_medications", 24, "expandable_textarea3"),),
|
||||
),
|
||||
),
|
||||
(
|
||||
@@ -331,7 +338,7 @@ _FORM_SECTIONS: tuple[tuple[str, tuple[tuple[tuple[str, str, int, str], ...], ..
|
||||
(("小便情况", "urine_condition", 24, "urine_condition_choices"),),
|
||||
(("大便情况", "stool_condition", 24, "stool_condition_choices"),),
|
||||
(("腰肾情况", "kidney_condition", 24, "kidney_condition_choices"),),
|
||||
(("其他补充", "symptoms", 24, "textarea3"),),
|
||||
(("其他补充", "symptoms", 24, "expandable_textarea3"),),
|
||||
),
|
||||
),
|
||||
("既往史", ((("既往史", "past_history", 24, "past_history_choices"),),)),
|
||||
@@ -757,9 +764,11 @@ class DiagnosisDialog(QDialog):
|
||||
parent: QWidget | None = None,
|
||||
*,
|
||||
permissions: Any = None,
|
||||
embedded: bool = False,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.repository = repository
|
||||
self._embedded = bool(embedded)
|
||||
self.permissions = (
|
||||
permissions
|
||||
if permissions is not None
|
||||
@@ -828,6 +837,8 @@ class DiagnosisDialog(QDialog):
|
||||
self._saving = False
|
||||
self._load_mode = "readonly"
|
||||
self._generation = 0
|
||||
self._dictionary_requested_generation = -1
|
||||
self._dictionary_error_message = ""
|
||||
self._save_generation = 0
|
||||
self._orders_generation = 0
|
||||
self._order_detail_generation = 0
|
||||
@@ -842,6 +853,7 @@ class DiagnosisDialog(QDialog):
|
||||
self._loading_tabs: set[str] = set()
|
||||
self._daily_todo_status: int | None = None
|
||||
self._recording_players: list[RecordingPlayerDialog] = []
|
||||
self._image_preview: ImagePreviewDialog | None = None
|
||||
self._inline_recording_cells: list[RecordingPlaybackCell] = []
|
||||
self._last_order_detail_dialog: QDialog | None = None
|
||||
self._local_audio_dialog: LocalAudioQueueDialog | None = None
|
||||
@@ -881,11 +893,17 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
|
||||
self.setObjectName("DiagnosisDialogRoot")
|
||||
self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
if self._embedded:
|
||||
self.setWindowFlags(Qt.WindowType.Widget)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, False)
|
||||
self.setMinimumSize(0, 0)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Expanding)
|
||||
else:
|
||||
self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.setMinimumSize(760, 520)
|
||||
self.resize(1024, 640)
|
||||
self.setWindowTitle("患者信息详情")
|
||||
self.setMinimumSize(760, 520)
|
||||
self.resize(1024, 640)
|
||||
self.setStyleSheet(DIAGNOSIS_QSS)
|
||||
|
||||
self.view_stack = QStackedLayout(self)
|
||||
@@ -910,16 +928,25 @@ class DiagnosisDialog(QDialog):
|
||||
root = QVBoxLayout(page)
|
||||
root.setContentsMargins(0, 0, 0, 0)
|
||||
root.setSpacing(0)
|
||||
self.readonly_header = QWidget(page)
|
||||
self.readonly_header.setObjectName("DiagnosisReadonlyHeader")
|
||||
header_layout = QVBoxLayout(self.readonly_header)
|
||||
header_layout.setContentsMargins(16, 16, 16, 0)
|
||||
header_layout.setSpacing(0)
|
||||
self.readonly_hero = self._build_readonly_hero()
|
||||
header_layout.addWidget(self.readonly_hero)
|
||||
root.addWidget(self.readonly_header)
|
||||
self.readonly_scroll = QScrollArea()
|
||||
self.readonly_scroll.setObjectName("DiagnosisReadonlyScroll")
|
||||
self.readonly_scroll.setWidgetResizable(True)
|
||||
self.readonly_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.readonly_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
self.readonly_scroll.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self.readonly_scroll.verticalScrollBar().setSingleStep(28)
|
||||
content = QWidget()
|
||||
self.readonly_content_layout = QVBoxLayout(content)
|
||||
self.readonly_content_layout.setContentsMargins(16, 16, 16, 16)
|
||||
self.readonly_content_layout.setSpacing(16)
|
||||
self.readonly_hero = self._build_readonly_hero()
|
||||
self.readonly_content_layout.addWidget(self.readonly_hero)
|
||||
self.readonly_error = QFrame()
|
||||
self.readonly_error.setObjectName("DiagnosisReadonlyErrorCard")
|
||||
self.readonly_error.setProperty("diagnosisReadonlyCard", True)
|
||||
@@ -946,6 +973,7 @@ class DiagnosisDialog(QDialog):
|
||||
self._add_readonly_section("daily", "日常记录", daily)
|
||||
notes = NotesTimeline(editable=False)
|
||||
notes.open_attachment_requested.connect(self._open_safe_resource)
|
||||
notes.preview_images_requested.connect(self._preview_note_images)
|
||||
self._notes_timelines.append(notes)
|
||||
self._add_readonly_section("notes", "医生备注 & 舌苔照片 & 检查报告", notes)
|
||||
orders = self._new_table("orders", "DiagnosisReadonlyOrdersTable")
|
||||
@@ -980,16 +1008,16 @@ class DiagnosisDialog(QDialog):
|
||||
left_layout = QHBoxLayout(self.readonly_hero_left)
|
||||
left_layout.setContentsMargins(0, 0, 0, 0)
|
||||
left_layout.setSpacing(12)
|
||||
back = QPushButton("← 返回")
|
||||
back.setObjectName("DiagnosisReadonlyBack")
|
||||
back.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
back.setStyleSheet(
|
||||
self.readonly_back_button = QPushButton("← 收起资料" if self._embedded else "← 返回")
|
||||
self.readonly_back_button.setObjectName("DiagnosisReadonlyBack")
|
||||
self.readonly_back_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.readonly_back_button.setStyleSheet(
|
||||
"QPushButton{height:32px;padding:0 8px;border:0;background:transparent;"
|
||||
"color:#5265F6;font-size:13px;font-weight:500;}"
|
||||
"QPushButton:hover,QPushButton:focus{background:#F0F2FF;border-radius:6px;}"
|
||||
"color:#1A1C1F;font-size:13px;font-weight:500;}"
|
||||
"QPushButton:hover,QPushButton:focus{background:#EEF1FA;border-radius:6px;}"
|
||||
)
|
||||
back.clicked.connect(self.reject)
|
||||
left_layout.addWidget(back)
|
||||
self.readonly_back_button.clicked.connect(self.reject)
|
||||
left_layout.addWidget(self.readonly_back_button)
|
||||
title = QLabel("患者信息详情")
|
||||
title.setObjectName("DiagnosisReadonlyTitle")
|
||||
left_layout.addWidget(title)
|
||||
@@ -1008,6 +1036,13 @@ class DiagnosisDialog(QDialog):
|
||||
self.readonly_status.setObjectName("DiagnosisReadonlyStatus")
|
||||
self.readonly_status.setProperty("severity", "neutral")
|
||||
right_layout.addWidget(self.readonly_status)
|
||||
self.readonly_close_button = QPushButton("×")
|
||||
self.readonly_close_button.setObjectName("DiagnosisCloseButton")
|
||||
self.readonly_close_button.setToolTip("关闭诊单详情")
|
||||
self.readonly_close_button.setAccessibleName("关闭诊单详情")
|
||||
self.readonly_close_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.readonly_close_button.clicked.connect(self.reject)
|
||||
right_layout.addWidget(self.readonly_close_button)
|
||||
layout.addWidget(self.readonly_hero_left, 0, 0)
|
||||
layout.addWidget(self.readonly_hero_right, 0, 1, Qt.AlignmentFlag.AlignRight)
|
||||
layout.setColumnStretch(0, 1)
|
||||
@@ -1234,11 +1269,12 @@ class DiagnosisDialog(QDialog):
|
||||
occupied = 0
|
||||
for label, key, span, field_kind in row_fields:
|
||||
editor = self._ensure_editor(key, field_kind)
|
||||
display = (
|
||||
editor.wrap_with_unit()
|
||||
if isinstance(editor, DiagnosisNumberEdit)
|
||||
else editor
|
||||
)
|
||||
if isinstance(editor, DiagnosisNumberEdit):
|
||||
display = editor.wrap_with_unit()
|
||||
elif isinstance(editor, ExpandableDiagnosisTextEdit):
|
||||
display = editor.wrap_with_expander(label)
|
||||
else:
|
||||
display = editor
|
||||
container = self._field_container(label, display, span, editor=editor)
|
||||
row_layout.addWidget(container, span)
|
||||
fields.append(container)
|
||||
@@ -1371,9 +1407,13 @@ class DiagnosisDialog(QDialog):
|
||||
columns=4 if multiple else 5,
|
||||
)
|
||||
self._choice_fields[key] = editor
|
||||
elif field_kind.startswith("textarea"):
|
||||
elif field_kind.startswith(("textarea", "expandable_textarea")):
|
||||
rows = int(field_kind[-1])
|
||||
editor = DiagnosisTextEdit(rows)
|
||||
editor = (
|
||||
ExpandableDiagnosisTextEdit(rows)
|
||||
if field_kind.startswith("expandable_")
|
||||
else DiagnosisTextEdit(rows)
|
||||
)
|
||||
else:
|
||||
editor = DiagnosisLineEdit()
|
||||
editor.setObjectName(f"DiagnosisField_{key.removeprefix('__')}")
|
||||
@@ -1406,6 +1446,7 @@ class DiagnosisDialog(QDialog):
|
||||
timeline.upload_requested.connect(self._upload_doctor_note_material)
|
||||
timeline.delete_attachment_requested.connect(self._delete_doctor_note_attachment)
|
||||
timeline.open_attachment_requested.connect(self._open_safe_resource)
|
||||
timeline.preview_images_requested.connect(self._preview_note_images)
|
||||
self.drawer_notes_timeline = timeline
|
||||
self._notes_timelines.append(timeline)
|
||||
return self._wrap_tab("DiagnosisTabNotes", timeline)
|
||||
@@ -1502,20 +1543,11 @@ class DiagnosisDialog(QDialog):
|
||||
layout.addWidget(toolbar)
|
||||
self.orders_table = self._new_table("orders", "DiagnosisTableOrders")
|
||||
layout.addWidget(self.orders_table, 1)
|
||||
footer = QHBoxLayout()
|
||||
self.orders_summary = QLabel("共 0 条")
|
||||
self.orders_summary.setObjectName("DiagnosisOrdersSummary")
|
||||
footer.addWidget(self.orders_summary)
|
||||
footer.addStretch(1)
|
||||
self.orders_previous = QPushButton("上一页")
|
||||
self.orders_previous.clicked.connect(lambda: self._change_orders_page(-1))
|
||||
footer.addWidget(self.orders_previous)
|
||||
self.orders_page_label = QLabel("1 / 1")
|
||||
footer.addWidget(self.orders_page_label)
|
||||
self.orders_next = QPushButton("下一页")
|
||||
self.orders_next.clicked.connect(lambda: self._change_orders_page(1))
|
||||
footer.addWidget(self.orders_next)
|
||||
layout.addLayout(footer)
|
||||
self.orders_list = InfiniteList(self._orders_page_size, page)
|
||||
for table in self._table_registry["orders"]:
|
||||
self.orders_list.bind(table)
|
||||
self._orders_footer_layout = layout
|
||||
layout.addWidget(self.orders_list)
|
||||
return page
|
||||
|
||||
def _wrap_tab(self, object_name: str, body: QWidget) -> QScrollArea:
|
||||
@@ -1676,22 +1708,23 @@ class DiagnosisDialog(QDialog):
|
||||
if hasattr(self, "readonly_ai_button"):
|
||||
self.readonly_ai_button.setVisible(can_open_diagnosis_ai_report(self.permissions))
|
||||
self.readonly_ai_button.setEnabled(self._diagnosis_id > 0)
|
||||
current_key = self.tabs.tabBar().tabData(self.tabs.currentIndex())
|
||||
self.tabs.clear()
|
||||
for key, label, codes in _TAB_DEFINITIONS:
|
||||
if not self._tab_allowed(codes):
|
||||
continue
|
||||
index = self.tabs.addTab(self._tab_pages[key], label)
|
||||
self.tabs.tabBar().setTabData(index, key)
|
||||
target = next(
|
||||
(
|
||||
index
|
||||
for index in range(self.tabs.count())
|
||||
if self.tabs.tabBar().tabData(index) == current_key
|
||||
),
|
||||
0,
|
||||
)
|
||||
self.tabs.setCurrentIndex(target)
|
||||
previous_key = self._current_tab_key()
|
||||
allowed_tabs = [
|
||||
(key, label) for key, label, codes in _TAB_DEFINITIONS if self._tab_allowed(codes)
|
||||
]
|
||||
if [self.tabs.tabBar().tabData(i) for i in range(self.tabs.count())] != [
|
||||
key for key, _label in allowed_tabs
|
||||
]:
|
||||
blocked = self.tabs.blockSignals(True)
|
||||
self.tabs.clear()
|
||||
target = 0
|
||||
for key, label in allowed_tabs:
|
||||
index = self.tabs.addTab(self._tab_pages[key], label)
|
||||
self.tabs.tabBar().setTabData(index, key)
|
||||
if key == previous_key:
|
||||
target = index
|
||||
self.tabs.setCurrentIndex(target)
|
||||
self.tabs.blockSignals(blocked)
|
||||
section_codes = {key: codes for key, _label, codes in _TAB_DEFINITIONS}
|
||||
for key, section in self._readonly_sections.items():
|
||||
section.setVisible(self._tab_allowed(section_codes.get(key, ())))
|
||||
@@ -1721,6 +1754,9 @@ class DiagnosisDialog(QDialog):
|
||||
self._sync_order_offset_actions()
|
||||
for panel in self._chat_panels:
|
||||
panel.sync_button.setVisible(self._can_chat_sync)
|
||||
self._sync_save_button()
|
||||
if self._current_tab_key() != previous_key:
|
||||
self._tab_changed(self.tabs.currentIndex())
|
||||
|
||||
def _show_message(self, text: str, kind: str = "info", action_text: str = "") -> None:
|
||||
self.drawer_banner.show_message(text, kind, action_text)
|
||||
@@ -1729,6 +1765,9 @@ class DiagnosisDialog(QDialog):
|
||||
self.readonly_error.show()
|
||||
|
||||
def _clear_message(self) -> None:
|
||||
if self._dictionary_error_message and self._authoritative_detail_loaded:
|
||||
self._show_message(self._dictionary_error_message, "warning", action_text="重试")
|
||||
return
|
||||
self.drawer_banner.clear()
|
||||
self.readonly_error.hide()
|
||||
|
||||
@@ -1784,6 +1823,8 @@ class DiagnosisDialog(QDialog):
|
||||
label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
||||
|
||||
def _sync_host_geometry(self) -> None:
|
||||
if self._embedded:
|
||||
return
|
||||
owner = self._owner
|
||||
if owner is None:
|
||||
if self.width() < 760 or self.height() < 520:
|
||||
@@ -1817,6 +1858,8 @@ class DiagnosisDialog(QDialog):
|
||||
layout.addWidget(self.readonly_hero_right, 0, 1, Qt.AlignmentFlag.AlignRight)
|
||||
|
||||
def _install_owner_filter(self) -> None:
|
||||
if self._embedded:
|
||||
return
|
||||
if self._owner is not None and not self._owner_filter_installed:
|
||||
self._owner.installEventFilter(self)
|
||||
self._owner_filter_installed = True
|
||||
@@ -1824,6 +1867,10 @@ class DiagnosisDialog(QDialog):
|
||||
def _rebind_owner(self) -> None:
|
||||
"""Resolve the live Shell window for every open/show cycle."""
|
||||
|
||||
if self._embedded:
|
||||
self._owner = None
|
||||
self._owner_filter_installed = False
|
||||
return
|
||||
parent = self.parentWidget()
|
||||
candidate = parent.window() if parent is not None else None
|
||||
if candidate is self:
|
||||
@@ -1846,8 +1893,9 @@ class DiagnosisDialog(QDialog):
|
||||
super().resizeEvent(event)
|
||||
|
||||
def showEvent(self, event: Any) -> None:
|
||||
self._rebind_owner()
|
||||
self._sync_host_geometry()
|
||||
if not self._embedded:
|
||||
self._rebind_owner()
|
||||
self._sync_host_geometry()
|
||||
self._update_drawer_geometry()
|
||||
self._reflow_readonly_hero()
|
||||
super().showEvent(event)
|
||||
@@ -1911,8 +1959,20 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
present_diagnosis_ai_report(self.repository, self.permissions, self, row)
|
||||
|
||||
def open_view_only(self, diagnosis_id: int, *, seed: Any = None) -> None:
|
||||
self.open_for(diagnosis_id, editable=False, seed=seed, view_only=True)
|
||||
def open_view_only(
|
||||
self,
|
||||
diagnosis_id: int,
|
||||
*,
|
||||
seed: Any = None,
|
||||
modeless: bool = False,
|
||||
) -> None:
|
||||
self.open_for(
|
||||
diagnosis_id,
|
||||
editable=False,
|
||||
seed=seed,
|
||||
view_only=True,
|
||||
modeless=modeless,
|
||||
)
|
||||
|
||||
def open_for(
|
||||
self,
|
||||
@@ -1920,9 +1980,12 @@ class DiagnosisDialog(QDialog):
|
||||
*,
|
||||
editable: bool = False,
|
||||
seed: Any = None,
|
||||
authoritative_detail: Any = None,
|
||||
view_only: bool = False,
|
||||
modeless: bool = False,
|
||||
auto_show: bool = True,
|
||||
) -> None:
|
||||
"""Open immediately, then replace the seed with authoritative server data."""
|
||||
"""Prepare a diagnosis view, optionally showing it immediately."""
|
||||
|
||||
self._rebind_owner()
|
||||
for player in list(self._recording_players):
|
||||
@@ -1950,6 +2013,7 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
self._authoritative_detail_loaded = False
|
||||
self._saving = False
|
||||
self._dictionary_error_message = ""
|
||||
self._generation += 1
|
||||
self._save_generation += 1
|
||||
self._orders_generation += 1
|
||||
@@ -1967,13 +2031,20 @@ class DiagnosisDialog(QDialog):
|
||||
self._daily_todo_status = None
|
||||
self._orders_page = 1
|
||||
self._orders_total = 0
|
||||
self._detail = seed
|
||||
self.orders_list.reset()
|
||||
footer_layout = (
|
||||
self._readonly_sections["orders"].layout()
|
||||
if self._standalone_readonly
|
||||
else self._orders_footer_layout
|
||||
)
|
||||
footer_layout.addWidget(self.orders_list)
|
||||
self._detail = authoritative_detail if authoritative_detail is not None else seed
|
||||
self.save_button.set_state("idle")
|
||||
self.refresh_permissions()
|
||||
self.view_stack.setCurrentWidget(
|
||||
self.readonly_page if self._standalone_readonly else self.drawer_overlay
|
||||
)
|
||||
self.setModal(not self._standalone_readonly)
|
||||
self.setModal(False if self._embedded else not modeless and not self._standalone_readonly)
|
||||
self.setWindowTitle(
|
||||
"患者信息详情"
|
||||
if self._standalone_readonly
|
||||
@@ -1999,15 +2070,38 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
self._clear_tables()
|
||||
self._clear_message()
|
||||
if seed is not None:
|
||||
self._render(seed, [], [])
|
||||
if self._detail is not None:
|
||||
self._render(self._detail, [], [])
|
||||
self._sync_form_interactivity()
|
||||
self._sync_save_button()
|
||||
self._sync_host_geometry()
|
||||
if auto_show:
|
||||
self.show()
|
||||
if not self._embedded:
|
||||
self.raise_()
|
||||
if authoritative_detail is not None:
|
||||
diagnosis = get_value(authoritative_detail, "diagnosis", None) or authoritative_detail
|
||||
patient = get_value(authoritative_detail, "patient", None) or {}
|
||||
self._patient_id = _int(
|
||||
first_value(
|
||||
diagnosis,
|
||||
"patient_id",
|
||||
"source_patient_id",
|
||||
default=first_value(patient, "patient_id", "id", default=0),
|
||||
),
|
||||
0,
|
||||
)
|
||||
self._authoritative_detail_loaded = True
|
||||
self._show_authoritative_content(True)
|
||||
self._clear_message()
|
||||
self._set_loading(False)
|
||||
if self._standalone_readonly:
|
||||
self._load_visible_readonly_sections()
|
||||
else:
|
||||
self._ensure_tab_loaded(self._current_tab_key())
|
||||
return
|
||||
self._show_message("正在加载权威诊单详情…", "info")
|
||||
self._set_loading(True)
|
||||
self._sync_host_geometry()
|
||||
self.show()
|
||||
self.raise_()
|
||||
self._start_detail_load()
|
||||
|
||||
def _start_detail_load(self) -> None:
|
||||
@@ -2049,14 +2143,26 @@ class DiagnosisDialog(QDialog):
|
||||
),
|
||||
0,
|
||||
)
|
||||
return {"detail": detail, "patient_id": patient_id}
|
||||
|
||||
def _load_dictionary_choices(self) -> dict[str, Any]:
|
||||
"""Load optional editor labels without extending the authoritative-detail gate."""
|
||||
dictionaries: dict[str, list[tuple[str, Any]]] = {}
|
||||
dictionary_errors: list[str] = []
|
||||
if callable(getattr(self.repository, "get_dictionary", None)):
|
||||
dictionary_types = {
|
||||
dictionary_types = sorted(
|
||||
{
|
||||
"diagnosis_type",
|
||||
*(item[0] for item in _CHOICE_DICTIONARIES.values()),
|
||||
}
|
||||
for dictionary_type in sorted(dictionary_types):
|
||||
)
|
||||
if callable(getattr(self.repository, "get_dictionaries", None)):
|
||||
raw = invoke(self.repository, "get_dictionaries", dictionary_types=dictionary_types)
|
||||
dictionaries = {
|
||||
key: _dictionary_choices(get_value(raw, key, []), key)
|
||||
for key in dictionary_types
|
||||
}
|
||||
elif callable(getattr(self.repository, "get_dictionary", None)):
|
||||
for dictionary_type in dictionary_types:
|
||||
try:
|
||||
raw = invoke(
|
||||
self.repository,
|
||||
@@ -2067,12 +2173,41 @@ class DiagnosisDialog(QDialog):
|
||||
except Exception as error:
|
||||
dictionary_errors.append(f"{dictionary_type} 字典:{friendly_error(error)}")
|
||||
return {
|
||||
"detail": detail,
|
||||
"patient_id": patient_id,
|
||||
"dictionaries": dictionaries,
|
||||
"dictionary_errors": dictionary_errors,
|
||||
}
|
||||
|
||||
def _ensure_dictionary_loaded(self, *, force: bool = False) -> None:
|
||||
if self._standalone_readonly or not self._authoritative_detail_loaded:
|
||||
return
|
||||
generation = self._generation
|
||||
if not force and self._dictionary_requested_generation == generation:
|
||||
return
|
||||
self._dictionary_requested_generation = generation
|
||||
clear_error = self.drawer_banner.label.text() == self._dictionary_error_message
|
||||
self._dictionary_error_message = ""
|
||||
if clear_error:
|
||||
self._clear_message()
|
||||
run_async(
|
||||
self._load_dictionary_choices,
|
||||
on_success=lambda result: self._dictionary_choices_loaded(result, generation),
|
||||
on_error=lambda error: self._dictionary_choices_loaded(
|
||||
{"dictionary_errors": [f"病历选项加载失败:{friendly_error(error)}"]}, generation
|
||||
),
|
||||
)
|
||||
|
||||
def _dictionary_choices_loaded(self, result: Any, generation: int) -> None:
|
||||
if generation != self._generation or not self._authoritative_detail_loaded:
|
||||
return
|
||||
# A clinician may already have edited fields while the optional labels load.
|
||||
# Update only choices; re-rendering the detail would overwrite that draft.
|
||||
self._apply_dictionary_choices(get_value(result, "dictionaries", {}) or {}, preserve=True)
|
||||
errors = get_value(result, "dictionary_errors", []) or []
|
||||
if errors:
|
||||
self._dictionary_requested_generation = -1
|
||||
self._dictionary_error_message = ";".join(str(item) for item in errors)
|
||||
self._show_message(self._dictionary_error_message, "warning", action_text="重试")
|
||||
|
||||
def _query_orders(self, diagnosis_id: int, patient_id: int, page: int) -> Any:
|
||||
filters: dict[str, Any] = {
|
||||
"context_diagnosis_id": diagnosis_id,
|
||||
@@ -2094,12 +2229,12 @@ class DiagnosisDialog(QDialog):
|
||||
detail = get_value(result, "detail", None)
|
||||
self._detail = detail
|
||||
self._patient_id = _int(get_value(result, "patient_id", 0), 0)
|
||||
self._apply_dictionary_choices(get_value(result, "dictionaries", {}) or {})
|
||||
self._authoritative_detail_loaded = True
|
||||
self._show_authoritative_content(True)
|
||||
self._render(detail, [], [])
|
||||
self._sync_form_interactivity()
|
||||
self._sync_save_button()
|
||||
self._set_loading(False)
|
||||
errors = get_value(result, "dictionary_errors", []) or []
|
||||
if errors:
|
||||
self._show_message(";".join(str(item) for item in errors), "warning")
|
||||
@@ -2126,7 +2261,9 @@ class DiagnosisDialog(QDialog):
|
||||
if generation == self._generation:
|
||||
self._set_loading(False)
|
||||
|
||||
def _apply_dictionary_choices(self, dictionaries: Mapping[str, Any]) -> None:
|
||||
def _apply_dictionary_choices(
|
||||
self, dictionaries: Mapping[str, Any], *, preserve: bool = False
|
||||
) -> None:
|
||||
diagnosis_type_editor = self.edit_fields.get("diagnosis_type")
|
||||
if isinstance(diagnosis_type_editor, DiagnosisComboBox):
|
||||
labels = {
|
||||
@@ -2143,15 +2280,17 @@ class DiagnosisDialog(QDialog):
|
||||
("会诊", "consultation"),
|
||||
)
|
||||
),
|
||||
preserve=False,
|
||||
preserve=preserve,
|
||||
)
|
||||
for key, (dictionary_type, _multiple) in _CHOICE_DICTIONARIES.items():
|
||||
if dictionary_type not in dictionaries:
|
||||
continue
|
||||
editor = self._choice_fields.get(key)
|
||||
choices = list(dictionaries.get(dictionary_type, []))
|
||||
if not _multiple:
|
||||
choices.insert(0, ("无", ""))
|
||||
if editor is not None:
|
||||
editor.set_choices(choices, preserve=False)
|
||||
editor.set_choices(choices, preserve=preserve)
|
||||
# Defer until the drawer has a real width so wrapped chips get height.
|
||||
QTimer.singleShot(0, self._sync_choice_field_heights)
|
||||
|
||||
@@ -2230,14 +2369,20 @@ class DiagnosisDialog(QDialog):
|
||||
if not self._authoritative_detail_loaded:
|
||||
self._retry_detail()
|
||||
return
|
||||
if (self._dictionary_error_message
|
||||
and self.drawer_banner.label.text() == self._dictionary_error_message):
|
||||
self._ensure_dictionary_loaded(force=True)
|
||||
return
|
||||
self._ensure_tab_loaded(self._current_tab_key(), force=True)
|
||||
|
||||
def _invalidate_requests(self) -> None:
|
||||
self._close_image_preview()
|
||||
self._stop_watching_local_audio_uploads()
|
||||
self._video_reload_pending = False
|
||||
self._generation += 1
|
||||
self._save_generation += 1
|
||||
self._orders_generation += 1
|
||||
self.orders_list.invalidate()
|
||||
self._order_detail_generation += 1
|
||||
self._daily_mutation_generation += 1
|
||||
self._notes_mutation_generation += 1
|
||||
@@ -2550,7 +2695,10 @@ class DiagnosisDialog(QDialog):
|
||||
table.set_empty_text(message)
|
||||
|
||||
def _ensure_tab_loaded(self, key: str, *, force: bool = False) -> None:
|
||||
if key == "basic" or not self._authoritative_detail_loaded or self._diagnosis_id <= 0:
|
||||
if not self._authoritative_detail_loaded or self._diagnosis_id <= 0:
|
||||
return
|
||||
if key == "basic":
|
||||
self._ensure_dictionary_loaded(force=force)
|
||||
return
|
||||
if key == "daily":
|
||||
source = next(
|
||||
@@ -2562,6 +2710,9 @@ class DiagnosisDialog(QDialog):
|
||||
return
|
||||
if not force and (key in self._loaded_tabs or key in self._loading_tabs):
|
||||
return
|
||||
if key == "orders":
|
||||
self._load_orders()
|
||||
return
|
||||
self._tab_generations[key] += 1
|
||||
generation = self._tab_generations[key]
|
||||
diagnosis_id = self._diagnosis_id
|
||||
@@ -2655,10 +2806,9 @@ class DiagnosisDialog(QDialog):
|
||||
self._fill_prescriptions(page_items(result))
|
||||
elif key == "orders":
|
||||
rows = page_items(result)
|
||||
self._orders_page = 1
|
||||
self._orders_page = self.orders_list.page
|
||||
self._orders_total = page_total(result, len(rows))
|
||||
self._fill_orders(rows)
|
||||
self._update_orders_pager()
|
||||
elif key == "assign":
|
||||
self._fill_assignments(page_items(result))
|
||||
elif key == "appointment":
|
||||
@@ -3342,6 +3492,27 @@ class DiagnosisDialog(QDialog):
|
||||
self._sync_order_offset_actions()
|
||||
self._mutation_error(error, diagnosis_id, generation, "offset")
|
||||
|
||||
def _close_image_preview(self) -> None:
|
||||
preview, self._image_preview = self._image_preview, None
|
||||
if preview is not None:
|
||||
with suppress(RuntimeError):
|
||||
preview.close()
|
||||
|
||||
def _image_preview_finished(self, _result: int) -> None:
|
||||
if self.sender() is self._image_preview:
|
||||
self._image_preview = None
|
||||
|
||||
def _preview_note_images(self, sources: Sequence[str], index: int) -> None:
|
||||
"""Keep the diagnosis open while viewing the clicked note's image group."""
|
||||
if not safe_image_sources(sources):
|
||||
QMessageBox.warning(self, "无法预览", "仅支持 HTTP(S) 服务端图片。")
|
||||
return
|
||||
self._close_image_preview()
|
||||
preview = ImagePreviewDialog(sources, index=index, title="舌象图片预览", parent=self)
|
||||
self._image_preview = preview
|
||||
preview.finished.connect(self._image_preview_finished)
|
||||
preview.open()
|
||||
|
||||
def _open_safe_resource(self, target: str) -> None:
|
||||
url = QUrl(str(target).strip())
|
||||
if not url.isValid() or url.scheme().lower() not in {"https", "http"} or not url.host():
|
||||
@@ -3371,8 +3542,7 @@ class DiagnosisDialog(QDialog):
|
||||
panel.set_unavailable("切换到聊天记录后加载归档数据。")
|
||||
for panel in self._daily_panels:
|
||||
panel.clear()
|
||||
self.orders_summary.setText("共 0 条")
|
||||
self.orders_page_label.setText("1 / 1")
|
||||
self.orders_list.update_state(1, 0)
|
||||
|
||||
@staticmethod
|
||||
def _set_row(table: QTableWidget, row: int, values: Sequence[Any]) -> None:
|
||||
@@ -3990,6 +4160,9 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
for row_index, row in enumerate(rows):
|
||||
order_id = _int(first_value(row, "id", "order_id"), 0)
|
||||
item = table.item(row_index, 0)
|
||||
if item is not None:
|
||||
item.setData(Qt.ItemDataRole.UserRole, row)
|
||||
if (
|
||||
self._can_order_detail
|
||||
and order_id > 0
|
||||
@@ -4661,52 +4834,44 @@ class DiagnosisDialog(QDialog):
|
||||
if generation == self._order_detail_generation and diagnosis_id == self._diagnosis_id:
|
||||
self._show_message(friendly_error(error), "danger")
|
||||
|
||||
def _update_orders_pager(self) -> None:
|
||||
pages = max(1, (self._orders_total + self._orders_page_size - 1) // self._orders_page_size)
|
||||
self.orders_summary.setText(f"共 {self._orders_total} 条")
|
||||
self.orders_page_label.setText(f"{self._orders_page} / {pages}")
|
||||
self.orders_previous.setEnabled(self._orders_page > 1)
|
||||
self.orders_next.setEnabled(self._orders_page < pages)
|
||||
|
||||
def _change_orders_page(self, offset: int) -> None:
|
||||
def _load_orders(self) -> None:
|
||||
if not self._can_patient_orders or self._diagnosis_id <= 0:
|
||||
return
|
||||
pages = max(1, (self._orders_total + self._orders_page_size - 1) // self._orders_page_size)
|
||||
target_page = self._orders_page + offset
|
||||
if target_page < 1 or target_page > pages:
|
||||
return
|
||||
self._orders_generation += 1
|
||||
generation = self._orders_generation
|
||||
self._tab_generations["orders"] += 1
|
||||
generation = self._tab_generations["orders"]
|
||||
diagnosis_id = self._diagnosis_id
|
||||
patient_id = self._patient_id
|
||||
self._show_message("正在加载患者订单…", "info")
|
||||
run_async(
|
||||
lambda: self._query_orders(diagnosis_id, patient_id, target_page),
|
||||
on_success=lambda result: self._apply_orders_page(
|
||||
result, diagnosis_id, target_page, generation
|
||||
self._loading_tabs.add("orders")
|
||||
if not self.orders_list.rows:
|
||||
self._set_tab_loading("orders")
|
||||
self.orders_list.reload(
|
||||
lambda page: self._query_orders(diagnosis_id, patient_id, page),
|
||||
apply=lambda result: self._apply_orders_result(
|
||||
result, diagnosis_id, generation
|
||||
),
|
||||
on_error=lambda error: self._orders_error(error, diagnosis_id, generation),
|
||||
on_error=lambda error: self._tab_load_error(
|
||||
"orders", error, diagnosis_id, generation
|
||||
),
|
||||
runner=run_async,
|
||||
query_key=(diagnosis_id, patient_id),
|
||||
)
|
||||
|
||||
def _apply_orders_page(
|
||||
def _apply_orders_result(
|
||||
self,
|
||||
result: Any,
|
||||
diagnosis_id: int,
|
||||
page: int,
|
||||
generation: int,
|
||||
) -> None:
|
||||
if generation != self._orders_generation or diagnosis_id != self._diagnosis_id:
|
||||
if (
|
||||
generation != self._tab_generations["orders"]
|
||||
or diagnosis_id != self._diagnosis_id
|
||||
or not self._authoritative_detail_loaded
|
||||
):
|
||||
return
|
||||
rows = page_items(result)
|
||||
self._orders_page = page
|
||||
self._orders_total = page_total(result, len(rows))
|
||||
self._fill_orders(rows)
|
||||
self._update_orders_pager()
|
||||
self._clear_message()
|
||||
|
||||
def _orders_error(self, error: Exception, diagnosis_id: int, generation: int) -> None:
|
||||
if generation == self._orders_generation and diagnosis_id == self._diagnosis_id:
|
||||
self._show_message(friendly_error(error), "danger")
|
||||
if self.orders_list.page == 0:
|
||||
self._fill_orders([])
|
||||
return
|
||||
self._apply_tab_result("orders", result, diagnosis_id, generation)
|
||||
|
||||
def _save(self) -> None:
|
||||
if (
|
||||
|
||||
@@ -40,76 +40,76 @@ _STATUS_LABELS = {
|
||||
"invalid": "无效录音",
|
||||
}
|
||||
_STATUS_COLORS = {
|
||||
"recording": "#5364F5",
|
||||
"pending": "#B26A00",
|
||||
"uploading": "#2F6FEB",
|
||||
"uploaded": "#07966B",
|
||||
"failed": "#DC4054",
|
||||
"invalid": "#7886AA",
|
||||
"recording": "#1A1C1F",
|
||||
"pending": "#A9691D",
|
||||
"uploading": "#1A1C1F",
|
||||
"uploaded": "#287B65",
|
||||
"failed": "#BE4B58",
|
||||
"invalid": "#606163",
|
||||
}
|
||||
_BUSINESS_TIMEZONE = timezone(timedelta(hours=8))
|
||||
|
||||
_LOCAL_AUDIO_QSS = """
|
||||
QDialog#LocalAudioQueueDialog {
|
||||
background: #F6F8FD;
|
||||
color: #111F46;
|
||||
background: #F7F7F7;
|
||||
color: #1A1C1F;
|
||||
}
|
||||
QFrame#LocalAudioQueueHeader, QFrame#LocalAudioQueueSummary,
|
||||
QFrame#LocalAudioQueueTableCard, QFrame#LocalAudioQueueFooter {
|
||||
background: #FFFFFF;
|
||||
border: 1px solid #E2E7F4;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 14px;
|
||||
}
|
||||
QLabel#LocalAudioQueueTitle {
|
||||
color: #111F46;
|
||||
color: #1A1C1F;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
}
|
||||
QLabel#LocalAudioQueueSubtitle, QLabel#LocalAudioQueueHint {
|
||||
color: #6E7C9F;
|
||||
color: #6A6B6D;
|
||||
font-size: 13px;
|
||||
}
|
||||
QLabel[queueSummary="true"] {
|
||||
background: #F3F5FB;
|
||||
border: 1px solid #E6EAF5;
|
||||
background: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
color: #3F4E75;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
QPushButton {
|
||||
min-height: 34px;
|
||||
border: 1px solid #D9E0F2;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 9px;
|
||||
background: #FFFFFF;
|
||||
color: #354365;
|
||||
color: #1A1C1F;
|
||||
padding: 0 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QPushButton:hover { background: #F1F3FF; border-color: #AEB8FF; }
|
||||
QPushButton:disabled { color: #A5AFC6; background: #F7F8FC; }
|
||||
QPushButton:hover { background: #EEF1FA; border-color: #8B9AD9; }
|
||||
QPushButton:disabled { color: #8E8F90; background: #F7F7F7; }
|
||||
QPushButton[variant="primary"] {
|
||||
color: #FFFFFF;
|
||||
background: #5661F4;
|
||||
border-color: #5661F4;
|
||||
background: #4F63D9;
|
||||
border-color: #4F63D9;
|
||||
}
|
||||
QPushButton[variant="danger"] { color: #D83E51; background: #FFF6F7; }
|
||||
QPushButton[variant="danger"] { color: #BE4B58; background: #FFF6F7; }
|
||||
QTableWidget#LocalAudioQueueTable {
|
||||
background: #FFFFFF;
|
||||
alternate-background-color: #FAFBFE;
|
||||
alternate-background-color: #F7F7F7;
|
||||
border: 0;
|
||||
gridline-color: #E8ECF5;
|
||||
color: #263452;
|
||||
selection-background-color: #EEF1FF;
|
||||
selection-color: #111F46;
|
||||
gridline-color: #EDEDEE;
|
||||
color: #1A1C1F;
|
||||
selection-background-color: #EEF1FA;
|
||||
selection-color: #1A1C1F;
|
||||
}
|
||||
QTableWidget#LocalAudioQueueTable::item { padding: 8px; }
|
||||
QHeaderView::section {
|
||||
background: #F5F7FC;
|
||||
color: #53617F;
|
||||
background: #F7F7F7;
|
||||
color: #6A6B6D;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #E1E6F1;
|
||||
border-bottom: 1px solid #EDEDEE;
|
||||
padding: 10px 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
@@ -371,7 +371,7 @@ class LocalAudioQueueDialog(QDialog):
|
||||
self._status_column,
|
||||
_STATUS_LABELS.get(record.status, record.status),
|
||||
)
|
||||
status_item.setForeground(QColor(_STATUS_COLORS.get(record.status, "#53617F")))
|
||||
status_item.setForeground(QColor(_STATUS_COLORS.get(record.status, "#606163")))
|
||||
status_item.setToolTip(
|
||||
f"已尝试 {record.attempts} 次"
|
||||
+ (f"\nCOS:{record.uploaded_url}" if record.uploaded_url else "")
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Compact, presentation-only disclosure for page search and overview regions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from PySide6.QtCore import QObject, QSize, Qt, Signal
|
||||
from PySide6.QtWidgets import QApplication, QPushButton, QWidget
|
||||
|
||||
from . import icons
|
||||
|
||||
|
||||
class FilterDisclosure(QObject):
|
||||
"""Keep query values and loading state intact while reclaiming list space.
|
||||
|
||||
Targets should be region containers, not individual permission-controlled
|
||||
controls. Showing a container preserves its children's explicit visibility.
|
||||
"""
|
||||
|
||||
expanded_changed = Signal(bool)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: QWidget,
|
||||
targets: Sequence[QWidget],
|
||||
*,
|
||||
expanded: bool = False,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self._targets = tuple(targets)
|
||||
self._expanded = bool(expanded)
|
||||
self.button = QPushButton(parent)
|
||||
self.button.setObjectName("FilterDisclosureButton")
|
||||
self.button.setCheckable(True)
|
||||
self.button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.button.setFixedHeight(32)
|
||||
self.button.setIconSize(QSize(14, 14))
|
||||
self.button.setStyleSheet("""
|
||||
QPushButton#FilterDisclosureButton {
|
||||
color: #1769E8; background: #FFFFFF; border: 1px solid #DBE5F2;
|
||||
border-radius: 6px; padding: 0 11px; min-height: 30px; max-height: 30px;
|
||||
min-width: 92px; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
QPushButton#FilterDisclosureButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
|
||||
QPushButton#FilterDisclosureButton:checked { background: #EAF2FF; border-color: #ADC8F2; }
|
||||
QPushButton#FilterDisclosureButton:focus { border-color: #1769E8; }
|
||||
QPushButton#FilterDisclosureButton:disabled { color: #8B97A8; border-color: #E3E9F1; }
|
||||
""")
|
||||
self.button.toggled.connect(self.set_expanded)
|
||||
self._apply()
|
||||
|
||||
@property
|
||||
def expanded(self) -> bool:
|
||||
return self._expanded
|
||||
|
||||
def set_expanded(self, expanded: bool) -> None:
|
||||
expanded = bool(expanded)
|
||||
changed = expanded != self._expanded
|
||||
self._expanded = expanded
|
||||
self._apply()
|
||||
if changed:
|
||||
self.expanded_changed.emit(expanded)
|
||||
|
||||
def _apply(self) -> None:
|
||||
# Keep keyboard focus on a visible control when folding a focused form.
|
||||
focused = QApplication.focusWidget()
|
||||
if not self._expanded and focused is not None and any(
|
||||
target is focused or target.isAncestorOf(focused) for target in self._targets
|
||||
):
|
||||
self.button.setFocus(Qt.FocusReason.OtherFocusReason)
|
||||
for target in self._targets:
|
||||
target.setVisible(self._expanded)
|
||||
blocked = self.button.blockSignals(True)
|
||||
self.button.setChecked(self._expanded)
|
||||
self.button.blockSignals(blocked)
|
||||
label = "收起筛选" if self._expanded else "展开筛选"
|
||||
self.button.setText(label)
|
||||
self.button.setAccessibleName(label)
|
||||
self.button.setAccessibleDescription("显示或收起检索条件和统计信息;收起保留当前筛选条件")
|
||||
self.button.setToolTip("收起保留当前筛选条件" if self._expanded else "展开检索条件和统计信息,当前筛选条件保持不变")
|
||||
self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", "#1769E8", 14))
|
||||
@@ -0,0 +1,794 @@
|
||||
"""Single source of truth for every line icon in the workstation.
|
||||
|
||||
Before this module the application drew its icons from nine independent
|
||||
painters (``ui/shell.py`` had two, ``ui/login.py`` two,
|
||||
``ui/pages/reception.py`` four, and ``ui/pages/prescriptions.py``,
|
||||
``ui/pages/patients.py`` and ``ui/diagnosis_index_widgets.py`` one each). They disagreed on everything that
|
||||
makes an icon set read as one family:
|
||||
|
||||
* seven stroke weights - 1.4, 1.5, 1.55, 1.6, 1.7, 2.0 and ``size / 11.5`` px;
|
||||
* four design grids - geometry authored against 14, 16, 18 and 24 px boxes, so
|
||||
the same glyph asked for at another size came out off-centre or clipped;
|
||||
* mixed fills and strokes inside one row of icons (a stroked ``search`` beside a
|
||||
solid ``down`` triangle);
|
||||
* integer ``QRect`` coordinates in the menu painter, which put a 1.6 px stroke
|
||||
across a pixel boundary and rendered visibly softer than its neighbours;
|
||||
* six near-identical indigos and two near-identical reds picked per call site
|
||||
instead of from the palette.
|
||||
|
||||
Everything here is authored once on a 24-unit grid with a 20-unit optical safe
|
||||
area, stroked with one weight formula, and scaled to the requested size by the
|
||||
painter transform. Glyphs are pure stroke unless a filled counter is part of
|
||||
the mark (a list bullet, the dot on an "i"), which keeps the whole set at a
|
||||
single apparent weight.
|
||||
|
||||
Icons are cached as well. List pages build one icon per action button per row,
|
||||
so the previous code re-ran a ``QPainter`` for every visible row on every
|
||||
refresh; the cache turns that into one paint per (kind, colour, size).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Callable
|
||||
from functools import lru_cache
|
||||
|
||||
from PySide6.QtCore import QPointF, QRectF, Qt
|
||||
from PySide6.QtGui import QColor, QIcon, QPainter, QPainterPath, QPen, QPixmap
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from .theme import COLORS, crisp_pixmap
|
||||
|
||||
#: Every glyph is drawn inside this box. Nothing is authored against the pixel
|
||||
#: size the caller asks for, which is what keeps a 14 px and a 24 px request
|
||||
#: optically identical instead of merely proportional.
|
||||
GRID = 24.0
|
||||
|
||||
#: Ideal stroke at the reference grid. ``2 / 24`` is the Feather/Lucide ratio;
|
||||
#: the clamp keeps the line from vanishing at 12 px or turning into a slab at
|
||||
#: 36 px, which is the range the shell actually asks for.
|
||||
_STROKE_RATIO = 2.0 / GRID
|
||||
_STROKE_MIN_PX = 1.25
|
||||
_STROKE_MAX_PX = 2.25
|
||||
|
||||
|
||||
def stroke_px(size: float) -> float:
|
||||
"""Return the on-screen stroke width used for an icon of ``size`` px."""
|
||||
|
||||
return max(_STROKE_MIN_PX, min(_STROKE_MAX_PX, size * _STROKE_RATIO))
|
||||
|
||||
|
||||
# --- Semantic colour roles ------------------------------------------------
|
||||
# Call sites name a role instead of a hex value. The seven painters replaced
|
||||
# here between them hardcoded #5265F6, #5761F4, #5469F0, #5E69F6, #5365F5,
|
||||
# #4965F5 and #6675F5 for what was always meant to be one accent.
|
||||
ROLES = {
|
||||
"default": COLORS["muted"],
|
||||
"muted": COLORS["muted"],
|
||||
"soft": COLORS["text_soft"],
|
||||
"strong": COLORS["text"],
|
||||
"accent": COLORS["indigo"],
|
||||
"on_accent": "#FFFFFF",
|
||||
"success": COLORS["success"],
|
||||
"warning": COLORS["warning"],
|
||||
"danger": COLORS["danger"],
|
||||
"info": COLORS["info"],
|
||||
"disabled": COLORS["disabled_text"],
|
||||
"inverse": "#FFFFFF",
|
||||
}
|
||||
|
||||
|
||||
def resolve_color(color: str) -> str:
|
||||
"""Accept either a semantic role name or a literal colour string."""
|
||||
|
||||
return ROLES.get(color, color)
|
||||
|
||||
|
||||
_GLYPHS: dict[str, Callable[[QPainter, float], None]] = {}
|
||||
|
||||
_Glyph = Callable[[QPainter, float], None]
|
||||
|
||||
|
||||
def _glyph(*names: str) -> Callable[[_Glyph], _Glyph]:
|
||||
def register(fn: _Glyph) -> _Glyph:
|
||||
for name in names:
|
||||
_GLYPHS[name] = fn
|
||||
return fn
|
||||
|
||||
return register
|
||||
|
||||
|
||||
def _line(p: QPainter, x1: float, y1: float, x2: float, y2: float) -> None:
|
||||
p.drawLine(QPointF(x1, y1), QPointF(x2, y2))
|
||||
|
||||
|
||||
def _polyline(p: QPainter, *points: tuple[float, float]) -> None:
|
||||
path = QPainterPath(QPointF(*points[0]))
|
||||
for point in points[1:]:
|
||||
path.lineTo(QPointF(*point))
|
||||
p.drawPath(path)
|
||||
|
||||
|
||||
def _circle(p: QPainter, cx: float, cy: float, r: float) -> None:
|
||||
p.drawEllipse(QPointF(cx, cy), r, r)
|
||||
|
||||
|
||||
def _dot(p: QPainter, cx: float, cy: float, r: float) -> None:
|
||||
"""Filled counter - used only where the mark itself is solid."""
|
||||
|
||||
pen = p.pen()
|
||||
p.setPen(Qt.PenStyle.NoPen)
|
||||
p.setBrush(pen.color())
|
||||
p.drawEllipse(QPointF(cx, cy), r, r)
|
||||
p.setBrush(Qt.BrushStyle.NoBrush)
|
||||
p.setPen(pen)
|
||||
|
||||
|
||||
def _page(p: QPainter, *, fold: bool = True) -> None:
|
||||
"""Shared document silhouette so every file-like glyph has one outline."""
|
||||
|
||||
path = QPainterPath(QPointF(14.0, 2.5))
|
||||
path.lineTo(QPointF(6.5, 2.5))
|
||||
path.quadTo(QPointF(5.0, 2.5), QPointF(5.0, 4.0))
|
||||
path.lineTo(QPointF(5.0, 20.0))
|
||||
path.quadTo(QPointF(5.0, 21.5), QPointF(6.5, 21.5))
|
||||
path.lineTo(QPointF(17.5, 21.5))
|
||||
path.quadTo(QPointF(19.0, 21.5), QPointF(19.0, 20.0))
|
||||
path.lineTo(QPointF(19.0, 7.5))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
if fold:
|
||||
_polyline(p, (14.0, 2.5), (14.0, 7.5), (19.0, 7.5))
|
||||
|
||||
|
||||
def _sparkle(p: QPainter, cx: float, cy: float, r: float) -> None:
|
||||
"""Four-point concave star - the one AI mark used across the product."""
|
||||
|
||||
path = QPainterPath(QPointF(cx, cy - r))
|
||||
path.quadTo(QPointF(cx, cy), QPointF(cx + r, cy))
|
||||
path.quadTo(QPointF(cx, cy), QPointF(cx, cy + r))
|
||||
path.quadTo(QPointF(cx, cy), QPointF(cx - r, cy))
|
||||
path.quadTo(QPointF(cx, cy), QPointF(cx, cy - r))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
|
||||
|
||||
def _panel(p: QPainter) -> None:
|
||||
p.drawRoundedRect(QRectF(2.5, 4.0, 19.0, 16.0), 3.0, 3.0)
|
||||
_line(p, 9.5, 4.0, 9.5, 20.0)
|
||||
|
||||
|
||||
# --- Navigation -----------------------------------------------------------
|
||||
|
||||
|
||||
@_glyph("reception", "workbench", "monitor")
|
||||
def _reception(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(2.5, 3.5, 19.0, 13.5), 3.0, 3.0)
|
||||
_polyline(p, (6.0, 10.5), (8.8, 10.5), (10.6, 7.5), (13.4, 13.5), (15.2, 10.5), (18.0, 10.5))
|
||||
_line(p, 12.0, 17.0, 12.0, 20.5)
|
||||
_line(p, 8.0, 20.5, 16.0, 20.5)
|
||||
|
||||
|
||||
@_glyph("appointments", "calendar")
|
||||
def _calendar(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(3.0, 5.0, 18.0, 16.5), 3.0, 3.0)
|
||||
_line(p, 3.0, 10.0, 21.0, 10.0)
|
||||
_line(p, 8.0, 2.75, 8.0, 7.0)
|
||||
_line(p, 16.0, 2.75, 16.0, 7.0)
|
||||
|
||||
|
||||
@_glyph("prescription_library", "library", "layers")
|
||||
def _layers(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(12.0, 2.5))
|
||||
path.lineTo(QPointF(21.0, 7.0))
|
||||
path.lineTo(QPointF(12.0, 11.5))
|
||||
path.lineTo(QPointF(3.0, 7.0))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
_polyline(p, (3.0, 12.0), (12.0, 16.5), (21.0, 12.0))
|
||||
_polyline(p, (3.0, 16.75), (12.0, 21.25), (21.0, 16.75))
|
||||
|
||||
|
||||
@_glyph("prescriptions", "file_check")
|
||||
def _file_check(p: QPainter, w: float) -> None:
|
||||
_page(p)
|
||||
_polyline(p, (8.5, 15.0), (10.9, 17.4), (15.5, 12.0))
|
||||
|
||||
|
||||
@_glyph("patients", "users")
|
||||
def _users(p: QPainter, w: float) -> None:
|
||||
_circle(p, 9.0, 8.0, 3.5)
|
||||
path = QPainterPath(QPointF(2.5, 20.5))
|
||||
path.quadTo(QPointF(2.5, 14.5), QPointF(9.0, 14.5))
|
||||
path.quadTo(QPointF(15.5, 14.5), QPointF(15.5, 20.5))
|
||||
p.drawPath(path)
|
||||
_circle(p, 17.6, 8.0, 2.8)
|
||||
tail = QPainterPath(QPointF(17.0, 13.9))
|
||||
tail.quadTo(QPointF(21.5, 14.6), QPointF(21.5, 20.5))
|
||||
p.drawPath(tail)
|
||||
|
||||
|
||||
@_glyph("consultations", "consult", "message", "other")
|
||||
def _message(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(6.5, 3.5))
|
||||
path.lineTo(QPointF(17.5, 3.5))
|
||||
path.quadTo(QPointF(20.5, 3.5), QPointF(20.5, 6.5))
|
||||
path.lineTo(QPointF(20.5, 13.5))
|
||||
path.quadTo(QPointF(20.5, 16.5), QPointF(17.5, 16.5))
|
||||
path.lineTo(QPointF(11.5, 16.5))
|
||||
path.lineTo(QPointF(7.0, 20.5))
|
||||
path.lineTo(QPointF(7.0, 16.5))
|
||||
path.quadTo(QPointF(3.5, 16.5), QPointF(3.5, 13.5))
|
||||
path.lineTo(QPointF(3.5, 6.5))
|
||||
path.quadTo(QPointF(3.5, 3.5), QPointF(6.5, 3.5))
|
||||
p.drawPath(path)
|
||||
_line(p, 7.75, 8.25, 16.25, 8.25)
|
||||
_line(p, 7.75, 11.75, 13.0, 11.75)
|
||||
|
||||
|
||||
# --- Shell chrome ---------------------------------------------------------
|
||||
|
||||
|
||||
@_glyph("fold", "panel_close")
|
||||
def _fold(p: QPainter, w: float) -> None:
|
||||
_panel(p)
|
||||
_polyline(p, (17.0, 9.0), (14.0, 12.0), (17.0, 15.0))
|
||||
|
||||
|
||||
@_glyph("expand", "panel_open")
|
||||
def _expand(p: QPainter, w: float) -> None:
|
||||
_panel(p)
|
||||
_polyline(p, (14.0, 9.0), (17.0, 12.0), (14.0, 15.0))
|
||||
|
||||
|
||||
@_glyph("search")
|
||||
def _search(p: QPainter, w: float) -> None:
|
||||
_circle(p, 10.5, 10.5, 6.25)
|
||||
_line(p, 15.15, 15.15, 19.75, 19.75)
|
||||
|
||||
|
||||
@_glyph("refresh", "rotate")
|
||||
def _refresh(p: QPainter, w: float) -> None:
|
||||
# The arc terminates exactly on the arrow corner so the mark reads as one
|
||||
# continuous stroke. The painters replaced here left a detached triangle
|
||||
# (shell) or two stray lines that never formed a head at all (prescriptions).
|
||||
radius = math.hypot(8.5, 3.5)
|
||||
start = math.degrees(math.atan2(3.5, 8.5))
|
||||
p.drawArc(
|
||||
QRectF(12.0 - radius, 12.0 - radius, radius * 2, radius * 2),
|
||||
round(start * 16),
|
||||
round((360.0 - start) * 16),
|
||||
)
|
||||
_polyline(p, (20.5, 3.5), (20.5, 8.5), (15.5, 8.5))
|
||||
|
||||
|
||||
@_glyph("ai", "spark", "sparkle", "assistant")
|
||||
def _ai(p: QPainter, w: float) -> None:
|
||||
_sparkle(p, 10.2, 11.8, 7.2)
|
||||
_sparkle(p, 18.0, 6.0, 3.2)
|
||||
|
||||
|
||||
@_glyph("fullscreen", "expand-corners", "maximize")
|
||||
def _fullscreen(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (9.0, 3.5), (3.5, 3.5), (3.5, 9.0))
|
||||
_polyline(p, (15.0, 3.5), (20.5, 3.5), (20.5, 9.0))
|
||||
_polyline(p, (3.5, 15.0), (3.5, 20.5), (9.0, 20.5))
|
||||
_polyline(p, (20.5, 15.0), (20.5, 20.5), (15.0, 20.5))
|
||||
|
||||
|
||||
@_glyph("minimize")
|
||||
def _minimize(p: QPainter, w: float) -> None:
|
||||
_line(p, 5.0, 12.0, 19.0, 12.0)
|
||||
|
||||
|
||||
@_glyph("close", "cross")
|
||||
def _close(p: QPainter, w: float) -> None:
|
||||
_line(p, 5.75, 5.75, 18.25, 18.25)
|
||||
_line(p, 18.25, 5.75, 5.75, 18.25)
|
||||
|
||||
|
||||
@_glyph("down", "chevron_down")
|
||||
def _down(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (5.5, 9.0), (12.0, 15.5), (18.5, 9.0))
|
||||
|
||||
|
||||
@_glyph("up", "chevron_up")
|
||||
def _up(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (5.5, 15.0), (12.0, 8.5), (18.5, 15.0))
|
||||
|
||||
|
||||
@_glyph("left", "chevron_left")
|
||||
def _left(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (15.0, 5.5), (8.5, 12.0), (15.0, 18.5))
|
||||
|
||||
|
||||
@_glyph("right", "chevron_right")
|
||||
def _right(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (9.0, 5.5), (15.5, 12.0), (9.0, 18.5))
|
||||
|
||||
|
||||
@_glyph("notification", "bell")
|
||||
def _bell(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(6.75, 17.5))
|
||||
path.lineTo(QPointF(6.75, 10.75))
|
||||
path.arcTo(QRectF(6.75, 5.0, 10.5, 11.5), 180.0, -180.0)
|
||||
path.lineTo(QPointF(17.25, 17.5))
|
||||
p.drawPath(path)
|
||||
_line(p, 4.5, 17.5, 19.5, 17.5)
|
||||
p.drawArc(QRectF(10.0, 17.4, 4.0, 3.6), 180 * 16, 180 * 16)
|
||||
|
||||
|
||||
@_glyph("settings", "sliders")
|
||||
def _settings(p: QPainter, w: float) -> None:
|
||||
_line(p, 3.5, 8.5, 20.5, 8.5)
|
||||
_line(p, 3.5, 15.5, 20.5, 15.5)
|
||||
_circle(p, 9.0, 8.5, 2.4)
|
||||
_circle(p, 15.0, 15.5, 2.4)
|
||||
|
||||
|
||||
# --- Row and toolbar actions ---------------------------------------------
|
||||
|
||||
|
||||
@_glyph("eye", "view")
|
||||
def _eye(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(2.5, 12.0))
|
||||
path.quadTo(QPointF(12.0, 2.5), QPointF(21.5, 12.0))
|
||||
path.quadTo(QPointF(12.0, 21.5), QPointF(2.5, 12.0))
|
||||
p.drawPath(path)
|
||||
_circle(p, 12.0, 12.0, 3.0)
|
||||
|
||||
|
||||
@_glyph("pencil", "edit")
|
||||
def _pencil(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(16.25, 3.0))
|
||||
path.lineTo(QPointF(20.75, 7.5))
|
||||
path.lineTo(QPointF(8.5, 19.75))
|
||||
path.lineTo(QPointF(3.0, 21.0))
|
||||
path.lineTo(QPointF(4.25, 15.5))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
_line(p, 13.0, 6.25, 17.5, 10.75)
|
||||
|
||||
|
||||
@_glyph("trash", "delete")
|
||||
def _trash(p: QPainter, w: float) -> None:
|
||||
_line(p, 3.5, 6.25, 20.5, 6.25)
|
||||
_polyline(p, (9.0, 6.25), (9.0, 3.5), (15.0, 3.5), (15.0, 6.25))
|
||||
path = QPainterPath(QPointF(5.75, 6.25))
|
||||
path.lineTo(QPointF(6.6, 19.4))
|
||||
path.quadTo(QPointF(6.7, 20.5), QPointF(7.8, 20.5))
|
||||
path.lineTo(QPointF(16.2, 20.5))
|
||||
path.quadTo(QPointF(17.3, 20.5), QPointF(17.4, 19.4))
|
||||
path.lineTo(QPointF(18.25, 6.25))
|
||||
p.drawPath(path)
|
||||
_line(p, 10.0, 10.0, 10.0, 16.75)
|
||||
_line(p, 14.0, 10.0, 14.0, 16.75)
|
||||
|
||||
|
||||
@_glyph("plus", "add")
|
||||
def _plus(p: QPainter, w: float) -> None:
|
||||
_line(p, 12.0, 4.75, 12.0, 19.25)
|
||||
_line(p, 4.75, 12.0, 19.25, 12.0)
|
||||
|
||||
|
||||
@_glyph("check")
|
||||
def _check(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (4.75, 12.5), (9.75, 17.5), (19.25, 7.0))
|
||||
|
||||
|
||||
@_glyph("check_circle", "health")
|
||||
def _check_circle(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 12.0, 8.75)
|
||||
_polyline(p, (7.75, 12.25), (10.75, 15.25), (16.25, 9.0))
|
||||
|
||||
|
||||
@_glyph("checkbox")
|
||||
def _checkbox(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(3.75, 3.75, 16.5, 16.5), 3.5, 3.5)
|
||||
|
||||
|
||||
@_glyph("lock")
|
||||
def _lock(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(4.5, 10.5, 15.0, 10.0), 2.75, 2.75)
|
||||
p.drawArc(QRectF(8.0, 3.75, 8.0, 13.5), 0, 180 * 16)
|
||||
_dot(p, 12.0, 15.5, 1.35)
|
||||
|
||||
|
||||
@_glyph("document", "file")
|
||||
def _document(p: QPainter, w: float) -> None:
|
||||
_page(p)
|
||||
_line(p, 8.5, 12.75, 15.5, 12.75)
|
||||
_line(p, 8.5, 16.75, 13.25, 16.75)
|
||||
|
||||
|
||||
@_glyph("report")
|
||||
def _report(p: QPainter, w: float) -> None:
|
||||
_page(p)
|
||||
_line(p, 8.75, 17.75, 8.75, 14.25)
|
||||
_line(p, 12.0, 17.75, 12.0, 10.5)
|
||||
_line(p, 15.25, 17.75, 15.25, 12.75)
|
||||
|
||||
|
||||
@_glyph("list")
|
||||
def _list(p: QPainter, w: float) -> None:
|
||||
for y in (6.5, 12.0, 17.5):
|
||||
_dot(p, 4.5, y, 1.2)
|
||||
_line(p, 8.75, y, 19.5, y)
|
||||
|
||||
|
||||
@_glyph("user", "person")
|
||||
def _user(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 8.0, 4.0)
|
||||
path = QPainterPath(QPointF(4.25, 20.5))
|
||||
path.quadTo(QPointF(4.25, 14.5), QPointF(12.0, 14.5))
|
||||
path.quadTo(QPointF(19.75, 14.5), QPointF(19.75, 20.5))
|
||||
p.drawPath(path)
|
||||
|
||||
|
||||
@_glyph("remove", "minus_circle")
|
||||
def _remove(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 12.0, 8.75)
|
||||
_line(p, 8.0, 12.0, 16.0, 12.0)
|
||||
|
||||
|
||||
@_glyph("stop", "close_circle")
|
||||
def _stop(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 12.0, 8.75)
|
||||
_line(p, 9.0, 9.0, 15.0, 15.0)
|
||||
_line(p, 15.0, 9.0, 9.0, 15.0)
|
||||
|
||||
|
||||
@_glyph("info")
|
||||
def _info(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 12.0, 8.75)
|
||||
_line(p, 12.0, 11.25, 12.0, 16.5)
|
||||
_dot(p, 12.0, 7.75, 1.0)
|
||||
|
||||
|
||||
@_glyph("picture", "image")
|
||||
def _picture(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(3.0, 4.5, 18.0, 15.0), 3.0, 3.0)
|
||||
_circle(p, 7.75, 8.75, 1.6)
|
||||
_polyline(p, (3.5, 17.75), (9.75, 12.25), (13.25, 15.5), (15.75, 13.25), (20.5, 17.75))
|
||||
|
||||
|
||||
@_glyph("meds", "pill")
|
||||
def _meds(p: QPainter, w: float) -> None:
|
||||
p.save()
|
||||
p.translate(12.0, 12.0)
|
||||
p.rotate(-45.0)
|
||||
p.drawRoundedRect(QRectF(-9.25, -4.5, 18.5, 9.0), 4.5, 4.5)
|
||||
_line(p, 0.0, -4.5, 0.0, 4.5)
|
||||
p.restore()
|
||||
|
||||
|
||||
@_glyph("daily", "clipboard")
|
||||
def _clipboard(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(8.5, 4.5))
|
||||
path.lineTo(QPointF(6.75, 4.5))
|
||||
path.quadTo(QPointF(4.25, 4.5), QPointF(4.25, 7.0))
|
||||
path.lineTo(QPointF(4.25, 19.0))
|
||||
path.quadTo(QPointF(4.25, 21.5), QPointF(6.75, 21.5))
|
||||
path.lineTo(QPointF(17.25, 21.5))
|
||||
path.quadTo(QPointF(19.75, 21.5), QPointF(19.75, 19.0))
|
||||
path.lineTo(QPointF(19.75, 7.0))
|
||||
path.quadTo(QPointF(19.75, 4.5), QPointF(17.25, 4.5))
|
||||
path.lineTo(QPointF(15.5, 4.5))
|
||||
p.drawPath(path)
|
||||
p.drawRoundedRect(QRectF(8.5, 2.5, 7.0, 4.0), 1.5, 1.5)
|
||||
_line(p, 8.0, 12.0, 16.0, 12.0)
|
||||
_line(p, 8.0, 16.25, 13.5, 16.25)
|
||||
|
||||
|
||||
@_glyph("followup", "calendar_clock")
|
||||
def _followup(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(13.0, 20.0))
|
||||
path.lineTo(QPointF(5.5, 20.0))
|
||||
path.quadTo(QPointF(3.0, 20.0), QPointF(3.0, 17.5))
|
||||
path.lineTo(QPointF(3.0, 7.5))
|
||||
path.quadTo(QPointF(3.0, 5.0), QPointF(5.5, 5.0))
|
||||
path.lineTo(QPointF(14.5, 5.0))
|
||||
path.quadTo(QPointF(17.0, 5.0), QPointF(17.0, 7.5))
|
||||
path.lineTo(QPointF(17.0, 9.0))
|
||||
p.drawPath(path)
|
||||
_line(p, 3.0, 9.5, 17.0, 9.5)
|
||||
_line(p, 7.0, 2.75, 7.0, 6.75)
|
||||
_line(p, 13.0, 2.75, 13.0, 6.75)
|
||||
_circle(p, 16.75, 16.75, 4.5)
|
||||
_polyline(p, (16.75, 14.25), (16.75, 16.75), (18.9, 16.75))
|
||||
|
||||
|
||||
@_glyph("brand", "logo")
|
||||
def _brand(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 12.0, 8.75)
|
||||
_polyline(p, (7.0, 12.0), (10.0, 12.0), (11.5, 8.5), (13.5, 15.5), (15.0, 12.0), (17.0, 12.0))
|
||||
|
||||
|
||||
# --- AI consultation ------------------------------------------------------
|
||||
|
||||
|
||||
@_glyph("chart", "analytics")
|
||||
def _analytics(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (3.5, 3.0), (3.5, 20.5), (21.0, 20.5))
|
||||
_polyline(p, (7.0, 16.5), (10.5, 8.5), (14.0, 13.0), (20.0, 5.5))
|
||||
|
||||
|
||||
@_glyph("trend")
|
||||
def _trend(p: QPainter, w: float) -> None:
|
||||
_polyline(p, (3.0, 18.0), (8.5, 9.5), (12.5, 13.5), (21.0, 5.5))
|
||||
_polyline(p, (15.5, 5.5), (21.0, 5.5), (21.0, 11.0))
|
||||
|
||||
|
||||
@_glyph("alert", "warning")
|
||||
def _alert(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(12.0, 3.0))
|
||||
path.lineTo(QPointF(21.5, 20.0))
|
||||
path.lineTo(QPointF(2.5, 20.0))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
_line(p, 12.0, 9.5, 12.0, 14.5)
|
||||
_dot(p, 12.0, 17.4, 1.05)
|
||||
|
||||
|
||||
@_glyph("mic", "microphone")
|
||||
def _mic(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(8.5, 2.5, 7.0, 12.0), 3.5, 3.5)
|
||||
p.drawArc(QRectF(5.0, 6.0, 14.0, 14.0), 0, -180 * 16)
|
||||
_line(p, 12.0, 17.5, 12.0, 21.0)
|
||||
_line(p, 8.25, 21.0, 15.75, 21.0)
|
||||
|
||||
|
||||
@_glyph("send")
|
||||
def _send(p: QPainter, w: float) -> None:
|
||||
path = QPainterPath(QPointF(21.0, 3.0))
|
||||
path.lineTo(QPointF(2.5, 10.5))
|
||||
path.lineTo(QPointF(10.25, 13.75))
|
||||
path.lineTo(QPointF(13.5, 21.5))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
_line(p, 10.25, 13.75, 21.0, 3.0)
|
||||
|
||||
|
||||
@_glyph("qr", "qrcode")
|
||||
def _qr(p: QPainter, w: float) -> None:
|
||||
"""Three finder squares plus a few modules - the shape people scan for."""
|
||||
|
||||
for x, y in ((3.0, 3.0), (14.0, 3.0), (3.0, 14.0)):
|
||||
p.drawRoundedRect(QRectF(x, y, 7.0, 7.0), 1.5, 1.5)
|
||||
_dot(p, x + 3.5, y + 3.5, 1.15)
|
||||
_line(p, 14.5, 14.5, 14.5, 17.0)
|
||||
_line(p, 18.0, 14.5, 21.0, 14.5)
|
||||
_line(p, 17.5, 18.0, 17.5, 21.0)
|
||||
_dot(p, 20.75, 20.75, 1.15)
|
||||
|
||||
|
||||
@_glyph("video", "call")
|
||||
def _video(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(2.5, 6.0, 13.5, 12.0), 3.0, 3.0)
|
||||
path = QPainterPath(QPointF(16.0, 10.5))
|
||||
path.lineTo(QPointF(21.5, 7.25))
|
||||
path.lineTo(QPointF(21.5, 16.75))
|
||||
path.lineTo(QPointF(16.0, 13.5))
|
||||
path.closeSubpath()
|
||||
p.drawPath(path)
|
||||
|
||||
|
||||
# --- Clinical measures ----------------------------------------------------
|
||||
# The vital-sign tiles and the lifestyle row used to carry two more bespoke
|
||||
# painters (22 px / 1.35 px stroke and 16 px / 1.3 px stroke). Beyond the extra
|
||||
# weights, two of their glyphs were simply wrong: "weight" read as a padlock and
|
||||
# "BMI" as the Venus symbol.
|
||||
|
||||
|
||||
@_glyph("height")
|
||||
def _height(p: QPainter, w: float) -> None:
|
||||
_line(p, 6.0, 3.5, 18.0, 3.5)
|
||||
_line(p, 6.0, 20.5, 18.0, 20.5)
|
||||
_line(p, 12.0, 5.75, 12.0, 18.25)
|
||||
_polyline(p, (9.5, 8.25), (12.0, 5.75), (14.5, 8.25))
|
||||
_polyline(p, (9.5, 15.75), (12.0, 18.25), (14.5, 15.75))
|
||||
|
||||
|
||||
@_glyph("weight", "scale")
|
||||
def _weight(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(3.0, 5.0, 18.0, 14.5), 3.5, 3.5)
|
||||
p.drawArc(QRectF(7.0, 10.0, 10.0, 10.0), 25 * 16, 130 * 16)
|
||||
_line(p, 12.0, 15.0, 9.9, 10.9)
|
||||
|
||||
|
||||
@_glyph("bmi", "body")
|
||||
def _bmi(p: QPainter, w: float) -> None:
|
||||
_circle(p, 12.0, 5.0, 2.75)
|
||||
_line(p, 12.0, 7.75, 12.0, 15.0)
|
||||
_line(p, 7.25, 11.0, 16.75, 11.0)
|
||||
_polyline(p, (8.5, 20.75), (12.0, 15.0), (15.5, 20.75))
|
||||
|
||||
|
||||
@_glyph("blood_pressure", "gauge", "bp")
|
||||
def _blood_pressure(p: QPainter, w: float) -> None:
|
||||
p.drawArc(QRectF(3.0, 5.5, 18.0, 18.0), 0, 180 * 16)
|
||||
_line(p, 3.0, 14.5, 21.0, 14.5)
|
||||
_line(p, 12.0, 14.5, 16.4, 9.4)
|
||||
_dot(p, 12.0, 14.5, 1.15)
|
||||
|
||||
|
||||
@_glyph("pulse", "heart")
|
||||
def _pulse(p: QPainter, w: float) -> None:
|
||||
heart = QPainterPath(QPointF(12.0, 20.25))
|
||||
heart.cubicTo(QPointF(3.2, 13.6), QPointF(2.2, 9.6), QPointF(4.7, 6.7))
|
||||
heart.cubicTo(QPointF(7.2, 4.0), QPointF(10.5, 4.8), QPointF(12.0, 7.7))
|
||||
heart.cubicTo(QPointF(13.5, 4.8), QPointF(16.8, 4.0), QPointF(19.3, 6.7))
|
||||
heart.cubicTo(QPointF(21.8, 9.6), QPointF(20.8, 13.6), QPointF(12.0, 20.25))
|
||||
heart.closeSubpath()
|
||||
p.drawPath(heart)
|
||||
_polyline(
|
||||
p, (5.6, 12.4), (9.0, 12.4), (10.6, 9.7), (13.2, 15.1), (14.7, 12.4), (18.4, 12.4)
|
||||
)
|
||||
|
||||
|
||||
@_glyph("smoke", "cigarette")
|
||||
def _smoke(p: QPainter, w: float) -> None:
|
||||
p.drawRoundedRect(QRectF(2.5, 14.0, 14.0, 5.0), 1.75, 1.75)
|
||||
_line(p, 13.0, 14.0, 13.0, 19.0)
|
||||
curl = QPainterPath(QPointF(19.0, 12.0))
|
||||
curl.quadTo(QPointF(21.5, 9.5), QPointF(19.0, 7.5))
|
||||
curl.quadTo(QPointF(16.5, 5.5), QPointF(19.0, 3.5))
|
||||
p.drawPath(curl)
|
||||
|
||||
|
||||
@_glyph("drink", "glass")
|
||||
def _drink(p: QPainter, w: float) -> None:
|
||||
bowl = QPainterPath(QPointF(6.5, 3.5))
|
||||
bowl.lineTo(QPointF(17.5, 3.5))
|
||||
bowl.lineTo(QPointF(13.75, 12.5))
|
||||
bowl.lineTo(QPointF(10.25, 12.5))
|
||||
bowl.closeSubpath()
|
||||
p.drawPath(bowl)
|
||||
_line(p, 7.75, 7.5, 16.25, 7.5)
|
||||
_line(p, 12.0, 12.5, 12.0, 20.0)
|
||||
_line(p, 8.0, 20.0, 16.0, 20.0)
|
||||
|
||||
|
||||
@_glyph("exercise", "run")
|
||||
def _exercise(p: QPainter, w: float) -> None:
|
||||
_circle(p, 15.75, 4.75, 2.5)
|
||||
_polyline(p, (14.5, 9.0), (9.75, 12.5), (6.0, 20.5))
|
||||
_polyline(p, (14.5, 9.0), (18.75, 12.75), (21.0, 10.75))
|
||||
_polyline(p, (11.75, 11.0), (15.25, 16.0), (13.25, 20.75))
|
||||
|
||||
|
||||
# --- Painting -------------------------------------------------------------
|
||||
|
||||
|
||||
def _device_ratio() -> float:
|
||||
app = QApplication.instance()
|
||||
if app is None:
|
||||
return 1.0
|
||||
screen = app.primaryScreen()
|
||||
if screen is None:
|
||||
return 1.0
|
||||
return max(1.0, float(screen.devicePixelRatio()))
|
||||
|
||||
|
||||
def _render(kind: str, color: str, size: int) -> QPixmap:
|
||||
canvas = crisp_pixmap(size)
|
||||
draw = _GLYPHS.get(kind)
|
||||
if draw is None:
|
||||
return canvas
|
||||
painter = QPainter(canvas)
|
||||
try:
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
# Inset the grid by half a stroke on every edge. Without it a glyph that
|
||||
# legitimately reaches grid unit 24 loses the outer half of its line to
|
||||
# the pixmap boundary at the smaller sizes - which is exactly how the old
|
||||
# painters lost the shell star's companion dot and flattened the top of
|
||||
# the calendar. Insetting here means every glyph can use the full grid.
|
||||
weight = stroke_px(size)
|
||||
scale = (size - weight) / GRID
|
||||
painter.translate(weight / 2.0, weight / 2.0)
|
||||
painter.scale(scale, scale)
|
||||
# The pen width is expressed on the design grid, so the on-screen weight
|
||||
# stays the same fraction of the box at every size the shell asks for.
|
||||
width = weight / scale
|
||||
pen = QPen(QColor(color), width)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
|
||||
painter.setPen(pen)
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
draw(painter, width)
|
||||
finally:
|
||||
painter.end()
|
||||
return canvas
|
||||
|
||||
|
||||
@lru_cache(maxsize=1024)
|
||||
def _cached_pixmap(kind: str, color: str, size: int, ratio: float) -> QPixmap:
|
||||
del ratio # part of the cache key only; crisp_pixmap reads it back itself
|
||||
return _render(kind, color, size)
|
||||
|
||||
|
||||
def pixmap(kind: str, color: str = "default", size: int = 18) -> QPixmap:
|
||||
"""Return a cached, device-pixel-correct pixmap for ``kind``."""
|
||||
|
||||
return _cached_pixmap(kind, resolve_color(color), int(size), _device_ratio())
|
||||
|
||||
|
||||
@lru_cache(maxsize=1024)
|
||||
def _cached_icon(kind: str, color: str, size: int, ratio: float) -> QIcon:
|
||||
result = QIcon(_cached_pixmap(kind, color, size, ratio))
|
||||
result.addPixmap(
|
||||
_cached_pixmap(kind, ROLES["disabled"], size, ratio),
|
||||
QIcon.Mode.Disabled,
|
||||
QIcon.State.Off,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def icon(kind: str, color: str = "default", size: int = 18) -> QIcon:
|
||||
"""Return a cached icon with a matching disabled variant already attached.
|
||||
|
||||
``color`` accepts a role name from :data:`ROLES` or a literal colour.
|
||||
"""
|
||||
|
||||
return _cached_icon(kind, resolve_color(color), int(size), _device_ratio())
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def _cached_state_icon(
|
||||
kind: str,
|
||||
size: int,
|
||||
normal: str,
|
||||
active: str,
|
||||
checked: str,
|
||||
disabled: str,
|
||||
ratio: float,
|
||||
) -> QIcon:
|
||||
result = QIcon()
|
||||
result.addPixmap(_cached_pixmap(kind, normal, size, ratio), QIcon.Mode.Normal, QIcon.State.Off)
|
||||
result.addPixmap(_cached_pixmap(kind, checked, size, ratio), QIcon.Mode.Normal, QIcon.State.On)
|
||||
result.addPixmap(_cached_pixmap(kind, active, size, ratio), QIcon.Mode.Active, QIcon.State.Off)
|
||||
result.addPixmap(_cached_pixmap(kind, checked, size, ratio), QIcon.Mode.Active, QIcon.State.On)
|
||||
result.addPixmap(
|
||||
_cached_pixmap(kind, disabled, size, ratio), QIcon.Mode.Disabled, QIcon.State.Off
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def state_icon(
|
||||
kind: str,
|
||||
*,
|
||||
size: int = 18,
|
||||
normal: str = "muted",
|
||||
active: str = "strong",
|
||||
checked: str = "inverse",
|
||||
disabled: str = "disabled",
|
||||
) -> QIcon:
|
||||
"""Return an icon carrying its own hover / selected / disabled colours.
|
||||
|
||||
Qt only tints an icon when a widget asks it to, so a single-pixmap icon on a
|
||||
selected navigation row keeps its resting grey and reads as switched off.
|
||||
"""
|
||||
|
||||
return _cached_state_icon(
|
||||
kind,
|
||||
int(size),
|
||||
resolve_color(normal),
|
||||
resolve_color(active),
|
||||
resolve_color(checked),
|
||||
resolve_color(disabled),
|
||||
_device_ratio(),
|
||||
)
|
||||
|
||||
|
||||
def available_kinds() -> tuple[str, ...]:
|
||||
"""Every glyph name this module answers to, aliases included."""
|
||||
|
||||
return tuple(sorted(_GLYPHS))
|
||||
|
||||
|
||||
def clear_cache() -> None:
|
||||
"""Drop cached pixmaps - used when the display scale factor changes."""
|
||||
|
||||
_cached_pixmap.cache_clear()
|
||||
_cached_icon.cache_clear()
|
||||
_cached_state_icon.cache_clear()
|
||||
@@ -0,0 +1,320 @@
|
||||
"""Incremental server lists with a compact status footer and stable view state."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QEvent, QSignalBlocker, Qt, QTimer
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractScrollArea,
|
||||
QCheckBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QTableWidget,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .widgets import first_value, get_value, page_items, page_total, run_async
|
||||
|
||||
|
||||
def record_key(row: Any) -> str:
|
||||
value = first_value(
|
||||
row, "id", "prescription_id", "appointment_id", "diagnosis_id", "order_id", "patient_id"
|
||||
)
|
||||
return str(value) if value is not None else repr(row)
|
||||
|
||||
|
||||
class ListSnapshot:
|
||||
"""Keep repository metadata available while replacing only the list payload."""
|
||||
|
||||
def __init__(self, rows: list[Any], total: int, source: Any) -> None:
|
||||
self.items = rows
|
||||
self.total = total
|
||||
self.source = source
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return get_value(self.source, name, None)
|
||||
|
||||
|
||||
class InfiniteList(QWidget):
|
||||
"""Bind to a scrolling view; fetch pages only as the visible list needs them.
|
||||
|
||||
Reloads use captured query arguments. Refreshing the same query rebuilds the
|
||||
loaded prefix atomically, so polling neither drops appended rows nor mixes
|
||||
an updated first page with an old tail. Failed appends retain the prior page
|
||||
and can be retried explicitly without an automatic request loop.
|
||||
"""
|
||||
|
||||
def __init__(self, page_size: int = 20, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("InfiniteList")
|
||||
self.setFixedHeight(24)
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(12, 0, 12, 0)
|
||||
self.summary_label = QLabel("", self)
|
||||
self.summary_label.setStyleSheet(
|
||||
"color: #5D6B80; font-size: 12px; background: transparent;"
|
||||
)
|
||||
layout.addWidget(self.summary_label)
|
||||
layout.addStretch(1)
|
||||
self.retry_button = QPushButton("加载失败,点击重试", self)
|
||||
self.retry_button.setFlat(True)
|
||||
self.retry_button.setStyleSheet(
|
||||
"color: #1769E8; font-size: 12px; padding: 0 4px; border: none; background: transparent; min-height: 20px; max-height: 20px; min-width: 0;"
|
||||
)
|
||||
self.retry_button.hide()
|
||||
self.retry_button.clicked.connect(self.retry)
|
||||
layout.addWidget(self.retry_button)
|
||||
self.page_size = page_size
|
||||
self.page = 0
|
||||
self.total = 0
|
||||
self.rows: list[Any] = []
|
||||
self.loading = False
|
||||
self.has_more = False
|
||||
self._generation = 0
|
||||
self._query_key: Any = object()
|
||||
self._view: QAbstractScrollArea | None = None
|
||||
self._views: list[QAbstractScrollArea] = []
|
||||
self._error = False
|
||||
self._configured = False
|
||||
self._timer = QTimer(self)
|
||||
self._timer.setSingleShot(True)
|
||||
self._timer.timeout.connect(self._maybe_load_more)
|
||||
|
||||
def bind(self, view: QAbstractScrollArea) -> None:
|
||||
if view in self._views:
|
||||
return
|
||||
self._views.append(view)
|
||||
self._view = view
|
||||
view.verticalScrollBar().valueChanged.connect(self._schedule_check)
|
||||
view.verticalScrollBar().rangeChanged.connect(self._schedule_check)
|
||||
view.viewport().installEventFilter(self)
|
||||
|
||||
def eventFilter(self, watched: Any, event: Any) -> bool:
|
||||
if event.type() in (QEvent.Type.Show, QEvent.Type.Resize):
|
||||
self._schedule_check()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _schedule_check(self, *_: Any) -> None:
|
||||
self._timer.start(30)
|
||||
|
||||
def _maybe_load_more(self) -> None:
|
||||
view = next((v for v in self._views if v.isVisible()), None)
|
||||
if view is None or self.loading or self._error or not self.has_more:
|
||||
return
|
||||
bar = view.verticalScrollBar()
|
||||
# pageStep respects both per-item and per-pixel Qt scrolling modes.
|
||||
if bar.maximum() - bar.value() <= max(1, bar.pageStep() // 4):
|
||||
self.load_more()
|
||||
|
||||
def invalidate(self) -> None:
|
||||
"""Disarm callbacks when a reusable dialog switches to another record."""
|
||||
self._generation += 1
|
||||
self._configured = False
|
||||
self.loading = self.has_more = self._error = False
|
||||
self.rows, self.page, self.total = [], 0, 0
|
||||
self._timer.stop()
|
||||
self.retry_button.hide()
|
||||
self._status()
|
||||
|
||||
reset = invalidate
|
||||
|
||||
def reload(
|
||||
self,
|
||||
fetch: Callable[[int], Any],
|
||||
apply: Callable[[Any], None],
|
||||
on_error: Callable[[Exception], None],
|
||||
*,
|
||||
runner: Callable[..., Any] = run_async,
|
||||
query_key: Any = None,
|
||||
on_finished: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
same_query = self._configured and query_key == self._query_key
|
||||
if same_query and self.loading:
|
||||
# Polling must not restart a slow prefix refresh indefinitely. The
|
||||
# caller may have advanced its own generation, so use its latest
|
||||
# render/error closures while the captured request finishes.
|
||||
self._apply, self._on_error = apply, on_error
|
||||
self._on_finished = on_finished
|
||||
return
|
||||
self._generation += 1
|
||||
self._query_key = query_key
|
||||
self._configured = True
|
||||
self._fetch, self._apply, self._on_error = fetch, apply, on_error
|
||||
self._runner, self._on_finished = runner, on_finished
|
||||
self._target = max(1, self.page) if same_query else 1
|
||||
self._reset_view = not same_query
|
||||
if not same_query:
|
||||
self.rows, self.page, self.total = [], 0, 0
|
||||
self.has_more = False
|
||||
self._render(ListSnapshot([], 0, None), preserve=False)
|
||||
self._begin(1, [], refresh=True)
|
||||
|
||||
def load_more(self) -> None:
|
||||
if not self._configured or self.loading or self._error or not self.has_more:
|
||||
return
|
||||
self._reset_view = False
|
||||
self._target = self.page + 1
|
||||
self._begin(self.page + 1, list(self.rows), refresh=False)
|
||||
|
||||
def retry(self) -> None:
|
||||
if self.loading or not self._error:
|
||||
return
|
||||
self._begin(self._failed_page, list(self._failed_rows), refresh=self._failed_refresh)
|
||||
|
||||
def _begin(self, page: int, rows: list[Any], *, refresh: bool) -> None:
|
||||
self.loading = True
|
||||
self._error = False
|
||||
self.retry_button.hide()
|
||||
self.summary_label.setText(
|
||||
f"已加载 {len(self.rows)} 条 · 正在加载…" if self.rows else "正在加载…"
|
||||
)
|
||||
generation = self._generation
|
||||
fetch = self._fetch
|
||||
self._runner(
|
||||
lambda: fetch(page),
|
||||
on_success=lambda result: self._received(result, generation, page, rows, refresh),
|
||||
on_error=lambda error: self._failed(error, generation, page, rows, refresh),
|
||||
on_finished=lambda: None,
|
||||
)
|
||||
|
||||
def _received(
|
||||
self, result: Any, generation: int, page: int, prior: list[Any], refresh: bool
|
||||
) -> None:
|
||||
if generation != self._generation:
|
||||
return
|
||||
incoming = page_items(result)
|
||||
merged = {record_key(row): row for row in prior}
|
||||
before = len(merged)
|
||||
for row in incoming:
|
||||
merged[record_key(row)] = row
|
||||
rows = list(merged.values())
|
||||
total = page_total(result, -1)
|
||||
more = (
|
||||
bool(incoming)
|
||||
and len(rows) > before
|
||||
and (len(rows) < total if total >= 0 else len(incoming) >= self.page_size)
|
||||
)
|
||||
# Retain first-page metadata (scope, counts, filter choices) on refresh.
|
||||
if page == 1:
|
||||
self._refresh_source = result
|
||||
source = self._refresh_source
|
||||
if refresh and page < self._target and more:
|
||||
self._begin(page + 1, rows, refresh=True)
|
||||
return
|
||||
self.rows, self.page = rows, page
|
||||
self.total = max(len(rows), total)
|
||||
self.has_more = more
|
||||
self._render(ListSnapshot(rows, self.total, source), preserve=not self._reset_view)
|
||||
self.loading = False
|
||||
self._status()
|
||||
if self._on_finished is not None:
|
||||
self._on_finished()
|
||||
self._schedule_check()
|
||||
|
||||
def _failed(
|
||||
self, error: Exception, generation: int, page: int, rows: list[Any], refresh: bool
|
||||
) -> None:
|
||||
if generation != self._generation:
|
||||
return
|
||||
self.loading = False
|
||||
self._error = True
|
||||
self._failed_page, self._failed_rows, self._failed_refresh = page, rows, refresh
|
||||
self.summary_label.setText(f"已加载 {len(self.rows)} 条" if self.rows else "暂未加载数据")
|
||||
self.retry_button.show()
|
||||
self._on_error(error)
|
||||
if self._on_finished is not None:
|
||||
self._on_finished()
|
||||
|
||||
def _status(self) -> None:
|
||||
if self.has_more:
|
||||
self.summary_label.setText(f"已加载 {len(self.rows)} / {self.total} 条 · 下拉加载更多")
|
||||
else:
|
||||
if self.total > len(self.rows):
|
||||
self.summary_label.setText(
|
||||
f"已加载 {len(self.rows)} / {self.total} 条 · 暂无更多数据"
|
||||
)
|
||||
else:
|
||||
self.summary_label.setText(
|
||||
f"共 {len(self.rows)} 条 · 已全部加载" if self.rows else "暂无数据"
|
||||
)
|
||||
|
||||
def update_state(self, page: int, total: int) -> None:
|
||||
"""Compatibility for existing render callbacks; requests own the state."""
|
||||
del page, total
|
||||
self._status()
|
||||
|
||||
def _render(self, snapshot: ListSnapshot, *, preserve: bool) -> None:
|
||||
view = next((v for v in self._views if v.isVisible()), self._view)
|
||||
if view is None:
|
||||
self._apply(snapshot)
|
||||
return
|
||||
bar = view.verticalScrollBar()
|
||||
scroll = bar.value()
|
||||
horizontal_scroll = view.horizontalScrollBar().value()
|
||||
selected: set[str] = set()
|
||||
checks: dict[tuple[str, int], Qt.CheckState] = {}
|
||||
widget_checks: dict[tuple[str, int, int], bool] = {}
|
||||
if preserve and isinstance(view, QTableWidget):
|
||||
for row in range(view.rowCount()):
|
||||
first = view.item(row, 0)
|
||||
if first is None:
|
||||
continue
|
||||
key = record_key(first.data(Qt.ItemDataRole.UserRole))
|
||||
if first.isSelected():
|
||||
selected.add(key)
|
||||
for column in range(view.columnCount()):
|
||||
item = view.item(row, column)
|
||||
if (
|
||||
item is not None
|
||||
and item.flags() & Qt.ItemFlag.ItemIsUserCheckable
|
||||
and item.data(Qt.ItemDataRole.CheckStateRole) is not None
|
||||
):
|
||||
checks[key, column] = item.checkState()
|
||||
widget = view.cellWidget(row, column)
|
||||
if widget is not None:
|
||||
boxes = (
|
||||
[widget]
|
||||
if isinstance(widget, QCheckBox)
|
||||
else widget.findChildren(QCheckBox)
|
||||
)
|
||||
for index, box in enumerate(boxes):
|
||||
widget_checks[key, column, index] = box.isChecked()
|
||||
blocker = QSignalBlocker(view)
|
||||
try:
|
||||
self._apply(snapshot)
|
||||
if preserve and isinstance(view, QTableWidget):
|
||||
if selected:
|
||||
view.clearSelection()
|
||||
for row in range(view.rowCount()):
|
||||
first = view.item(row, 0)
|
||||
if first is None:
|
||||
continue
|
||||
key = record_key(first.data(Qt.ItemDataRole.UserRole))
|
||||
if key in selected:
|
||||
view.selectRow(row)
|
||||
for column in range(view.columnCount()):
|
||||
item = view.item(row, column)
|
||||
if item is not None and (key, column) in checks:
|
||||
item.setCheckState(checks[key, column])
|
||||
widget = view.cellWidget(row, column)
|
||||
if widget is not None:
|
||||
boxes = (
|
||||
[widget]
|
||||
if isinstance(widget, QCheckBox)
|
||||
else widget.findChildren(QCheckBox)
|
||||
)
|
||||
for index, box in enumerate(boxes):
|
||||
if (key, column, index) in widget_checks:
|
||||
box.setChecked(widget_checks[key, column, index])
|
||||
bar.setValue(min(scroll, bar.maximum()) if preserve else bar.minimum())
|
||||
view.horizontalScrollBar().setValue(horizontal_scroll)
|
||||
finally:
|
||||
blocker.unblock()
|
||||
if isinstance(view, QTableWidget):
|
||||
view.itemSelectionChanged.emit()
|
||||
|
||||
|
||||
__all__ = ["InfiniteList", "ListSnapshot"]
|
||||
@@ -21,6 +21,7 @@ from PySide6.QtGui import (
|
||||
QResizeEvent,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QCheckBox,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
@@ -43,7 +44,7 @@ from PySide6.QtWidgets import (
|
||||
from doctor_workstation import __version__
|
||||
from doctor_workstation.resources import app_icon_path, brand_lockup_path
|
||||
|
||||
from .theme import crisp_pixmap
|
||||
from . import icons
|
||||
from .widgets import BusyOverlay, MessageBanner, friendly_error, invoke, run_async
|
||||
|
||||
|
||||
@@ -71,7 +72,7 @@ class _VisibleCheckBox(QCheckBox):
|
||||
)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor("#FFFFFF" if self.isEnabled() else "#98A2B3")
|
||||
color = QColor("#FFFFFF" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(QPen(color, 2, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
|
||||
painter.drawLine(
|
||||
QPoint(indicator.left() + 4, indicator.center().y()),
|
||||
@@ -90,7 +91,7 @@ class _AccountLineEdit(QLineEdit):
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(_round_pen("#8292B6", 1.5))
|
||||
painter.setPen(_round_pen("#6A6B6D", 1.5))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawEllipse(QRectF(24, 14.5, 8, 8))
|
||||
painter.drawRoundedRect(QRectF(19, 27, 18, 9), 4.5, 4.5)
|
||||
@@ -104,7 +105,7 @@ class _DemoCheckBox(_VisibleCheckBox):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
center = QPointF(self.width() - 9, self.height() / 2)
|
||||
painter.setPen(_round_pen("#92A0BF", 1.4))
|
||||
painter.setPen(_round_pen("#8E8F90", 1.4))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawEllipse(center, 7, 7)
|
||||
painter.drawLine(center + QPointF(0, -1), center + QPointF(0, 4))
|
||||
@@ -112,10 +113,9 @@ class _DemoCheckBox(_VisibleCheckBox):
|
||||
|
||||
|
||||
def _font(pixel_size: int, weight: QFont.Weight = QFont.Weight.Normal) -> QFont:
|
||||
font = QFont("Microsoft YaHei UI")
|
||||
font = QFont(QApplication.font())
|
||||
font.setPixelSize(pixel_size)
|
||||
font.setWeight(weight)
|
||||
font.setHintingPreference(QFont.HintingPreference.PreferFullHinting)
|
||||
return font
|
||||
|
||||
|
||||
@@ -291,10 +291,10 @@ class _BrandPanel(QWidget):
|
||||
bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
background = QLinearGradient(bounds.topLeft(), bounds.bottomRight())
|
||||
background.setColorAt(0.0, QColor("#FFFFFF"))
|
||||
background.setColorAt(0.7, QColor("#FEFEFF"))
|
||||
background.setColorAt(1.0, QColor("#F9FBFF"))
|
||||
background.setColorAt(0.7, QColor("#FFFFFF"))
|
||||
background.setColorAt(1.0, QColor("#F7F7F7"))
|
||||
painter.setBrush(background)
|
||||
painter.setPen(QPen(QColor("#E4E9F4"), 1))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
painter.drawRoundedRect(bounds, 24, 24)
|
||||
|
||||
width, height = float(self.width()), float(self.height())
|
||||
@@ -315,15 +315,15 @@ class _BrandPanel(QWidget):
|
||||
|
||||
tag_rect = QRectF(left, 238, 119, 40)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor("#F0F2FF"))
|
||||
painter.setBrush(QColor("#EEF1FA"))
|
||||
painter.drawRoundedRect(tag_rect, 11, 11)
|
||||
painter.setFont(_font(17, QFont.Weight.DemiBold))
|
||||
painter.setPen(QColor("#5265F6"))
|
||||
painter.setFont(_font(17, QFont.Weight.Medium))
|
||||
painter.setPen(QColor("#4F63D9"))
|
||||
painter.drawText(tag_rect, Qt.AlignmentFlag.AlignCenter, "医生工作站")
|
||||
|
||||
copy_left = left + 4
|
||||
painter.setFont(_font(51, QFont.Weight.Bold))
|
||||
painter.setPen(QColor("#14224A"))
|
||||
painter.setFont(_font(48, QFont.Weight.Medium))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(QPointF(copy_left, 354), "把诊间工作,")
|
||||
painter.drawText(QPointF(copy_left, 424), "留在一个")
|
||||
prefix_width = painter.fontMetrics().horizontalAdvance("留在一个")
|
||||
@@ -333,8 +333,8 @@ class _BrandPanel(QWidget):
|
||||
copy_left + prefix_width + 264,
|
||||
0,
|
||||
)
|
||||
highlight.setColorAt(0.0, QColor("#4258EC"))
|
||||
highlight.setColorAt(1.0, QColor("#6975FF"))
|
||||
highlight.setColorAt(0.0, QColor("#4F63D9"))
|
||||
highlight.setColorAt(1.0, QColor("#4F63D9"))
|
||||
painter.setPen(QPen(QBrush(highlight), 1))
|
||||
painter.drawText(QPointF(copy_left + prefix_width, 424), "安静的界面里")
|
||||
suffix_x = (
|
||||
@@ -342,19 +342,19 @@ class _BrandPanel(QWidget):
|
||||
+ prefix_width
|
||||
+ painter.fontMetrics().horizontalAdvance("安静的界面里")
|
||||
)
|
||||
painter.setPen(QColor("#14224A"))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(QPointF(suffix_x, 424), "。")
|
||||
|
||||
body_left = left + 6
|
||||
painter.setFont(_font(20))
|
||||
painter.setPen(QColor("#7181A7"))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(
|
||||
QPointF(body_left, 492), "接诊、问诊、患者与处方信息统一呈现,"
|
||||
)
|
||||
painter.drawText(QPointF(body_left, 525), "帮助医生专注于每一次沟通。")
|
||||
|
||||
painter.setFont(_font(16))
|
||||
painter.setPen(QColor("#7484A9"))
|
||||
painter.setPen(QColor("#6A6B6D"))
|
||||
painter.drawText(
|
||||
QPointF(body_left, height - 85), "本工作站仅供获授权的医疗人员使用"
|
||||
)
|
||||
@@ -366,7 +366,7 @@ class _RevealButton(QToolButton):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor("#8796B8" if self.isEnabled() else "#B8C0D1")
|
||||
color = QColor("#6A6B6D" if self.isEnabled() else "#BDBDBE")
|
||||
painter.setPen(_round_pen(color, 2))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
eye = QPainterPath(QPointF(7, self.height() / 2))
|
||||
@@ -392,11 +392,11 @@ class _ServerButton(QPushButton):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75)
|
||||
painter.setBrush(QColor("#F8FAFF") if self.underMouse() else QColor("#FFFFFF"))
|
||||
painter.setPen(QPen(QColor("#D8DFEE"), 1.5))
|
||||
painter.setBrush(QColor("#FFFFFF") if self.underMouse() else QColor("#FFFFFF"))
|
||||
painter.setPen(QPen(QColor("#E4E4E5"), 1.5))
|
||||
painter.drawRoundedRect(rect, 12, 12)
|
||||
color = QColor("#17264B" if self.isEnabled() else "#A2ABC0")
|
||||
painter.setPen(_round_pen("#7C8DB2", 1.8))
|
||||
color = QColor("#1A1C1F" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(_round_pen("#6A6B6D", 1.8))
|
||||
center = QPointF(29, self.height() / 2)
|
||||
painter.drawEllipse(center, 8, 8)
|
||||
painter.drawEllipse(center, 2.8, 2.8)
|
||||
@@ -420,7 +420,7 @@ class _ServerButton(QPushButton):
|
||||
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
|
||||
"服务器设置",
|
||||
)
|
||||
painter.setPen(_round_pen("#94A1BC", 2))
|
||||
painter.setPen(_round_pen("#8E8F90", 2))
|
||||
x, y = self.width() - 28, self.height() / 2
|
||||
if self.isChecked():
|
||||
painter.drawLine(QPointF(x - 5, y + 3), QPointF(x, y - 3))
|
||||
@@ -460,6 +460,7 @@ class LoginWindow(QMainWindow):
|
||||
super().__init__(parent)
|
||||
self.repository = repository
|
||||
self.config = config
|
||||
self.debug_mode = bool(getattr(config, "debug_mode", False))
|
||||
if demo_repository is None:
|
||||
demo_repository = getattr(config, "demo_repository", None)
|
||||
self.demo_repository = demo_repository
|
||||
@@ -481,12 +482,8 @@ class LoginWindow(QMainWindow):
|
||||
canvas.setStyleSheet(
|
||||
"""
|
||||
QWidget#LoginCanvas {
|
||||
color: #17264B;
|
||||
background: qlineargradient(
|
||||
x1:0, y1:0, x2:1, y2:1,
|
||||
stop:0 #F8FAFF, stop:0.58 #FBFCFF, stop:1 #F1F5FF
|
||||
);
|
||||
font-family: "Microsoft YaHei UI";
|
||||
color: #1A1C1F;
|
||||
background-color: #F4F6FA;
|
||||
font-size: 16px;
|
||||
}
|
||||
QWidget#LoginBrandPanel {
|
||||
@@ -495,28 +492,28 @@ class LoginWindow(QMainWindow):
|
||||
}
|
||||
QFrame#LoginCard {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #E1E6F0;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 20px;
|
||||
}
|
||||
QFrame#LoginCard QFrame#SubtleCard {
|
||||
background-color: #F8FAFF;
|
||||
border: 1px solid #DCE2EF;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#LoginCard QLabel { color: #17264B; background: transparent; }
|
||||
QFrame#LoginCard QLabel[role="muted"] { color: #7382A5; }
|
||||
QFrame#LoginCard QLabel { color: #1A1C1F; background: transparent; }
|
||||
QFrame#LoginCard QLabel[role="muted"] { color: #606163; }
|
||||
QFrame#LoginCard QLabel[role="danger"] { color: #C43E55; }
|
||||
QFrame#LoginCard QCheckBox#AllowSelfSignedCertificate { color: #9A6813; }
|
||||
QFrame#LoginCard QLineEdit,
|
||||
QFrame#LoginCard QSpinBox {
|
||||
color: #17264B;
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #D6DEED;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 12px;
|
||||
padding: 0 16px;
|
||||
font-size: 17px;
|
||||
selection-background-color: #E5E9FF;
|
||||
selection-color: #17264B;
|
||||
selection-background-color: #EEF1FA;
|
||||
selection-color: #1A1C1F;
|
||||
}
|
||||
QFrame#LoginCard QLineEdit#AccountEdit {
|
||||
min-height: 52px;
|
||||
@@ -524,9 +521,9 @@ class LoginWindow(QMainWindow):
|
||||
padding-left: 52px;
|
||||
}
|
||||
QFrame#LoginCard QLineEdit:hover,
|
||||
QFrame#LoginCard QSpinBox:hover { border-color: #9AA8FF; }
|
||||
QFrame#LoginCard QSpinBox:hover { border-color: #8B9AD9; }
|
||||
QFrame#LoginCard QLineEdit:focus,
|
||||
QFrame#LoginCard QSpinBox:focus { border: 1.5px solid #7080F7; }
|
||||
QFrame#LoginCard QSpinBox:focus { border: 1.5px solid #8B9AD9; }
|
||||
QFrame#LoginCard QLineEdit#PasswordEdit {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
@@ -536,31 +533,31 @@ class LoginWindow(QMainWindow):
|
||||
QFrame#LoginCard QCheckBox#DemoModeCheck { spacing: 10px; }
|
||||
QFrame#PasswordField {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #D6DEED;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#PasswordField:focus-within { border-color: #7080F7; }
|
||||
QFrame#PasswordField:focus-within { border-color: #8B9AD9; }
|
||||
QFrame#LoginCard QCheckBox {
|
||||
color: #6F7FA3;
|
||||
color: #606163;
|
||||
spacing: 13px;
|
||||
font-size: 16px;
|
||||
}
|
||||
QFrame#LoginCard QCheckBox::indicator {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border: 1px solid #CFD8EB;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 6px;
|
||||
background-color: #FFFFFF;
|
||||
}
|
||||
QFrame#LoginCard QCheckBox::indicator:hover { border-color: #7A8AF8; }
|
||||
QFrame#LoginCard QCheckBox::indicator:hover { border-color: #8B9AD9; }
|
||||
QFrame#LoginCard QCheckBox::indicator:checked {
|
||||
border-color: #6475F5;
|
||||
background-color: #6475F5;
|
||||
border-color: #4F63D9;
|
||||
background-color: #4F63D9;
|
||||
}
|
||||
QFrame#LoginCard QToolButton#PasswordReveal {
|
||||
min-width: 87px;
|
||||
max-width: 87px;
|
||||
color: #8290B0;
|
||||
color: #6A6B6D;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
@@ -569,14 +566,11 @@ class LoginWindow(QMainWindow):
|
||||
min-height: 58px;
|
||||
max-height: 58px;
|
||||
color: #FFFFFF;
|
||||
background: qlineargradient(
|
||||
x1:0, y1:0, x2:1, y2:0,
|
||||
stop:0 #5B6BF1, stop:0.55 #6675FA, stop:1 #5865F2
|
||||
);
|
||||
background-color: #4F63D9;
|
||||
border: 0;
|
||||
border-radius: 12px;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
font-weight: 500;
|
||||
}
|
||||
QFrame#LoginCard QPushButton#ServerSettingsToggle {
|
||||
min-height: 56px;
|
||||
@@ -584,17 +578,17 @@ class LoginWindow(QMainWindow):
|
||||
padding: 0;
|
||||
}
|
||||
QFrame#LoginCard QPushButton[variant="primary"]:hover {
|
||||
background-color: #5262ED;
|
||||
background-color: #4156C4;
|
||||
}
|
||||
QFrame#LoginCard QPushButton[variant="secondary"] {
|
||||
color: #4353BD;
|
||||
background-color: #EDF0FF;
|
||||
border: 1px solid #D3DAFC;
|
||||
color: #1A1C1F;
|
||||
background-color: #F0F0F0;
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QFrame#LoginCard QPushButton[variant="secondary"]:hover {
|
||||
background-color: #DCE3FF;
|
||||
border-color: #8B98F8;
|
||||
background-color: #E4E4E5;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
QScrollArea#LoginAreaScroll,
|
||||
QScrollArea#LoginAreaScroll > QWidget > QWidget {
|
||||
@@ -628,6 +622,12 @@ class LoginWindow(QMainWindow):
|
||||
spacing = 20
|
||||
self.login_root.setContentsMargins(*margins)
|
||||
self.login_root.setSpacing(spacing)
|
||||
# Keep the form fully visible when the 60/40 desktop split would
|
||||
# otherwise crop its fixed-width card. Small windows focus on login.
|
||||
self.brand_panel.setVisible(width >= 1120)
|
||||
self.login_area_layout.setContentsMargins(
|
||||
0, min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
||||
)
|
||||
super().resizeEvent(event)
|
||||
|
||||
def _build_brand_panel(self) -> QWidget:
|
||||
@@ -646,20 +646,19 @@ class LoginWindow(QMainWindow):
|
||||
area.setFrameShape(QFrame.Shape.NoFrame)
|
||||
area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
area.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
area.setMinimumWidth(492)
|
||||
content = QWidget()
|
||||
content.setObjectName("LoginAreaContent")
|
||||
area.setWidget(content)
|
||||
self.login_scroll = area
|
||||
outer = QVBoxLayout(content)
|
||||
# The supplied 1536×1024 capture contains a 60 px native title bar.
|
||||
# Its card begins at y=198, i.e. y=138 in the 1536×964 client area.
|
||||
# The root starts at y=34, so the deterministic lead inset is 104 px.
|
||||
outer.setContentsMargins(0, 104, 0, 0)
|
||||
self.login_area_layout = outer
|
||||
outer.setContentsMargins(0, 40, 0, 12)
|
||||
|
||||
self.card = QFrame()
|
||||
self.card.setObjectName("LoginCard")
|
||||
self.card.setFixedWidth(480)
|
||||
self.card.setMinimumHeight(694)
|
||||
self.card.setMinimumHeight(620)
|
||||
self.card.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)
|
||||
card_shadow = QGraphicsDropShadowEffect(self.card)
|
||||
card_shadow.setBlurRadius(38)
|
||||
@@ -674,13 +673,13 @@ class LoginWindow(QMainWindow):
|
||||
|
||||
title = QLabel("欢迎回来")
|
||||
title.setObjectName("LoginTitle")
|
||||
title.setStyleSheet("color:#14224A; font-size:33px; font-weight:700;")
|
||||
title.setStyleSheet("color:#1A1C1F; font-size:30px; font-weight:500;")
|
||||
title.setContentsMargins(1, -3, 0, 3)
|
||||
title.setFixedHeight(46)
|
||||
card_layout.addWidget(title)
|
||||
subtitle = QLabel("使用医生账号登录工作站")
|
||||
subtitle.setProperty("role", "muted")
|
||||
subtitle.setStyleSheet("color:#7382A5; font-size:18px;")
|
||||
subtitle.setStyleSheet("color:#606163; font-size:18px;")
|
||||
subtitle.setContentsMargins(1, 8, 0, 0)
|
||||
subtitle.setFixedHeight(27)
|
||||
card_layout.addWidget(subtitle)
|
||||
@@ -690,7 +689,7 @@ class LoginWindow(QMainWindow):
|
||||
card_layout.addWidget(self.error_banner)
|
||||
|
||||
account_label = QLabel("账号")
|
||||
account_label.setStyleSheet("color:#17264B; font-size:18px; font-weight:600;")
|
||||
account_label.setStyleSheet("color:#1A1C1F; font-size:16px; font-weight:500;")
|
||||
account_label.setContentsMargins(0, -2, 0, 2)
|
||||
account_label.setFixedHeight(24)
|
||||
card_layout.addWidget(account_label)
|
||||
@@ -706,7 +705,7 @@ class LoginWindow(QMainWindow):
|
||||
card_layout.addSpacing(21)
|
||||
|
||||
password_label = QLabel("密码")
|
||||
password_label.setStyleSheet("color:#17264B; font-size:18px; font-weight:600;")
|
||||
password_label.setStyleSheet("color:#1A1C1F; font-size:16px; font-weight:500;")
|
||||
password_label.setContentsMargins(0, -3, 0, 3)
|
||||
password_label.setFixedHeight(24)
|
||||
card_layout.addWidget(password_label)
|
||||
@@ -751,6 +750,7 @@ class LoginWindow(QMainWindow):
|
||||
if self.demo_repository is None:
|
||||
self.demo_check.setToolTip("当前未配置演示数据")
|
||||
self.demo_check.toggled.connect(self._on_demo_toggled)
|
||||
self.demo_check.setVisible(self.debug_mode)
|
||||
choices.addWidget(self.demo_check)
|
||||
card_layout.addLayout(choices)
|
||||
card_layout.addSpacing(26)
|
||||
@@ -765,25 +765,29 @@ class LoginWindow(QMainWindow):
|
||||
self.login_button.setGraphicsEffect(login_shadow)
|
||||
self.login_button.clicked.connect(self.submit)
|
||||
card_layout.addWidget(self.login_button)
|
||||
card_layout.addSpacing(20)
|
||||
|
||||
self.debug_settings_section = QWidget()
|
||||
self.debug_settings_section.setObjectName("DebugSettingsSection")
|
||||
debug_settings_layout = QVBoxLayout(self.debug_settings_section)
|
||||
debug_settings_layout.setContentsMargins(0, 0, 0, 0)
|
||||
debug_settings_layout.setSpacing(0)
|
||||
debug_settings_layout.addSpacing(20)
|
||||
divider = QHBoxLayout()
|
||||
divider.setSpacing(18)
|
||||
line_left = QFrame()
|
||||
line_left.setFrameShape(QFrame.Shape.HLine)
|
||||
line_left.setStyleSheet("color:#DFE4F0; background:#DFE4F0; max-height:1px;")
|
||||
line_left.setStyleSheet("color:#EDEDEE; background:#EDEDEE; max-height:1px;")
|
||||
divider.addWidget(line_left, 1)
|
||||
divider_text = QLabel("或")
|
||||
divider_text.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
divider_text.setStyleSheet("color:#7C89A8; font-size:16px;")
|
||||
divider_text.setStyleSheet("color:#6A6B6D; font-size:16px;")
|
||||
divider_text.setFixedSize(38, 22)
|
||||
divider.addWidget(divider_text)
|
||||
line_right = QFrame()
|
||||
line_right.setFrameShape(QFrame.Shape.HLine)
|
||||
line_right.setStyleSheet("color:#DFE4F0; background:#DFE4F0; max-height:1px;")
|
||||
line_right.setStyleSheet("color:#EDEDEE; background:#EDEDEE; max-height:1px;")
|
||||
divider.addWidget(line_right, 1)
|
||||
card_layout.addLayout(divider)
|
||||
card_layout.addSpacing(20)
|
||||
debug_settings_layout.addLayout(divider)
|
||||
debug_settings_layout.addSpacing(20)
|
||||
|
||||
self.server_toggle = _ServerButton("服务器设置 +")
|
||||
self.server_toggle.setObjectName("ServerSettingsToggle")
|
||||
@@ -791,7 +795,7 @@ class LoginWindow(QMainWindow):
|
||||
self.server_toggle.setCheckable(True)
|
||||
self.server_toggle.setFixedHeight(56)
|
||||
self.server_toggle.clicked.connect(self._toggle_server_panel)
|
||||
card_layout.addWidget(self.server_toggle)
|
||||
debug_settings_layout.addWidget(self.server_toggle)
|
||||
|
||||
self.server_panel = QFrame()
|
||||
self.server_panel.setObjectName("SubtleCard")
|
||||
@@ -850,9 +854,11 @@ class LoginWindow(QMainWindow):
|
||||
self.server_hint.setWordWrap(True)
|
||||
server_layout.addWidget(self.server_hint)
|
||||
self.server_panel.setVisible(False)
|
||||
card_layout.addSpacing(9)
|
||||
card_layout.addWidget(self.server_panel)
|
||||
card_layout.addSpacing(12)
|
||||
debug_settings_layout.addSpacing(9)
|
||||
debug_settings_layout.addWidget(self.server_panel)
|
||||
debug_settings_layout.addSpacing(12)
|
||||
self.debug_settings_section.setVisible(self.debug_mode)
|
||||
card_layout.addWidget(self.debug_settings_section)
|
||||
|
||||
footnote_row = QHBoxLayout()
|
||||
footnote_row.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -865,7 +871,7 @@ class LoginWindow(QMainWindow):
|
||||
footnote_row.addWidget(lock)
|
||||
footnote = QLabel("登录即表示你同意遵守机构的数据安全与隐私规范。")
|
||||
footnote.setProperty("role", "muted")
|
||||
footnote.setStyleSheet("color:#7A89AA; font-size:15px;")
|
||||
footnote.setStyleSheet("color:#6A6B6D; font-size:15px;")
|
||||
footnote.setContentsMargins(0, -4, 0, 4)
|
||||
footnote.setWordWrap(True)
|
||||
footnote.setFixedHeight(40)
|
||||
@@ -874,12 +880,12 @@ class LoginWindow(QMainWindow):
|
||||
self.version_label = QLabel(f"当前版本 {__version__}")
|
||||
self.version_label.setObjectName("LoginVersionLabel")
|
||||
self.version_label.setProperty("role", "muted")
|
||||
self.version_label.setStyleSheet("color:#8B98B5; font-size:13px;")
|
||||
self.version_label.setStyleSheet("color:#6A6B6D; font-size:13px;")
|
||||
self.version_label.setContentsMargins(0, 8, 0, 0)
|
||||
card_layout.addWidget(self.version_label, 0, Qt.AlignmentFlag.AlignRight)
|
||||
|
||||
outer.addWidget(
|
||||
self.card, 0, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
|
||||
self.card, 0, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop
|
||||
)
|
||||
outer.addStretch(1)
|
||||
self.busy_overlay = BusyOverlay(self.card, "正在验证账号…")
|
||||
@@ -891,28 +897,11 @@ class LoginWindow(QMainWindow):
|
||||
|
||||
@staticmethod
|
||||
def _account_icon() -> QIcon:
|
||||
pixmap = crisp_pixmap(24)
|
||||
painter = QPainter(pixmap)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(_round_pen("#8292B6", 2))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawEllipse(QPointF(12, 7.5), 4.2, 4.2)
|
||||
painter.drawRoundedRect(QRectF(4.5, 14, 15, 7), 3.5, 3.5)
|
||||
painter.end()
|
||||
return QIcon(pixmap)
|
||||
return icons.icon("user", "muted", 24)
|
||||
|
||||
@staticmethod
|
||||
def _lock_icon() -> QIcon:
|
||||
pixmap = crisp_pixmap(20)
|
||||
painter = QPainter(pixmap)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(_round_pen("#8FA0C4", 1.6))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRoundedRect(QRectF(5, 8, 10, 9), 2, 2)
|
||||
painter.drawArc(QRectF(7, 3, 6, 9), 0, 180 * 16)
|
||||
painter.drawLine(QPointF(10, 11), QPointF(10, 14))
|
||||
painter.end()
|
||||
return QIcon(pixmap)
|
||||
return icons.icon("lock", "muted", 20)
|
||||
|
||||
def _restore_settings(self) -> None:
|
||||
configured_account = getattr(self.config, "remembered_account", "")
|
||||
@@ -922,8 +911,13 @@ class LoginWindow(QMainWindow):
|
||||
configured_url = getattr(self.config, "base_url", "") or getattr(
|
||||
self.config, "api_base_url", ""
|
||||
)
|
||||
restored_url = (
|
||||
self.settings.value("server/base_url", configured_url)
|
||||
if self.debug_mode
|
||||
else configured_url
|
||||
)
|
||||
self.server_url_edit.setText(
|
||||
str(self.settings.value("server/base_url", configured_url) or "")
|
||||
str(restored_url or "")
|
||||
)
|
||||
try:
|
||||
configured_timeout = getattr(self.config, "request_timeout", 60)
|
||||
@@ -937,15 +931,22 @@ class LoginWindow(QMainWindow):
|
||||
configured_verify_ssl = _setting_bool(
|
||||
getattr(self.config, "verify_ssl", True), True
|
||||
)
|
||||
verify_ssl = _setting_bool(
|
||||
self.settings.value("server/verify_ssl", configured_verify_ssl),
|
||||
configured_verify_ssl,
|
||||
verify_ssl = (
|
||||
_setting_bool(
|
||||
self.settings.value("server/verify_ssl", configured_verify_ssl),
|
||||
configured_verify_ssl,
|
||||
)
|
||||
if self.debug_mode
|
||||
else configured_verify_ssl
|
||||
)
|
||||
self.allow_self_signed_check.setChecked(not verify_ssl)
|
||||
if self.demo_repository is not None and bool(
|
||||
if self.debug_mode and self.demo_repository is not None and bool(
|
||||
getattr(self.config, "demo_mode", False)
|
||||
):
|
||||
self.demo_check.setChecked(True)
|
||||
elif not self.debug_mode:
|
||||
self.demo_check.setChecked(False)
|
||||
self.active_repository = self.repository
|
||||
self.account_edit.setText(remembered)
|
||||
self.restore_remembered_credentials()
|
||||
if remembered:
|
||||
@@ -954,6 +955,8 @@ class LoginWindow(QMainWindow):
|
||||
self.account_edit.setFocus()
|
||||
|
||||
def _credential_scope(self) -> str:
|
||||
if not self.debug_mode:
|
||||
return str(getattr(self.config, "api_base_url", "") or "").strip().rstrip("/")
|
||||
if hasattr(self, "server_url_edit"):
|
||||
scope = self.server_url_edit.text().strip()
|
||||
if scope:
|
||||
@@ -1000,6 +1003,12 @@ class LoginWindow(QMainWindow):
|
||||
self.reveal_button.setText("隐藏" if visible else "显示")
|
||||
|
||||
def _on_demo_toggled(self, enabled: bool) -> None:
|
||||
if enabled and not self.debug_mode:
|
||||
self.demo_check.blockSignals(True)
|
||||
self.demo_check.setChecked(False)
|
||||
self.demo_check.blockSignals(False)
|
||||
self.active_repository = self.repository
|
||||
return
|
||||
self.active_repository = self.demo_repository if enabled else self.repository
|
||||
self.server_toggle.setEnabled(not enabled and not self._loading)
|
||||
self.demo_mode_changed.emit(enabled)
|
||||
@@ -1013,6 +1022,10 @@ class LoginWindow(QMainWindow):
|
||||
self.password_edit.setPlaceholderText("请输入密码")
|
||||
|
||||
def _toggle_server_panel(self, expanded: bool) -> None:
|
||||
if not self.debug_mode:
|
||||
self.server_toggle.setChecked(False)
|
||||
self.server_panel.hide()
|
||||
return
|
||||
self.server_panel.setVisible(expanded)
|
||||
self.server_toggle.setText("服务器设置 -" if expanded else "服务器设置 +")
|
||||
self.server_panel.updateGeometry()
|
||||
@@ -1027,6 +1040,13 @@ class LoginWindow(QMainWindow):
|
||||
self._apply_server_settings(announce=True)
|
||||
|
||||
def _apply_server_settings(self, *, announce: bool) -> bool:
|
||||
if not self.debug_mode:
|
||||
base_url = str(getattr(self.config, "api_base_url", "") or "").strip()
|
||||
if base_url:
|
||||
self.server_url_edit.setText(base_url)
|
||||
return True
|
||||
self.error_banner.show_message("线上服务器地址尚未配置,请联系管理员。", "warning")
|
||||
return False
|
||||
base_url = self.server_url_edit.text().strip().rstrip("/")
|
||||
if base_url and not base_url.startswith(
|
||||
("https://", "http://localhost", "http://127.0.0.1")
|
||||
@@ -1079,7 +1099,7 @@ class LoginWindow(QMainWindow):
|
||||
def submit(self) -> None:
|
||||
if self._loading:
|
||||
return
|
||||
demo_mode = self.demo_check.isChecked()
|
||||
demo_mode = self.debug_mode and self.demo_check.isChecked()
|
||||
remember_account = self.remember_check.isChecked()
|
||||
account = self.account_edit.text().strip()
|
||||
password = self.password_edit.text()
|
||||
@@ -1150,9 +1170,13 @@ class LoginWindow(QMainWindow):
|
||||
self.password_edit.setEnabled(not loading)
|
||||
self.remember_check.setEnabled(not loading)
|
||||
self.reveal_button.setEnabled(not loading)
|
||||
self.demo_check.setEnabled(not loading and self.demo_repository is not None)
|
||||
self.server_toggle.setEnabled(not loading and not self.demo_check.isChecked())
|
||||
self.server_panel.setEnabled(not loading)
|
||||
self.demo_check.setEnabled(
|
||||
self.debug_mode and not loading and self.demo_repository is not None
|
||||
)
|
||||
self.server_toggle.setEnabled(
|
||||
self.debug_mode and not loading and not self.demo_check.isChecked()
|
||||
)
|
||||
self.server_panel.setEnabled(self.debug_mode and not loading)
|
||||
self.server_url_edit.setEnabled(not loading)
|
||||
self.timeout_spin.setEnabled(not loading)
|
||||
self.allow_self_signed_check.setEnabled(not loading)
|
||||
@@ -1184,7 +1208,7 @@ class LoginWindow(QMainWindow):
|
||||
if remember_account is None:
|
||||
remember_account = self.remember_check.isChecked()
|
||||
scope = self._credential_scope()
|
||||
is_demo = bool(payload.get("demo_mode"))
|
||||
is_demo = self.debug_mode and bool(payload.get("demo_mode"))
|
||||
password_saved = False
|
||||
clearer = getattr(self.credential_store, "clear_password", None)
|
||||
if (
|
||||
@@ -1223,13 +1247,18 @@ class LoginWindow(QMainWindow):
|
||||
|
||||
def _on_login_error(self, error: Exception) -> None:
|
||||
error_text = str(error).lower()
|
||||
if (
|
||||
certificate_error = (
|
||||
"certificate_verify_failed" in error_text
|
||||
or "self-signed certificate" in error_text
|
||||
):
|
||||
)
|
||||
if certificate_error and self.debug_mode:
|
||||
self.server_toggle.setChecked(True)
|
||||
self._toggle_server_panel(True)
|
||||
message = friendly_error(error)
|
||||
message = (
|
||||
friendly_error(error)
|
||||
if self.debug_mode or not certificate_error
|
||||
else "服务器证书校验失败,请联系管理员检查线上域名和证书配置。"
|
||||
)
|
||||
self.error_banner.show_message(message, "danger")
|
||||
self.login_failed.emit(message)
|
||||
self.password_edit.selectAll()
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Motion tokens and helpers.
|
||||
|
||||
The product had two `QGraphicsOpacityEffect` uses and no `QPropertyAnimation`
|
||||
at all, so every state change was an instant cut: pages replaced each other
|
||||
between one frame and the next, drawers appeared fully formed, toasts blinked
|
||||
in and out. Nothing was slow - it just gave the eye no continuity to follow,
|
||||
which is what reads as "not smooth" however fast the code underneath is.
|
||||
|
||||
Everything here is short. A workstation is used all day, so transitions are
|
||||
tuned to be felt rather than watched: 110-260 ms, ease-out on entry, and travel
|
||||
measured in single-digit pixels. Anything longer starts costing the user time.
|
||||
|
||||
Qt stylesheets have no `transition` property, so this is `QPropertyAnimation`
|
||||
throughout. Two rules keep that safe:
|
||||
|
||||
* an animation must be owned, or PySide garbage-collects it mid-flight and the
|
||||
widget freezes half-faded - :func:`_own` parks it on the target;
|
||||
* a `QGraphicsOpacityEffect` forces the whole widget subtree through an
|
||||
offscreen render path, which would make a table scroll badly for the rest of
|
||||
the session - every fade here removes its effect when it finishes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QAbstractAnimation,
|
||||
QEasingCurve,
|
||||
QEvent,
|
||||
QObject,
|
||||
QPoint,
|
||||
QPropertyAnimation,
|
||||
Qt,
|
||||
QTimer,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractScrollArea,
|
||||
QGraphicsOpacityEffect,
|
||||
QStackedWidget,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
#: Durations in milliseconds.
|
||||
FAST = 110 # hover-scale feedback, small fades
|
||||
BASE = 170 # the default: page and panel transitions
|
||||
SLOW = 260 # large travel, e.g. a drawer crossing the workspace
|
||||
|
||||
#: Entering elements decelerate; elements that move between two known places
|
||||
#: ease in and out; large travel gets a longer tail so it never looks linear.
|
||||
EASE_ENTER = QEasingCurve.Type.OutCubic
|
||||
EASE_MOVE = QEasingCurve.Type.InOutCubic
|
||||
EASE_TRAVEL = QEasingCurve.Type.OutQuint
|
||||
|
||||
#: How far an entering surface rises, in device-independent pixels. Kept small
|
||||
#: on purpose: a page that slides a long way reads as a slideshow, not an app.
|
||||
RISE = 8
|
||||
|
||||
|
||||
def reduced_motion() -> bool:
|
||||
"""Whether animation should be skipped entirely.
|
||||
|
||||
Off by default under the offscreen platform so widget grabs in tests and in
|
||||
the packaging smoke checks capture a settled frame rather than a frame from
|
||||
the middle of a fade. ``DOCTOR_MOTION=on`` / ``off`` overrides either way.
|
||||
"""
|
||||
|
||||
override = os.getenv("DOCTOR_MOTION", "").strip().lower()
|
||||
if override in {"off", "0", "false", "none", "reduce"}:
|
||||
return True
|
||||
if override in {"on", "1", "true", "full"}:
|
||||
return False
|
||||
return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen"
|
||||
|
||||
|
||||
def _own(target: QWidget, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
|
||||
"""Park an animation on its target so Python does not collect it early."""
|
||||
|
||||
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", None) or {}
|
||||
previous = running.get(key)
|
||||
if previous is not None:
|
||||
previous.stop()
|
||||
running[key] = animation
|
||||
target._doctor_motion = running
|
||||
return animation
|
||||
|
||||
|
||||
def animate(
|
||||
target: Any,
|
||||
prop: bytes,
|
||||
start: Any,
|
||||
end: Any,
|
||||
*,
|
||||
duration: int = BASE,
|
||||
easing: QEasingCurve.Type = EASE_ENTER,
|
||||
key: str | None = None,
|
||||
owner: QWidget | None = None,
|
||||
on_finished: Callable[[], None] | None = None,
|
||||
) -> QPropertyAnimation | None:
|
||||
"""Animate one Qt property, or apply the end value outright if motion is off.
|
||||
|
||||
``owner`` keeps the animation alive independently of ``target``. Fades
|
||||
animate a ``QGraphicsOpacityEffect`` that is deleted the moment the fade
|
||||
ends, so parenting the animation to the effect would destroy the animation
|
||||
from inside its own ``finished`` emission.
|
||||
"""
|
||||
|
||||
if reduced_motion():
|
||||
target.setProperty(prop.decode() if isinstance(prop, bytes) else prop, end)
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
return None
|
||||
animation = QPropertyAnimation(target, prop, owner if owner is not None else target)
|
||||
animation.setDuration(duration)
|
||||
animation.setEasingCurve(easing)
|
||||
animation.setStartValue(start)
|
||||
animation.setEndValue(end)
|
||||
if on_finished is not None:
|
||||
animation.finished.connect(on_finished)
|
||||
_own(owner if owner is not None else target, key or prop.decode(), animation)
|
||||
animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
|
||||
return animation
|
||||
|
||||
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect:
|
||||
effect = widget.graphicsEffect()
|
||||
if not isinstance(effect, QGraphicsOpacityEffect):
|
||||
effect = QGraphicsOpacityEffect(widget)
|
||||
widget.setGraphicsEffect(effect)
|
||||
effect.setEnabled(True)
|
||||
return effect
|
||||
|
||||
|
||||
def _drop_effect(widget: QWidget) -> None:
|
||||
"""Detach the opacity effect once a fade is done.
|
||||
|
||||
Leaving it attached keeps the widget on Qt's offscreen composite path, which
|
||||
is exactly the sort of quiet, permanent frame-rate tax this module exists to
|
||||
avoid introducing.
|
||||
|
||||
The detach is deferred by one event-loop turn on purpose. ``finished`` is
|
||||
emitted from inside the animation, and ``setGraphicsEffect(None)`` deletes
|
||||
the old effect immediately - tearing down the object graph underneath a
|
||||
signal that is still being delivered.
|
||||
"""
|
||||
|
||||
def detach() -> None:
|
||||
try:
|
||||
if isinstance(widget.graphicsEffect(), QGraphicsOpacityEffect):
|
||||
widget.setGraphicsEffect(None)
|
||||
except RuntimeError: # the widget went away while the fade was running
|
||||
pass
|
||||
|
||||
QTimer.singleShot(0, detach)
|
||||
|
||||
|
||||
def fade_in(
|
||||
widget: QWidget,
|
||||
*,
|
||||
duration: int = BASE,
|
||||
start: float = 0.0,
|
||||
easing: QEasingCurve.Type = EASE_ENTER,
|
||||
) -> None:
|
||||
"""Fade a widget up to full opacity, showing it first if needed."""
|
||||
|
||||
if reduced_motion():
|
||||
widget.show()
|
||||
return
|
||||
effect = _opacity_effect(widget)
|
||||
effect.setOpacity(start)
|
||||
widget.show()
|
||||
animate(
|
||||
effect,
|
||||
b"opacity",
|
||||
start,
|
||||
1.0,
|
||||
duration=duration,
|
||||
easing=easing,
|
||||
key="fade",
|
||||
owner=widget,
|
||||
on_finished=lambda: _drop_effect(widget),
|
||||
)
|
||||
|
||||
|
||||
def fade_out(
|
||||
widget: QWidget,
|
||||
*,
|
||||
duration: int = FAST,
|
||||
hide: bool = True,
|
||||
on_finished: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Fade a widget down, optionally hiding it when the fade completes."""
|
||||
|
||||
if reduced_motion():
|
||||
if hide:
|
||||
widget.hide()
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
return
|
||||
effect = _opacity_effect(widget)
|
||||
|
||||
def done() -> None:
|
||||
if hide:
|
||||
widget.hide()
|
||||
_drop_effect(widget)
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
|
||||
animate(
|
||||
effect,
|
||||
b"opacity",
|
||||
float(effect.opacity()),
|
||||
0.0,
|
||||
duration=duration,
|
||||
easing=EASE_MOVE,
|
||||
key="fade",
|
||||
owner=widget,
|
||||
on_finished=done,
|
||||
)
|
||||
|
||||
|
||||
def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None:
|
||||
"""Fade a surface in while it settles upward by a few pixels.
|
||||
|
||||
The rise is what makes a swap read as one surface replacing another rather
|
||||
than as a repaint; keeping it under ten pixels stops it becoming a gesture
|
||||
the user has to wait out.
|
||||
"""
|
||||
|
||||
if reduced_motion():
|
||||
widget.show()
|
||||
return
|
||||
fade_in(widget, duration=duration)
|
||||
if rise:
|
||||
origin = widget.pos()
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
animate(
|
||||
widget,
|
||||
b"pos",
|
||||
widget.pos(),
|
||||
origin,
|
||||
duration=duration,
|
||||
easing=EASE_ENTER,
|
||||
key="enter",
|
||||
)
|
||||
|
||||
|
||||
def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None:
|
||||
"""Change the current page of a stack with a short cross-fade.
|
||||
|
||||
``QStackedWidget`` swaps pages between two frames with nothing in between,
|
||||
which is the single most-seen transition in this product - it happens on
|
||||
every sidebar click and on every list that toggles to its empty state.
|
||||
"""
|
||||
|
||||
if index < 0 or index >= stack.count() or stack.currentIndex() == index:
|
||||
stack.setCurrentIndex(index)
|
||||
return
|
||||
stack.setCurrentIndex(index)
|
||||
page = stack.currentWidget()
|
||||
if page is None or reduced_motion():
|
||||
return
|
||||
enter(page, rise=rise)
|
||||
|
||||
|
||||
# --- Smooth scrolling -----------------------------------------------------
|
||||
|
||||
#: One wheel notch travels this far, and takes this long to get there. Qt's
|
||||
#: default is an instant jump of three lines per notch, which on a long clinical
|
||||
#: record is the single jerkiest thing in the interface.
|
||||
SCROLL_STEP = 120
|
||||
SCROLL_MS = 190
|
||||
|
||||
|
||||
class _SmoothScroller(QObject):
|
||||
"""Animate a scroll area's wheel movement instead of jumping to it."""
|
||||
|
||||
def __init__(self, area: QAbstractScrollArea, *, orientation: Qt.Orientation) -> None:
|
||||
super().__init__(area)
|
||||
self._bar = (
|
||||
area.verticalScrollBar()
|
||||
if orientation is Qt.Orientation.Vertical
|
||||
else area.horizontalScrollBar()
|
||||
)
|
||||
self._target = self._bar.value()
|
||||
self._animation = QPropertyAnimation(self._bar, b"value", self)
|
||||
self._animation.setEasingCurve(EASE_ENTER)
|
||||
self._animation.setDuration(SCROLL_MS)
|
||||
# Keyboard, programmatic and drag movements must not be fought over: when
|
||||
# nothing is animating, the wheel target follows wherever the bar went.
|
||||
self._bar.valueChanged.connect(self._sync_target)
|
||||
area.viewport().installEventFilter(self)
|
||||
|
||||
def _sync_target(self, value: int) -> None:
|
||||
if self._animation.state() != QAbstractAnimation.State.Running:
|
||||
self._target = value
|
||||
|
||||
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt API
|
||||
del watched
|
||||
if event.type() is not QEvent.Type.Wheel or reduced_motion():
|
||||
return False
|
||||
delta = event.angleDelta().y() or event.angleDelta().x()
|
||||
if not delta or event.modifiers() & Qt.KeyboardModifier.ControlModifier:
|
||||
return False
|
||||
lower, upper = self._bar.minimum(), self._bar.maximum()
|
||||
# Re-clamp first: the range can shrink underneath a running animation
|
||||
# when the content behind it reloads, which would otherwise leave the
|
||||
# pending target past the end of the new content.
|
||||
self._target = max(lower, min(upper, self._target))
|
||||
target = self._target - round(delta / 120.0 * SCROLL_STEP)
|
||||
target = max(lower, min(upper, target))
|
||||
# At either end, hand the wheel back so an enclosing scroll area still
|
||||
# gets it - swallowing it there is what makes nested panes feel stuck.
|
||||
if target == self._target:
|
||||
return False
|
||||
self._target = target
|
||||
self._animation.stop()
|
||||
self._animation.setStartValue(self._bar.value())
|
||||
self._animation.setEndValue(target)
|
||||
self._animation.start()
|
||||
return True
|
||||
|
||||
|
||||
def install_smooth_scroll(
|
||||
area: QAbstractScrollArea,
|
||||
*,
|
||||
orientation: Qt.Orientation = Qt.Orientation.Vertical,
|
||||
) -> None:
|
||||
"""Give a scroll area eased wheel scrolling."""
|
||||
|
||||
if getattr(area, "_doctor_smooth_scroll", None) is not None:
|
||||
return
|
||||
area._doctor_smooth_scroll = _SmoothScroller(area, orientation=orientation)
|
||||
|
||||
|
||||
def press_feedback(widget: QWidget) -> None:
|
||||
"""Mark a widget so the shared stylesheet can give it a pressed transform.
|
||||
|
||||
Qt has no CSS transitions, so the visual step itself lives in the palette's
|
||||
pressed state; this only tags the widget as one that should get it.
|
||||
"""
|
||||
|
||||
widget.setProperty("motionPress", True)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BASE",
|
||||
"EASE_ENTER",
|
||||
"EASE_MOVE",
|
||||
"EASE_TRAVEL",
|
||||
"FAST",
|
||||
"RISE",
|
||||
"SLOW",
|
||||
"animate",
|
||||
"enter",
|
||||
"fade_in",
|
||||
"fade_out",
|
||||
"install_smooth_scroll",
|
||||
"press_feedback",
|
||||
"reduced_motion",
|
||||
"switch_stack",
|
||||
]
|
||||