Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a676d0936b | ||
|
|
aab0babd7e | ||
|
|
d34fe2e67e |
@@ -0,0 +1,156 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createRequire } from 'node:module'
|
||||
const require = createRequire(import.meta.url)
|
||||
const ts = require('typescript')
|
||||
const adminRoot = process.env.IDENTITY_UI_ROOT || path.resolve(import.meta.dirname, '..')
|
||||
const file = path.join(adminRoot, 'src/views/permission/identity/index.vue')
|
||||
const source = readFileSync(file, 'utf8')
|
||||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)?.[1] || ''
|
||||
function load(names, scope = {}) {
|
||||
const ast = ts.createSourceFile(
|
||||
'identity.ts',
|
||||
script,
|
||||
ts.ScriptTarget.ES2022,
|
||||
true,
|
||||
ts.ScriptKind.TS
|
||||
)
|
||||
const found = ast.statements.filter(
|
||||
(node) => ts.isFunctionDeclaration(node) && names.includes(node.name?.text)
|
||||
)
|
||||
assert.equal(found.length, names.length, 'all requested functions exist in the actual SFC')
|
||||
const output = ts.transpileModule(found.map((node) => node.getText(ast)).join('\n'), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
return new Function(...Object.keys(scope), output + '\nreturn {' + names.join(',') + '}')(
|
||||
...Object.values(scope)
|
||||
)
|
||||
}
|
||||
|
||||
test('adds exactly the requested department/access/check-time columns and retains native pagination', () => {
|
||||
for (const label of ['部门', '应用访问状态', '最近校验时间'])
|
||||
assert.ok(source.includes(`label="${label}"`), label)
|
||||
assert.match(source, /const query = reactive\(\{ q: '', state: '', page: 1, pageSize: 20 \}\)/)
|
||||
assert.match(source, /query\.page = 1/)
|
||||
assert.match(source, /v-model:current-page="query.page"/)
|
||||
const actions = source.split('<el-table-column label="操作"')[1].split('</el-table>')[0]
|
||||
assert.equal((actions.match(/type="primary"/g) || []).length, 2)
|
||||
assert.match(actions, /<el-dropdown/)
|
||||
})
|
||||
|
||||
test('department strings distinguish unassigned from unavailable data', () => {
|
||||
const { departmentText } = load(['departmentText'])
|
||||
assert.equal(departmentText({ dept_names: ['销售一部', '运营部'] }), '销售一部、运营部')
|
||||
assert.equal(departmentText({ dept_names: [] }), '未分配')
|
||||
assert.equal(departmentText({}), '未知')
|
||||
assert.equal(departmentText({ dept_names: null }), '未知')
|
||||
assert.equal(departmentText({ dept_names: [42] }), '未知')
|
||||
})
|
||||
|
||||
test('authorization is never inferred from verified binding or enabled local account', () => {
|
||||
const { applicationAccess } = load(['applicationAccess'])
|
||||
const row = { disable: 0, iam: { state: 'verified' } }
|
||||
assert.equal(applicationAccess(row).text, '未知')
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'verified', access: { allowed: true } } }).text,
|
||||
'已授权'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'verified', access: { allowed: false } } }).text,
|
||||
'未授权'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'verified', access: { allowed: 'true' } } }).text,
|
||||
'未知'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'unknown', access: { allowed: true } } }).text,
|
||||
'未知'
|
||||
)
|
||||
})
|
||||
|
||||
test('unlinked, revoked, service failure and unknown remain distinct without stale allow=true', () => {
|
||||
const { applicationAccess } = load(['applicationAccess'])
|
||||
assert.equal(applicationAccess({ iam: { state: 'unlinked' } }).text, '未关联')
|
||||
assert.equal(
|
||||
applicationAccess({ iam: { state: 'revoked', access: { allowed: false } } }).text,
|
||||
'未关联'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({
|
||||
iam: { state: 'unknown', access: { allowed: null, reason: 'SERVICE_UNAVAILABLE' } }
|
||||
}).text,
|
||||
'服务异常'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({
|
||||
iam: { state: 'verified', access: { allowed: true, reason: 'SERVICE_UNAVAILABLE' } }
|
||||
}).text,
|
||||
'服务异常'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({
|
||||
iam: { state: 'verified', access: { allowed: false, reason: 'NOT_LINKED' } }
|
||||
}).text,
|
||||
'未关联'
|
||||
)
|
||||
assert.equal(applicationAccess({ iam: { state: 'unknown' } }).text, '未知')
|
||||
for (const [reason, expected] of Object.entries({
|
||||
NOT_AUTHORIZED: '未授权',
|
||||
ACCOUNT_DISABLED: 'IAM账号停用',
|
||||
BINDING_CONFLICT: '关联冲突',
|
||||
ACCOUNT_MISMATCH: '身份不匹配'
|
||||
})) {
|
||||
assert.equal(
|
||||
applicationAccess({ iam: { state: 'unknown', access: { allowed: null, reason } } })
|
||||
.text,
|
||||
expected
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ iam: { state: 'verified', access: { allowed: true, reason } } })
|
||||
.text,
|
||||
expected
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('Unix seconds display Beijing time and absent/invalid timestamps never become a fake recent check', () => {
|
||||
const { checkedAtText } = load(['checkedAtText'])
|
||||
assert.equal(checkedAtText(1700000000), '2023/11/15 06:13:20')
|
||||
assert.equal(checkedAtText('1700000000'), checkedAtText(1700000000))
|
||||
for (const value of [null, undefined, 0, '', '0']) assert.equal(checkedAtText(value), '未校验')
|
||||
for (const value of [true, 'invalid', -1, Infinity, 1700000000000])
|
||||
assert.equal(checkedAtText(value), '未知')
|
||||
})
|
||||
|
||||
test('disabled writes are guarded even if an event handler is invoked directly', async () => {
|
||||
let notices = 0,
|
||||
posts = 0
|
||||
const drawerError = { value: '' }
|
||||
const scope = {
|
||||
ElMessage: { warning: () => notices++ },
|
||||
selected: { value: { disable: 1 } },
|
||||
drawerError,
|
||||
iamPost: async () => {
|
||||
posts++
|
||||
}
|
||||
}
|
||||
const { isLocalDisabled, open, submit } = load(['isLocalDisabled', 'open', 'submit'], scope)
|
||||
for (const disable of [1, true, '1']) assert.equal(isLocalDisabled({ disable }), true)
|
||||
for (const disable of [0, false, '0']) assert.equal(isLocalDisabled({ disable }), false)
|
||||
open({ disable: 1 }, 'bind')
|
||||
await submit()
|
||||
assert.equal(notices, 1)
|
||||
assert.equal(posts, 0)
|
||||
assert.match(drawerError.value, /停用/)
|
||||
})
|
||||
|
||||
test('all row write actions are disabled while audit remains readable with an explanation', () => {
|
||||
const actions = source.split('<el-table-column label="操作"')[1].split('</el-table>')[0]
|
||||
assert.ok((actions.match(/isLocalDisabled\(row\)/g) || []).length >= 5)
|
||||
assert.match(actions, /command="audit">审计记录/)
|
||||
assert.match(actions, /停用.*审计/)
|
||||
assert.match(source, /isLocalDisabled\(selected\)/)
|
||||
})
|
||||
@@ -9,6 +9,7 @@ import useAppStore from './stores/modules/app'
|
||||
import useSettingStore from './stores/modules/setting'
|
||||
import useUserStore from './stores/modules/user'
|
||||
import ChatNotifyToast from './components/chat-notify-toast/index.vue'
|
||||
import RevisitDueToast from './components/revisit-due-toast/index.vue'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const settingStore = useSettingStore()
|
||||
@@ -58,6 +59,8 @@ watch(
|
||||
<el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex">
|
||||
<router-view />
|
||||
<ChatNotifyToast v-if="showChatNotifyToast" />
|
||||
<!-- 复诊到期弹窗(右下角):与会话通知并列挂载,复用同一条件避免未绑企微时无意义轮询 -->
|
||||
<RevisitDueToast v-if="showChatNotifyToast" />
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -5,6 +5,14 @@ export function getConfig() {
|
||||
return request.get({ url: '/config/getConfig' })
|
||||
}
|
||||
|
||||
// 运行时读取医生网页面诊切换时间,与服务端拦截规则共用配置。
|
||||
export function getDoctorWebConsultationPolicy() {
|
||||
return request.get(
|
||||
{ url: '/config/doctorWebConsultation', params: { _t: Date.now() } },
|
||||
{ withToken: false, isOpenRetry: false }
|
||||
)
|
||||
}
|
||||
|
||||
// 工作台主页
|
||||
export function getWorkbench() {
|
||||
return request.get({ url: '/workbench/index' })
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 复诊到期弹窗(需求 4)接口:/adminapi/tcm.revisitDue/<action>
|
||||
* 契约见 docs/plans/assistant-revisit-reach-reminder-2026-10-12.md §3.3。
|
||||
* 写接口后端 show=1,成功提示由 utils/request 统一弹出,调用方不要重复 ElMessage。
|
||||
*/
|
||||
|
||||
/** 弹窗条目(RevisitDueLogic::formatItem) */
|
||||
export interface RevisitDueToastItem {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
assistant_id: number
|
||||
patient_name: string
|
||||
current_slot: number
|
||||
next_slot: number
|
||||
medication_days: number
|
||||
/** 'YYYY-MM-DD' 或 '' */
|
||||
due_date: string
|
||||
overdue_days: number | null
|
||||
/** overdue | missed(弹窗只含这两态) */
|
||||
state: string
|
||||
state_text: string
|
||||
severe: 0 | 1
|
||||
missed_count: number
|
||||
snooze_count: number
|
||||
/** 0~3,3 = 居中模态 */
|
||||
escalation_level: number
|
||||
contact_count: number
|
||||
promised_date: string
|
||||
next_remind_at: number
|
||||
next_remind_at_text: string
|
||||
/** 下一次点「延迟」会顺延的秒数(按钮文案用) */
|
||||
next_snooze_seconds: number
|
||||
appointment_date: string
|
||||
closed_state: number
|
||||
}
|
||||
|
||||
/** 汇总计数(RevisitDueLogic::buildSummary) */
|
||||
export interface RevisitDueToastSummary {
|
||||
enabled: boolean
|
||||
due_total: number
|
||||
max_overdue_days: number
|
||||
warning_total: number
|
||||
promise_max_days: number
|
||||
contact_max_per_cycle: number
|
||||
work_hours: [string, string]
|
||||
}
|
||||
|
||||
export interface RevisitDuePendingResult {
|
||||
items: RevisitDueToastItem[]
|
||||
summary: RevisitDueToastSummary
|
||||
}
|
||||
|
||||
/** 写接口返回处理后的当前行(幂等:被他人处理时也返回当前行) */
|
||||
export type RevisitDueWriteResult = RevisitDueToastItem
|
||||
|
||||
export interface RevisitDueSnoozeAllResult {
|
||||
items: RevisitDueToastItem[]
|
||||
snoozed: number
|
||||
skipped: number
|
||||
message: string
|
||||
}
|
||||
|
||||
/** 轮询接口不走统一 code 处理:权限不足 / 开关关闭时不要每分钟弹一次错误提示 */
|
||||
const POLL_OPTIONS = {
|
||||
isTransformResponse: false,
|
||||
ignoreCancelToken: true,
|
||||
isOpenRetry: false,
|
||||
retryCount: 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗待办(60s 轮询):本人到期未挂号 / 过号且已到提醒时刻的项,每次返回全集。
|
||||
* 非 code=1 一律 reject(调用方静默处理),避免轮询刷错误提示。
|
||||
*/
|
||||
export async function revisitDuePending(): Promise<RevisitDuePendingResult> {
|
||||
const res = await request.get({ url: '/tcm.revisitDue/pending' }, POLL_OPTIONS)
|
||||
if (res && typeof res === 'object' && Number(res.code) === 1) {
|
||||
return res.data as RevisitDuePendingResult
|
||||
}
|
||||
return Promise.reject(res?.msg ?? 'revisit due pending failed')
|
||||
}
|
||||
|
||||
/** 仅计数,不更新弹出时间 */
|
||||
export function revisitDueSummary(): Promise<RevisitDueToastSummary> {
|
||||
return request.get({ url: '/tcm.revisitDue/summary' })
|
||||
}
|
||||
|
||||
/** 延迟一次(幂等) */
|
||||
export function revisitDueSnooze(params: { id: number }): Promise<RevisitDueWriteResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/snooze', params })
|
||||
}
|
||||
|
||||
/** 批量延迟(仅 escalation_level<=1 的项) */
|
||||
export function revisitDueSnoozeAll(params: {
|
||||
ids: number[]
|
||||
}): Promise<RevisitDueSnoozeAllResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/snoozeAll', params })
|
||||
}
|
||||
|
||||
/** 已联系:记录患者承诺复诊日 */
|
||||
export function revisitDueContact(params: {
|
||||
id: number
|
||||
promised_date: string
|
||||
remark?: string
|
||||
}): Promise<RevisitDueWriteResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/contact', params })
|
||||
}
|
||||
|
||||
/** 人工关闭(reason lost|other,remark 必填 ≤200) */
|
||||
export function revisitDueClose(params: {
|
||||
id: number
|
||||
reason: 'lost' | 'other'
|
||||
remark: string
|
||||
}): Promise<RevisitDueWriteResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/close', params })
|
||||
}
|
||||
|
||||
/** 主管视图列表行(RevisitDueLists,按角色 data_scope 收窄) */
|
||||
export interface RevisitDueListRow {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
patient_name: string
|
||||
assistant_id: number
|
||||
assistant_name: string
|
||||
dept_name: string
|
||||
current_slot: number
|
||||
next_slot: number
|
||||
medication_days: number
|
||||
/** 14/21/28/30 或 0=其它 */
|
||||
rule_days: number
|
||||
anchor_date: string
|
||||
due_date: string
|
||||
overdue_days: number | null
|
||||
days_left: number | null
|
||||
state: string
|
||||
state_text: string
|
||||
severe: 0 | 1
|
||||
appointment_state: number
|
||||
appointment_date: string
|
||||
snooze_count: number
|
||||
escalation_level: number
|
||||
contact_count: number
|
||||
promised_date: string
|
||||
missed_count: number
|
||||
closed_state: number
|
||||
closed_state_text: string
|
||||
handle_reason: string
|
||||
handle_remark: string
|
||||
first_shown_at_text: string
|
||||
last_snoozed_at_text: string
|
||||
computed_at_text: string
|
||||
}
|
||||
|
||||
/** 主管视图筛选参数(state:due|warning|booked|visited|contacted|no_days|pending|closed;days_bucket:14|21|28|30|other) */
|
||||
export interface RevisitDueListsParams {
|
||||
assistant_id?: number | ''
|
||||
dept_id?: number | ''
|
||||
state?: string
|
||||
days_bucket?: string
|
||||
min_snooze?: number | ''
|
||||
keyword?: string
|
||||
page_no?: number
|
||||
page_size?: number
|
||||
/** 1 = 导出(export-data 组件追加) */
|
||||
export?: number
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/** 主管视图:复诊到期跟进分页列表(lists/count/page_no/page_size/extend 包络,供 usePaging / export-data 消费) */
|
||||
export function revisitDueLists(params: RevisitDueListsParams) {
|
||||
return request.get({ url: '/tcm.revisitDue/lists', params })
|
||||
}
|
||||
|
||||
/** 事件流水行(RevisitDueLogic::logs) */
|
||||
export interface RevisitDueLogRow {
|
||||
id: number
|
||||
/** 1 延迟 2 已联系 3 人工关闭 4 自动关闭-已挂号 5 自动关闭-已面诊 6 周期重置 7 重新打开 8 企微推送 9 医助变更 10 形态升级 11 首次弹出 */
|
||||
event: number
|
||||
event_text: string
|
||||
snooze_count_after: number
|
||||
level_after: number
|
||||
overdue_days: number
|
||||
/** payload JSON 解析后的对象(next_remind_at / promised_date / appointment_id / order_id / remark / from_assistant 等) */
|
||||
payload_arr: Record<string, any>
|
||||
operator_id: number
|
||||
operator_name: string
|
||||
create_time_text: string
|
||||
}
|
||||
|
||||
/** 主管视图:某条提醒的事件流水(按 due_id,时间倒序由后端决定) */
|
||||
export function revisitDueLogs(params: { due_id: number }) {
|
||||
return request.get({ url: '/tcm.revisitDue/logs', params })
|
||||
}
|
||||
@@ -24,6 +24,24 @@ export type DesktopWorkstationConfig = {
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopWorkstationDownload = DesktopPackage & {
|
||||
platform: 'windows_x64' | 'macos_arm64' | 'macos_x64'
|
||||
label: string
|
||||
}
|
||||
|
||||
export type DesktopWorkstationDownloads = {
|
||||
version: string
|
||||
packages: DesktopWorkstationDownload[]
|
||||
}
|
||||
|
||||
// 仅返回已发布的安装包,不要求医生拥有系统设置权限。
|
||||
export function getDesktopWorkstationDownloads() {
|
||||
return request.get(
|
||||
{ url: '/setting.desktop_workstation/downloads' },
|
||||
{ withToken: false }
|
||||
) as Promise<DesktopWorkstationDownloads>
|
||||
}
|
||||
|
||||
export function getDesktopWorkstationConfig() {
|
||||
return request.get({
|
||||
url: '/setting.desktop_workstation/getConfig'
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export interface PrescriptionAiVisibilityConfig {
|
||||
role_ids: number[]
|
||||
admin_ids: number[]
|
||||
}
|
||||
|
||||
export interface PrescriptionAiVisibilityOptions {
|
||||
roles: { id: number; name: string }[]
|
||||
admins: { id: number; name: string; account: string }[]
|
||||
}
|
||||
|
||||
export interface PrescriptionAiCapabilities {
|
||||
agreement_visible: boolean
|
||||
can_manage_visibility: boolean
|
||||
}
|
||||
|
||||
// A failed or malformed read must never become an empty policy that can be saved.
|
||||
function readVisibilityConfig(value: unknown): PrescriptionAiVisibilityConfig {
|
||||
const config = value as Partial<PrescriptionAiVisibilityConfig> | null
|
||||
const validIds = (ids: unknown): ids is number[] =>
|
||||
Array.isArray(ids) && ids.every((id) => Number.isSafeInteger(id) && id > 0)
|
||||
if (!config || !validIds(config.role_ids) || !validIds(config.admin_ids)) {
|
||||
throw new Error('可见范围配置响应格式不正确')
|
||||
}
|
||||
return { role_ids: [...config.role_ids], admin_ids: [...config.admin_ids] }
|
||||
}
|
||||
|
||||
export async function getPrescriptionAiVisibilityConfig() {
|
||||
const data = await request.get({ url: '/tcm.prescriptionAi/getVisibilityConfig' })
|
||||
return readVisibilityConfig(data)
|
||||
}
|
||||
|
||||
export async function setPrescriptionAiVisibilityConfig(params: PrescriptionAiVisibilityConfig) {
|
||||
const data = await request.post({ url: '/tcm.prescriptionAi/setVisibilityConfig', params })
|
||||
return readVisibilityConfig(data)
|
||||
}
|
||||
|
||||
export function getPrescriptionAiVisibilityOptions() {
|
||||
return request.get({
|
||||
url: '/tcm.prescriptionAi/visibilityOptions'
|
||||
}) as Promise<PrescriptionAiVisibilityOptions>
|
||||
}
|
||||
|
||||
export function getPrescriptionAiCapabilities() {
|
||||
return request.get({
|
||||
url: '/tcm.prescriptionAi/capabilities'
|
||||
}) as Promise<PrescriptionAiCapabilities>
|
||||
}
|
||||
+88
-4
@@ -204,8 +204,26 @@ export function commissionSettlementConfirmRevoke(params: Record<string, any>) {
|
||||
return request.post({ url: '/stats.commissionSettlement/confirmRevoke', params })
|
||||
}
|
||||
|
||||
/** 复诊接诊率(按月):当月 N 诊接诊率,部门 → 医助分组 + 合计;剔除「继承」指派 */
|
||||
export function revisitRateOverview(params: { month?: string; dept_ids?: string }) {
|
||||
/**
|
||||
* 复诊接诊率口径:
|
||||
* - slot(默认,后端 config project.revisit_rate.default_inherit_mode):继承按继承时诊次计入每列独立分母(visit{N}_den = 新指派数 + 起算诊次 ≤ N 的继承数)
|
||||
* - exclude:继承不计分母(旧口径,assigned_count / visit{N}_count / visit{N}_rate 与 2026-10 前一致)
|
||||
*/
|
||||
export type RevisitRateInheritMode = 'exclude' | 'slot'
|
||||
|
||||
/** 被指派明细行类型:new 新指派 / inherit 继承 / all 两者(默认) */
|
||||
export type RevisitRateAssignKind = 'new' | 'inherit' | 'all'
|
||||
|
||||
/**
|
||||
* 复诊接诊率(按月):部门 → 医助分组 + 合计。
|
||||
* 返回 inherit_mode、slots,行含 assigned_count(新指派)、inherit_count、assigned_total_count、
|
||||
* visit{N}_count/_den/_rate、visit_all_count/_den/_rate、visit2_rate_new_assign(旧口径二诊率)
|
||||
*/
|
||||
export function revisitRateOverview(params: {
|
||||
month?: string
|
||||
dept_ids?: string
|
||||
inherit_mode?: RevisitRateInheritMode
|
||||
}) {
|
||||
return request.get({ url: '/stats.revisitRate/overview', params })
|
||||
}
|
||||
|
||||
@@ -214,23 +232,29 @@ export function revisitRateDeptOptions() {
|
||||
return request.get({ url: '/stats.revisitRate/deptOptions' })
|
||||
}
|
||||
|
||||
/** 复诊接诊率:「被指派数」点击下钻(按诊单聚合明细) */
|
||||
/**
|
||||
* 复诊接诊率:「新指派数 / 继承数 / 被指派合计」点击下钻(按诊单聚合明细)。
|
||||
* 行含 assign_type(new|inherit)、inherit_visit_slot(继承时诊次 k)、entry_slot(起算诊次)
|
||||
*/
|
||||
export function revisitRateAssignLines(params: {
|
||||
month?: string
|
||||
dept_ids?: string
|
||||
assistant_id?: number
|
||||
dept_id?: number
|
||||
inherit_mode?: RevisitRateInheritMode
|
||||
kind?: RevisitRateAssignKind
|
||||
}) {
|
||||
return request.get({ url: '/stats.revisitRate/assignLines', params })
|
||||
}
|
||||
|
||||
/** 复诊接诊率:「N 诊单数」点击下钻(具体订单明细) */
|
||||
/** 复诊接诊率:「N 诊单数」点击下钻(具体订单明细);slot=0 为全部 N≥2(复诊合计单数),行含 visit_slot */
|
||||
export function revisitRateVisitOrderLines(params: {
|
||||
month?: string
|
||||
slot: number
|
||||
dept_ids?: string
|
||||
assistant_id?: number
|
||||
dept_id?: number
|
||||
inherit_mode?: RevisitRateInheritMode
|
||||
}) {
|
||||
return request.get({ url: '/stats.revisitRate/visitOrderLines', params })
|
||||
}
|
||||
@@ -253,3 +277,63 @@ export function assistantPerformanceOverview(params: {
|
||||
}) {
|
||||
return request.get({ url: '/stats.assistantPerformance/overview', params })
|
||||
}
|
||||
|
||||
/** 「我的复诊接诊率」卡片返回(RevisitRateLogic::assistantOverview,仅本人行) */
|
||||
export interface AssistantRevisitRateResult {
|
||||
month: string
|
||||
inherit_mode: RevisitRateInheritMode
|
||||
/** 诊次列范围(2~N) */
|
||||
slots: number[]
|
||||
/** false = 本人不属于二中心子树(复诊接诊率仅统计二中心医助) */
|
||||
in_scope: boolean
|
||||
/** 本人行:assigned_count / inherit_count / assigned_total_count / visit{N}_count|_den|_rate / visit_all_*;无数据为 null */
|
||||
row: Record<string, any> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 医助个人业绩:我的复诊接诊率(按月,仅本人行;口径与复诊接诊率页一致,
|
||||
* 继承患者按继承时诊次从第 k+1 诊起计入分母)
|
||||
*/
|
||||
export function assistantPerformanceRevisitRate(params: {
|
||||
month?: string
|
||||
}): Promise<AssistantRevisitRateResult> {
|
||||
return request.get({ url: '/stats.assistantPerformance/revisitRate', params })
|
||||
}
|
||||
|
||||
|
||||
/** 独立指派周期统计,与原 revisitRate 按月报表分别调用。 */
|
||||
export type RevisitRateCohortType = 'new' | 'inherit'
|
||||
|
||||
export interface RevisitRateQuery {
|
||||
start_date: string
|
||||
end_date: string
|
||||
dept_ids?: string
|
||||
assistant_id?: number
|
||||
}
|
||||
|
||||
export interface RevisitRateDetailQuery extends RevisitRateQuery {
|
||||
scope_assistant_id?: number
|
||||
dept_id?: number
|
||||
}
|
||||
|
||||
const revisitCohortPrefix = (cohortType: RevisitRateCohortType) =>
|
||||
cohortType === 'inherit' ? '/stats.revisitInheritRate' : '/stats.revisitAssignRate'
|
||||
|
||||
export function revisitCohortOverview(params: RevisitRateQuery, cohortType: RevisitRateCohortType) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/overview`, params })
|
||||
}
|
||||
|
||||
export function revisitCohortDeptOptions(cohortType: RevisitRateCohortType) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/deptOptions` })
|
||||
}
|
||||
|
||||
export function revisitCohortAssignLines(params: RevisitRateDetailQuery, cohortType: RevisitRateCohortType) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/assignLines`, params })
|
||||
}
|
||||
|
||||
export function revisitCohortVisitOrderLines(
|
||||
params: RevisitRateDetailQuery & { slot: number },
|
||||
cohortType: RevisitRateCohortType
|
||||
) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/visitOrderLines`, params })
|
||||
}
|
||||
|
||||
@@ -227,6 +227,29 @@ export function getCallRecords(params: any) {
|
||||
return request.get({ url: '/tcm.diagnosis/getCallRecords', params })
|
||||
}
|
||||
|
||||
export interface ConsultationCallRecord {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
call_type?: number
|
||||
status?: number
|
||||
start_time?: number
|
||||
start_time_text?: string
|
||||
end_time_text?: string
|
||||
duration_text?: string
|
||||
transcript_text?: string | null
|
||||
transcription_status?: string
|
||||
transcription_status_text?: string
|
||||
transcription_segment_count?: number
|
||||
}
|
||||
|
||||
/** 按诊单读取每次面诊已保存的文字;不触发语音识别或转写写入。 */
|
||||
export function getConsultationTranscripts(params: { diagnosis_id: number }, signal?: AbortSignal) {
|
||||
return request.get<ConsultationCallRecord[]>(
|
||||
{ url: '/tcm.diagnosis/getCallRecords', params, signal },
|
||||
{ ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
// 将 TRTC 房间号写入通话记录(与云端录制回调 room 关联)
|
||||
export function bindCallRoom(params: { diagnosis_id: number; room_id: string }) {
|
||||
return request.post({ url: '/tcm.diagnosis/bindCallRoom', params })
|
||||
@@ -490,8 +513,10 @@ export function prescriptionOrderPatchPrescriptionUsage(params: {
|
||||
times_per_day: number
|
||||
usage_days: number
|
||||
medication_days: number
|
||||
dosage_bag_count?: number
|
||||
aux_times_per_day?: number
|
||||
aux_usage_days?: number
|
||||
aux_dosage_bag_count?: number
|
||||
}) {
|
||||
return request.post({ url: '/tcm.prescriptionOrder/patchPrescriptionUsage', params })
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<DoctorWebConsultationNotice v-if="!isMinimized" />
|
||||
<div v-show="!isMinimized" class="chat-container">
|
||||
<div v-if="!isReady" class="loading-container">
|
||||
<el-icon class="is-loading"><Loading /></el-icon>
|
||||
@@ -131,6 +132,8 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick, watch, computed, onMounted, onUnmounted } from 'vue'
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { Loading, Close, Rank, Camera, Fold, Expand } from '@element-plus/icons-vue'
|
||||
import { uploadImageBlob, uploadVideoBlob } from '@/api/file'
|
||||
import { addDoctorNote } from '@/api/patient'
|
||||
@@ -195,8 +198,9 @@ const appointmentTypeLabel = computed(() => confirmedTypeLabel.value || appointm
|
||||
const serverAllowsVideo = ref(false)
|
||||
const serverAllowsAudio = ref(false)
|
||||
const callDisabledReason = ref('正在确认挂号类型')
|
||||
const canVideoCall = computed(() => serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
|
||||
const canAudioCall = computed(() => serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
|
||||
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
|
||||
const canVideoCall = computed(() => !webConsultationBlocked.value && serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
|
||||
const canAudioCall = computed(() => !webConsultationBlocked.value && serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
|
||||
let releaseAppointmentCallGuard: (() => void) | undefined
|
||||
let chatContextVersion = 0
|
||||
let outgoingCallType = 2
|
||||
@@ -253,6 +257,7 @@ function syncAppointmentCallPolicy(res: {
|
||||
}
|
||||
|
||||
async function prepareAppointmentCall(callType: number) {
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
const contextVersion = chatContextVersion
|
||||
const allowed = () => callType === 1 ? canAudioCall.value : canVideoCall.value
|
||||
if (!visible.value || !allowed()) {
|
||||
@@ -266,6 +271,7 @@ async function prepareAppointmentCall(callType: number) {
|
||||
})
|
||||
if (!visible.value || chatContextVersion !== contextVersion) throw new Error('当前问诊已切换,请重新发起通话')
|
||||
syncAppointmentCallPolicy(res)
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
if (!allowed()) {
|
||||
feedback.msgWarning(callDisabledReason.value)
|
||||
throw new Error(callDisabledReason.value)
|
||||
@@ -713,6 +719,14 @@ function installTUICallKitRoomHooks() {
|
||||
wrap('calls')
|
||||
wrap('call')
|
||||
wrap('groupCall')
|
||||
// 已登录 SDK 的旧聊天窗口也不能在截止后接起新面诊。
|
||||
const originalAccept = server.accept
|
||||
if (typeof originalAccept === 'function') {
|
||||
server.accept = async function patchedAccept(...args: unknown[]) {
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
return originalAccept.apply(server, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function doBindCallRoom(rid: string) {
|
||||
@@ -1099,6 +1113,7 @@ watch(() => activeConversation.value, async (newConversation) => {
|
||||
})
|
||||
|
||||
const open = async (data: { patientId: number; patientName: string; diagnosisId?: number; appointmentId?: number; appointmentType?: string | null }) => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
stopChatArchiveWatch(true)
|
||||
const contextVersion = ++chatContextVersion
|
||||
releaseAppointmentCallGuard?.()
|
||||
@@ -1260,6 +1275,7 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
|
||||
|
||||
// 群组视频通话(多人通话):当前医生作为发起方,默认先邀请当前会话患者
|
||||
const startGroupVideoCall = async () => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
if (!canVideoCall.value) {
|
||||
feedback.msgWarning(appointmentType.value === 'text' ? '图文问诊不支持视频通话' : callDisabledReason.value)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<template>
|
||||
<el-alert
|
||||
class="doctor-web-consultation-notice"
|
||||
:type="consultationReminder.type"
|
||||
:closable="false"
|
||||
show-icon
|
||||
:title="consultationReminder.title"
|
||||
>
|
||||
<p>{{ consultationReminder.description }}</p>
|
||||
<p v-if="policyLoadFailed">
|
||||
面诊切换时间更新失败,请重新获取最新设置。
|
||||
<el-button link type="primary" @click="refreshConsultationPolicy()">刷新切换时间</el-button>
|
||||
</p>
|
||||
<p v-if="consultationReminder.countdown" class="notice-countdown">
|
||||
距网页端面诊停用还有 {{ consultationReminder.countdown }}(北京时间)
|
||||
</p>
|
||||
<div class="notice-downloads">
|
||||
<a
|
||||
v-for="item in downloads.packages"
|
||||
:key="item.platform"
|
||||
class="installer-link"
|
||||
:href="item.url"
|
||||
:download="item.filename || undefined"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<el-icon><Download /></el-icon>
|
||||
下载 {{ item.label }}安装包
|
||||
</a>
|
||||
<span v-if="downloadsLoading && !downloads.packages.length">正在获取安装包…</span>
|
||||
<template v-else-if="!downloads.packages.length">
|
||||
<span>{{ downloadsFailed ? '安装包加载失败,请重试。' : '安装包暂未发布,请联系管理员获取。' }}</span>
|
||||
<el-button link type="primary" @click="loadDownloads(true)">重新获取</el-button>
|
||||
</template>
|
||||
<el-button v-else-if="downloadsFailed" link type="primary" @click="loadDownloads(true)">刷新安装包</el-button>
|
||||
</div>
|
||||
<p v-if="downloads.packages.length" class="install-instructions">
|
||||
<span v-if="downloads.version">当前版本 v{{ downloads.version }} · </span>
|
||||
安装完成后,使用当前医生账号登录桌面应用。
|
||||
</p>
|
||||
<p v-if="hasWindowsInstaller" class="install-instructions">
|
||||
Windows 安装包适用于 Windows 10 1809 及以上版本、Windows 11(64位)。
|
||||
</p>
|
||||
</el-alert>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { useDesktopWorkstationDownloads } from '@/hooks/useDesktopWorkstationDownloads'
|
||||
import { Download } from '@element-plus/icons-vue'
|
||||
import { computed, watch } from 'vue'
|
||||
|
||||
const { consultationReminder, policyLoadFailed, refreshConsultationPolicy } = useDoctorWebConsultation()
|
||||
const { downloads, downloadsLoading, downloadsFailed, loadDownloads } = useDesktopWorkstationDownloads()
|
||||
const hasWindowsInstaller = computed(() => downloads.value.packages.some(item => item.platform === 'windows_x64'))
|
||||
watch(() => consultationReminder.value.phase, () => { void loadDownloads(true) })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.doctor-web-consultation-notice {
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.doctor-web-consultation-notice p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.notice-countdown {
|
||||
font-weight: 600;
|
||||
}
|
||||
.notice-downloads {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.installer-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
background: #2563eb;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
text-decoration: none;
|
||||
}
|
||||
.installer-link:hover {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
.installer-link:focus-visible {
|
||||
outline: 2px solid #1d4ed8;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.doctor-web-consultation-notice .install-instructions {
|
||||
margin-top: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { getConsultationTranscripts, type ConsultationCallRecord } from '@/api/tcm'
|
||||
import { normalizeConsultationRecords } from '@/utils/consultation-transcripts'
|
||||
|
||||
export function useConsultationTranscripts(diagnosisId: () => number) {
|
||||
const records = ref<ConsultationCallRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let sequence = 0
|
||||
let controller: AbortController | undefined
|
||||
|
||||
const refresh = async () => {
|
||||
const id = Number(diagnosisId())
|
||||
const request = ++sequence
|
||||
controller?.abort()
|
||||
error.value = ''
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
records.value = []
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
controller = new AbortController()
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await getConsultationTranscripts({ diagnosis_id: id }, controller.signal)
|
||||
if (request !== sequence || Number(diagnosisId()) !== id) return
|
||||
records.value = normalizeConsultationRecords(result, id)
|
||||
} catch (reason: any) {
|
||||
if (request !== sequence || Number(diagnosisId()) !== id) return
|
||||
error.value = String(reason?.msg || reason?.message || '面诊文字对话加载失败,请重试')
|
||||
} finally {
|
||||
if (request === sequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(diagnosisId, () => {
|
||||
records.value = []
|
||||
void refresh()
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
sequence++
|
||||
controller?.abort()
|
||||
records.value = []
|
||||
})
|
||||
return { records, loading, error, refresh }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { onMounted, onUnmounted, ref, shallowRef } from 'vue'
|
||||
import {
|
||||
getDesktopWorkstationDownloads,
|
||||
type DesktopWorkstationDownload,
|
||||
type DesktopWorkstationDownloads
|
||||
} from '@/api/setting/desktop_workstation'
|
||||
|
||||
// 接诊台、列表和聊天窗口共用一个请求与短缓存。
|
||||
const downloads = shallowRef<DesktopWorkstationDownloads>({ version: '', packages: [] })
|
||||
const downloadsLoading = ref(false)
|
||||
const downloadsFailed = ref(false)
|
||||
let pending: Promise<void> | undefined
|
||||
let loadedAt = 0
|
||||
const CACHE_MS = 5 * 60 * 1000
|
||||
|
||||
export function normalizeDesktopDownloads(value: DesktopWorkstationDownloads): DesktopWorkstationDownloads {
|
||||
const platforms = ['windows_x64', 'macos_arm64', 'macos_x64']
|
||||
const packages: DesktopWorkstationDownload[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of Array.isArray(value?.packages) ? value.packages : []) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if (!platforms.includes(item.platform) || seen.has(item.platform)) continue
|
||||
try {
|
||||
const url = new URL(item.url)
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) continue
|
||||
if (!/^[a-f\d]{64}$/i.test(item.sha256)) continue
|
||||
packages.push({ ...item, url: url.href })
|
||||
seen.add(item.platform)
|
||||
} catch { /* 配置异常时不生成无效下载链接。 */ }
|
||||
}
|
||||
return { version: String(value?.version || ''), packages }
|
||||
}
|
||||
|
||||
export function useDesktopWorkstationDownloads() {
|
||||
const loadDownloads = (force = false): Promise<void> => {
|
||||
if (pending) return pending
|
||||
if (!force && loadedAt > 0 && Date.now() - loadedAt < CACHE_MS) return Promise.resolve()
|
||||
downloadsLoading.value = true
|
||||
downloadsFailed.value = false
|
||||
pending = getDesktopWorkstationDownloads().then(data => {
|
||||
downloads.value = normalizeDesktopDownloads(data)
|
||||
loadedAt = Date.now()
|
||||
}).catch(() => {
|
||||
downloadsFailed.value = true
|
||||
}).finally(() => {
|
||||
downloadsLoading.value = false
|
||||
pending = undefined
|
||||
})
|
||||
return pending
|
||||
}
|
||||
const refreshOnFocus = () => { void loadDownloads() }
|
||||
onMounted(() => {
|
||||
void loadDownloads()
|
||||
window.addEventListener('focus', refreshOnFocus)
|
||||
})
|
||||
onUnmounted(() => window.removeEventListener('focus', refreshOnFocus))
|
||||
|
||||
return { downloads, downloadsLoading, downloadsFailed, loadDownloads }
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { getDoctorWebConsultationPolicy } from '@/api/app'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import feedback from '@/utils/feedback'
|
||||
import {
|
||||
doctorWebConsultationMessage,
|
||||
doctorWebConsultationReminder,
|
||||
hasDoctorWebConsultationExpired,
|
||||
isConsultationDoctor,
|
||||
isDoctorWebConsultationBlocked,
|
||||
normalizeDoctorWebConsultationPolicy
|
||||
} from '@/utils/doctor-web-consultation'
|
||||
|
||||
// 多个列表、公告及聊天窗口共用请求;配置更新无需重新构建前端。
|
||||
let pending: Promise<void> | undefined
|
||||
let lastAttemptAt = 0
|
||||
const REFRESH_MS = 60 * 1000
|
||||
const policyLoadFailed = ref(false)
|
||||
|
||||
export function useDoctorWebConsultation() {
|
||||
const userStore = useUserStore()
|
||||
const now = ref(Date.now())
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
const updateClock = () => { now.value = Date.now() + (userStore.serverTimeOffsetMs || 0) }
|
||||
const policy = computed(() => normalizeDoctorWebConsultationPolicy(userStore.userInfo.web_consultation_policy))
|
||||
|
||||
const loadPolicy = (force = false): Promise<void> => {
|
||||
if (pending) return pending
|
||||
if (!force && lastAttemptAt > 0 && Date.now() - lastAttemptAt < REFRESH_MS) return Promise.resolve()
|
||||
lastAttemptAt = Date.now()
|
||||
pending = getDoctorWebConsultationPolicy().then(data => {
|
||||
const next = normalizeDoctorWebConsultationPolicy(data)
|
||||
if (!next) throw new Error('网页面诊时间配置无效')
|
||||
userStore.userInfo.web_consultation_policy = next
|
||||
userStore.serverTimeOffsetMs = next.server_time * 1000 - Date.now()
|
||||
policyLoadFailed.value = false
|
||||
updateClock()
|
||||
}).catch(() => {
|
||||
// 保留最近一次有效配置,后端仍逐次校验实际截止时间。
|
||||
policyLoadFailed.value = true
|
||||
}).finally(() => { pending = undefined })
|
||||
return pending
|
||||
}
|
||||
const refreshConsultationPolicy = () => loadPolicy(true)
|
||||
const refreshOnFocus = () => {
|
||||
updateClock()
|
||||
void refreshConsultationPolicy()
|
||||
}
|
||||
const refreshOnVisible = () => {
|
||||
if (document.visibilityState !== 'hidden') refreshOnFocus()
|
||||
}
|
||||
|
||||
// 登录响应和配置刷新响应均提供服务器时刻,避免本机时区/时钟影响规则。
|
||||
watch(() => userStore.serverTimeOffsetMs, updateClock, { immediate: true })
|
||||
|
||||
onMounted(() => {
|
||||
updateClock()
|
||||
void refreshConsultationPolicy()
|
||||
timer = setInterval(() => {
|
||||
updateClock()
|
||||
void loadPolicy()
|
||||
}, 1000)
|
||||
window.addEventListener('focus', refreshOnFocus)
|
||||
document.addEventListener('visibilitychange', refreshOnVisible)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer)
|
||||
window.removeEventListener('focus', refreshOnFocus)
|
||||
document.removeEventListener('visibilitychange', refreshOnVisible)
|
||||
})
|
||||
|
||||
const isDoctor = computed(() => isConsultationDoctor(userStore.userInfo))
|
||||
const webConsultationExpired = computed(() => hasDoctorWebConsultationExpired(policy.value, now.value))
|
||||
const consultationReminder = computed(() => doctorWebConsultationReminder(policy.value, now.value))
|
||||
const webConsultationMessage = computed(() => doctorWebConsultationMessage(policy.value))
|
||||
const webConsultationBlocked = computed(() => isDoctorWebConsultationBlocked(userStore.userInfo, policy.value, now.value))
|
||||
const ensureWebConsultationAllowed = () => {
|
||||
updateClock()
|
||||
if (!webConsultationBlocked.value) return true
|
||||
feedback.msgWarning(webConsultationMessage.value)
|
||||
return false
|
||||
}
|
||||
|
||||
return {
|
||||
isDoctor, consultationReminder, webConsultationExpired, webConsultationBlocked,
|
||||
webConsultationMessage, ensureWebConsultationAllowed, policyLoadFailed, refreshConsultationPolicy
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ConsultationCallRecord } from '@/api/tcm'
|
||||
|
||||
export function normalizeConsultationRecords(value: unknown, diagnosisId: number): ConsultationCallRecord[] {
|
||||
if (!Array.isArray(value)) throw new Error('面诊记录返回格式异常,请重试')
|
||||
const seen = new Set<number>()
|
||||
return value.filter(row => {
|
||||
if (!row || !Number.isSafeInteger(Number(row.id)) || Number(row.id) <= 0 || seen.has(Number(row.id))) return false
|
||||
if (row.diagnosis_id != null && Number(row.diagnosis_id) !== diagnosisId) return false
|
||||
seen.add(Number(row.id))
|
||||
return true
|
||||
}).map(row => ({
|
||||
...row,
|
||||
id: Number(row.id),
|
||||
diagnosis_id: diagnosisId,
|
||||
transcript_text: typeof row.transcript_text === 'string' ? row.transcript_text.replace(/\r\n/g, '\n').trim() : ''
|
||||
})).sort((a, b) => b.id - a.id)
|
||||
}
|
||||
|
||||
export function consultationTranscriptText(row?: ConsultationCallRecord | null): string {
|
||||
return typeof row?.transcript_text === 'string' ? row.transcript_text.trim() : ''
|
||||
}
|
||||
|
||||
export function consultationTranscriptStatus(row: ConsultationCallRecord) {
|
||||
switch (row.transcription_status) {
|
||||
case 'running': return { label: '录音转写中', type: 'info' as const }
|
||||
case 'completed': return { label: '文字已生成', type: 'success' as const }
|
||||
case 'partial': return { label: '文字部分保存', type: 'warning' as const }
|
||||
case 'failed': return { label: '文字生成失败', type: 'danger' as const }
|
||||
default: return consultationTranscriptText(row)
|
||||
? { label: '文字已保存', type: 'success' as const }
|
||||
: { label: '未生成文字', type: 'info' as const }
|
||||
}
|
||||
}
|
||||
|
||||
export function consultationTranscriptEmptyText(row: ConsultationCallRecord): string {
|
||||
if (row.transcription_status === 'running') return '正在转写,可点击刷新查看最新保存的文字。'
|
||||
if (row.transcription_status === 'failed') return '本次面诊文字生成失败,暂无已保存的对话。'
|
||||
if (Number(row.status) === 3) return '本次通话未接听,暂无文字对话。'
|
||||
if (Number(row.status) === 4) return '本次通话已取消,暂无文字对话。'
|
||||
return '本次面诊暂无已保存的文字对话。'
|
||||
}
|
||||
|
||||
export function consultationCallLabel(row: ConsultationCallRecord): string {
|
||||
return Number(row.call_type) === 1 ? '语音面诊' : Number(row.call_type) === 2 ? '视频面诊' : '面诊记录'
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// 所有时间由服务端配置提供,浏览器不保留独立的截止日期。
|
||||
export type DoctorWebConsultationPolicy = {
|
||||
cutoff_at: string
|
||||
approaching_at: string
|
||||
urgent_at: string
|
||||
server_time: number
|
||||
}
|
||||
|
||||
export type DoctorWebConsultationPhase = 'prepare' | 'approaching' | 'last_day' | 'expired'
|
||||
|
||||
export function normalizeDoctorWebConsultationPolicy(value: unknown): DoctorWebConsultationPolicy | undefined {
|
||||
if (!value || typeof value !== 'object') return undefined
|
||||
const policy = value as DoctorWebConsultationPolicy
|
||||
const timestamps = [policy.approaching_at, policy.urgent_at, policy.cutoff_at].map(date =>
|
||||
typeof date === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(date) ? Date.parse(date) : NaN
|
||||
)
|
||||
if (timestamps.some(time => !Number.isFinite(time)) || timestamps[0] > timestamps[1] || timestamps[1] > timestamps[2]) return undefined
|
||||
if (!Number.isFinite(policy.server_time) || policy.server_time <= 0) return undefined
|
||||
return { cutoff_at: policy.cutoff_at, approaching_at: policy.approaching_at, urgent_at: policy.urgent_at, server_time: policy.server_time }
|
||||
}
|
||||
|
||||
export function doctorWebConsultationDate(policy: DoctorWebConsultationPolicy): string {
|
||||
// 无论医生电脑所在时区为何,公告始终显示北京时间。
|
||||
const parts = new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23'
|
||||
}).formatToParts(new Date(policy.cutoff_at))
|
||||
const part = (type: string) => parts.find(item => item.type === type)?.value || ''
|
||||
const seconds = part('second') === '00' ? '' : `:${part('second')}`
|
||||
return `${part('year')}年${part('month')}月${part('day')}日${part('hour')}:${part('minute')}${seconds}(北京时间)`
|
||||
}
|
||||
|
||||
export function doctorWebConsultationMessage(policy?: DoctorWebConsultationPolicy): string {
|
||||
return `网页端面诊已${policy ? `于${doctorWebConsultationDate(policy)}` : ''}停用,请医生使用桌面应用进行面诊。`
|
||||
}
|
||||
|
||||
export function doctorWebConsultationReminder(policy?: DoctorWebConsultationPolicy, now = Date.now()) {
|
||||
if (!policy) return {
|
||||
phase: 'prepare' as DoctorWebConsultationPhase,
|
||||
type: 'info' as const,
|
||||
title: '系统公告:医生桌面应用安装指引',
|
||||
description: '请各位医生提前下载并安装桌面应用,使用当前医生账号登录。',
|
||||
countdown: ''
|
||||
}
|
||||
const cutoffDate = doctorWebConsultationDate(policy)
|
||||
const remaining = Date.parse(policy.cutoff_at) - now
|
||||
const days = Math.floor(remaining / 86400000)
|
||||
const hours = Math.floor(remaining / 3600000) % 24
|
||||
const minutes = Math.floor(remaining / 60000) % 60
|
||||
const countdown = remaining <= 0 ? '' : remaining < 60000 ? '不足1分钟' :
|
||||
`${days > 0 ? `${days}天` : ''}${hours > 0 ? `${hours}小时` : ''}${minutes > 0 ? `${minutes}分钟` : ''}`
|
||||
|
||||
if (remaining <= 0) return {
|
||||
phase: 'expired' as DoctorWebConsultationPhase,
|
||||
type: 'error' as const,
|
||||
title: '系统公告:医生网页端面诊已停用',
|
||||
description: doctorWebConsultationMessage(policy),
|
||||
countdown: ''
|
||||
}
|
||||
if (now >= Date.parse(policy.urgent_at)) return {
|
||||
phase: 'last_day' as DoctorWebConsultationPhase,
|
||||
type: 'error' as const,
|
||||
title: '系统公告:医生网页端面诊停用最后提醒',
|
||||
description: `请各位医生在${cutoffDate}前完成桌面应用的安装与登录。届时接诊台、问诊列表的网页端面诊功能将同步停用,请使用桌面应用进行面诊。`,
|
||||
countdown
|
||||
}
|
||||
if (now >= Date.parse(policy.approaching_at)) return {
|
||||
phase: 'approaching' as DoctorWebConsultationPhase,
|
||||
type: 'warning' as const,
|
||||
title: '系统公告:医生网页端面诊即将停用',
|
||||
description: `网页端面诊将于${cutoffDate}停用。请各位医生尽快下载桌面应用,完成安装并使用当前医生账号登录,接诊台、问诊列表将同步执行此规则。`,
|
||||
countdown
|
||||
}
|
||||
return {
|
||||
phase: 'prepare' as DoctorWebConsultationPhase,
|
||||
type: 'info' as const,
|
||||
title: '系统公告:请提前安装医生桌面应用',
|
||||
description: `请各位医生提前下载并安装桌面应用,使用当前医生账号登录试用。自${cutoffDate}起,接诊台、问诊列表的网页端面诊功能将停用,请提前做好准备。`,
|
||||
countdown: ''
|
||||
}
|
||||
}
|
||||
|
||||
export function isConsultationDoctor(user: Record<string, any>): boolean {
|
||||
return Number(user.root) !== 1 && Array.isArray(user.role_ids) && user.role_ids.some(role => Number(role) === 1)
|
||||
}
|
||||
|
||||
export function hasDoctorWebConsultationExpired(policy?: DoctorWebConsultationPolicy, now = Date.now()): boolean {
|
||||
return !!policy && now >= Date.parse(policy.cutoff_at)
|
||||
}
|
||||
|
||||
export function isDoctorWebConsultationBlocked(
|
||||
user: Record<string, any>,
|
||||
policy?: DoctorWebConsultationPolicy,
|
||||
now = Date.now()
|
||||
): boolean {
|
||||
return isConsultationDoctor(user) && hasDoctorWebConsultationExpired(policy, now)
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
/**
|
||||
* 复诊节点(revisit_due)前端纯函数集合
|
||||
*
|
||||
* 数据契约与后端 `RevisitDueService::buildListPayload` 输出一致(方案 docs/plans/assistant-revisit-reach-reminder-2026-10-12.md 契约 C):
|
||||
* 所有日期为 'Y-m-d' 字符串或 '';无快照且无法计算时后端返回 state='none' 的对象,前端显示「—」。
|
||||
*
|
||||
* 本文件只做 state → 文案 / 颜色 class / el-tag type 的映射与日期、天数文案拼装,不含任何请求或响应式逻辑,
|
||||
* 供 PC 列表、H5 卡片、只读页三处共用(RevisitNodeCell.vue + readonly.vue)。
|
||||
*/
|
||||
|
||||
export type RevisitDueState =
|
||||
| 'visited'
|
||||
| 'booked'
|
||||
| 'missed'
|
||||
| 'contacted'
|
||||
| 'overdue'
|
||||
| 'warning'
|
||||
| 'pending'
|
||||
| 'no_days'
|
||||
| 'none'
|
||||
|
||||
/** 列表行 `revisit_due` 对象(契约 C) */
|
||||
export interface RevisitDue {
|
||||
current_slot: number
|
||||
next_slot: number
|
||||
valid_order_count: number
|
||||
medication_days: number
|
||||
/** 0=缺失 1=订单 2=处方 */
|
||||
days_src: 0 | 1 | 2
|
||||
/** 14/21/28/30 或 0=其它 */
|
||||
rule_days: number
|
||||
/** 0=无 1=签收 2=发货 3=下单 */
|
||||
anchor_src: 0 | 1 | 2 | 3
|
||||
anchor_date: string
|
||||
order_date: string
|
||||
due_date: string
|
||||
days_left: number | null
|
||||
overdue_days: number | null
|
||||
state: RevisitDueState | string
|
||||
state_text: string
|
||||
severe: 0 | 1
|
||||
/** 0=无 1=已约 3=已面诊 4=过号 */
|
||||
appointment_state: number
|
||||
appointment_date: string
|
||||
snooze_count: number
|
||||
escalation_level: number
|
||||
promised_date: string
|
||||
missed_count: number
|
||||
first_touch_date: string
|
||||
in_care_days: number | null
|
||||
total_medication_days: number
|
||||
closed_state: number
|
||||
}
|
||||
|
||||
/** 「复诊状态」筛选下拉选项(请求参数 revisit_state;due = overdue ∪ missed) */
|
||||
export const REVISIT_STATE_FILTER_OPTIONS: Array<{ label: string; value: string }> = [
|
||||
{ label: '到期未挂号 / 过号', value: 'due' },
|
||||
{ label: '即将到期', value: 'warning' },
|
||||
{ label: '已约待面诊', value: 'booked' },
|
||||
{ label: '已面诊', value: 'visited' },
|
||||
{ label: '已联系', value: 'contacted' },
|
||||
{ label: '缺开药天数', value: 'no_days' },
|
||||
{ label: '未到期', value: 'pending' }
|
||||
]
|
||||
|
||||
/** 「开药天数档」筛选下拉选项(请求参数 revisit_days_bucket) */
|
||||
export const REVISIT_DAYS_BUCKET_OPTIONS: Array<{ label: string; value: string }> = [
|
||||
{ label: '14 天', value: '14' },
|
||||
{ label: '21 天', value: '21' },
|
||||
{ label: '28 天', value: '28' },
|
||||
{ label: '30 天', value: '30' },
|
||||
{ label: '其它天数', value: 'other' }
|
||||
]
|
||||
|
||||
/** state → 默认文案(后端 state_text 缺失时兜底) */
|
||||
const STATE_LABEL: Record<string, string> = {
|
||||
visited: '已面诊',
|
||||
booked: '已约',
|
||||
missed: '过号',
|
||||
contacted: '已联系',
|
||||
overdue: '超期',
|
||||
warning: '即将到期',
|
||||
pending: '未到期',
|
||||
no_days: '缺开药天数',
|
||||
none: '—'
|
||||
}
|
||||
|
||||
const toInt = (v: unknown, fallback = 0): number => {
|
||||
if (v === null || v === undefined || v === '') return fallback
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? Math.trunc(n) : fallback
|
||||
}
|
||||
|
||||
const toNullableInt = (v: unknown): number | null => {
|
||||
if (v === null || v === undefined || v === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? Math.trunc(n) : null
|
||||
}
|
||||
|
||||
const toDateStr = (v: unknown): string => {
|
||||
if (v === null || v === undefined) return ''
|
||||
const s = String(v).trim()
|
||||
if (s === '' || s === '0000-00-00') return ''
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* 把列表行 / 详情里的 `revisit_due` 原始值规整为 RevisitDue;
|
||||
* 字段缺失(旧接口)或非对象时返回 null,调用方据此不渲染。
|
||||
*/
|
||||
export function normalizeRevisitDue(raw: unknown): RevisitDue | null {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const state = String(r.state ?? 'none').trim() || 'none'
|
||||
const daysSrc = toInt(r.days_src)
|
||||
const anchorSrc = toInt(r.anchor_src)
|
||||
return {
|
||||
current_slot: toInt(r.current_slot),
|
||||
next_slot: toInt(r.next_slot),
|
||||
valid_order_count: toInt(r.valid_order_count),
|
||||
medication_days: toInt(r.medication_days),
|
||||
days_src: (daysSrc === 1 || daysSrc === 2 ? daysSrc : 0) as 0 | 1 | 2,
|
||||
rule_days: toInt(r.rule_days),
|
||||
anchor_src: (anchorSrc >= 1 && anchorSrc <= 3 ? anchorSrc : 0) as 0 | 1 | 2 | 3,
|
||||
anchor_date: toDateStr(r.anchor_date),
|
||||
order_date: toDateStr(r.order_date),
|
||||
due_date: toDateStr(r.due_date),
|
||||
days_left: toNullableInt(r.days_left),
|
||||
overdue_days: toNullableInt(r.overdue_days),
|
||||
state,
|
||||
state_text: String(r.state_text ?? '').trim(),
|
||||
severe: toInt(r.severe) === 1 ? 1 : 0,
|
||||
appointment_state: toInt(r.appointment_state),
|
||||
appointment_date: toDateStr(r.appointment_date),
|
||||
snooze_count: toInt(r.snooze_count),
|
||||
escalation_level: toInt(r.escalation_level),
|
||||
promised_date: toDateStr(r.promised_date),
|
||||
missed_count: toInt(r.missed_count),
|
||||
first_touch_date: toDateStr(r.first_touch_date),
|
||||
in_care_days: toNullableInt(r.in_care_days),
|
||||
total_medication_days: toInt(r.total_medication_days),
|
||||
closed_state: toInt(r.closed_state)
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否有可展示的复诊节点(state !== 'none') */
|
||||
export function hasRevisitDue(due: RevisitDue | null | undefined): due is RevisitDue {
|
||||
return !!due && due.state !== 'none' && due.state !== ''
|
||||
}
|
||||
|
||||
/** 行级标红:到期未挂号 / 过号未面诊;人工关闭或已自动关闭(closed_state!==0)的行不标红,与「复诊到期」chip / 筛选口径一致 */
|
||||
export function isRevisitDueHighlight(due: RevisitDue | null | undefined): boolean {
|
||||
return (
|
||||
hasRevisitDue(due) &&
|
||||
toInt(due.closed_state) === 0 &&
|
||||
(due.state === 'overdue' || due.state === 'missed')
|
||||
)
|
||||
}
|
||||
|
||||
/** 深红:超期达到 severe_overdue_days(后端已算好 severe=1) */
|
||||
export function isRevisitDueSevere(due: RevisitDue | null | undefined): boolean {
|
||||
return isRevisitDueHighlight(due) && Number(due?.severe) === 1
|
||||
}
|
||||
|
||||
/**
|
||||
* el-table :row-class-name 片段:
|
||||
* '' | 'row-revisit-overdue' | 'row-revisit-overdue row-revisit-overdue-deep'
|
||||
*/
|
||||
export function revisitRowClassName(due: RevisitDue | null | undefined): string {
|
||||
if (!isRevisitDueHighlight(due)) return ''
|
||||
return isRevisitDueSevere(due) ? 'row-revisit-overdue row-revisit-overdue-deep' : 'row-revisit-overdue'
|
||||
}
|
||||
|
||||
/** 'YYYY-MM-DD' → 'MM-DD';非法/空值返回 '' */
|
||||
export function formatRevisitMonthDay(date: string | null | undefined): string {
|
||||
const s = toDateStr(date)
|
||||
if (!s) return ''
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s)
|
||||
if (m) return `${m[2]}-${m[3]}`
|
||||
return s
|
||||
}
|
||||
|
||||
/** 用药起算锚点来源文案(行 2 末尾) */
|
||||
export function revisitAnchorSrcText(src: number | null | undefined): string {
|
||||
const n = toInt(src)
|
||||
if (n === 1) return '签收起'
|
||||
if (n === 2) return '发货起'
|
||||
if (n === 3) return '下单起'
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 开药天数来源文案(tooltip 用) */
|
||||
export function revisitDaysSrcText(src: number | null | undefined): string {
|
||||
const n = toInt(src)
|
||||
if (n === 1) return '订单'
|
||||
if (n === 2) return '处方'
|
||||
return '缺失'
|
||||
}
|
||||
|
||||
/** 是否缺开药天数(days_src=0 或 medication_days<=0) */
|
||||
export function isRevisitDaysMissing(due: RevisitDue | null | undefined): boolean {
|
||||
if (!hasRevisitDue(due)) return false
|
||||
return toInt(due.days_src) === 0 || toInt(due.medication_days) <= 0
|
||||
}
|
||||
|
||||
/** 「第 N 诊」文案 */
|
||||
export function revisitSlotText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const slot = toInt(due.current_slot)
|
||||
return slot > 0 ? `第 ${slot} 诊` : '未成交'
|
||||
}
|
||||
|
||||
/** 「开药 X 天」或「缺开药天数」 */
|
||||
export function revisitMedicationDaysText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
if (isRevisitDaysMissing(due)) return '缺开药天数'
|
||||
return `开药 ${toInt(due.medication_days)} 天`
|
||||
}
|
||||
|
||||
/** 「药尽 MM-DD」;缺天数无 due_date 时返回 '' */
|
||||
export function revisitDueDateText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const md = formatRevisitMonthDay(due.due_date)
|
||||
return md ? `药尽 ${md}` : ''
|
||||
}
|
||||
|
||||
/** state 兜底文案(后端 state_text 为空时使用) */
|
||||
export function revisitStateLabel(state: string | null | undefined): string {
|
||||
const key = String(state ?? '').trim()
|
||||
return STATE_LABEL[key] ?? (key || '—')
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态 chip 文案:优先后端 state_text;为空时按 state + 数字自行拼装,
|
||||
* 保证旧接口 / 字段缺失时也可读。
|
||||
*/
|
||||
export function revisitStateChipText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
if (due.state_text) return due.state_text
|
||||
const state = String(due.state)
|
||||
switch (state) {
|
||||
case 'overdue': {
|
||||
const n = toInt(due.overdue_days)
|
||||
return n <= 0 ? '今日应挂号' : `超期 ${n} 天`
|
||||
}
|
||||
case 'missed': {
|
||||
const md = formatRevisitMonthDay(due.appointment_date)
|
||||
return md ? `过号 ${md}` : '过号'
|
||||
}
|
||||
case 'booked': {
|
||||
const md = formatRevisitMonthDay(due.appointment_date)
|
||||
return md ? `已约 ${md}` : '已约'
|
||||
}
|
||||
case 'visited': {
|
||||
const md = formatRevisitMonthDay(due.appointment_date)
|
||||
return md ? `已面诊 ${md}` : '已面诊'
|
||||
}
|
||||
case 'contacted': {
|
||||
const md = formatRevisitMonthDay(due.promised_date)
|
||||
return md ? `已联系·约 ${md}` : '已联系'
|
||||
}
|
||||
case 'warning':
|
||||
case 'pending': {
|
||||
const n = due.days_left
|
||||
return n === null ? revisitStateLabel(state) : `剩 ${n} 天`
|
||||
}
|
||||
default:
|
||||
return revisitStateLabel(state)
|
||||
}
|
||||
}
|
||||
|
||||
/** 状态 chip 的 el-tag type */
|
||||
export function revisitStateTagType(
|
||||
state: string | null | undefined
|
||||
): 'danger' | 'warning' | 'primary' | 'success' | 'info' {
|
||||
switch (String(state ?? '')) {
|
||||
case 'overdue':
|
||||
case 'missed':
|
||||
return 'danger'
|
||||
case 'warning':
|
||||
case 'no_days':
|
||||
return 'warning'
|
||||
case 'booked':
|
||||
case 'contacted':
|
||||
return 'primary'
|
||||
case 'visited':
|
||||
return 'success'
|
||||
default:
|
||||
return 'info'
|
||||
}
|
||||
}
|
||||
|
||||
/** 状态 chip 的 el-tag effect:红为 dark;描边态(已联系 / 缺天数)为 plain;其余 light */
|
||||
export function revisitStateTagEffect(state: string | null | undefined): 'dark' | 'light' | 'plain' {
|
||||
switch (String(state ?? '')) {
|
||||
case 'overdue':
|
||||
case 'missed':
|
||||
return 'dark'
|
||||
case 'contacted':
|
||||
case 'no_days':
|
||||
return 'plain'
|
||||
default:
|
||||
return 'light'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态 → 徽标颜色 class(复用列表 / 只读页既有的 unserved-* 色板):
|
||||
* overdue/missed → unserved-red;warning/no_days → unserved-orange;
|
||||
* visited → unserved-green;booked/contacted → unserved-blue;其余 → unserved-muted
|
||||
*/
|
||||
export function revisitStateColorClass(
|
||||
state: string | null | undefined
|
||||
): 'unserved-red' | 'unserved-orange' | 'unserved-green' | 'unserved-blue' | 'unserved-muted' {
|
||||
switch (String(state ?? '')) {
|
||||
case 'overdue':
|
||||
case 'missed':
|
||||
return 'unserved-red'
|
||||
case 'warning':
|
||||
case 'no_days':
|
||||
return 'unserved-orange'
|
||||
case 'visited':
|
||||
return 'unserved-green'
|
||||
case 'booked':
|
||||
case 'contacted':
|
||||
return 'unserved-blue'
|
||||
default:
|
||||
return 'unserved-muted'
|
||||
}
|
||||
}
|
||||
|
||||
/** 状态 chip 附加 class(组件内样式钩子):rv-chip rv-chip--<state> [rv-chip--severe] */
|
||||
export function revisitStateChipClass(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return 'rv-chip'
|
||||
const cls = ['rv-chip', `rv-chip--${String(due.state)}`]
|
||||
if (isRevisitDueSevere(due)) cls.push('rv-chip--severe')
|
||||
return cls.join(' ')
|
||||
}
|
||||
|
||||
/** 行 4:「已延迟 N 次」 */
|
||||
export function revisitSnoozeText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const n = toInt(due.snooze_count)
|
||||
return n > 0 ? `已延迟 ${n} 次` : ''
|
||||
}
|
||||
|
||||
/** 行 4:「已联系 约 MM-DD」 */
|
||||
export function revisitContactText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const md = formatRevisitMonthDay(due.promised_date)
|
||||
return md ? `已联系 约 ${md}` : ''
|
||||
}
|
||||
|
||||
/** 行 4 合并文案:仅 snooze_count>0 或 promised_date 有值时非空 */
|
||||
export function revisitFollowLineText(due: RevisitDue | null | undefined): string {
|
||||
const parts = [revisitSnoozeText(due), revisitContactText(due)].filter((s) => s !== '')
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** 行 2:「MM-DD 开药 · 开药 X 天 · 签收起」 */
|
||||
export function revisitOrderLineText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const parts: string[] = []
|
||||
const md = formatRevisitMonthDay(due.order_date)
|
||||
if (md) parts.push(`${md} 开药`)
|
||||
parts.push(revisitMedicationDaysText(due))
|
||||
if (!isRevisitDaysMissing(due)) {
|
||||
const anchor = revisitAnchorSrcText(due.anchor_src)
|
||||
if (anchor) parts.push(anchor)
|
||||
}
|
||||
return parts.filter((s) => s !== '').join(' · ')
|
||||
}
|
||||
|
||||
/** 诊次 tag tooltip 行 */
|
||||
export function revisitTooltipLines(due: RevisitDue | null | undefined): string[] {
|
||||
if (!hasRevisitDue(due)) return []
|
||||
const lines: string[] = []
|
||||
const offset = Math.max(0, toInt(due.current_slot) - toInt(due.valid_order_count))
|
||||
lines.push(`有效订单 ${toInt(due.valid_order_count)} 笔 · 诊次偏移 +${offset}`)
|
||||
if (toInt(due.next_slot) > 0) lines.push(`待复诊:第 ${toInt(due.next_slot)} 诊`)
|
||||
const first = formatRevisitMonthDay(due.first_touch_date)
|
||||
if (first) {
|
||||
const care = due.in_care_days
|
||||
lines.push(care === null ? `首次触达 ${first}` : `首次触达 ${first} · 在管 ${care} 天`)
|
||||
}
|
||||
if (toInt(due.total_medication_days) > 0) lines.push(`累计开药 ${toInt(due.total_medication_days)} 天`)
|
||||
const anchorMd = formatRevisitMonthDay(due.anchor_date)
|
||||
const anchorSrc = revisitAnchorSrcText(due.anchor_src)
|
||||
if (anchorMd && anchorSrc) lines.push(`用药起算 ${anchorMd}(${anchorSrc.replace(/起$/, '')})`)
|
||||
if (!isRevisitDaysMissing(due)) lines.push(`开药天数来源:${revisitDaysSrcText(due.days_src)}`)
|
||||
if (toInt(due.missed_count) > 0) lines.push(`曾过号 ${toInt(due.missed_count)} 次`)
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读页徽标文案:「第 N 诊 · 药尽 MM-DD · 超期 N 天」
|
||||
* 无 due_date 时省略中段;尾段为状态 chip 文案。
|
||||
*/
|
||||
export function revisitBadgeText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const parts = [revisitSlotText(due), revisitDueDateText(due), revisitStateChipText(due)]
|
||||
return parts.filter((s) => s !== '').join(' · ')
|
||||
}
|
||||
@@ -312,6 +312,17 @@
|
||||
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
|
||||
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -325,6 +336,17 @@
|
||||
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
|
||||
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -943,6 +965,15 @@
|
||||
label-width="108px"
|
||||
>
|
||||
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.times_per_day"
|
||||
@@ -968,6 +999,15 @@
|
||||
</el-form-item>
|
||||
<template v-if="detailHasAuxHerbs">
|
||||
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="aux_dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="aux_times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.aux_times_per_day"
|
||||
@@ -1432,10 +1472,12 @@ const patchUsageVisible = ref(false)
|
||||
const patchUsageSaving = ref(false)
|
||||
const patchUsageFormRef = ref<FormInstance>()
|
||||
const patchUsageForm = reactive({
|
||||
dosage_bag_count: 1 as number | undefined,
|
||||
times_per_day: 3 as number | undefined,
|
||||
usage_days: 7 as number | undefined,
|
||||
aux_times_per_day: 3 as number | undefined,
|
||||
aux_usage_days: 7 as number | undefined,
|
||||
aux_dosage_bag_count: 1 as number | undefined,
|
||||
medication_days: undefined as number | undefined
|
||||
})
|
||||
const patchUsageRules = computed<FormRules>(() => {
|
||||
@@ -1444,9 +1486,15 @@ const patchUsageRules = computed<FormRules>(() => {
|
||||
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
|
||||
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
|
||||
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
}
|
||||
return rules
|
||||
})
|
||||
@@ -1459,6 +1507,7 @@ function openPatchUsageDialog() {
|
||||
return
|
||||
}
|
||||
const aux = detailAuxUsage.value
|
||||
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
|
||||
patchUsageForm.times_per_day =
|
||||
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
|
||||
patchUsageForm.usage_days =
|
||||
@@ -1468,16 +1517,20 @@ function openPatchUsageDialog() {
|
||||
patchUsageForm.aux_usage_days =
|
||||
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
|
||||
const md = Number(ord.medication_days)
|
||||
patchUsageForm.aux_dosage_bag_count =
|
||||
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
|
||||
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
|
||||
patchUsageVisible.value = true
|
||||
nextTick(() => patchUsageFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function resetPatchUsageForm() {
|
||||
patchUsageForm.dosage_bag_count = 1
|
||||
patchUsageForm.times_per_day = 3
|
||||
patchUsageForm.usage_days = 7
|
||||
patchUsageForm.aux_times_per_day = 3
|
||||
patchUsageForm.aux_usage_days = 7
|
||||
patchUsageForm.aux_dosage_bag_count = 1
|
||||
patchUsageForm.medication_days = undefined
|
||||
}
|
||||
|
||||
@@ -1498,17 +1551,25 @@ async function submitPatchUsage() {
|
||||
times_per_day: number
|
||||
usage_days: number
|
||||
medication_days: number
|
||||
dosage_bag_count?: number
|
||||
aux_times_per_day?: number
|
||||
aux_usage_days?: number
|
||||
aux_dosage_bag_count?: number
|
||||
} = {
|
||||
id: ordId,
|
||||
times_per_day: Number(patchUsageForm.times_per_day),
|
||||
usage_days: Number(patchUsageForm.usage_days),
|
||||
medication_days: Number(patchUsageForm.medication_days)
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
|
||||
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
|
||||
}
|
||||
}
|
||||
await prescriptionOrderPatchPrescriptionUsage(payload)
|
||||
feedback.msgSuccess('保存成功')
|
||||
@@ -1763,7 +1824,7 @@ async function refresh() {
|
||||
detailLogisticsExpress.value = String(d.express_company || 'auto') || 'auto'
|
||||
void fetchLogisticsTrace()
|
||||
}
|
||||
if (props.loadRelatedData) void fetchLogs(id)
|
||||
if (props.loadRelatedData) await fetchLogs(id)
|
||||
const diagId = d.diagnosis_id
|
||||
if (props.loadRelatedData && diagId) {
|
||||
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
|
||||
|
||||
@@ -883,6 +883,17 @@
|
||||
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
|
||||
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -896,6 +907,17 @@
|
||||
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
|
||||
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -2261,6 +2283,15 @@
|
||||
label-width="96px"
|
||||
>
|
||||
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.times_per_day"
|
||||
@@ -2286,6 +2317,15 @@
|
||||
</el-form-item>
|
||||
<template v-if="detailHasAuxHerbs">
|
||||
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="aux_dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="aux_times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.aux_times_per_day"
|
||||
@@ -3954,10 +3994,12 @@ const patchUsageVisible = ref(false)
|
||||
const patchUsageSaving = ref(false)
|
||||
const patchUsageFormRef = ref<FormInstance>()
|
||||
const patchUsageForm = reactive({
|
||||
dosage_bag_count: 1 as number | undefined,
|
||||
times_per_day: 3 as number | undefined,
|
||||
usage_days: 7 as number | undefined,
|
||||
aux_times_per_day: 3 as number | undefined,
|
||||
aux_usage_days: 7 as number | undefined,
|
||||
aux_dosage_bag_count: 1 as number | undefined,
|
||||
medication_days: undefined as number | undefined
|
||||
})
|
||||
const patchUsageRules = computed<FormRules>(() => {
|
||||
@@ -3966,9 +4008,15 @@ const patchUsageRules = computed<FormRules>(() => {
|
||||
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
|
||||
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
|
||||
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
}
|
||||
return rules
|
||||
})
|
||||
@@ -3981,6 +4029,7 @@ function openPatchUsageDialog() {
|
||||
return
|
||||
}
|
||||
const aux = detailAuxUsage.value
|
||||
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
|
||||
patchUsageForm.times_per_day =
|
||||
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
|
||||
patchUsageForm.usage_days =
|
||||
@@ -3990,16 +4039,20 @@ function openPatchUsageDialog() {
|
||||
patchUsageForm.aux_usage_days =
|
||||
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
|
||||
const md = Number(ord.medication_days)
|
||||
patchUsageForm.aux_dosage_bag_count =
|
||||
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
|
||||
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
|
||||
patchUsageVisible.value = true
|
||||
nextTick(() => patchUsageFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function resetPatchUsageForm() {
|
||||
patchUsageForm.dosage_bag_count = 1
|
||||
patchUsageForm.times_per_day = 3
|
||||
patchUsageForm.usage_days = 7
|
||||
patchUsageForm.aux_times_per_day = 3
|
||||
patchUsageForm.aux_usage_days = 7
|
||||
patchUsageForm.aux_dosage_bag_count = 1
|
||||
patchUsageForm.medication_days = undefined
|
||||
}
|
||||
|
||||
@@ -4020,17 +4073,25 @@ async function submitPatchUsage() {
|
||||
times_per_day: number
|
||||
usage_days: number
|
||||
medication_days: number
|
||||
dosage_bag_count?: number
|
||||
aux_times_per_day?: number
|
||||
aux_usage_days?: number
|
||||
aux_dosage_bag_count?: number
|
||||
} = {
|
||||
id: ordId,
|
||||
times_per_day: Number(patchUsageForm.times_per_day),
|
||||
usage_days: Number(patchUsageForm.usage_days),
|
||||
medication_days: Number(patchUsageForm.medication_days)
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
|
||||
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
|
||||
}
|
||||
}
|
||||
await prescriptionOrderPatchPrescriptionUsage(payload)
|
||||
feedback.msgSuccess('保存成功')
|
||||
|
||||
@@ -144,6 +144,17 @@
|
||||
>
|
||||
<el-table-column type="selection" width="48" />
|
||||
<el-table-column label="订单号" prop="order_no" min-width="150" />
|
||||
|
||||
<el-table-column label="处方业务订单号" min-width="210">
|
||||
<template #default="{ row }">
|
||||
<div v-if="row.prescription_orders?.length" class="flex flex-col gap-1">
|
||||
<span v-for="order in row.prescription_orders" :key="order.id" class="break-all">
|
||||
{{ order.order_no }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">未关联</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="患者信息" min-width="150">
|
||||
<template #default="{ row }">
|
||||
@@ -302,6 +313,14 @@
|
||||
<el-tag :type="getStatusTag(detailData.status)">
|
||||
{{ getStatusText(detailData.status) }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="处方业务订单号" :span="2">
|
||||
<div v-if="detailData.prescription_orders?.length" class="flex flex-col gap-1">
|
||||
<span v-for="order in detailData.prescription_orders" :key="order.id" class="break-all">
|
||||
{{ order.order_no }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">未关联</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="患者姓名">
|
||||
{{ detailData.patient?.patient_name || '待关联' }}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="reception-page">
|
||||
<DoctorWebConsultationNotice />
|
||||
<!-- 页头 -->
|
||||
<div class="reception-header">
|
||||
<div class="header-left">
|
||||
@@ -83,10 +84,18 @@
|
||||
<el-icon v-else><ChatDotRound /></el-icon>
|
||||
</button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="发起通话" placement="top">
|
||||
<button class="row-icon-btn call" @click="handleCall(row)">
|
||||
<el-icon><Phone /></el-icon>
|
||||
</button>
|
||||
<el-tooltip :content="webConsultationBlocked ? webConsultationMessage : '发起通话'" placement="top">
|
||||
<span class="row-call-action">
|
||||
<button
|
||||
class="row-icon-btn call"
|
||||
:disabled="webConsultationBlocked"
|
||||
:aria-label="webConsultationBlocked ? webConsultationMessage : '发起通话'"
|
||||
@click="handleCall(row)"
|
||||
>
|
||||
<el-icon><Phone /></el-icon>
|
||||
<span v-if="webConsultationBlocked">已停用</span>
|
||||
</button>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
@@ -189,6 +198,8 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent, onMounted, onUnmounted } from 'vue'
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { receptionQueue, receptionDetail, notifyAssistant, addDoctorNote } from '@/api/patient'
|
||||
import NoteTimeline from './components/NoteTimeline.vue'
|
||||
import PatientInfoCard from '@/views/tcm/diagnosis/components/PatientInfoCard.vue'
|
||||
@@ -211,6 +222,7 @@ const DiagnosisEdit = defineAsyncComponent(() => import('@/views/tcm/diagnosis/e
|
||||
|
||||
const POLL_MS = 5_000
|
||||
const PAGE_SIZE = 15
|
||||
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
|
||||
|
||||
interface QueueRow {
|
||||
id: number
|
||||
@@ -438,6 +450,7 @@ const handleSearch = async () => {
|
||||
}
|
||||
|
||||
const handleCall = async (row: QueueRow) => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
const sourcePatientId = Number(row.source_patient_id || 0)
|
||||
const diagnosisId = Number(row.diagnosis_id || 0)
|
||||
if (!sourcePatientId) {
|
||||
@@ -454,6 +467,7 @@ const handleCall = async (row: QueueRow) => {
|
||||
appointment_id: Number(row.id),
|
||||
diagnosis_id: diagnosisId
|
||||
})
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
chatDialogRef.value?.open({
|
||||
patientId: sourcePatientId,
|
||||
patientName: row.patient_name,
|
||||
@@ -1004,16 +1018,25 @@ onUnmounted(() => {
|
||||
font-size: 15px;
|
||||
padding: 0;
|
||||
}
|
||||
.row-icon-btn:hover {
|
||||
.row-call-action {
|
||||
display: inline-flex;
|
||||
}
|
||||
.row-icon-btn.call:disabled {
|
||||
width: auto;
|
||||
gap: 4px;
|
||||
padding: 0 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.row-icon-btn:hover:not(:disabled) {
|
||||
background: var(--rx-accent-soft);
|
||||
color: var(--rx-accent-strong);
|
||||
border-color: var(--rx-accent);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.row-icon-btn:active {
|
||||
.row-icon-btn:active:not(:disabled) {
|
||||
transform: scale(0.92);
|
||||
}
|
||||
.row-icon-btn.notify:hover {
|
||||
.row-icon-btn.notify:hover:not(:disabled) {
|
||||
background: #fff7e6;
|
||||
color: var(--rx-warning);
|
||||
border-color: var(--rx-warning);
|
||||
|
||||
@@ -51,10 +51,13 @@
|
||||
<el-table-column prop="id" label="ID" width="70" />
|
||||
<el-table-column prop="account" label="本地账号" min-width="140" />
|
||||
<el-table-column prop="name" label="姓名" min-width="120" />
|
||||
<el-table-column label="部门" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ departmentText(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="本地状态" width="110"
|
||||
><template #default="{ row }"
|
||||
><el-tag :type="row.disable ? 'danger' : 'success'">{{
|
||||
row.disable ? '停用' : row.root ? '敏感账号' : '正常'
|
||||
><el-tag :type="isLocalDisabled(row) ? 'danger' : 'success'">{{
|
||||
isLocalDisabled(row) ? '停用' : row.root ? '敏感账号' : '正常'
|
||||
}}</el-tag></template
|
||||
></el-table-column
|
||||
>
|
||||
@@ -76,12 +79,23 @@
|
||||
</div></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="应用访问状态" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="applicationAccess(row).type">{{
|
||||
applicationAccess(row).text
|
||||
}}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近校验时间" min-width="190">
|
||||
<template #default="{ row }">{{ checkedAtText(row.iam?.checked_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" min-width="210"
|
||||
><template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
row.iam.state === 'verified' ||
|
||||
!can(row.iam.state === 'revoked' ? 'rebind' : 'bind')
|
||||
@@ -93,6 +107,7 @@
|
||||
link
|
||||
type="primary"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
row.iam.state === 'verified' ||
|
||||
!can('create') ||
|
||||
@@ -107,18 +122,29 @@
|
||||
><el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
command="rebind"
|
||||
:disabled="(!!row.root && !reviewAllowed) || !can('rebind')"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
!can('rebind')
|
||||
"
|
||||
>换绑</el-dropdown-item
|
||||
>
|
||||
<el-dropdown-item
|
||||
command="unbind"
|
||||
:disabled="(!!row.root && !reviewAllowed) || !can('unbind')"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
!can('unbind')
|
||||
"
|
||||
>解绑</el-dropdown-item
|
||||
>
|
||||
<el-dropdown-item command="audit">审计记录</el-dropdown-item>
|
||||
</el-dropdown-menu></template
|
||||
></el-dropdown
|
||||
>
|
||||
<div v-if="isLocalDisabled(row)" class="text-xs text-gray-500 mt-1">
|
||||
本地账号已停用,关联操作不可用;审计记录仍可查看。
|
||||
</div>
|
||||
</template></el-table-column
|
||||
>
|
||||
</el-table>
|
||||
@@ -285,7 +311,10 @@
|
||||
type="primary"
|
||||
:loading="busy"
|
||||
:disabled="
|
||||
!confirmed || !operation.reason.trim() || result?.status === 'succeeded'
|
||||
isLocalDisabled(selected) ||
|
||||
!confirmed ||
|
||||
!operation.reason.trim() ||
|
||||
result?.status === 'succeeded'
|
||||
"
|
||||
@click="submit"
|
||||
>{{
|
||||
@@ -455,6 +484,56 @@ const validIdentity = computed(
|
||||
? !!newEmployee.username.trim() && !!newEmployee.display_name.trim()
|
||||
: !!operation.employee_id)
|
||||
)
|
||||
function isLocalDisabled(row: any): boolean {
|
||||
return row?.disable === true || row?.disable === 1 || row?.disable === '1'
|
||||
}
|
||||
function departmentText(row: any): string {
|
||||
if (!Array.isArray(row?.dept_names)) return '未知'
|
||||
if (row.dept_names.length === 0) return '未分配'
|
||||
if (!row.dept_names.every((name: unknown) => typeof name === 'string' && name.trim()))
|
||||
return '未知'
|
||||
return row.dept_names.map((name: string) => name.trim()).join('、')
|
||||
}
|
||||
function applicationAccess(row: any): {
|
||||
text: string
|
||||
type: 'success' | 'warning' | 'info' | 'danger'
|
||||
} {
|
||||
const iam = row?.iam
|
||||
const reason = iam?.access?.reason
|
||||
if (['SERVICE_UNAVAILABLE', 'STATUS_UNAVAILABLE'].includes(reason)) {
|
||||
return { text: '服务异常', type: 'warning' }
|
||||
}
|
||||
if (reason === 'NOT_AUTHORIZED') return { text: '未授权', type: 'warning' }
|
||||
if (reason === 'ACCOUNT_DISABLED') return { text: 'IAM账号停用', type: 'danger' }
|
||||
if (reason === 'BINDING_CONFLICT') return { text: '关联冲突', type: 'warning' }
|
||||
if (reason === 'ACCOUNT_MISMATCH') return { text: '身份不匹配', type: 'warning' }
|
||||
if (
|
||||
['unlinked', 'revoked'].includes(iam?.state) ||
|
||||
['NOT_LINKED', 'LOCAL_ACCOUNT_LINK_REQUIRED', 'BINDING_REVOKED'].includes(reason)
|
||||
) {
|
||||
return { text: '未关联', type: 'info' }
|
||||
}
|
||||
if (iam?.access?.allowed === false) return { text: '未授权', type: 'warning' }
|
||||
if (iam?.state === 'verified' && iam?.access?.allowed === true) {
|
||||
return { text: '已授权', type: 'success' }
|
||||
}
|
||||
return { text: '未知', type: 'info' }
|
||||
}
|
||||
function checkedAtText(value: unknown): string {
|
||||
if (value == null || value === '' || value === 0 || value === '0') return '未校验'
|
||||
const seconds = typeof value === 'number' || typeof value === 'string' ? Number(value) : NaN
|
||||
if (!Number.isInteger(seconds) || seconds <= 0 || seconds > 253402300799) return '未知'
|
||||
return new Date(seconds * 1000).toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false
|
||||
})
|
||||
}
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -473,6 +552,10 @@ function reload() {
|
||||
void load()
|
||||
}
|
||||
function open(row: any, kind: IdentityOperation['kind']) {
|
||||
if (isLocalDisabled(row)) {
|
||||
ElMessage.warning('本地账号已停用,请先启用账号后再维护关联。')
|
||||
return
|
||||
}
|
||||
if (kind === 'bind' && row.iam.state === 'revoked') kind = 'rebind'
|
||||
selected.value = row
|
||||
Object.assign(operation, {
|
||||
@@ -519,6 +602,10 @@ function choose(row: any) {
|
||||
}
|
||||
}
|
||||
async function submit() {
|
||||
if (isLocalDisabled(selected.value)) {
|
||||
drawerError.value = '本地账号已停用,请先启用账号后再维护关联。'
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
try {
|
||||
if (!submittedPayload.value) {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
<template>
|
||||
<div class="prescription-ai-visibility">
|
||||
<el-card v-loading="loading" shadow="never" class="!border-none">
|
||||
<div class="text-xl font-medium mb-[20px]">处方 AI 一致度可见范围</div>
|
||||
<el-alert type="info" :closable="false" show-icon class="mb-5">
|
||||
<template #title>指定用户组或用户可查看一致度</template>
|
||||
<div class="leading-6">
|
||||
用户命中任一指定系统角色,或被单独指定,即可查看桌面端“与 AI
|
||||
一致度”、逐味对照和一致度统计。AI
|
||||
报告继续按原有权限开放,已有报告不受影响,患者与处方的数据范围保持原有规则。
|
||||
</div>
|
||||
</el-alert>
|
||||
|
||||
<el-alert
|
||||
v-if="loadError"
|
||||
:title="loadError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-5"
|
||||
/>
|
||||
<div v-if="loading" role="status" class="mb-5">正在读取当前可见范围…</div>
|
||||
|
||||
<el-form
|
||||
v-if="hasLoaded"
|
||||
class="ls-form"
|
||||
:model="formData"
|
||||
:disabled="!ready || loading || saving"
|
||||
label-width="140px"
|
||||
>
|
||||
<el-form-item label="指定用户组" prop="role_ids">
|
||||
<div class="w-full max-w-[640px]">
|
||||
<el-select
|
||||
v-model="formData.role_ids"
|
||||
class="w-full"
|
||||
multiple
|
||||
filterable
|
||||
clearable
|
||||
placeholder="请选择系统角色,可搜索角色名称"
|
||||
>
|
||||
<el-option
|
||||
v-for="role in roleOptions"
|
||||
:key="role.id"
|
||||
:label="role.name"
|
||||
:value="role.id"
|
||||
/>
|
||||
</el-select>
|
||||
<div class="form-tips">账号拥有任一指定角色即可命中。</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="指定用户" prop="admin_ids">
|
||||
<div class="w-full max-w-[640px]">
|
||||
<el-select
|
||||
v-model="formData.admin_ids"
|
||||
class="w-full"
|
||||
multiple
|
||||
filterable
|
||||
clearable
|
||||
placeholder="请选择用户,可搜索姓名或账号"
|
||||
>
|
||||
<el-option
|
||||
v-for="admin in adminOptions"
|
||||
:key="admin.id"
|
||||
:label="admin.label"
|
||||
:value="admin.id"
|
||||
/>
|
||||
</el-select>
|
||||
<div class="form-tips">
|
||||
单独指定的用户无需同时命中用户组。当前不在可选列表中的已配置 ID
|
||||
会保留,移除后保存才会取消该项授权。
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="生效规则">
|
||||
<div>
|
||||
<div class="leading-6">指定用户组与指定用户按“或”生效。</div>
|
||||
<div class="form-tips">
|
||||
两项均为空时,所有账号(包括超级管理员)均隐藏一致度、对照与统计。
|
||||
拥有本页管理权限不自动获得一致度查看权,超级管理员也需命中上述名单。
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-alert
|
||||
v-if="ready && !formData.role_ids.length && !formData.admin_ids.length"
|
||||
title="当前选择为空:保存后所有账号将隐藏一致度、对照与统计,AI 报告仍保留。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-5"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="saveError"
|
||||
:title="saveError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-5"
|
||||
/>
|
||||
<el-button :disabled="loading || saving" @click="loadConfig">
|
||||
{{ loadError ? '重试加载' : '重新加载' }}
|
||||
</el-button>
|
||||
</el-card>
|
||||
|
||||
<footer-btns v-if="canManage">
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="saving"
|
||||
:disabled="!ready || loading || saving"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
{{ saving ? '正在保存' : '保存' }}
|
||||
</el-button>
|
||||
</footer-btns>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="prescriptionAiVisibility">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
|
||||
import type {
|
||||
PrescriptionAiVisibilityConfig,
|
||||
PrescriptionAiVisibilityOptions
|
||||
} from '@/api/setting/prescription_ai_visibility'
|
||||
import {
|
||||
getPrescriptionAiCapabilities,
|
||||
getPrescriptionAiVisibilityConfig,
|
||||
getPrescriptionAiVisibilityOptions,
|
||||
setPrescriptionAiVisibilityConfig
|
||||
} from '@/api/setting/prescription_ai_visibility'
|
||||
import feedback from '@/utils/feedback'
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const ready = ref(false)
|
||||
const hasLoaded = ref(false)
|
||||
const canManage = ref(false)
|
||||
const loadError = ref('')
|
||||
const saveError = ref('')
|
||||
const formData = reactive<PrescriptionAiVisibilityConfig>({ role_ids: [], admin_ids: [] })
|
||||
const optionsData = reactive<PrescriptionAiVisibilityOptions>({ roles: [], admins: [] })
|
||||
|
||||
const roleOptions = computed(() => {
|
||||
const options = new Map(optionsData.roles.map((role) => [role.id, role]))
|
||||
for (const id of formData.role_ids) {
|
||||
if (!options.has(id)) {
|
||||
options.set(id, { id, name: `已配置角色 #${id}(当前不在可选列表)` })
|
||||
}
|
||||
}
|
||||
return [...options.values()]
|
||||
})
|
||||
|
||||
const adminOptions = computed(() => {
|
||||
const options = new Map(
|
||||
optionsData.admins.map((admin) => [
|
||||
admin.id,
|
||||
{ id: admin.id, label: `${admin.name || `用户 #${admin.id}`}(${admin.account})` }
|
||||
])
|
||||
)
|
||||
for (const id of formData.admin_ids) {
|
||||
if (!options.has(id)) {
|
||||
options.set(id, { id, label: `已配置用户 #${id}(当前不在可选列表)` })
|
||||
}
|
||||
}
|
||||
return [...options.values()]
|
||||
})
|
||||
|
||||
const assignConfig = (config: PrescriptionAiVisibilityConfig) => {
|
||||
formData.role_ids = [...config.role_ids]
|
||||
formData.admin_ids = [...config.admin_ids]
|
||||
}
|
||||
|
||||
const loadConfig = async () => {
|
||||
if (loading.value || saving.value) return
|
||||
loading.value = true
|
||||
ready.value = false
|
||||
canManage.value = false
|
||||
loadError.value = ''
|
||||
saveError.value = ''
|
||||
try {
|
||||
const capabilities = await getPrescriptionAiCapabilities()
|
||||
if (capabilities.can_manage_visibility !== true) {
|
||||
loadError.value = '当前账号无权管理处方 AI 一致度可见范围。'
|
||||
return
|
||||
}
|
||||
canManage.value = true
|
||||
const [config, options] = await Promise.all([
|
||||
getPrescriptionAiVisibilityConfig(),
|
||||
getPrescriptionAiVisibilityOptions()
|
||||
])
|
||||
if (!Array.isArray(options?.roles) || !Array.isArray(options?.admins)) {
|
||||
throw new Error('可选用户组或用户响应格式不正确')
|
||||
}
|
||||
// Apply both responses together; an incomplete load cannot overwrite the current policy.
|
||||
assignConfig(config)
|
||||
optionsData.roles = options.roles
|
||||
optionsData.admins = options.admins
|
||||
hasLoaded.value = true
|
||||
ready.value = true
|
||||
} catch {
|
||||
loadError.value = '可见范围加载失败,尚未读取完整配置。请重试加载后再保存。'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!ready.value || !canManage.value || loading.value || saving.value) return
|
||||
saving.value = true
|
||||
saveError.value = ''
|
||||
try {
|
||||
const config = await setPrescriptionAiVisibilityConfig({
|
||||
role_ids: [...formData.role_ids],
|
||||
admin_ids: [...formData.admin_ids]
|
||||
})
|
||||
assignConfig(config)
|
||||
feedback.msgSuccess('可见范围已保存')
|
||||
} catch {
|
||||
saveError.value = '保存结果未确认,当前选择已保留。请重试保存,或重新加载以确认服务端策略。'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
void loadConfig()
|
||||
</script>
|
||||
@@ -56,6 +56,70 @@
|
||||
/>
|
||||
<el-empty v-else description="暂无数据" />
|
||||
</el-card>
|
||||
|
||||
<!-- 我的复诊接诊率(方案 §10 D1-h):仅本人行,口径与「复诊接诊率」报表一致 -->
|
||||
<el-card v-if="canViewRevisitRate" class="!border-none mt-4" shadow="never">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<div class="card-header-left">
|
||||
<span class="card-title">我的复诊接诊率</span>
|
||||
<el-date-picker
|
||||
v-model="revisitMonth"
|
||||
type="month"
|
||||
value-format="YYYY-MM"
|
||||
placeholder="选择月份"
|
||||
:clearable="false"
|
||||
:disabled-date="disableFutureMonth"
|
||||
size="small"
|
||||
style="width: 130px"
|
||||
@change="fetchRevisitRate"
|
||||
/>
|
||||
</div>
|
||||
<span class="card-hint">{{ revisitMonthText }} · 与「复诊接诊率」报表同口径</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-loading="revisitLoading" class="revisit-rate-body">
|
||||
<template v-if="revisitRow">
|
||||
<div class="revisit-kpi-grid">
|
||||
<div class="revisit-kpi-card">
|
||||
<div class="stats-kpi-label">新指派数</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ Number(revisitRow.assigned_count ?? 0) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">当月新指派给我的患者</div>
|
||||
</div>
|
||||
<div class="revisit-kpi-card">
|
||||
<div class="stats-kpi-label">继承数</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ Number(revisitRow.inherit_count ?? 0) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">当月继承给我的患者</div>
|
||||
</div>
|
||||
<div class="revisit-kpi-card is-primary">
|
||||
<div class="stats-kpi-label">复诊合计接诊率</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ formatRate(revisitRow.visit_all_rate) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">{{ visitAllFractionText }}</div>
|
||||
</div>
|
||||
<div v-for="slot in revisitSlots" :key="slot" class="revisit-kpi-card">
|
||||
<div class="stats-kpi-label">{{ slotLabel(slot) }}接诊率</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ formatRate(slotMetric(slot, 'rate')) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">{{ slotFractionText(slot) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-empty v-else :description="revisitEmptyText" :image-size="72" />
|
||||
<div class="revisit-caliber">
|
||||
口径:N 诊接诊率 = 当月 N 诊成交单数 ÷ N 诊分母(新指派数 + 起算诊次 ≤ N 的继承数),分母为 0 显示「—」;
|
||||
<template v-if="revisitInheritMode === 'exclude'">当前为旧口径,继承患者不计入分母;</template>
|
||||
<template v-else>继承患者按继承时诊次从第 k+1 诊起计入;</template>
|
||||
复诊合计 = 各诊次成交单数之和 ÷ 被指派合计(新指派 ∪ 继承),可超过 100%。
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -63,7 +127,12 @@
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import vCharts from 'vue-echarts'
|
||||
import { assistantPerformanceOverview } from '@/api/stats'
|
||||
import {
|
||||
assistantPerformanceOverview,
|
||||
assistantPerformanceRevisitRate,
|
||||
type AssistantRevisitRateResult
|
||||
} from '@/api/stats'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
const loading = ref(false)
|
||||
const dateRange = ref<string[]>([])
|
||||
@@ -191,8 +260,78 @@ const handleReset = () => {
|
||||
fetchData()
|
||||
}
|
||||
|
||||
// ── 我的复诊接诊率(方案 §10 D1-h)────────────────────────
|
||||
/** 权限点由 server/sql/1.9.20261012/10_add_assistant_revisit_rate_menu.sql 登记并自动授予已有个人业绩页的角色 */
|
||||
const canViewRevisitRate = hasPermission(['stats.assistantPerformance/revisitRate'])
|
||||
|
||||
const initNow = new Date()
|
||||
const currentMonth = `${initNow.getFullYear()}-${String(initNow.getMonth() + 1).padStart(2, '0')}`
|
||||
const revisitMonth = ref<string>(currentMonth)
|
||||
const revisitLoading = ref(false)
|
||||
const revisitResult = ref<AssistantRevisitRateResult | null>(null)
|
||||
|
||||
const revisitRow = computed(() => revisitResult.value?.row ?? null)
|
||||
const revisitInheritMode = computed(() => revisitResult.value?.inherit_mode ?? 'slot')
|
||||
const revisitSlots = computed(() =>
|
||||
(revisitResult.value?.slots ?? []).map((s) => Number(s)).filter((s) => s >= 2)
|
||||
)
|
||||
const revisitMonthText = computed(() => {
|
||||
const [y, m] = (revisitResult.value?.month || revisitMonth.value).split('-')
|
||||
return y && m ? `${y} 年 ${Number(m)} 月` : revisitMonth.value
|
||||
})
|
||||
/** row=null:非二中心医助(in_scope=false)与「当月无被指派患者」文案区分 */
|
||||
const revisitEmptyText = computed(() => {
|
||||
if (revisitResult.value && revisitResult.value.in_scope === false) {
|
||||
return '暂无数据(仅二中心医助统计)'
|
||||
}
|
||||
return revisitMonth.value === currentMonth ? '本月暂无被指派患者' : '该月暂无被指派患者'
|
||||
})
|
||||
|
||||
const disableFutureMonth = (date: Date) => {
|
||||
const now = new Date()
|
||||
return date.getFullYear() * 12 + date.getMonth() > now.getFullYear() * 12 + now.getMonth()
|
||||
}
|
||||
|
||||
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
|
||||
const slotLabel = (slot: number) => {
|
||||
if (slot >= 2 && slot <= 10) return `${cnDigits[slot]}诊`
|
||||
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
|
||||
return `${slot}诊`
|
||||
}
|
||||
|
||||
const formatRate = (rate: unknown) =>
|
||||
rate === null || rate === undefined || rate === '' ? '—' : `${Number(rate)}%`
|
||||
|
||||
/** 读取本人行的 visit{N}_count / visit{N}_den / visit{N}_rate */
|
||||
const slotMetric = (slot: number, kind: 'count' | 'den' | 'rate') =>
|
||||
revisitRow.value?.[`visit${slot}_${kind}`]
|
||||
|
||||
/** 「成交 N 单 / 分母 M」 */
|
||||
const fractionText = (count: unknown, den: unknown) =>
|
||||
`成交 ${Number(count ?? 0)} 单 / 分母 ${Number(den ?? 0)}`
|
||||
|
||||
const slotFractionText = (slot: number) =>
|
||||
fractionText(slotMetric(slot, 'count'), slotMetric(slot, 'den'))
|
||||
|
||||
const visitAllFractionText = computed(() =>
|
||||
fractionText(revisitRow.value?.visit_all_count, revisitRow.value?.visit_all_den)
|
||||
)
|
||||
|
||||
const fetchRevisitRate = async () => {
|
||||
if (!canViewRevisitRate) return
|
||||
revisitLoading.value = true
|
||||
try {
|
||||
revisitResult.value = await assistantPerformanceRevisitRate({ month: revisitMonth.value })
|
||||
} catch {
|
||||
// 错误提示由 utils/request 统一弹出;失败时保留上一次结果
|
||||
} finally {
|
||||
revisitLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchData()
|
||||
fetchRevisitRate()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -270,4 +409,57 @@ onMounted(() => {
|
||||
.stats-chart {
|
||||
height: 360px;
|
||||
}
|
||||
|
||||
.card-header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.revisit-rate-body {
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.revisit-kpi-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.revisit-kpi-card {
|
||||
background: linear-gradient(145deg, #ffffff, #f7f9ff);
|
||||
border: 1px solid #ebf1ff;
|
||||
border-radius: 12px;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.revisit-kpi-card.is-primary {
|
||||
background: linear-gradient(145deg, #ffffff, #eef3ff);
|
||||
border-color: #d9e4ff;
|
||||
}
|
||||
|
||||
.revisit-kpi-value {
|
||||
margin-top: 8px;
|
||||
font-size: 24px;
|
||||
line-height: 1.1;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.revisit-kpi-card.is-primary .revisit-kpi-value {
|
||||
color: #4a78ff;
|
||||
}
|
||||
|
||||
.revisit-kpi-sub {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.revisit-caliber {
|
||||
margin-top: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -67,7 +67,10 @@
|
||||
</el-form>
|
||||
<div class="log-hint">
|
||||
由每日定时任务「待分配诊单自动指派」写入:按上月二诊复诊接诊率分档轮询分配(>70% 每人3条/日,60%~70%
|
||||
每人2条/日,50%~60% 每人1条/日,<50% 不分)。「回退」可将已分配医助撤回到自动分配前的原医助(通常为一中心),并写入指派日志。
|
||||
每人2条/日,50%~60% 每人1条/日,<50% 不分)。「回退」可将已分配医助撤回到自动分配前的原医助(通常为一中心),并写入指派日志(原医助重新接手按「继承」记录)。
|
||||
<br />
|
||||
口径版本:<b>v1 旧口径</b> = 分母仅新指派(visit2_rate_new_assign);<b>v2 新口径</b> = 每列独立分母,继承按继承时诊次计入(visit2_rate)。
|
||||
每条日志同时记录两套率并标注本批次分档所用口径(配置 project.revisit_rate.auto_assign_tier_field);2026-10 前的历史行仅有旧口径率。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
@@ -137,7 +140,7 @@
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.assistant_id) > 0">
|
||||
<div>{{ row.assistant_name || '#' + row.assistant_id }}</div>
|
||||
<div class="cell-sub">上月二诊接诊率 {{ formatRate(row.visit2_rate) }}</div>
|
||||
<div class="cell-sub">上月二诊接诊率 {{ formatRate(tierRate(row)) }}</div>
|
||||
</template>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
@@ -145,6 +148,29 @@
|
||||
<el-table-column label="档位" width="100" align="center">
|
||||
<template #default="{ row }">{{ row.tier_text || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="分档口径" min-width="150">
|
||||
<template #header>
|
||||
<span>分档口径</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
effect="dark"
|
||||
content="本批次分档所用口径;下方为两套口径的上月二诊接诊率(新口径 = 每列独立分母 / 旧口径 = 分母仅新指派)"
|
||||
>
|
||||
<el-icon class="col-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.action) === 1">
|
||||
<el-tag :type="row.rate_version === 'v2' ? 'primary' : 'info'" size="small">
|
||||
{{ row.rate_version_text || row.rate_version || 'v1' }}
|
||||
</el-tag>
|
||||
<div class="cell-sub">
|
||||
新口径 {{ formatRate(row.visit2_rate) }} · 旧口径 {{ formatRate(row.visit2_rate_new_assign) }}
|
||||
</div>
|
||||
</template>
|
||||
<span v-else class="cell-sub">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="轮次" width="70" align="center">
|
||||
<template #default="{ row }">
|
||||
{{ Number(row.round_no) > 0 ? '第' + row.round_no + '轮' : '—' }}
|
||||
@@ -186,6 +212,7 @@
|
||||
import { autoAssignLogLists, autoAssignLogRollback } from '@/api/stats'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
|
||||
const dateRange = ref<[string, string] | null>(null)
|
||||
@@ -241,6 +268,14 @@ const handleReset = () => {
|
||||
const formatRate = (rate: number | null | undefined) =>
|
||||
rate === null || rate === undefined ? '—' : `${rate}%`
|
||||
|
||||
/** 「医助」列显示的接诊率 = 本批次分档所用口径的率(v1 旧口径取 visit2_rate_new_assign,历史行无该列时回落 visit2_rate) */
|
||||
const tierRate = (row: any): number | null | undefined => {
|
||||
if (row?.rate_version === 'v1' && row?.visit2_rate_new_assign !== null && row?.visit2_rate_new_assign !== undefined) {
|
||||
return row.visit2_rate_new_assign
|
||||
}
|
||||
return row?.visit2_rate
|
||||
}
|
||||
|
||||
const rowSelectable = (row: any) => Number(row.can_rollback) === 1
|
||||
|
||||
const onSelectionChange = (rows: any[]) => {
|
||||
@@ -315,5 +350,12 @@ onMounted(() => getLists())
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.col-hint {
|
||||
margin-left: 2px;
|
||||
vertical-align: -2px;
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,901 @@
|
||||
<template>
|
||||
<div class="revisit-rate-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true" class="rate-filter-form">
|
||||
<el-form-item :label="dateLabel">
|
||||
<el-date-picker
|
||||
v-model="dateRange"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
range-separator="至"
|
||||
:clearable="false"
|
||||
style="width: 280px"
|
||||
@change="loadData"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-tree-select
|
||||
v-model="deptId"
|
||||
:data="deptTreeOptions"
|
||||
placeholder="二中心(全部)"
|
||||
clearable
|
||||
filterable
|
||||
check-strictly
|
||||
node-key="id"
|
||||
:default-expand-all="true"
|
||||
:props="deptTreeProps"
|
||||
style="width: 210px"
|
||||
@change="handleDeptChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="医助">
|
||||
<el-select
|
||||
v-model="assistantId"
|
||||
placeholder="全部医助"
|
||||
filterable
|
||||
clearable
|
||||
:loading="optionsLoading"
|
||||
style="width: 180px"
|
||||
@change="loadData"
|
||||
>
|
||||
<el-option
|
||||
v-for="assistant in assistantOptions"
|
||||
:key="assistant.id"
|
||||
:label="assistant.name"
|
||||
:value="assistant.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
|
||||
<el-button :disabled="loading" @click="handleReset">重置</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-popover placement="bottom-start" :width="540" trigger="hover">
|
||||
<template #reference>
|
||||
<span class="rate-caliber-trigger"
|
||||
><el-icon><InfoFilled /></el-icon>统计口径</span
|
||||
>
|
||||
</template>
|
||||
<div class="rate-caliber">
|
||||
<p>
|
||||
<b>{{ cohortLabel }}</b
|
||||
>:按所选{{
|
||||
dateLabel
|
||||
}}范围确定患者,订单从对应指派后累计至查询当天;结束日期允许选择未来日期,但未来订单不会提前计入。
|
||||
</p>
|
||||
<p v-if="isInherit">
|
||||
<b>继承诊次重新起算</b>:继承后的第 1 笔有效订单算二诊,第 2
|
||||
笔算三诊,依次递增;不使用继承前的全局诊次,也不叠加诊次偏移。只统计继承患者,不混入新指派患者。
|
||||
</p>
|
||||
<p v-else>
|
||||
只统计新指派患者,不混入继承患者。继承患者在独立的「继承复诊接诊率」页面统计。
|
||||
</p>
|
||||
<p>
|
||||
<b>N 诊接诊率</b> = N 诊单数 ÷ 本页{{ cohortLabel }};分母为 0
|
||||
显示「—」。<b>复诊合计接诊率</b> = 复诊合计单数 ÷ 本页{{
|
||||
cohortLabel
|
||||
}},表示人均复诊成交单数,可超过 100%。
|
||||
</p>
|
||||
<p>
|
||||
订单仅计入有效业务订单,剔除已取消 / 拒收 /
|
||||
退款;归属按服务端的患者持有记录计算。医助按人事部门归组;仅统计「二中心」及其组织下级,选定部门时包含其下级。
|
||||
</p>
|
||||
<p>
|
||||
部门行和合计行按诊单去重,不能直接将医助行相加。灰字为「单数 /
|
||||
分母」。
|
||||
</p>
|
||||
</div>
|
||||
</el-popover>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-alert class="mt-3" type="info" :closable="false" show-icon :title="reportHint" />
|
||||
<el-alert
|
||||
v-if="optionsError"
|
||||
class="mt-3"
|
||||
type="warning"
|
||||
:title="optionsError"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="queryError"
|
||||
class="mt-3"
|
||||
type="error"
|
||||
:title="queryError"
|
||||
:closable="false"
|
||||
/>
|
||||
</el-card>
|
||||
|
||||
<div class="rate-kpi-grid">
|
||||
<div
|
||||
v-for="card in summaryCards"
|
||||
:key="card.key"
|
||||
class="rate-kpi-card"
|
||||
:class="{ 'is-clickable': card.clickable }"
|
||||
@click="card.clickable && card.onClick()"
|
||||
>
|
||||
<div class="rate-kpi-label">{{ card.label }}</div>
|
||||
<div class="rate-kpi-value">{{ card.value }}</div>
|
||||
<div v-if="card.sub" class="rate-kpi-sub">{{ card.sub }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-card class="!border-none mt-4" shadow="never">
|
||||
<template #header>
|
||||
<div class="rate-card-header">
|
||||
<span>{{ reportTitle }} · 部门 / 医助明细</span>
|
||||
<span class="rate-card-hint">{{ dateLabel }}:{{ rangeText }}</span>
|
||||
<span v-if="observedUntil" class="rate-card-hint"
|
||||
>订单统计截至:{{ observedUntil }}</span
|
||||
>
|
||||
</div>
|
||||
<div class="rate-card-hint mt-2">
|
||||
点击{{ cohortLabel }}、各诊次单数可查看患者与订单;底栏合计按诊单去重。
|
||||
</div>
|
||||
</template>
|
||||
<el-table
|
||||
v-loading="loading"
|
||||
:data="rows"
|
||||
size="small"
|
||||
border
|
||||
row-key="row_key"
|
||||
:tree-props="{ children: 'children' }"
|
||||
:default-expand-all="true"
|
||||
show-summary
|
||||
:summary-method="getSummaries"
|
||||
>
|
||||
<el-table-column label="部门 / 医助" min-width="200" fixed>
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.is_dept" class="rate-dept-cell"
|
||||
>{{ row.dept_name
|
||||
}}<span class="rate-dept-count"
|
||||
>{{ row.assistant_count }} 人</span
|
||||
></span
|
||||
>
|
||||
<span v-else>{{ row.assistant_name }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
:prop="cohortCountKey"
|
||||
:label="cohortLabel"
|
||||
min-width="100"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ cohortLabel }}</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="`所选${dateLabel}范围内的${cohortLabel},部门和合计按诊单去重`"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row[cohortCountKey] > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row)"
|
||||
>{{ row[cohortCountKey] }}</el-link
|
||||
>
|
||||
<span v-else>{{ row[cohortCountKey] ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template v-for="slot in visitSlots" :key="slot">
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_count`"
|
||||
:label="`${slotLabel(slot)}单数`"
|
||||
min-width="96"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ slotLabel(slot) }}单数</span>
|
||||
<el-tooltip effect="dark" placement="top" :content="slotCountTip(slot)"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderLines && row[`visit${slot}_count`] > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderDetail(slot, row)"
|
||||
>{{ row[`visit${slot}_count`] }}</el-link
|
||||
>
|
||||
<span v-else>{{ row[`visit${slot}_count`] ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_rate`"
|
||||
:label="`${slotLabel(slot)}接诊率`"
|
||||
min-width="110"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ slotLabel(slot) }}接诊率</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="`${slotLabel(slot)}单数 ÷ ${cohortLabel};分母为 0 显示「—」`"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{
|
||||
formatRate(row[`visit${slot}_rate`])
|
||||
}}</span
|
||||
><span class="rate-cell-sub">{{
|
||||
denText(row, `visit${slot}`)
|
||||
}}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</template>
|
||||
<el-table-column
|
||||
prop="visit_all_count"
|
||||
label="复诊合计单数"
|
||||
min-width="110"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>复诊合计单数</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
content="所选患者从对应指派后累计至查询当天的全部复诊订单数"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderLines && row.visit_all_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderDetail(0, row)"
|
||||
>{{ row.visit_all_count }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="visit_all_rate"
|
||||
label="复诊合计接诊率"
|
||||
min-width="128"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>复诊合计接诊率</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="`复诊合计单数 ÷ ${cohortLabel};表示人均复诊成交单数,可超过 100%`"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span
|
||||
><span class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
<el-dialog
|
||||
v-model="detailVisible"
|
||||
:title="detailTitle"
|
||||
width="1080px"
|
||||
top="6vh"
|
||||
destroy-on-close
|
||||
@close="invalidateDetail"
|
||||
>
|
||||
<p class="rate-detail-hint">{{ detailHint }}</p>
|
||||
<el-alert
|
||||
v-if="detailError"
|
||||
class="mb-3"
|
||||
type="error"
|
||||
:title="detailError"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-table
|
||||
v-loading="detailLoading"
|
||||
:data="detailRows"
|
||||
size="small"
|
||||
border
|
||||
stripe
|
||||
max-height="60vh"
|
||||
>
|
||||
<template v-if="detailType === 'assign'">
|
||||
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
|
||||
<el-table-column prop="patient_name" label="患者" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewPatientDetail && row.diagnosis_id"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openPatientDetail(row.diagnosis_id)"
|
||||
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.patient_name || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
|
||||
><template #default="{ row }">{{
|
||||
row.patient_phone || '—'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
prop="assistant_names"
|
||||
:label="isInherit ? '继承医助' : '被指派医助'"
|
||||
min-width="140"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
prop="assign_count"
|
||||
:label="isInherit ? '范围内继承次数' : '范围内指派次数'"
|
||||
width="120"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="first_assign_time_text"
|
||||
:label="isInherit ? '首次继承时间' : '首次指派时间'"
|
||||
min-width="160"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="last_assign_time_text"
|
||||
:label="isInherit ? '最近继承时间' : '最近指派时间'"
|
||||
min-width="160"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<el-table-column
|
||||
prop="order_no"
|
||||
label="订单号"
|
||||
min-width="180"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderDetail && row.order_id"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderInfo(row.order_id)"
|
||||
>{{ row.order_no || `#${row.order_id}` }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
v-if="detailSlot === 0 || isInherit"
|
||||
prop="visit_slot"
|
||||
:label="isInherit ? '继承后诊次' : '诊次'"
|
||||
width="100"
|
||||
align="center"
|
||||
><template #default="{ row }">{{
|
||||
slotLabel(Number(row.visit_slot))
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
v-if="isInherit"
|
||||
prop="global_visit_slot"
|
||||
label="全局诊次(参考)"
|
||||
width="130"
|
||||
align="center"
|
||||
><template #default="{ row }">{{
|
||||
row.global_visit_slot ? slotLabel(Number(row.global_visit_slot)) : '—'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
|
||||
<el-table-column prop="patient_name" label="患者" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewPatientDetail && row.diagnosis_id"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openPatientDetail(row.diagnosis_id)"
|
||||
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.patient_name || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
|
||||
><template #default="{ row }">{{
|
||||
row.patient_phone || '—'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column prop="amount" label="金额" width="100" align="right"
|
||||
><template #default="{ row }">¥ {{ row.amount }}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
prop="cohort_assign_time_text"
|
||||
:label="isInherit ? '继承时间' : '指派时间'"
|
||||
min-width="160"
|
||||
/>
|
||||
<el-table-column prop="create_time_text" label="下单时间" min-width="160" />
|
||||
<el-table-column prop="assistant_name" label="持有医助" min-width="100" />
|
||||
<el-table-column prop="creator_name" label="订单创建人" min-width="100" />
|
||||
</template>
|
||||
</el-table>
|
||||
<div class="rate-detail-footer">共 {{ detailCount }} 条</div>
|
||||
</el-dialog>
|
||||
<order-detail-drawer ref="orderDetailRef" readonly append-to-body />
|
||||
<diagnosis-edit-popup ref="diagnosisEditRef" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
import {
|
||||
revisitCohortAssignLines,
|
||||
revisitCohortDeptOptions,
|
||||
revisitCohortOverview,
|
||||
revisitCohortVisitOrderLines,
|
||||
type RevisitRateCohortType,
|
||||
type RevisitRateDetailQuery,
|
||||
type RevisitRateQuery
|
||||
} from '@/api/stats'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
const props = defineProps<{ cohortType: RevisitRateCohortType }>()
|
||||
const OrderDetailDrawer = defineAsyncComponent(
|
||||
() => import('@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue')
|
||||
)
|
||||
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
|
||||
|
||||
interface MetricPack extends Record<string, any> {
|
||||
assigned_count: number
|
||||
inherit_count: number
|
||||
assigned_total_count: number
|
||||
visit_all_count: number
|
||||
visit_all_den: number
|
||||
visit_all_rate: number | null
|
||||
}
|
||||
interface StatsRow extends MetricPack {
|
||||
row_key: string
|
||||
is_dept: 0 | 1
|
||||
dept_id: number
|
||||
dept_name: string
|
||||
assistant_id?: number
|
||||
assistant_name?: string
|
||||
assistant_count?: number
|
||||
children?: StatsRow[]
|
||||
}
|
||||
interface DeptOption {
|
||||
id: number
|
||||
pid: number
|
||||
name: string
|
||||
}
|
||||
interface DeptTreeNode extends DeptOption {
|
||||
children?: DeptTreeNode[]
|
||||
}
|
||||
interface AssistantOption {
|
||||
id: number
|
||||
name: string
|
||||
dept_id: number
|
||||
}
|
||||
interface SummaryCard {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
sub: string
|
||||
clickable: boolean
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
const isInherit = computed(() => props.cohortType === 'inherit')
|
||||
const cohortLabel = computed(() => (isInherit.value ? '继承数' : '新指派数'))
|
||||
const cohortCountKey = computed(() => (isInherit.value ? 'inherit_count' : 'assigned_count'))
|
||||
const dateLabel = computed(() => (isInherit.value ? '继承日期' : '指派日期'))
|
||||
const reportTitle = computed(() => (isInherit.value ? '继承复诊接诊率' : '按指派周期复诊率'))
|
||||
const reportHint = computed(() =>
|
||||
isInherit.value
|
||||
? '按继承日期范围选择患者,订单累计至查询当天。继承后第 1 笔有效订单算二诊,第 2 笔算三诊;忽略继承前全局诊次及偏移,新指派患者另页统计。'
|
||||
: '按新指派日期范围选择患者,订单累计至查询当天,跨月继续累计。继承患者在独立的「继承复诊接诊率」页面统计。'
|
||||
)
|
||||
const permissionPrefix = computed(() =>
|
||||
isInherit.value ? 'stats.revisitInheritRate' : 'stats.revisitAssignRate'
|
||||
)
|
||||
const canViewAssignLines = computed(() => hasPermission([`${permissionPrefix.value}/assignLines`]))
|
||||
const canViewOrderLines = computed(() =>
|
||||
hasPermission([`${permissionPrefix.value}/visitOrderLines`])
|
||||
)
|
||||
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
|
||||
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
|
||||
|
||||
const formatDate = (date: Date) =>
|
||||
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
|
||||
const defaultDateRange = (): [string, string] => {
|
||||
const now = new Date()
|
||||
return [formatDate(new Date(now.getFullYear(), now.getMonth(), 1)), formatDate(now)]
|
||||
}
|
||||
const dateRange = ref<[string, string]>(defaultDateRange())
|
||||
const deptId = ref<number | undefined>()
|
||||
const assistantId = ref<number | undefined>()
|
||||
const loading = ref(false)
|
||||
const queryError = ref('')
|
||||
const rows = ref<StatsRow[]>([])
|
||||
const total = ref<MetricPack | null>(null)
|
||||
const visitSlots = ref<number[]>([2, 3, 4])
|
||||
const observedUntil = ref('')
|
||||
/** 下钻只复用已展示报表的查询快照,避免读取正在编辑的筛选。 */
|
||||
const loadedQuery = ref<RevisitRateQuery | null>(null)
|
||||
let overviewRequestId = 0
|
||||
let disposed = false
|
||||
const rangeText = computed(() =>
|
||||
loadedQuery.value
|
||||
? `${loadedQuery.value.start_date} 至 ${loadedQuery.value.end_date}`
|
||||
: `${dateRange.value[0]} 至 ${dateRange.value[1]}`
|
||||
)
|
||||
const currentQuery = (): RevisitRateQuery => ({
|
||||
start_date: dateRange.value[0],
|
||||
end_date: dateRange.value[1],
|
||||
dept_ids: deptId.value ? String(deptId.value) : '',
|
||||
assistant_id: assistantId.value || undefined
|
||||
})
|
||||
|
||||
const deptOptions = ref<DeptOption[]>([])
|
||||
const allAssistants = ref<AssistantOption[]>([])
|
||||
const optionsLoading = ref(false)
|
||||
const optionsError = ref('')
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
const deptTreeOptions = computed<DeptTreeNode[]>(() => {
|
||||
const nodes = new Map<number, DeptTreeNode>()
|
||||
deptOptions.value.forEach((item) => nodes.set(item.id, { ...item, children: [] }))
|
||||
const roots: DeptTreeNode[] = []
|
||||
nodes.forEach((node) => {
|
||||
const parent = nodes.get(node.pid)
|
||||
if (parent && parent !== node) parent.children!.push(node)
|
||||
else roots.push(node)
|
||||
})
|
||||
const stripEmptyChildren = (node: DeptTreeNode) => {
|
||||
if (node.children?.length) node.children.forEach(stripEmptyChildren)
|
||||
else delete node.children
|
||||
}
|
||||
roots.forEach(stripEmptyChildren)
|
||||
return roots
|
||||
})
|
||||
const selectedDeptIds = computed(() => {
|
||||
if (!deptId.value) return null
|
||||
const ids = new Set<number>([Number(deptId.value)])
|
||||
let expanded = true
|
||||
while (expanded) {
|
||||
expanded = false
|
||||
deptOptions.value.forEach((item) => {
|
||||
if (ids.has(item.pid) && !ids.has(item.id)) {
|
||||
ids.add(item.id)
|
||||
expanded = true
|
||||
}
|
||||
})
|
||||
}
|
||||
return ids
|
||||
})
|
||||
const assistantOptions = computed(() =>
|
||||
allAssistants.value.filter(
|
||||
(item) => !selectedDeptIds.value || selectedDeptIds.value.has(item.dept_id)
|
||||
)
|
||||
)
|
||||
const handleDeptChange = () => {
|
||||
if (assistantId.value && !assistantOptions.value.some((item) => item.id === assistantId.value))
|
||||
assistantId.value = undefined
|
||||
void loadData()
|
||||
}
|
||||
const loadDeptOptions = async () => {
|
||||
optionsLoading.value = true
|
||||
optionsError.value = ''
|
||||
try {
|
||||
const res = await revisitCohortDeptOptions(props.cohortType)
|
||||
if (disposed) return
|
||||
deptOptions.value = (res?.rows ?? []).map((item: DeptOption) => ({
|
||||
...item,
|
||||
id: Number(item.id),
|
||||
pid: Number(item.pid)
|
||||
}))
|
||||
allAssistants.value = (res?.assistants ?? []).map((item: AssistantOption) => ({
|
||||
...item,
|
||||
id: Number(item.id),
|
||||
dept_id: Number(item.dept_id)
|
||||
}))
|
||||
} catch {
|
||||
if (!disposed) optionsError.value = '部门及医助选项加载失败,请刷新页面重试。'
|
||||
} finally {
|
||||
if (!disposed) optionsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
|
||||
const slotLabel = (slot: number) => {
|
||||
if (slot === 0) return '复诊合计'
|
||||
if (slot >= 1 && slot <= 10) return `${cnDigits[slot]}诊`
|
||||
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
|
||||
return `${slot}诊`
|
||||
}
|
||||
const slotCountTip = (slot: number) =>
|
||||
isInherit.value
|
||||
? `所选继承患者在继承后的第 ${slot - 1} 笔有效订单数,累计至查询当天;不使用继承前全局诊次和偏移`
|
||||
: `所选新指派患者的${slotLabel(slot)}有效订单数,从对应指派后累计至查询当天`
|
||||
const formatRate = (rate: number | null | undefined) =>
|
||||
rate === null || rate === undefined ? '—' : `${rate}%`
|
||||
const denText = (row: Record<string, any>, prefix: string) =>
|
||||
`${Number(row[`${prefix}_count`] ?? 0)} / ${row[`${prefix}_den`] ?? '—'}`
|
||||
const summaryCards = computed<SummaryCard[]>(() => {
|
||||
const t = total.value
|
||||
const cards: SummaryCard[] = [
|
||||
{
|
||||
key: 'cohort',
|
||||
label: cohortLabel.value,
|
||||
value: t ? String(t[cohortCountKey.value] ?? 0) : '—',
|
||||
sub: `按${dateLabel.value}范围选择患者`,
|
||||
clickable: !!(canViewAssignLines.value && t && t[cohortCountKey.value] > 0),
|
||||
onClick: () => void openAssignDetail(null)
|
||||
}
|
||||
]
|
||||
visitSlots.value.forEach((slot) =>
|
||||
cards.push({
|
||||
key: `visit${slot}`,
|
||||
label: `${slotLabel(slot)}接诊率`,
|
||||
value: t ? formatRate(t[`visit${slot}_rate`]) : '—',
|
||||
sub: t
|
||||
? `${slotLabel(slot)}下单 ${t[`visit${slot}_count`] ?? 0} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}`
|
||||
: '',
|
||||
clickable: !!(canViewOrderLines.value && t && t[`visit${slot}_count`] > 0),
|
||||
onClick: () => void openOrderDetail(slot, null)
|
||||
})
|
||||
)
|
||||
cards.push({
|
||||
key: 'visit_all',
|
||||
label: '复诊合计接诊率',
|
||||
value: t ? formatRate(t.visit_all_rate) : '—',
|
||||
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 分母 ${t.visit_all_den ?? '—'}` : '',
|
||||
clickable: !!(canViewOrderLines.value && t && t.visit_all_count > 0),
|
||||
onClick: () => void openOrderDetail(0, null)
|
||||
})
|
||||
return cards
|
||||
})
|
||||
/** 服务端已按诊单去重,合计不能由各医助行相加。 */
|
||||
const getSummaries = ({ columns }: { columns: Array<{ property?: string }> }) =>
|
||||
columns.map((column, index) => {
|
||||
if (index === 0) return '合计'
|
||||
const t = total.value
|
||||
if (!t) return ''
|
||||
const prop = column.property || ''
|
||||
if (prop === cohortCountKey.value) return String(t[prop] ?? 0)
|
||||
const match = /^visit(\d+|_all)_(count|rate)$/.exec(prop)
|
||||
if (!match) return ''
|
||||
return match[2] === 'rate'
|
||||
? `${formatRate(t[prop])}(${denText(t, `visit${match[1]}`)})`
|
||||
: String(t[prop] ?? 0)
|
||||
})
|
||||
|
||||
const loadData = async () => {
|
||||
const requestId = ++overviewRequestId
|
||||
invalidateDetail()
|
||||
detailVisible.value = false
|
||||
loadedQuery.value = null
|
||||
rows.value = []
|
||||
total.value = null
|
||||
observedUntil.value = ''
|
||||
queryError.value = ''
|
||||
loading.value = true
|
||||
const query = currentQuery()
|
||||
try {
|
||||
const res = await revisitCohortOverview(query, props.cohortType)
|
||||
if (disposed || requestId !== overviewRequestId) return
|
||||
rows.value = res?.rows ?? []
|
||||
total.value = res?.total ?? null
|
||||
observedUntil.value = res?.observed_until ?? ''
|
||||
const slots: number[] = Array.isArray(res?.slots) ? res.slots.map(Number) : []
|
||||
visitSlots.value = slots.length
|
||||
? [
|
||||
...new Set(
|
||||
slots.filter((slot) => Number.isInteger(slot) && slot >= 2 && slot <= 50)
|
||||
)
|
||||
].sort((a, b) => a - b)
|
||||
: [2, 3, 4]
|
||||
loadedQuery.value = { ...query }
|
||||
} catch {
|
||||
if (!disposed && requestId === overviewRequestId)
|
||||
queryError.value = '报表加载失败,请重新查询。'
|
||||
} finally {
|
||||
if (!disposed && requestId === overviewRequestId) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const detailVisible = ref(false)
|
||||
const detailType = ref<'assign' | 'orders'>('assign')
|
||||
const detailTitle = ref('')
|
||||
const detailHint = ref('')
|
||||
const detailLoading = ref(false)
|
||||
const detailError = ref('')
|
||||
const detailRows = ref<any[]>([])
|
||||
const detailCount = ref(0)
|
||||
const detailSlot = ref(2)
|
||||
let detailRequestId = 0
|
||||
const invalidateDetail = () => {
|
||||
++detailRequestId
|
||||
detailLoading.value = false
|
||||
detailRows.value = []
|
||||
detailCount.value = 0
|
||||
detailError.value = ''
|
||||
}
|
||||
const rowScope = (
|
||||
row: StatsRow | null
|
||||
): Pick<RevisitRateDetailQuery, 'scope_assistant_id' | 'dept_id'> & { label: string } => {
|
||||
if (!row) return { label: '合计' }
|
||||
return row.is_dept
|
||||
? { dept_id: row.dept_id, label: row.dept_name }
|
||||
: { scope_assistant_id: row.assistant_id, label: row.assistant_name || '' }
|
||||
}
|
||||
const openDetail = async (type: 'assign' | 'orders', slot: number, row: StatsRow | null) => {
|
||||
if (loading.value || !loadedQuery.value) return
|
||||
if (type === 'assign' ? !canViewAssignLines.value : !canViewOrderLines.value) return
|
||||
const query = { ...loadedQuery.value }
|
||||
const { label, ...scope } = rowScope(row)
|
||||
const requestId = ++detailRequestId
|
||||
detailType.value = type
|
||||
detailSlot.value = slot
|
||||
detailTitle.value = `${label} · ${type === 'assign' ? `${cohortLabel.value}明细` : `${slotLabel(slot)}订单明细`}(${query.start_date} 至 ${query.end_date})`
|
||||
detailHint.value = `${dateLabel.value}:${query.start_date} 至 ${query.end_date};订单统计截至:${observedUntil.value || '查询当天'}${isInherit.value && type === 'orders' ? '。继承后首笔有效订单算二诊,全局诊次仅供参考。' : '。'}`
|
||||
detailRows.value = []
|
||||
detailCount.value = 0
|
||||
detailError.value = ''
|
||||
detailLoading.value = true
|
||||
detailVisible.value = true
|
||||
try {
|
||||
// assistant_id 保留顶层筛选,scope_assistant_id 独立约束医助行。
|
||||
const params: RevisitRateDetailQuery = { ...query, ...scope }
|
||||
const res =
|
||||
type === 'assign'
|
||||
? await revisitCohortAssignLines(params, props.cohortType)
|
||||
: await revisitCohortVisitOrderLines({ ...params, slot }, props.cohortType)
|
||||
if (disposed || requestId !== detailRequestId || !detailVisible.value) return
|
||||
detailRows.value = res?.rows ?? []
|
||||
detailCount.value = Number(res?.count ?? detailRows.value.length)
|
||||
} catch {
|
||||
if (!disposed && requestId === detailRequestId)
|
||||
detailError.value = '明细加载失败,请关闭后重试。'
|
||||
} finally {
|
||||
if (!disposed && requestId === detailRequestId) detailLoading.value = false
|
||||
}
|
||||
}
|
||||
const openAssignDetail = (row: StatsRow | null) => openDetail('assign', 0, row)
|
||||
const openOrderDetail = (slot: number, row: StatsRow | null) => openDetail('orders', slot, row)
|
||||
const orderDetailRef = ref<{ open: (id: number) => void } | null>(null)
|
||||
const openOrderInfo = (orderId: number) => {
|
||||
if (canViewOrderDetail && orderId) orderDetailRef.value?.open(orderId)
|
||||
}
|
||||
const diagnosisEditRef = ref<{ openViewOnly: (id: number) => void } | null>(null)
|
||||
const openPatientDetail = (diagnosisId: number) => {
|
||||
if (canViewPatientDetail && diagnosisId) diagnosisEditRef.value?.openViewOnly(diagnosisId)
|
||||
}
|
||||
const handleReset = () => {
|
||||
dateRange.value = defaultDateRange()
|
||||
deptId.value = undefined
|
||||
assistantId.value = undefined
|
||||
void loadData()
|
||||
}
|
||||
onMounted(() => {
|
||||
void loadDeptOptions()
|
||||
void loadData()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
++overviewRequestId
|
||||
++detailRequestId
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.revisit-rate-page {
|
||||
.rate-filter-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px 0;
|
||||
:deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
.rate-caliber-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
cursor: help;
|
||||
}
|
||||
.rate-kpi-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.rate-kpi-card {
|
||||
background: var(--el-bg-color);
|
||||
border-radius: 8px;
|
||||
padding: 16px 20px;
|
||||
&.is-clickable {
|
||||
cursor: pointer;
|
||||
transition: box-shadow 0.15s ease;
|
||||
&:hover {
|
||||
box-shadow: var(--el-box-shadow-light);
|
||||
}
|
||||
}
|
||||
.rate-kpi-label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rate-kpi-value {
|
||||
margin-top: 6px;
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.rate-kpi-sub {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
.rate-card-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
}
|
||||
.rate-card-hint {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.rate-dept-cell {
|
||||
font-weight: 600;
|
||||
.rate-dept-count {
|
||||
margin-left: 6px;
|
||||
font-weight: 400;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
.rate-th-hint {
|
||||
margin-left: 2px;
|
||||
vertical-align: -2px;
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
.rate-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
line-height: 1.3;
|
||||
.rate-cell-main {
|
||||
font-weight: 500;
|
||||
}
|
||||
.rate-cell-sub {
|
||||
font-size: 11px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
}
|
||||
.rate-detail-hint {
|
||||
margin: 0 0 12px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.rate-detail-footer {
|
||||
margin-top: 10px;
|
||||
text-align: right;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.rate-caliber {
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--el-text-color-regular);
|
||||
p + p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<cohort-report cohort-type="new" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="revisitAssignRateStatsPage">
|
||||
import CohortReport from './components/CohortReport.vue'
|
||||
</script>
|
||||
@@ -0,0 +1,863 @@
|
||||
<template>
|
||||
<div class="revisit-due-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true" class="due-filter-form">
|
||||
<el-form-item label="医助">
|
||||
<el-select
|
||||
v-model="queryParams.assistant_id"
|
||||
clearable
|
||||
filterable
|
||||
placeholder="全部"
|
||||
class="w-[160px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in assistantOptions"
|
||||
:key="item.id"
|
||||
:label="item.name"
|
||||
:value="Number(item.id)"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-tree-select
|
||||
v-model="queryParams.dept_id"
|
||||
:data="deptTreeOptions"
|
||||
placeholder="全部(二中心)"
|
||||
clearable
|
||||
filterable
|
||||
check-strictly
|
||||
node-key="id"
|
||||
:default-expand-all="true"
|
||||
:props="deptTreeProps"
|
||||
class="w-[200px]"
|
||||
@change="doSearch"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select
|
||||
v-model="queryParams.state"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="w-[170px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="opt in stateOptions"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="开药天数">
|
||||
<el-select
|
||||
v-model="queryParams.days_bucket"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="w-[120px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="opt in REVISIT_DAYS_BUCKET_OPTIONS"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="延迟次数 ≥">
|
||||
<el-input-number
|
||||
v-model="minSnooze"
|
||||
:min="0"
|
||||
:max="999"
|
||||
:step="1"
|
||||
step-strictly
|
||||
controls-position="right"
|
||||
placeholder="不限"
|
||||
class="!w-[120px]"
|
||||
@change="onMinSnoozeChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="患者">
|
||||
<el-input
|
||||
v-model="queryParams.keyword"
|
||||
placeholder="患者姓名"
|
||||
clearable
|
||||
class="w-[160px]"
|
||||
@keyup.enter="doSearch"
|
||||
@clear="doSearch"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="doSearch">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
<export-data
|
||||
class="ml-2.5"
|
||||
:fetch-fun="revisitDueLists"
|
||||
:params="queryParams"
|
||||
:page-size="pager.size"
|
||||
export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 延迟次数 / 患者)"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="due-hint">
|
||||
每位患者(诊单)一行,取最新有效业务订单为本轮周期:预计复诊日 = 用药起算日(签收 → 发货 → 下单)+ 开药天数;
|
||||
到期仍无有效挂号 / 过号未面诊的行标红,持有医助登录后台会收到右下角弹窗。
|
||||
「延迟次数」为医助在弹窗上点「延迟」的累计次数(越多说明越未跟进),「已联系」为填写患者承诺复诊日的次数,
|
||||
「人工关闭」由医助填原因关闭、在此标记供主管复核。数据范围按角色数据权限收窄;状态按今天实时推导。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none mt-3" shadow="never">
|
||||
<el-table
|
||||
:data="pager.lists"
|
||||
v-loading="pager.loading"
|
||||
size="default"
|
||||
stripe
|
||||
row-key="id"
|
||||
:row-class-name="rowClassName"
|
||||
>
|
||||
<el-table-column label="患者" min-width="120" fixed="left">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ row.patient_name || '—' }}</div>
|
||||
<div class="cell-sub">诊单 #{{ row.diagnosis_id }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="医助" min-width="100">
|
||||
<template #default="{ row }">{{ assistantText(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="部门" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.dept_name || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="诊次" width="110" align="center">
|
||||
<template #header>
|
||||
<span>诊次</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
effect="dark"
|
||||
content="患者当前已完成诊次 = 有效业务订单数 + 诊单诊次偏移,与复诊接诊率同口径;下一行为待复诊诊次"
|
||||
>
|
||||
<el-icon class="col-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ slotText(row) }}</div>
|
||||
<div v-if="Number(row.next_slot) > 0" class="cell-sub">
|
||||
待复诊第 {{ row.next_slot }} 诊
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="开药天数" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.medication_days) > 0">
|
||||
<span>{{ row.medication_days }} 天</span>
|
||||
<el-tag
|
||||
v-if="Number(row.rule_days) > 0"
|
||||
size="small"
|
||||
type="info"
|
||||
effect="plain"
|
||||
class="ml-1"
|
||||
>
|
||||
{{ row.rule_days }} 档
|
||||
</el-tag>
|
||||
</template>
|
||||
<span v-else class="text-missing">缺开药天数</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="预计复诊" width="110">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ row.due_date || '—' }}</div>
|
||||
<div v-if="row.anchor_date" class="cell-sub">
|
||||
起算 {{ formatRevisitMonthDay(row.anchor_date) }}
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="超期天数" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<span :class="['overdue-cell', overdueCell(row).cls]">
|
||||
{{ overdueCell(row).text }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<el-tag
|
||||
:type="revisitStateTagType(row.state)"
|
||||
:effect="revisitStateTagEffect(row.state)"
|
||||
size="small"
|
||||
:class="revisitStateChipClass(dueOf(row))"
|
||||
>
|
||||
{{ chipText(row) }}
|
||||
</el-tag>
|
||||
<el-tag
|
||||
v-if="Number(row.closed_state) === 4"
|
||||
size="small"
|
||||
type="info"
|
||||
effect="plain"
|
||||
class="ml-1"
|
||||
>
|
||||
人工关闭
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="延迟次数" width="100" align="center">
|
||||
<template #header>
|
||||
<span>延迟次数</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
effect="dark"
|
||||
content="医助在到期弹窗上点「延迟」的累计次数;1~2 次 L1、3~4 次 L2、≥5 次 L3(居中强制模态)。换医助后清零"
|
||||
>
|
||||
<el-icon class="col-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<span :class="['snooze-cell', snoozeClass(row)]">
|
||||
{{ Number(row.snooze_count ?? 0) }}
|
||||
</span>
|
||||
<div v-if="Number(row.escalation_level) > 0" class="cell-sub">
|
||||
等级 L{{ row.escalation_level }}
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="已联系" width="80" align="center">
|
||||
<template #default="{ row }">{{ Number(row.contact_count ?? 0) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="承诺日" width="100">
|
||||
<template #default="{ row }">{{ row.promised_date || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="过号" width="70" align="center">
|
||||
<template #default="{ row }">{{ Number(row.missed_count ?? 0) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="关闭原因" min-width="170" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.closed_state) === 4">
|
||||
<span>{{ handleReasonText(row.handle_reason) }}</span>
|
||||
<span v-if="row.handle_remark" class="cell-sub">
|
||||
:{{ row.handle_remark }}
|
||||
</span>
|
||||
</template>
|
||||
<span v-else-if="Number(row.closed_state) > 0" class="cell-sub">
|
||||
{{ row.closed_state_text || '—' }}
|
||||
</span>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" fixed="right" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-perms="['tcm.revisitDue/logs']"
|
||||
link
|
||||
type="primary"
|
||||
@click="openLogs(row)"
|
||||
>
|
||||
流水
|
||||
</el-button>
|
||||
<el-button link type="primary" @click="goDiagnosis(row)">去诊单</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-drawer
|
||||
v-model="logVisible"
|
||||
:title="logTitle"
|
||||
direction="rtl"
|
||||
size="540px"
|
||||
destroy-on-close
|
||||
>
|
||||
<div v-loading="logLoading" class="log-drawer-body">
|
||||
<div v-if="logRow" class="log-summary">
|
||||
<div class="log-summary-row">
|
||||
<span>医助:{{ assistantText(logRow) }}</span>
|
||||
<span>{{ slotText(logRow) }}</span>
|
||||
<span v-if="logRow.due_date">预计复诊 {{ logRow.due_date }}</span>
|
||||
</div>
|
||||
<div class="log-summary-row">
|
||||
<el-tag
|
||||
:type="revisitStateTagType(logRow.state)"
|
||||
:effect="revisitStateTagEffect(logRow.state)"
|
||||
size="small"
|
||||
:class="revisitStateChipClass(dueOf(logRow))"
|
||||
>
|
||||
{{ chipText(logRow) }}
|
||||
</el-tag>
|
||||
<span class="cell-sub">{{ followCountText(logRow) }}</span>
|
||||
</div>
|
||||
<div v-if="hasShownMeta(logRow)" class="log-summary-row cell-sub">
|
||||
<span v-if="logRow.first_shown_at_text">
|
||||
首次弹出 {{ logRow.first_shown_at_text }}
|
||||
</span>
|
||||
<span v-if="logRow.last_snoozed_at_text">
|
||||
最近延迟 {{ logRow.last_snoozed_at_text }}
|
||||
</span>
|
||||
<span v-if="logRow.computed_at_text">
|
||||
重算于 {{ logRow.computed_at_text }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-timeline v-if="logRows.length" class="mt-3">
|
||||
<el-timeline-item
|
||||
v-for="item in logRows"
|
||||
:key="item.id"
|
||||
:timestamp="item.create_time_text"
|
||||
placement="top"
|
||||
:type="eventTimelineType(item.event)"
|
||||
:hollow="!isUserEvent(item.event)"
|
||||
>
|
||||
<div class="log-event">
|
||||
<span class="log-event-title">
|
||||
{{ item.event_text || eventLabel(item.event) }}
|
||||
</span>
|
||||
<span class="log-event-operator">{{ operatorText(item) }}</span>
|
||||
</div>
|
||||
<div class="log-event-meta">
|
||||
<span>延迟 {{ Number(item.snooze_count_after ?? 0) }} 次</span>
|
||||
<span>等级 L{{ Number(item.level_after ?? 0) }}</span>
|
||||
<span>{{ logOverdueText(item.overdue_days) }}</span>
|
||||
</div>
|
||||
<div v-if="payloadEntries(item).length" class="log-event-payload">
|
||||
<span
|
||||
v-for="p in payloadEntries(item)"
|
||||
:key="p.key"
|
||||
class="log-payload-chip"
|
||||
>
|
||||
{{ p.label }}:{{ p.value }}
|
||||
</span>
|
||||
</div>
|
||||
</el-timeline-item>
|
||||
</el-timeline>
|
||||
<el-empty v-else-if="!logLoading" description="暂无流水" :image-size="80" />
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="statsRevisitDue">
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import {
|
||||
revisitDueLists,
|
||||
revisitDueLogs,
|
||||
type RevisitDueListRow,
|
||||
type RevisitDueListsParams,
|
||||
type RevisitDueLogRow
|
||||
} from '@/api/revisitDue'
|
||||
import { revisitRateDeptOptions } from '@/api/stats'
|
||||
import { getAssistants } from '@/api/tcm'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import {
|
||||
REVISIT_DAYS_BUCKET_OPTIONS,
|
||||
REVISIT_STATE_FILTER_OPTIONS,
|
||||
formatRevisitMonthDay,
|
||||
normalizeRevisitDue,
|
||||
revisitRowClassName,
|
||||
revisitStateChipClass,
|
||||
revisitStateChipText,
|
||||
revisitStateTagEffect,
|
||||
revisitStateTagType,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
interface DeptTreeNode {
|
||||
id: number
|
||||
name: string
|
||||
pid: number
|
||||
children?: DeptTreeNode[]
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
/** 状态筛选:诊单列表的 7 个状态 + 主管视图专有「人工关闭」 */
|
||||
const stateOptions = [...REVISIT_STATE_FILTER_OPTIONS, { label: '人工关闭', value: 'closed' }]
|
||||
|
||||
const assistantOptions = ref<Array<{ id: number; name: string }>>([])
|
||||
const deptTreeOptions = ref<DeptTreeNode[]>([])
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
|
||||
const queryParams = reactive<RevisitDueListsParams>({
|
||||
assistant_id: '',
|
||||
dept_id: '',
|
||||
state: '',
|
||||
days_bucket: '',
|
||||
min_snooze: '',
|
||||
keyword: ''
|
||||
})
|
||||
/** el-input-number 清空时为 null/undefined,单独持有后再写回 queryParams 的 '' */
|
||||
const minSnooze = ref<number | undefined>(undefined)
|
||||
|
||||
const { pager, getLists, resetPage } = usePaging({
|
||||
fetchFun: revisitDueLists,
|
||||
params: queryParams
|
||||
})
|
||||
|
||||
const doSearch = () => resetPage()
|
||||
|
||||
const onMinSnoozeChange = (val: number | undefined | null) => {
|
||||
queryParams.min_snooze = val === null || val === undefined ? '' : Number(val)
|
||||
doSearch()
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
queryParams.assistant_id = ''
|
||||
queryParams.dept_id = ''
|
||||
queryParams.state = ''
|
||||
queryParams.days_bucket = ''
|
||||
queryParams.min_snooze = ''
|
||||
queryParams.keyword = ''
|
||||
minSnooze.value = undefined
|
||||
doSearch()
|
||||
}
|
||||
|
||||
// ── 单元格 ──────────────────────────────────────────
|
||||
/** 列表行 → 复诊节点对象(复用 utils/revisitDue 的 chip 映射;缺失字段按默认值补齐) */
|
||||
const dueOf = (row: RevisitDueListRow | Record<string, any>): RevisitDue | null =>
|
||||
normalizeRevisitDue(row)
|
||||
|
||||
const rowClassName = ({ row }: { row: RevisitDueListRow }) => revisitRowClassName(dueOf(row))
|
||||
|
||||
const assistantText = (row: RevisitDueListRow) =>
|
||||
row.assistant_name || (Number(row.assistant_id) > 0 ? `#${row.assistant_id}` : '—')
|
||||
|
||||
const slotText = (row: RevisitDueListRow) => {
|
||||
const slot = Number(row.current_slot ?? 0)
|
||||
return slot > 0 ? `第 ${slot} 诊` : '未成交'
|
||||
}
|
||||
|
||||
const chipText = (row: RevisitDueListRow) =>
|
||||
revisitStateChipText(dueOf(row)) || row.state_text || '—'
|
||||
|
||||
/** 抽屉摘要:「延迟 N 次 · 已联系 N 次 · 过号 N 次」 */
|
||||
const followCountText = (row: RevisitDueListRow) => {
|
||||
const snooze = Number(row.snooze_count ?? 0)
|
||||
const contact = Number(row.contact_count ?? 0)
|
||||
const missed = Number(row.missed_count ?? 0)
|
||||
return `延迟 ${snooze} 次 · 已联系 ${contact} 次 · 过号 ${missed} 次`
|
||||
}
|
||||
|
||||
const hasShownMeta = (row: RevisitDueListRow) =>
|
||||
!!(row.first_shown_at_text || row.last_snoozed_at_text || row.computed_at_text)
|
||||
|
||||
const toNullableNumber = (v: unknown): number | null => {
|
||||
if (v === null || v === undefined || v === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
|
||||
/** 超期天数列:到期/过号红字(深红 = severe),其它状态显示剩余天数或历史超期 */
|
||||
const overdueCell = (row: RevisitDueListRow): { text: string; cls: string } => {
|
||||
const od = toNullableNumber(row.overdue_days)
|
||||
const dl = toNullableNumber(row.days_left)
|
||||
const isDue = row.state === 'overdue' || row.state === 'missed'
|
||||
if (isDue && od !== null && od >= 0) {
|
||||
return {
|
||||
text: od === 0 ? '今日到期' : `${od} 天`,
|
||||
cls: Number(row.severe) === 1 ? 'is-severe' : 'is-overdue'
|
||||
}
|
||||
}
|
||||
if (od !== null && od > 0) {
|
||||
return { text: `${od} 天`, cls: 'is-muted' }
|
||||
}
|
||||
if (dl !== null && dl >= 0) {
|
||||
return { text: `剩 ${dl} 天`, cls: 'is-muted' }
|
||||
}
|
||||
return { text: '—', cls: '' }
|
||||
}
|
||||
|
||||
const snoozeClass = (row: RevisitDueListRow) => {
|
||||
const level = Number(row.escalation_level ?? 0)
|
||||
if (level >= 3) return 'is-level-3'
|
||||
if (level === 2) return 'is-level-2'
|
||||
if (level === 1) return 'is-level-1'
|
||||
return ''
|
||||
}
|
||||
|
||||
const handleReasonText = (reason: string | null | undefined) => {
|
||||
const key = String(reason ?? '').trim()
|
||||
if (key === 'lost') return '患者流失'
|
||||
if (key === 'other') return '其它'
|
||||
return key || '人工关闭'
|
||||
}
|
||||
|
||||
// ── 流水抽屉 ──────────────────────────────────────────
|
||||
const logVisible = ref(false)
|
||||
const logLoading = ref(false)
|
||||
const logRow = ref<RevisitDueListRow | null>(null)
|
||||
const logRows = ref<RevisitDueLogRow[]>([])
|
||||
|
||||
const logTitle = computed(() =>
|
||||
logRow.value ? `${logRow.value.patient_name || '患者'} · 复诊到期流水` : '复诊到期流水'
|
||||
)
|
||||
|
||||
const EVENT_LABEL: Record<number, string> = {
|
||||
1: '延迟',
|
||||
2: '已联系',
|
||||
3: '人工关闭',
|
||||
4: '自动关闭 · 已挂号',
|
||||
5: '自动关闭 · 已面诊',
|
||||
6: '周期重置(新订单)',
|
||||
7: '重新打开(挂号取消 / 过号)',
|
||||
8: '企微推送',
|
||||
9: '医助变更',
|
||||
10: '形态升级',
|
||||
11: '首次弹出'
|
||||
}
|
||||
|
||||
const eventLabel = (event: number) => EVENT_LABEL[Number(event)] ?? `事件 ${event}`
|
||||
|
||||
/** 1 延迟 / 2 已联系 / 3 人工关闭 由医助操作,实心节点;其余系统事件空心 */
|
||||
const isUserEvent = (event: number) => [1, 2, 3].includes(Number(event))
|
||||
|
||||
type TimelineType = 'primary' | 'success' | 'warning' | 'danger' | 'info'
|
||||
|
||||
const eventTimelineType = (event: number): TimelineType => {
|
||||
switch (Number(event)) {
|
||||
case 1:
|
||||
return 'warning'
|
||||
case 2:
|
||||
case 6:
|
||||
return 'primary'
|
||||
case 4:
|
||||
case 5:
|
||||
return 'success'
|
||||
case 7:
|
||||
case 10:
|
||||
return 'danger'
|
||||
default:
|
||||
return 'info'
|
||||
}
|
||||
}
|
||||
|
||||
const operatorText = (item: RevisitDueLogRow) => {
|
||||
if (item.operator_name) return item.operator_name
|
||||
return Number(item.operator_id) > 0 ? `#${item.operator_id}` : '系统'
|
||||
}
|
||||
|
||||
const logOverdueText = (days: number | null | undefined) => {
|
||||
const n = toNullableNumber(days)
|
||||
if (n === null) return ''
|
||||
if (n > 0) return `超期 ${n} 天`
|
||||
if (n === 0) return '到期当天'
|
||||
return `未到期(剩 ${-n} 天)`
|
||||
}
|
||||
|
||||
const PAYLOAD_LABEL: Record<string, string> = {
|
||||
next_remind_at: '下次提醒',
|
||||
next_remind_at_text: '下次提醒',
|
||||
promised_date: '承诺日',
|
||||
appointment_id: '挂号单',
|
||||
appointment_date: '预约日',
|
||||
order_id: '订单',
|
||||
source_order_id: '周期订单',
|
||||
remark: '备注',
|
||||
reason: '原因',
|
||||
from_assistant: '原医助',
|
||||
from_assistant_id: '原医助',
|
||||
to_assistant: '新医助',
|
||||
to_assistant_id: '新医助',
|
||||
interval: '间隔(秒)',
|
||||
level: '等级',
|
||||
channel: '渠道',
|
||||
message: '说明'
|
||||
}
|
||||
|
||||
const formatPayloadValue = (key: string, value: unknown): string => {
|
||||
if (value === null || value === undefined || value === '') return ''
|
||||
if (typeof value === 'object') return JSON.stringify(value)
|
||||
// 秒级时间戳(next_remind_at 等)转本地时间
|
||||
if (/_at$/.test(key) && typeof value === 'number' && value > 1e9) {
|
||||
const d = new Date(value * 1000)
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
return `${date} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
interface PayloadEntry {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
/** payload_arr → [{key,label,value}],有 *_text 版本时隐藏对应原始时间戳 */
|
||||
const payloadEntries = (item: RevisitDueLogRow): PayloadEntry[] => {
|
||||
const payload = item.payload_arr
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return []
|
||||
const out: PayloadEntry[] = []
|
||||
for (const [key, raw] of Object.entries(payload)) {
|
||||
if (`${key}_text` in payload) continue
|
||||
const value = formatPayloadValue(key, raw)
|
||||
if (value === '') continue
|
||||
out.push({ key, label: PAYLOAD_LABEL[key] ?? key, value })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const openLogs = async (row: RevisitDueListRow) => {
|
||||
logRow.value = row
|
||||
logVisible.value = true
|
||||
logLoading.value = true
|
||||
logRows.value = []
|
||||
try {
|
||||
// 契约「返回 list」:兼容直接返回数组或 { list } / { lists } 包络
|
||||
const res: any = await revisitDueLogs({ due_id: Number(row.id) })
|
||||
const list = Array.isArray(res) ? res : (res?.list ?? res?.lists ?? [])
|
||||
logRows.value = Array.isArray(list) ? list : []
|
||||
} finally {
|
||||
logLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const goDiagnosis = (row: RevisitDueListRow) => {
|
||||
const id = Number(row.diagnosis_id ?? 0)
|
||||
if (id <= 0) return
|
||||
router.push({ path: '/tcm/diagnosis', query: { id: String(id) } })
|
||||
}
|
||||
|
||||
// ── 下拉数据 ──────────────────────────────────────────
|
||||
const buildDeptTree = (flat: Array<{ id: number; pid: number; name: string }>): DeptTreeNode[] => {
|
||||
const map = new Map<number, DeptTreeNode>()
|
||||
for (const d of flat) {
|
||||
map.set(Number(d.id), { id: Number(d.id), pid: Number(d.pid), name: d.name, children: [] })
|
||||
}
|
||||
const roots: DeptTreeNode[] = []
|
||||
for (const d of flat) {
|
||||
const node = map.get(Number(d.id))!
|
||||
if (Number(d.pid) > 0 && map.has(Number(d.pid))) {
|
||||
map.get(Number(d.pid))!.children!.push(node)
|
||||
} else {
|
||||
roots.push(node)
|
||||
}
|
||||
}
|
||||
const strip = (n: DeptTreeNode) => {
|
||||
if (n.children?.length) {
|
||||
n.children.forEach(strip)
|
||||
} else {
|
||||
delete n.children
|
||||
}
|
||||
}
|
||||
roots.forEach(strip)
|
||||
return roots
|
||||
}
|
||||
|
||||
const loadOptions = async () => {
|
||||
const [assistants, depts] = await Promise.allSettled([
|
||||
getAssistants(),
|
||||
revisitRateDeptOptions()
|
||||
])
|
||||
if (assistants.status === 'fulfilled') {
|
||||
assistantOptions.value = Array.isArray(assistants.value) ? assistants.value : []
|
||||
}
|
||||
if (depts.status === 'fulfilled') {
|
||||
deptTreeOptions.value = buildDeptTree(depts.value?.rows ?? [])
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 下拉与列表并行加载,不阻塞首屏
|
||||
void loadOptions()
|
||||
getLists()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.revisit-due-page {
|
||||
.due-filter-form {
|
||||
:deep(.el-form-item) {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.due-hint {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.cell-main {
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.cell-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.col-hint {
|
||||
margin-left: 2px;
|
||||
vertical-align: -2px;
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.text-missing {
|
||||
color: #ea580c;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.overdue-cell.is-overdue {
|
||||
color: var(--el-color-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.overdue-cell.is-severe {
|
||||
color: #b91c1c;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.overdue-cell.is-muted {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.snooze-cell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.snooze-cell.is-level-1 {
|
||||
color: #ea580c;
|
||||
}
|
||||
|
||||
.snooze-cell.is-level-2 {
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
|
||||
.snooze-cell.is-level-3 {
|
||||
color: #b91c1c;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 行级标红:与诊单列表一致(utils/revisitDue.ts revisitRowClassName) */
|
||||
:deep(.el-table__row.row-revisit-overdue) {
|
||||
border-left: 3px solid var(--el-color-danger);
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.06) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
:deep(.el-table__row.row-revisit-overdue:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep) {
|
||||
border-left-color: #b91c1c;
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.14) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
/* 状态 chip 配色:与 RevisitNodeCell 一致 */
|
||||
:deep(.rv-chip) {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--overdue),
|
||||
:deep(.rv-chip--missed) {
|
||||
--el-tag-bg-color: #dc2626;
|
||||
--el-tag-border-color: #dc2626;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--severe) {
|
||||
font-weight: 700;
|
||||
--el-tag-bg-color: #b91c1c;
|
||||
--el-tag-border-color: #b91c1c;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--warning) {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-bg-color: rgba(234, 88, 12, 0.1);
|
||||
--el-tag-border-color: rgba(234, 88, 12, 0.3);
|
||||
}
|
||||
|
||||
:deep(.rv-chip--no_days) {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-border-color: #ea580c;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--visited) {
|
||||
--el-tag-text-color: #16a34a;
|
||||
--el-tag-bg-color: rgba(22, 163, 74, 0.1);
|
||||
--el-tag-border-color: rgba(22, 163, 74, 0.3);
|
||||
}
|
||||
|
||||
:deep(.rv-chip--booked) {
|
||||
--el-tag-text-color: #4a5dff;
|
||||
--el-tag-bg-color: rgba(74, 93, 255, 0.1);
|
||||
--el-tag-border-color: rgba(74, 93, 255, 0.3);
|
||||
}
|
||||
}
|
||||
|
||||
.log-drawer-body {
|
||||
min-height: 200px;
|
||||
}
|
||||
|
||||
.log-summary {
|
||||
padding: 12px 14px;
|
||||
border-radius: 8px;
|
||||
background: var(--el-fill-color-light);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.log-summary-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 14px;
|
||||
}
|
||||
|
||||
.log-event {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.log-event-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.log-event-operator {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-event-meta {
|
||||
margin-top: 4px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.log-event-payload {
|
||||
margin-top: 6px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.log-payload-chip {
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
padding: 0 8px;
|
||||
border-radius: 4px;
|
||||
background: var(--el-fill-color);
|
||||
color: var(--el-text-color-regular);
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,7 @@
|
||||
<template>
|
||||
<cohort-report cohort-type="inherit" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="revisitInheritRateStatsPage">
|
||||
import CohortReport from '../revisit_assign_rate/components/CohortReport.vue'
|
||||
</script>
|
||||
@@ -29,12 +29,18 @@
|
||||
@change="loadData"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="口径">
|
||||
<el-radio-group v-model="inheritMode" size="small" @change="loadData">
|
||||
<el-radio-button value="exclude">原口径(继承不计分母)</el-radio-button>
|
||||
<el-radio-button value="slot">新口径(继承按继承时诊次计入)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
|
||||
<el-button :disabled="loading" @click="handleReset">重置</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-popover placement="bottom-start" :width="500" trigger="hover">
|
||||
<el-popover placement="bottom-start" :width="560" trigger="hover">
|
||||
<template #reference>
|
||||
<span class="rate-caliber-trigger">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
@@ -43,16 +49,29 @@
|
||||
</template>
|
||||
<div class="rate-caliber">
|
||||
<p>
|
||||
<b>当月被指派总数</b>:当月内诊单被指派给医助(按指派操作时间落月,<b>剔除勾选「继承」的指派</b>)的诊单数,按「医助 × 诊单」去重;部门行 / 合计行按诊单去重;<b>再剔除</b>名下存在履约「拒收 / 退款」业务订单的诊单。
|
||||
<b>{{ isSlotMode ? '新指派数' : '当月被指派数' }}</b>:当月内诊单被指派给医助(按指派操作时间落月,<b>不含勾选「继承」的指派</b>)的诊单数,按「医助 × 诊单」去重;部门行 / 合计行按诊单去重;<b>再剔除</b>名下存在履约「拒收 / 退款」业务订单的诊单。与业绩看板「被指派数」同口径。
|
||||
</p>
|
||||
<template v-if="isSlotMode">
|
||||
<p>
|
||||
<b>继承数</b>:当月勾选「继承」转接给该医助的诊单数(同一诊单多次继承取最早;同月既新指派又继承给同一医助只算新指派;历史「回退自动分配」行按继承处理;指派给自己的记录忽略)。<b>继承时诊次 k</b> = 继承时刻之前患者已完成的诊次(有效实单数 + 偏移),<b>起算诊次 = max(2, k+1)</b>:继承者只对第 k+1 诊及以后负责。
|
||||
</p>
|
||||
<p>
|
||||
<b>N 诊分母</b> = 新指派数 + 起算诊次 ≤ N 的继承数(每列独立);<b>N 诊接诊率</b> = N 诊单数 ÷ N 诊分母,分母为 0 显示「—」。<b>复诊合计</b>:单数 = 各诊次单数之和,分母 = 新指派 ∪ 继承(被指派合计),比率可超过 100%(人均复诊成交单数)。
|
||||
</p>
|
||||
<p class="rate-caliber-note">
|
||||
继承分母依赖指派记录的「继承」标记(2026-06 起写入),之前的转接无法回溯;切换为「旧口径」可对照上线前数字。
|
||||
</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p>
|
||||
<b>旧口径</b>:继承指派不计入分母,N 诊分母 = 新指派数(对所有 N 相同),新指派数 / N 诊单数 / N 诊接诊率与 2026-10 之前完全一致;继承数恒为 0。切换为「新口径」后继承按继承时诊次计入每列独立分母。
|
||||
</p>
|
||||
</template>
|
||||
<p>
|
||||
<b>诊次(第 N 次下单)</b>:患者(诊单)名下计入业绩的业务订单(剔除已取消 / 拒收 / 退款)按下单时间升序编号为「实单序号」,<b>统计诊次 = 实单序号 + 诊单偏移</b>(默认偏移 0 → 第 1 笔实单为一诊)。诊次<b>跨月累计不重置</b>。诊单可在「业务订单」tab 配置偏移量。
|
||||
</p>
|
||||
<p>
|
||||
<b>诊次(第 N 次下单)</b>:患者(诊单)名下计入业绩的业务订单(剔除已取消 / 拒收 / 退款)按下单时间升序编号为「实单序号」,<b>统计诊次 = 实单序号 + 诊单偏移</b>(默认偏移 0 → 第 1 笔实单为一诊;偏移 1 → 第 1 笔实单为二诊;偏移 2 → 第 1 笔实单为三诊,5 笔实单等价七诊)。诊次<b>跨月累计不重置</b>。诊单可在「业务订单」tab 配置偏移量。
|
||||
</p>
|
||||
<p>
|
||||
<b>当月 N 诊单数</b>:当月内下单且诊次为 N 的订单数,归属下单时点<b>持有该患者的医助</b>(指派可在往月;释放后不再归属;「继承」指派会转移持有人但不计被指派数)。
|
||||
</p>
|
||||
<p>
|
||||
<b>当月 N 诊接诊率</b> = 当月 N 诊单数 ÷ 当月被指派总数。往月指派、当月成交会推高分子,比率可能超过 100%;医助当月无新指派但旗下有成交时,被指派数为 0、比率显示「—」。
|
||||
<b>当月 N 诊单数</b>:当月内下单且诊次为 N 的订单数,归属下单时点<b>持有该患者的医助</b>(指派可在往月;释放后不再归属;继承会转移持有人)。往月指派、当月成交会推高分子,比率可能超过 100%。
|
||||
</p>
|
||||
<p>
|
||||
医助按人事部门归组;<b>仅统计「二中心」及其组织下级</b>;部门下拉与未选时的默认范围均限定在该子树,选定部门时含其组织下级。
|
||||
@@ -81,7 +100,9 @@
|
||||
<template #header>
|
||||
<div class="rate-card-header">
|
||||
<span>部门 · 医助明细({{ monthText }})</span>
|
||||
<span class="rate-card-hint">点击「被指派数 / N诊单数」可查看具体诊单与订单;底栏合计的被指派数按诊单去重</span>
|
||||
<span class="rate-card-hint">
|
||||
点击「新指派数 / 继承数 / 被指派合计 / N诊单数 / 复诊合计单数」可查看具体诊单与订单;接诊率下方灰字为「单数 / 分母」;底栏合计按诊单去重
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-table
|
||||
@@ -104,19 +125,88 @@
|
||||
<span v-else>{{ row.assistant_name }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assigned_count" label="当月被指派数" min-width="110" align="right">
|
||||
<el-table-column
|
||||
prop="assigned_count"
|
||||
:label="isSlotMode ? '新指派数' : '当月被指派数'"
|
||||
min-width="96"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ isSlotMode ? '新指派数' : '当月被指派数' }}</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
content="当月非继承指派的「医助 × 诊单」去重数(剔除名下有拒收/退款订单的诊单),与业绩看板「被指派数」同口径"
|
||||
>
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row.assigned_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row)"
|
||||
@click="openAssignDetail(row, 'new')"
|
||||
>
|
||||
{{ row.assigned_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.assigned_count }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
v-if="isSlotMode"
|
||||
prop="inherit_count"
|
||||
label="继承数"
|
||||
min-width="88"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>继承数</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
content="当月勾选「继承」转接给该医助的诊单数(按继承时诊次 k 从第 k+1 诊起计入分母;点击查看每条的继承时诊次与起算诊次)"
|
||||
>
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row.inherit_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row, 'inherit')"
|
||||
>
|
||||
{{ row.inherit_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.inherit_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
v-if="isSlotMode"
|
||||
prop="assigned_total_count"
|
||||
label="被指派合计"
|
||||
min-width="100"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>被指派合计</span>
|
||||
<el-tooltip effect="dark" placement="top" content="新指派 ∪ 继承(按诊单去重),即「复诊合计接诊率」的分母">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row.assigned_total_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row, 'all')"
|
||||
>
|
||||
{{ row.assigned_total_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.assigned_total_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template v-for="slot in visitSlots" :key="slot">
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_count`"
|
||||
@@ -149,12 +239,64 @@
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_rate`"
|
||||
:label="`${slotLabel(slot)}接诊率`"
|
||||
min-width="96"
|
||||
min-width="104"
|
||||
align="right"
|
||||
>
|
||||
<template #default="{ row }">{{ formatRate(row[`visit${slot}_rate`]) }}</template>
|
||||
<template #header>
|
||||
<span>{{ slotLabel(slot) }}接诊率</span>
|
||||
<el-tooltip effect="dark" placement="top" :content="rateHeaderTip(slot)">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{ formatRate(row[`visit${slot}_rate`]) }}</span>
|
||||
<span v-if="isSlotMode" class="rate-cell-sub">{{ denText(row, `visit${slot}`) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</template>
|
||||
<el-table-column prop="visit_all_count" label="复诊合计单数" min-width="110" align="right">
|
||||
<template #header>
|
||||
<span>复诊合计单数</span>
|
||||
<el-tooltip effect="dark" placement="top" content="当月内下单、诊次 ≥ 2 的订单数之和(= 各 N 诊单数之和)">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderLines && row.visit_all_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderDetail(0, row)"
|
||||
>
|
||||
{{ row.visit_all_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="visit_all_rate" label="复诊合计接诊率" min-width="118" align="right">
|
||||
<template #header>
|
||||
<span>复诊合计接诊率</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="
|
||||
isSlotMode
|
||||
? '复诊合计单数 ÷ 被指派合计(新指派 ∪ 继承);可超过 100%,语义为人均复诊成交单数'
|
||||
: '复诊合计单数 ÷ 新指派数(旧口径继承不计分母);可超过 100%'
|
||||
"
|
||||
>
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span>
|
||||
<span v-if="isSlotMode" class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
@@ -162,7 +304,7 @@
|
||||
<el-dialog
|
||||
v-model="detailVisible"
|
||||
:title="detailTitle"
|
||||
width="980px"
|
||||
width="1080px"
|
||||
top="6vh"
|
||||
destroy-on-close
|
||||
>
|
||||
@@ -193,6 +335,33 @@
|
||||
<template #default="{ row }">{{ row.patient_phone || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assistant_names" label="被指派医助" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column v-if="isSlotMode" prop="assign_type" label="指派类型" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.assign_type === 'inherit' ? 'warning' : 'success'" size="small">
|
||||
{{ row.assign_type_text || (row.assign_type === 'inherit' ? '继承' : '新指派') }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="isSlotMode" prop="inherit_visit_slot" label="继承时诊次" width="100" align="center">
|
||||
<template #header>
|
||||
<span>继承时诊次</span>
|
||||
<el-tooltip effect="dark" placement="top" content="k:继承时刻之前患者已完成的诊次(有效实单数 + 偏移);新指派无此值">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
{{ row.assign_type === 'inherit' ? `第 ${Number(row.inherit_visit_slot ?? 0)} 诊` : '—' }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="entry_slot" label="起算诊次" width="96" align="center">
|
||||
<template #header>
|
||||
<span>起算诊次</span>
|
||||
<el-tooltip effect="dark" placement="top" content="从该诊次列起计入分母:继承 = max(2, k+1);新指派 = 2(二诊)">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">{{ entrySlotText(row.entry_slot) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assign_count" label="当月指派次数" width="110" align="right" />
|
||||
<el-table-column prop="last_assign_time_text" label="最近指派时间" min-width="160" />
|
||||
</template>
|
||||
@@ -210,6 +379,9 @@
|
||||
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="detailSlot === 0" prop="visit_slot" label="诊次" width="80" align="center">
|
||||
<template #default="{ row }">{{ slotLabel(Number(row.visit_slot)) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
|
||||
<el-table-column prop="patient_name" label="患者" min-width="100">
|
||||
<template #default="{ row }">
|
||||
@@ -251,7 +423,9 @@ import {
|
||||
revisitRateAssignLines,
|
||||
revisitRateDeptOptions,
|
||||
revisitRateOverview,
|
||||
revisitRateVisitOrderLines
|
||||
revisitRateVisitOrderLines,
|
||||
type RevisitRateAssignKind,
|
||||
type RevisitRateInheritMode
|
||||
} from '@/api/stats'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
@@ -263,7 +437,14 @@ const OrderDetailDrawer = defineAsyncComponent(
|
||||
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
|
||||
|
||||
interface MetricPack extends Record<string, any> {
|
||||
/** 新指派数(语义不变) */
|
||||
assigned_count: number
|
||||
inherit_count?: number
|
||||
assigned_total_count?: number
|
||||
visit_all_count?: number
|
||||
visit_all_den?: number
|
||||
visit_all_rate?: number | null
|
||||
visit2_rate_new_assign?: number | null
|
||||
}
|
||||
|
||||
interface StatsRow extends MetricPack {
|
||||
@@ -289,11 +470,14 @@ const canViewOrderLines = hasPermission(['stats.revisitRate/visitOrderLines'])
|
||||
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
|
||||
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
|
||||
|
||||
/** 接口动态返回的诊次分档(最少 2~4,按数据扩展到五诊、六诊…) */
|
||||
/** 接口动态返回的诊次分档(最少 2~4,按分子最大诊次 / 最大起算诊次扩展到五诊、六诊…) */
|
||||
const visitSlots = ref<number[]>([2, 3, 4])
|
||||
|
||||
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
|
||||
const slotLabel = (slot: number) => {
|
||||
if (slot === 0) {
|
||||
return '复诊合计'
|
||||
}
|
||||
if (slot >= 2 && slot <= 10) {
|
||||
return `${cnDigits[slot]}诊`
|
||||
}
|
||||
@@ -307,6 +491,8 @@ const initNow = new Date()
|
||||
const currentMonth = `${initNow.getFullYear()}-${String(initNow.getMonth() + 1).padStart(2, '0')}`
|
||||
const month = ref<string>(currentMonth)
|
||||
const deptId = ref<number | undefined>(undefined)
|
||||
/** 口径:首次加载不传、取后端默认(config default_inherit_mode),之后以用户选择为准 */
|
||||
const inheritMode = ref<RevisitRateInheritMode | ''>('')
|
||||
const loading = ref(false)
|
||||
const rows = ref<StatsRow[]>([])
|
||||
const total = ref<MetricPack | null>(null)
|
||||
@@ -314,6 +500,8 @@ const total = ref<MetricPack | null>(null)
|
||||
const deptTreeOptions = ref<DeptTreeNode[]>([])
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
|
||||
const isSlotMode = computed(() => inheritMode.value !== 'exclude')
|
||||
|
||||
const monthText = computed(() => {
|
||||
const [y, m] = month.value.split('-')
|
||||
return y && m ? `${y}年${Number(m)}月` : month.value
|
||||
@@ -322,9 +510,30 @@ const monthText = computed(() => {
|
||||
const formatRate = (rate: number | null | undefined) =>
|
||||
rate === null || rate === undefined ? '—' : `${rate}%`
|
||||
|
||||
/** 接诊率单元格下方灰字:单数 / 分母 */
|
||||
const denText = (row: Record<string, any>, prefix: string) => {
|
||||
const cnt = Number(row[`${prefix}_count`] ?? 0)
|
||||
const den = row[`${prefix}_den`]
|
||||
return `${cnt} / ${den === null || den === undefined ? '—' : den}`
|
||||
}
|
||||
|
||||
const rateHeaderTip = (slot: number) =>
|
||||
isSlotMode.value
|
||||
? `${slotLabel(slot)}单数 ÷ ${slotLabel(slot)}分母;分母 = 当月新指派数 + 起算诊次 ≤ ${slot} 的继承数;分母为 0 显示「—」`
|
||||
: `${slotLabel(slot)}单数 ÷ 当月新指派数(旧口径:继承不计分母);分母为 0 显示「—」`
|
||||
|
||||
const entrySlotText = (entry: unknown) => {
|
||||
const n = Number(entry ?? 0)
|
||||
if (n <= 0) {
|
||||
return '—'
|
||||
}
|
||||
return n > 50 ? `${n}(仅计合计)` : slotLabel(n)
|
||||
}
|
||||
|
||||
const baseQuery = () => ({
|
||||
month: month.value,
|
||||
dept_ids: deptId.value ? String(deptId.value) : ''
|
||||
dept_ids: deptId.value ? String(deptId.value) : '',
|
||||
inherit_mode: (inheritMode.value || undefined) as RevisitRateInheritMode | undefined
|
||||
})
|
||||
|
||||
interface SummaryCard {
|
||||
@@ -341,11 +550,11 @@ const summaryCards = computed<SummaryCard[]>(() => {
|
||||
const cards: SummaryCard[] = [
|
||||
{
|
||||
key: 'assigned',
|
||||
label: '当月被指派总数',
|
||||
label: isSlotMode.value ? '当月新指派数' : '当月被指派数',
|
||||
value: t ? String(t.assigned_count) : '—',
|
||||
sub: '',
|
||||
sub: t && isSlotMode.value ? `继承 ${t.inherit_count ?? 0} · 被指派合计 ${t.assigned_total_count ?? 0}` : '',
|
||||
clickable: !!(canViewAssignLines && t && t.assigned_count > 0),
|
||||
onClick: () => openAssignDetail(null)
|
||||
onClick: () => openAssignDetail(null, 'new')
|
||||
}
|
||||
]
|
||||
for (const slot of visitSlots.value) {
|
||||
@@ -355,11 +564,19 @@ const summaryCards = computed<SummaryCard[]>(() => {
|
||||
key: `visit${slot}`,
|
||||
label: `当月${slotLabel(slot)}接诊率`,
|
||||
value: t ? formatRate(rate) : '—',
|
||||
sub: t ? `${slotLabel(slot)}下单 ${cnt} 单` : '',
|
||||
sub: t ? `${slotLabel(slot)}下单 ${cnt} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}` : '',
|
||||
clickable: !!(canViewOrderLines && cnt > 0),
|
||||
onClick: () => openOrderDetail(slot, null)
|
||||
})
|
||||
}
|
||||
cards.push({
|
||||
key: 'visit_all',
|
||||
label: '当月复诊合计接诊率',
|
||||
value: t ? formatRate(t.visit_all_rate) : '—',
|
||||
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 被指派合计 ${t.visit_all_den ?? '—'}` : '',
|
||||
clickable: !!(canViewOrderLines && t && Number(t.visit_all_count) > 0),
|
||||
onClick: () => openOrderDetail(0, null)
|
||||
})
|
||||
return cards
|
||||
})
|
||||
|
||||
@@ -374,15 +591,16 @@ const getSummaries = ({ columns }: { columns: any[] }) => {
|
||||
return ''
|
||||
}
|
||||
const prop = String(col.property || '')
|
||||
if (prop === 'assigned_count') {
|
||||
return String(t.assigned_count)
|
||||
if (prop === 'assigned_count' || prop === 'inherit_count' || prop === 'assigned_total_count') {
|
||||
return String(t[prop] ?? 0)
|
||||
}
|
||||
if (/^visit\d+_count$/.test(prop)) {
|
||||
const m = /^visit(\d+|all)_(count|den|rate)$/.exec(prop)
|
||||
if (m) {
|
||||
if (m[2] === 'rate') {
|
||||
return `${formatRate(t[prop])}(${denText(t, `visit${m[1]}`)})`
|
||||
}
|
||||
return String(t[prop] ?? '')
|
||||
}
|
||||
if (/^visit\d+_rate$/.test(prop)) {
|
||||
return formatRate(t[prop])
|
||||
}
|
||||
return ''
|
||||
})
|
||||
}
|
||||
@@ -404,6 +622,9 @@ const loadData = async () => {
|
||||
if (res?.month) {
|
||||
month.value = res.month
|
||||
}
|
||||
if (res?.inherit_mode === 'slot' || res?.inherit_mode === 'exclude') {
|
||||
inheritMode.value = res.inherit_mode
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -449,6 +670,8 @@ const detailType = ref<'assign' | 'orders'>('assign')
|
||||
const detailTitle = ref('')
|
||||
const detailLoading = ref(false)
|
||||
const detailRows = ref<any[]>([])
|
||||
/** 订单明细的诊次(0 = 复诊合计,表格多显示「诊次」列) */
|
||||
const detailSlot = ref(2)
|
||||
|
||||
/** row 为 null 时表示合计(当前部门筛选范围) */
|
||||
const rowScope = (row: StatsRow | null): { assistant_id?: number; dept_id?: number; label: string } => {
|
||||
@@ -461,13 +684,19 @@ const rowScope = (row: StatsRow | null): { assistant_id?: number; dept_id?: numb
|
||||
return { assistant_id: row.assistant_id, label: row.assistant_name || '' }
|
||||
}
|
||||
|
||||
const openAssignDetail = async (row: StatsRow | null) => {
|
||||
const assignKindLabel: Record<RevisitRateAssignKind, string> = {
|
||||
new: '新指派明细',
|
||||
inherit: '继承明细',
|
||||
all: '被指派合计明细'
|
||||
}
|
||||
|
||||
const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKind = 'all') => {
|
||||
if (!canViewAssignLines) {
|
||||
return
|
||||
}
|
||||
const scope = rowScope(row)
|
||||
detailType.value = 'assign'
|
||||
detailTitle.value = `${scope.label} · 被指派明细(${monthText.value})`
|
||||
detailTitle.value = `${scope.label} · ${assignKindLabel[kind]}(${monthText.value})`
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
detailRows.value = []
|
||||
@@ -475,7 +704,8 @@ const openAssignDetail = async (row: StatsRow | null) => {
|
||||
const res = await revisitRateAssignLines({
|
||||
...baseQuery(),
|
||||
assistant_id: scope.assistant_id,
|
||||
dept_id: scope.dept_id
|
||||
dept_id: scope.dept_id,
|
||||
kind
|
||||
})
|
||||
detailRows.value = res?.rows ?? []
|
||||
} finally {
|
||||
@@ -483,12 +713,14 @@ const openAssignDetail = async (row: StatsRow | null) => {
|
||||
}
|
||||
}
|
||||
|
||||
/** slot=0 表示全部诊次 ≥ 2(复诊合计单数) */
|
||||
const openOrderDetail = async (slot: number, row: StatsRow | null) => {
|
||||
if (!canViewOrderLines) {
|
||||
return
|
||||
}
|
||||
const scope = rowScope(row)
|
||||
detailType.value = 'orders'
|
||||
detailSlot.value = slot
|
||||
detailTitle.value = `${scope.label} · ${slotLabel(slot)}订单明细(${monthText.value})`
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
@@ -529,6 +761,7 @@ const openPatientDetail = (diagnosisId: number) => {
|
||||
const handleReset = () => {
|
||||
month.value = currentMonth
|
||||
deptId.value = undefined
|
||||
inheritMode.value = ''
|
||||
loadData()
|
||||
}
|
||||
|
||||
@@ -623,6 +856,22 @@ onMounted(() => {
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.rate-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
line-height: 1.3;
|
||||
|
||||
.rate-cell-main {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rate-cell-sub {
|
||||
font-size: 11px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rate-detail-footer {
|
||||
@@ -640,5 +889,10 @@ onMounted(() => {
|
||||
p + p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.rate-caliber-note {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="appointment-list">
|
||||
<DoctorWebConsultationNotice />
|
||||
<el-card class="list-card !border-none" shadow="never">
|
||||
<!-- 单行工具栏:Tab(主) + 搜索(辅) -->
|
||||
<div class="list-toolbar">
|
||||
@@ -559,6 +560,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import { defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="apt-h5">
|
||||
<DoctorWebConsultationNotice />
|
||||
<template v-if="currentView === 'list'">
|
||||
<header class="apt-h5-topbar">
|
||||
<div class="apt-h5-search">
|
||||
@@ -412,6 +413,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="tcmAppointmentH5">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
|
||||
import { appointmentDetail, appointmentLists, cancelAppointment, completeAppointment } from '@/api/doctor'
|
||||
import { getWeappConfig } from '@/api/channel/weapp'
|
||||
|
||||
@@ -12,9 +12,21 @@
|
||||
{{ assistantLogCellText(row, 'to') }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="继承" width="72" align="center">
|
||||
<el-table-column label="继承" width="118" align="center">
|
||||
<template #header>
|
||||
<span>继承</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
content="继承时第 k 诊:继承时刻之前患者已完成的诊次(有效实单数 + 偏移),复诊接诊率从第 k+1 诊起计入新医助分母;2026-10 前的继承记录无此快照"
|
||||
>
|
||||
<el-icon class="assign-log-col-hint"><QuestionFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-tag v-if="Number(row.is_inherit) === 1" type="success" size="small">是</el-tag>
|
||||
<template v-if="Number(row.is_inherit) === 1">
|
||||
<el-tag type="success" size="small">是</el-tag>
|
||||
<div v-if="inheritSlotText(row)" class="assign-log-inherit-slot">{{ inheritSlotText(row) }}</div>
|
||||
</template>
|
||||
<span v-else class="text-gray-400">否</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -85,6 +97,20 @@ function relatedPoCreateTimeCell(row: Record<string, unknown>): string {
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||
}
|
||||
|
||||
/** 对应日志表 inherit_visit_slot / inherit_visit_slot_calc_time:后端已拼好「继承时第 k 诊」文案,缺失时按快照列兜底 */
|
||||
function inheritSlotText(row: Record<string, unknown>): string {
|
||||
const text = row.inherit_visit_slot_text
|
||||
if (text != null && String(text).trim() !== '') {
|
||||
return String(text)
|
||||
}
|
||||
const calcTime = Number(row.inherit_visit_slot_calc_time)
|
||||
if (!Number.isFinite(calcTime) || calcTime <= 0) {
|
||||
return ''
|
||||
}
|
||||
const k = Number(row.inherit_visit_slot)
|
||||
return Number.isFinite(k) && k > 0 ? `继承时第 ${k} 诊` : '继承时未成交'
|
||||
}
|
||||
|
||||
function assistantLogCellText(row: Record<string, unknown>, side: 'from' | 'to'): string {
|
||||
const nameKey = side === 'from' ? 'from_assistant_name' : 'to_assistant_name'
|
||||
const idKey = side === 'from' ? 'from_assistant_id' : 'to_assistant_id'
|
||||
@@ -132,4 +158,11 @@ defineExpose({ refresh: load })
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.assign-log-inherit-slot {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
<template>
|
||||
<section class="consultation-transcripts">
|
||||
<header class="transcript-toolbar">
|
||||
<div>
|
||||
<h3>面诊文字对话</h3>
|
||||
<p>按每次通话分别查看已保存的文字记录。</p>
|
||||
</div>
|
||||
<el-button :loading="loading" @click="refresh"><el-icon><Refresh /></el-icon>刷新</el-button>
|
||||
</header>
|
||||
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon class="transcript-error" />
|
||||
<div v-loading="loading" class="transcript-body">
|
||||
<template v-if="records.length">
|
||||
<aside class="transcript-sessions" aria-label="历次面诊记录">
|
||||
<el-input v-model="search" clearable placeholder="搜索面诊时间或对话内容" :prefix-icon="Search" />
|
||||
<p class="session-count">{{ filteredRecords.length }} 条面诊记录</p>
|
||||
<div class="session-list">
|
||||
<button
|
||||
v-for="row in pageRecords"
|
||||
:key="row.id"
|
||||
type="button"
|
||||
class="session-item"
|
||||
:class="{ selected: selectedId === row.id }"
|
||||
:aria-pressed="selectedId === row.id"
|
||||
@click="selectedId = row.id"
|
||||
>
|
||||
<span class="session-time">{{ row.start_time_text || '开始时间未记录' }}</span>
|
||||
<span class="session-meta">{{ consultationCallLabel(row) }} · 记录 #{{ row.id }}</span>
|
||||
<el-tag size="small" :type="consultationTranscriptStatus(row).type">{{ consultationTranscriptStatus(row).label }}</el-tag>
|
||||
<span class="session-preview">{{ preview(row) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<el-pagination
|
||||
v-if="filteredRecords.length > PAGE_SIZE"
|
||||
v-model:current-page="page"
|
||||
:page-size="PAGE_SIZE"
|
||||
:total="filteredRecords.length"
|
||||
layout="prev, pager, next"
|
||||
small
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<article v-if="selectedRecord" class="transcript-detail" :key="`${diagnosisId}-${selectedRecord.id}`">
|
||||
<header class="transcript-detail-header">
|
||||
<div>
|
||||
<h4>{{ selectedRecord.start_time_text || '开始时间未记录' }} · {{ consultationCallLabel(selectedRecord) }}</h4>
|
||||
<p>
|
||||
通话记录 #{{ selectedRecord.id }}
|
||||
<span v-if="selectedRecord.duration_text"> · 时长 {{ selectedRecord.duration_text }}</span>
|
||||
<span v-if="selectedRecord.end_time_text"> · 结束 {{ selectedRecord.end_time_text }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<el-button v-if="selectedText" :loading="copying" @click="copyTranscript">复制全文</el-button>
|
||||
</header>
|
||||
<div class="transcript-status">
|
||||
<el-tag :type="consultationTranscriptStatus(selectedRecord).type">{{ consultationTranscriptStatus(selectedRecord).label }}</el-tag>
|
||||
<span>{{ callStatusText(selectedRecord.status) }}</span>
|
||||
<span v-if="selectedRecord.transcription_segment_count">{{ selectedRecord.transcription_segment_count }} 段对话</span>
|
||||
</div>
|
||||
<p v-if="selectedRecord.transcription_status === 'partial'" class="transcript-note">本次文字记录不完整,以下展示已保存的内容。</p>
|
||||
<p v-else-if="selectedRecord.transcription_status === 'failed' && selectedText" class="transcript-note">本次转写未完成,以下展示已保存的内容。</p>
|
||||
<p v-else-if="selectedRecord.transcription_status === 'running' && selectedText" class="transcript-note">转写仍在进行,可刷新查看最新保存的文字。</p>
|
||||
<pre v-if="selectedText" class="transcript-text">{{ selectedText }}</pre>
|
||||
<el-empty v-else :description="consultationTranscriptEmptyText(selectedRecord)" :image-size="72" />
|
||||
</article>
|
||||
<el-empty v-else description="没有匹配的面诊记录,请调整搜索内容" class="transcript-detail" :image-size="72" />
|
||||
</template>
|
||||
<el-empty v-else-if="!loading && !error" description="该诊单暂无面诊通话记录" :image-size="80" class="transcript-empty" />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Refresh, Search } from '@element-plus/icons-vue'
|
||||
import type { ConsultationCallRecord } from '@/api/tcm'
|
||||
import { useConsultationTranscripts } from '@/hooks/useConsultationTranscripts'
|
||||
import {
|
||||
consultationCallLabel,
|
||||
consultationTranscriptEmptyText,
|
||||
consultationTranscriptStatus,
|
||||
consultationTranscriptText
|
||||
} from '@/utils/consultation-transcripts'
|
||||
import feedback from '@/utils/feedback'
|
||||
|
||||
const props = defineProps<{ diagnosisId: number }>()
|
||||
const { records, loading, error, refresh } = useConsultationTranscripts(() => props.diagnosisId)
|
||||
const search = ref('')
|
||||
const selectedId = ref<number | null>(null)
|
||||
const page = ref(1)
|
||||
const copying = ref(false)
|
||||
const PAGE_SIZE = 10
|
||||
const filteredRecords = computed(() => {
|
||||
const term = search.value.trim().toLocaleLowerCase()
|
||||
return records.value.filter(row => row.diagnosis_id === props.diagnosisId &&
|
||||
(!term || `${row.start_time_text || ''} ${row.id} ${consultationTranscriptText(row)}`.toLocaleLowerCase().includes(term)))
|
||||
})
|
||||
const pageRecords = computed(() => filteredRecords.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE))
|
||||
const selectedRecord = computed(() => filteredRecords.value.find(row => row.id === selectedId.value))
|
||||
const selectedText = computed(() => consultationTranscriptText(selectedRecord.value))
|
||||
watch(filteredRecords, rows => {
|
||||
if (!rows.some(row => row.id === selectedId.value)) {
|
||||
const selected = rows.find(row => consultationTranscriptText(row)) || rows[0]
|
||||
selectedId.value = selected?.id ?? null
|
||||
page.value = selected ? Math.floor(rows.indexOf(selected) / PAGE_SIZE) + 1 : 1
|
||||
}
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(rows.length / PAGE_SIZE)))
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
watch(search, () => { page.value = 1 }, { flush: 'sync' })
|
||||
|
||||
function preview(row: ConsultationCallRecord): string {
|
||||
const text = consultationTranscriptText(row).replace(/\s+/g, ' ')
|
||||
return text ? text.slice(0, 90) + (text.length > 90 ? '…' : '') : consultationTranscriptEmptyText(row)
|
||||
}
|
||||
function callStatusText(value?: number): string {
|
||||
return ({ 1: '进行中', 2: '已结束', 3: '未接听', 4: '已取消' } as Record<number, string>)[Number(value)] || '状态未记录'
|
||||
}
|
||||
async function copyTranscript() {
|
||||
const text = selectedText.value
|
||||
if (!text || copying.value) return
|
||||
if (!navigator.clipboard?.writeText) {
|
||||
feedback.msgWarning('当前浏览器不支持自动复制,请选中文字复制')
|
||||
return
|
||||
}
|
||||
copying.value = true
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
feedback.msgSuccess('已复制本次面诊文字对话')
|
||||
} catch {
|
||||
feedback.msgWarning('复制失败,请选中文字复制')
|
||||
} finally {
|
||||
copying.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.consultation-transcripts { padding: 4px 0 16px; }
|
||||
.transcript-toolbar, .transcript-detail-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.transcript-toolbar { margin-bottom: 20px; }
|
||||
.transcript-toolbar h3, .transcript-detail h4 { margin: 0; color: var(--el-text-color-primary); font-weight: 600; }
|
||||
.transcript-toolbar h3 { font-size: 18px; }
|
||||
.transcript-toolbar p, .transcript-detail-header p { margin: 7px 0 0; color: var(--el-text-color-secondary); line-height: 1.7; font-size: 13px; }
|
||||
.transcript-error { margin-bottom: 16px; }
|
||||
.transcript-body { display: flex; min-height: 360px; border-top: 1px solid var(--el-border-color-lighter); }
|
||||
.transcript-sessions { flex: 0 0 282px; min-width: 0; padding: 18px 18px 0 0; border-right: 1px solid var(--el-border-color-lighter); }
|
||||
.session-count { margin: 12px 0 8px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.session-list { display: flex; flex-direction: column; gap: 8px; max-height: 580px; overflow-y: auto; margin-bottom: 12px; }
|
||||
.session-item { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; width: 100%; padding: 13px 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 7px; background: var(--el-bg-color); text-align: left; cursor: pointer; font: inherit; }
|
||||
.session-item:hover, .session-item.selected { border-color: var(--el-color-primary); background: var(--el-color-primary-light-9); }
|
||||
.session-item:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
|
||||
.session-time { color: var(--el-text-color-primary); font-size: 14px; font-weight: 600; }
|
||||
.session-meta, .session-preview { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
|
||||
.session-preview { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.transcript-detail { flex: 1; min-width: 0; padding: 20px 0 0 24px; }
|
||||
.transcript-detail h4 { font-size: 16px; line-height: 1.7; }
|
||||
.transcript-status { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin: 16px 0; color: var(--el-text-color-secondary); font-size: 13px; }
|
||||
.transcript-note { padding: 10px 12px; background: var(--el-color-warning-light-9); color: var(--el-color-warning-dark-2); font-size: 13px; line-height: 1.7; }
|
||||
.transcript-text { margin: 0; padding: 20px 0; color: var(--el-text-color-primary); white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: 15px; line-height: 2; user-select: text; }
|
||||
.transcript-empty { flex: 1; }
|
||||
@media (max-width: 900px) {
|
||||
.transcript-body { flex-direction: column; }
|
||||
.transcript-sessions { flex-basis: auto; padding: 16px 0; border-right: 0; border-bottom: 1px solid var(--el-border-color-lighter); }
|
||||
.session-list { max-height: 300px; }
|
||||
.transcript-detail { padding: 20px 0 0; }
|
||||
.transcript-detail-header { flex-wrap: wrap; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,303 @@
|
||||
<template>
|
||||
<div :class="['rv-cell', { 'rv-cell--compact': compact }]">
|
||||
<!-- 行 1:[第 N 诊] tag + 已开方/未开方 + 复诊医生 -->
|
||||
<div class="rv-line rv-line--head">
|
||||
<el-tooltip
|
||||
v-if="showDue && tooltipLines.length"
|
||||
placement="top"
|
||||
:show-after="300"
|
||||
:hide-after="0"
|
||||
>
|
||||
<template #content>
|
||||
<div class="rv-tooltip">
|
||||
<div v-for="line in tooltipLines" :key="line">{{ line }}</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-tag size="small" :type="slotTagType" effect="light" class="rv-slot-tag">
|
||||
{{ slotText }}
|
||||
</el-tag>
|
||||
</el-tooltip>
|
||||
<el-tag
|
||||
v-else-if="showDue"
|
||||
size="small"
|
||||
:type="slotTagType"
|
||||
effect="light"
|
||||
class="rv-slot-tag"
|
||||
>
|
||||
{{ slotText }}
|
||||
</el-tag>
|
||||
<span
|
||||
v-if="prescribedLabel"
|
||||
:class="['rv-prescribed', hasPrescription ? 'rv-prescribed--yes' : 'rv-prescribed--no']"
|
||||
>
|
||||
{{ prescribedLabel }}
|
||||
</span>
|
||||
<span v-if="followupDoctorName" class="rv-doctor">
|
||||
<span v-if="prescribedLabel" class="rv-dot">·</span>{{ followupDoctorName }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-if="showDue">
|
||||
<!-- 行 2:最新开药日 · 开药 X 天 · 锚点来源;缺天数时橙色 -->
|
||||
<div class="rv-line rv-line--order">
|
||||
<span v-if="orderDateText" class="rv-order-date">{{ orderDateText }} 开药</span>
|
||||
<span v-if="orderDateText" class="rv-dot">·</span>
|
||||
<span :class="['rv-days', { 'rv-days--missing': daysMissing }]">{{ medicationText }}</span>
|
||||
<template v-if="!daysMissing && anchorText">
|
||||
<span class="rv-dot">·</span>
|
||||
<span class="rv-anchor">{{ anchorText }}</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 行 3:药尽 MM-DD + 状态 chip -->
|
||||
<div class="rv-line rv-line--due">
|
||||
<span v-if="dueDateText" class="rv-due-date">{{ dueDateText }}</span>
|
||||
<el-tag
|
||||
v-if="chipText"
|
||||
size="small"
|
||||
:type="chipType"
|
||||
:effect="chipEffect"
|
||||
:class="chipClass"
|
||||
>
|
||||
{{ chipText }}
|
||||
</el-tag>
|
||||
</div>
|
||||
|
||||
<!-- 行 4:已延迟 N 次 · 已联系 约 MM-DD(有值才显示) -->
|
||||
<div v-if="followLineText" class="rv-line rv-line--follow">{{ followLineText }}</div>
|
||||
</template>
|
||||
<span v-else class="rv-none">—</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 复诊节点单元格(PC 列表 / H5 卡片紧凑 / 只读页 三处共用)
|
||||
*
|
||||
* 只负责展示,不发请求;数据来自列表行 `revisit_due`(契约 C),由父组件用
|
||||
* `normalizeRevisitDue` 规整后传入。state='none' 或 due 为 null 时仅显示行 1 + 「—」。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
|
||||
import {
|
||||
formatRevisitMonthDay,
|
||||
hasRevisitDue,
|
||||
isRevisitDaysMissing,
|
||||
revisitAnchorSrcText,
|
||||
revisitDueDateText,
|
||||
revisitFollowLineText,
|
||||
revisitMedicationDaysText,
|
||||
revisitSlotText,
|
||||
revisitStateChipClass,
|
||||
revisitStateChipText,
|
||||
revisitStateTagEffect,
|
||||
revisitStateTagType,
|
||||
revisitTooltipLines,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 规整后的复诊节点对象;null / state='none' 显示「—」 */
|
||||
due: RevisitDue | null
|
||||
/** H5 紧凑模式:更小字号、更紧行距 */
|
||||
compact?: boolean
|
||||
/** 是否已开方(决定「已开方/未开方」默认文案与颜色) */
|
||||
hasPrescription?: boolean
|
||||
/** 复诊医生(原列表 followup_doctor_name) */
|
||||
followupDoctorName?: string
|
||||
/** 自定义「已开方/未开方」文案;传 '' 隐藏该段(H5 卡片头已有标签时用) */
|
||||
prescribedText?: string
|
||||
}>(),
|
||||
{
|
||||
compact: false,
|
||||
hasPrescription: false,
|
||||
followupDoctorName: ''
|
||||
}
|
||||
)
|
||||
|
||||
const showDue = computed(() => hasRevisitDue(props.due))
|
||||
|
||||
const prescribedLabel = computed(() => {
|
||||
if (props.prescribedText !== undefined) return props.prescribedText
|
||||
return props.hasPrescription ? '已开方' : '未开方'
|
||||
})
|
||||
|
||||
const slotText = computed(() => revisitSlotText(props.due))
|
||||
const slotTagType = computed<'primary' | 'info'>(() =>
|
||||
showDue.value && Number(props.due?.current_slot) > 0 ? 'primary' : 'info'
|
||||
)
|
||||
const tooltipLines = computed(() => revisitTooltipLines(props.due))
|
||||
|
||||
const orderDateText = computed(() => (showDue.value ? formatRevisitMonthDay(props.due?.order_date) : ''))
|
||||
const daysMissing = computed(() => isRevisitDaysMissing(props.due))
|
||||
const medicationText = computed(() => revisitMedicationDaysText(props.due))
|
||||
const anchorText = computed(() => (showDue.value ? revisitAnchorSrcText(props.due?.anchor_src) : ''))
|
||||
|
||||
const dueDateText = computed(() => revisitDueDateText(props.due))
|
||||
const chipText = computed(() => revisitStateChipText(props.due))
|
||||
const chipType = computed(() => revisitStateTagType(props.due?.state))
|
||||
const chipEffect = computed(() => revisitStateTagEffect(props.due?.state))
|
||||
const chipClass = computed(() => revisitStateChipClass(props.due))
|
||||
|
||||
const followLineText = computed(() => revisitFollowLineText(props.due))
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.rv-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
line-height: 1.35;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.rv-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.rv-line--head {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.rv-slot-tag {
|
||||
font-weight: 600;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.rv-prescribed {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rv-prescribed--yes {
|
||||
color: #4a5dff;
|
||||
}
|
||||
|
||||
.rv-prescribed--no {
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.rv-doctor {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.rv-dot {
|
||||
color: var(--el-text-color-placeholder);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rv-line--order {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.rv-days--missing {
|
||||
color: #ea580c;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.rv-anchor {
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.rv-line--due {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rv-due-date {
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 状态 chip:el-tag 基础色由 type/effect 决定,这里只补深红加粗与描边细节。
|
||||
前缀 .rv-cell 提高特异性,压过 Element 的 .el-tag--dark.el-tag--danger 变量定义 */
|
||||
.rv-cell .rv-chip {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--overdue,
|
||||
.rv-cell .rv-chip--missed {
|
||||
--el-tag-bg-color: #dc2626;
|
||||
--el-tag-border-color: #dc2626;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--severe,
|
||||
.rv-cell .rv-chip--overdue.rv-chip--severe,
|
||||
.rv-cell .rv-chip--missed.rv-chip--severe {
|
||||
font-weight: 700;
|
||||
--el-tag-bg-color: #b91c1c;
|
||||
--el-tag-border-color: #b91c1c;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--warning {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-bg-color: rgba(234, 88, 12, 0.1);
|
||||
--el-tag-border-color: rgba(234, 88, 12, 0.3);
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--no_days {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-border-color: #ea580c;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--visited {
|
||||
--el-tag-text-color: #16a34a;
|
||||
--el-tag-bg-color: rgba(22, 163, 74, 0.1);
|
||||
--el-tag-border-color: rgba(22, 163, 74, 0.3);
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--booked {
|
||||
--el-tag-text-color: #4a5dff;
|
||||
--el-tag-bg-color: rgba(74, 93, 255, 0.1);
|
||||
--el-tag-border-color: rgba(74, 93, 255, 0.3);
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--contacted {
|
||||
--el-tag-text-color: #4a5dff;
|
||||
--el-tag-border-color: #4a5dff;
|
||||
}
|
||||
|
||||
.rv-line--follow {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.rv-none {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.rv-tooltip {
|
||||
line-height: 1.6;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* H5 紧凑模式 */
|
||||
.rv-cell--compact {
|
||||
gap: 2px;
|
||||
|
||||
.rv-line--head,
|
||||
.rv-line--due,
|
||||
.rv-prescribed {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rv-line--order,
|
||||
.rv-line--follow,
|
||||
.rv-doctor {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.rv-none {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -744,6 +744,20 @@
|
||||
<el-empty v-else description="请先保存诊单后再查看视频录制回放记录" />
|
||||
</el-tab-pane>
|
||||
<el-tab-pane
|
||||
v-if="hasCallTranscriptPermission"
|
||||
label="面诊文字对话"
|
||||
name="callTranscript"
|
||||
:disabled="!formData.id"
|
||||
lazy
|
||||
>
|
||||
<consultation-transcript-panel
|
||||
v-if="visible && activeTab === 'callTranscript' && formData.id"
|
||||
:key="Number(formData.id)"
|
||||
:diagnosis-id="Number(formData.id)"
|
||||
/>
|
||||
<el-empty v-else-if="!formData.id" description="请先保存诊单后再查看面诊文字对话" />
|
||||
</el-tab-pane>
|
||||
<el-tab-pane
|
||||
v-if="hasPermission(['tcm.diagnosis/chat'])"
|
||||
label="聊天记录"
|
||||
name="chat"
|
||||
@@ -827,6 +841,7 @@ import FollowupAudioPanel from './components/FollowupAudioPanel.vue'
|
||||
import { followupAudioCapabilities, type FollowupCapabilities } from '@/api/followupAudio'
|
||||
import CaseRecordList from './components/CaseRecordList.vue'
|
||||
import CallRecordPanel from './components/CallRecordPanel.vue'
|
||||
import ConsultationTranscriptPanel from './components/ConsultationTranscriptPanel.vue'
|
||||
import ImChatRecordPanel from './components/ImChatRecordPanel.vue'
|
||||
import AssignLogPanel from './components/AssignLogPanel.vue'
|
||||
import AppointmentRecordPanel from './components/AppointmentRecordPanel.vue'
|
||||
@@ -862,6 +877,7 @@ const submitting = ref(false)
|
||||
/** 拥有后手机号可正常编辑,失焦不再强制脱敏 */
|
||||
const hasPhonePlainPermission = computed(() => hasPermission(['tcm.diagnosis/phonePlain']))
|
||||
const hasDailyRecordPermission = computed(() => hasPermission(['tcm.diagnosis/dailyRecord']))
|
||||
const hasCallTranscriptPermission = computed(() => hasPermission(['tcm.diagnosis/huifang']) || hasPermission(['tcm.diagnosis/getCallRecords']))
|
||||
const hasFollowupAudioPermission = computed(() => hasPermission(['tcm.diagnosis/followupAudio']))
|
||||
const patientBasicLocked = ref(false)
|
||||
const canEditPatientBasicFromApi = ref(true)
|
||||
@@ -930,12 +946,15 @@ watch(() => activeTab.value, async (tab) => {
|
||||
}
|
||||
})
|
||||
|
||||
watch([visible, activeTab], () => {
|
||||
watch([visible, activeTab, hasCallTranscriptPermission], () => {
|
||||
if (!visible.value) return
|
||||
if (activeTab.value === 'chat' && !hasPermission(['tcm.diagnosis/chat'])) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (activeTab.value === 'visit' && !hasPermission(['tcm.diagnosis/huifang'])) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (activeTab.value === 'callTranscript' && !hasCallTranscriptPermission.value) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
formData.pending_assign !== '1' &&
|
||||
formData.pending_booking !== '1' &&
|
||||
formData.completed_appointment !== '1' &&
|
||||
formData.revisit_state === '' &&
|
||||
!hasLatestAppointmentFilter() &&
|
||||
formData.appointment_date === tab.value
|
||||
}
|
||||
@@ -30,6 +31,14 @@
|
||||
待预约
|
||||
<em v-if="pendingBookingCount !== undefined">{{ pendingBookingCount }}</em>
|
||||
</span>
|
||||
<!-- 复诊到期:到期未挂号 ∪ 过号未面诊(revisit_state=due),点击默认按药尽日升序 -->
|
||||
<span
|
||||
:class="['chip', 'chip-revisit-due', { active: formData.revisit_state === 'due' }]"
|
||||
@click="handleRevisitDueTabClick"
|
||||
>
|
||||
复诊到期
|
||||
<em v-if="revisitDueCount !== undefined">{{ revisitDueCount }}</em>
|
||||
</span>
|
||||
<span
|
||||
:class="['chip', 'chip-completed-visit', { active: formData.completed_appointment === '1' }]"
|
||||
@click="handleCompletedVisitTabClick"
|
||||
@@ -147,6 +156,36 @@
|
||||
:value="String(item.value)"
|
||||
/>
|
||||
</el-select>
|
||||
<el-select
|
||||
v-model="formData.revisit_state"
|
||||
placeholder="复诊状态"
|
||||
clearable
|
||||
size="small"
|
||||
class="revisit-state-select"
|
||||
@change="handleRevisitFilterChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in revisitStateFilterOptions"
|
||||
:key="item.value"
|
||||
:label="item.label"
|
||||
:value="item.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-select
|
||||
v-model="formData.revisit_days_bucket"
|
||||
placeholder="开药天数档"
|
||||
clearable
|
||||
size="small"
|
||||
class="revisit-days-bucket-select"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in revisitDaysBucketOptions"
|
||||
:key="item.value"
|
||||
:label="item.label"
|
||||
:value="item.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-button size="small" @click="handleReset">重置</el-button>
|
||||
</div>
|
||||
</el-card>
|
||||
@@ -278,22 +317,20 @@
|
||||
<span v-else class="status-unconfirmed">未确认</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="复诊" min-width="120">
|
||||
<!-- 复诊节点:吞掉原「复诊」「开方」两列;排序走后端 sort_revisit_due(药尽日,NULL 置后) -->
|
||||
<el-table-column
|
||||
label="复诊节点"
|
||||
prop="revisit_due_date"
|
||||
min-width="180"
|
||||
sortable="custom"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<div v-if="row.has_prescription" class="followup-cell">
|
||||
<div class="followup-time">{{ row.followup_time_text || '—' }}</div>
|
||||
<div class="followup-doctor">{{ row.followup_doctor_name || '—' }}</div>
|
||||
<el-tag
|
||||
v-if="row.followup_rx_voided"
|
||||
type="info"
|
||||
size="small"
|
||||
effect="plain"
|
||||
class="followup-void-tag"
|
||||
>
|
||||
处方已作废
|
||||
</el-tag>
|
||||
</div>
|
||||
<span v-else class="followup-none">无</span>
|
||||
<revisit-node-cell
|
||||
:due="revisitDueOf(row)"
|
||||
:has-prescription="!!row.has_prescription"
|
||||
:followup-doctor-name="row.followup_doctor_name || ''"
|
||||
:prescribed-text="prescribedTextOf(row)"
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="助理" width="100" show-overflow-tooltip>
|
||||
@@ -301,12 +338,6 @@
|
||||
<span class="assistant-cell">{{ getAssistantName(row.assistant_id || row.assistant) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="开方" width="72" align="center">
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.has_prescription" class="status-prescribed">已开方</span>
|
||||
<span v-else class="status-unprescribed">未开方</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
label="未服务天数"
|
||||
prop="unserved_days"
|
||||
@@ -519,7 +550,6 @@
|
||||
</el-form-item>
|
||||
<el-form-item label="继承">
|
||||
<el-checkbox v-model="assignForm.is_inherit">继承</el-checkbox>
|
||||
<span class="text-gray-400 text-xs ml-2">勾选后写入指派记录</span>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="assignMode === 'batch'" label="已选择">
|
||||
<div class="text-gray-500">{{ batchAssignIds.length }} 条诊单记录</div>
|
||||
@@ -737,7 +767,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="tcmDiagnosis">
|
||||
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard } from '@/api/tcm'
|
||||
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard, diagnosisReadonlyDetail } from '@/api/tcm'
|
||||
import { orderCreate } from '@/api/order'
|
||||
import { cancelAppointment } from '@/api/doctor'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
@@ -752,6 +782,15 @@ import { useRoute, useRouter } from 'vue-router'
|
||||
import { computed, defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
|
||||
import dayjs from 'dayjs'
|
||||
import DaterangePicker from '@/components/daterange-picker/index.vue'
|
||||
import RevisitNodeCell from './components/RevisitNodeCell.vue'
|
||||
import { formatGender } from '@/utils/diag-display'
|
||||
import {
|
||||
normalizeRevisitDue,
|
||||
REVISIT_DAYS_BUCKET_OPTIONS,
|
||||
REVISIT_STATE_FILTER_OPTIONS,
|
||||
revisitRowClassName,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
const EditPopup = defineAsyncComponent(() => import('./edit.vue'))
|
||||
const DetailPopup = defineAsyncComponent(() => import('./detail.vue'))
|
||||
@@ -798,6 +837,12 @@ const formData = reactive({
|
||||
latest_assign_end_date: '' as string,
|
||||
/** 未服务天数排序:desc=天数多到少 asc=少到多 */
|
||||
sort_unserved_days: '' as '' | 'asc' | 'desc',
|
||||
/** 复诊状态筛选:due(到期未挂号∪过号)|warning|booked|visited|contacted|no_days|pending,空=不限 */
|
||||
revisit_state: '' as string,
|
||||
/** 开药天数档筛选:14|21|28|30|other,空=不限 */
|
||||
revisit_days_bucket: '' as string,
|
||||
/** 复诊节点(药尽日)排序:asc=最早到期在前(NULL 置后) desc 反之;与 sort_unserved_days 互斥 */
|
||||
sort_revisit_due: '' as '' | 'asc' | 'desc',
|
||||
diagnosis_confirmed: '' as '' | '0' | '1',
|
||||
appointment_date: '' as string,
|
||||
has_appointment: '' as '' | '0' | '1',
|
||||
@@ -898,11 +943,13 @@ function buildSharedDiagnosisFilterPayload(): Record<string, unknown> {
|
||||
latest_appointment_end_date: formData.latest_appointment_end_date,
|
||||
latest_appointment_channel_source: formData.latest_appointment_channel_source,
|
||||
latest_assign_start_date: formData.latest_assign_start_date,
|
||||
latest_assign_end_date: formData.latest_assign_end_date
|
||||
latest_assign_end_date: formData.latest_assign_end_date,
|
||||
revisit_state: formData.revisit_state,
|
||||
revisit_days_bucket: formData.revisit_days_bucket
|
||||
}
|
||||
}
|
||||
|
||||
/** 顶部 Tab 角标 count 请求:带上共用筛选,再叠加各 Tab 专属条件 */
|
||||
/** 顶部 Tab 角标 count 请求:带上共用筛选,再叠加各 Tab 专属条件(revisit_state 视为 Tab 条件,角标间互不影响) */
|
||||
function buildDateCountRequestPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
page_no: 1,
|
||||
@@ -915,6 +962,8 @@ function buildDateCountRequestPayload(overrides: Record<string, unknown> = {}):
|
||||
pending_assign_order_month: '',
|
||||
pending_assign_keyword: '',
|
||||
sort_unserved_days: '',
|
||||
revisit_state: '',
|
||||
sort_revisit_due: '',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
@@ -960,6 +1009,9 @@ function clearSecondaryFiltersWhenPendingAssignWideSearch() {
|
||||
formData.latest_assign_start_date = ''
|
||||
formData.latest_assign_end_date = ''
|
||||
formData.sort_unserved_days = ''
|
||||
formData.revisit_state = ''
|
||||
formData.revisit_days_bucket = ''
|
||||
formData.sort_revisit_due = ''
|
||||
formData.pending_assign_order_month = ''
|
||||
activeTab.value = 'all'
|
||||
if (kw1 !== '') {
|
||||
@@ -996,6 +1048,7 @@ const handleDateTabClick = async (value: string) => {
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.has_appointment = ''
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
formData.appointment_date = value
|
||||
pager.page = 1
|
||||
@@ -1012,6 +1065,7 @@ const handlePendingBookingTabClick = async () => {
|
||||
formData.completed_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = '0'
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
@@ -1027,6 +1081,7 @@ const handleCompletedVisitTabClick = async () => {
|
||||
formData.completed_appointment = '1'
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
@@ -1039,6 +1094,7 @@ const handlePendingAssignTabClick = async () => {
|
||||
formData.completed_appointment = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
if (!formData.pending_assign_order_month) {
|
||||
formData.pending_assign_order_month = dayjs().format('YYYY-MM')
|
||||
@@ -1057,10 +1113,66 @@ const onPendingAssignOrderMonthChange = async (val: string | null) => {
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
// 获取各日期挂号数量 + 全部 + 待预约 + 已完成 + 待分配医助数量
|
||||
/** 复诊状态 / 开药天数档 下拉选项(文案与请求值映射在 utils/revisitDue.ts) */
|
||||
const revisitStateFilterOptions = REVISIT_STATE_FILTER_OPTIONS
|
||||
const revisitDaysBucketOptions = REVISIT_DAYS_BUCKET_OPTIONS
|
||||
|
||||
/** 顶部「复诊到期」角标:revisit_state=due 的 count */
|
||||
const revisitDueCount = ref<number | undefined>(undefined)
|
||||
|
||||
/** 切换其它顶部 Tab 时清掉复诊 chip 状态与其排序(revisit_days_bucket 属「更多筛选」,保留) */
|
||||
const clearRevisitTabFilters = () => {
|
||||
formData.revisit_state = ''
|
||||
formData.sort_revisit_due = ''
|
||||
}
|
||||
|
||||
/** 顶部「复诊到期」chip:到期未挂号 ∪ 过号未面诊,默认按药尽日升序(超期最多在前) */
|
||||
const handleRevisitDueTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_assign_order_month = ''
|
||||
formData.pending_assign_keyword = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = ''
|
||||
clearLatestAppointmentFilters()
|
||||
formData.revisit_state = 'due'
|
||||
formData.sort_revisit_due = 'asc'
|
||||
formData.sort_unserved_days = ''
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
/** 「更多筛选 → 复诊状态」下拉:与顶部日期 Tab 互斥(同 chip 语义),选中后不再默认当天挂号 */
|
||||
const handleRevisitFilterChange = () => {
|
||||
if (formData.revisit_state !== '') {
|
||||
formData.appointment_date = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
const noSortYet = formData.sort_revisit_due === '' && formData.sort_unserved_days === ''
|
||||
if (formData.revisit_state === 'due' && noSortYet) {
|
||||
formData.sort_revisit_due = 'asc'
|
||||
}
|
||||
} else {
|
||||
formData.sort_revisit_due = ''
|
||||
}
|
||||
doSearch()
|
||||
}
|
||||
|
||||
/** 列表行 revisit_due → 规整对象(旧接口无字段时为 null,单元格显示「—」) */
|
||||
const revisitDueOf = (row: any): RevisitDue | null => normalizeRevisitDue(row?.revisit_due)
|
||||
|
||||
/** 「复诊节点」行 1 的开方文案:已开方 / 已开方(处方已作废) / 未开方 */
|
||||
const prescribedTextOf = (row: any): string => {
|
||||
if (!row?.has_prescription) return '未开方'
|
||||
return row.followup_rx_voided ? '已开方(处方已作废)' : '已开方'
|
||||
}
|
||||
|
||||
// 获取各日期挂号数量 + 全部 + 待预约 + 已完成 + 待分配医助数量 + 复诊到期数量
|
||||
const fetchDateCounts = async () => {
|
||||
try {
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending] = await Promise.all([
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending, revisitDue] = await Promise.all([
|
||||
tcmDiagnosisLists(
|
||||
buildDateCountRequestPayload({ appointment_date: yesterdayStr.value, has_appointment: '' }) as any
|
||||
),
|
||||
@@ -1081,7 +1193,10 @@ const fetchDateCounts = async () => {
|
||||
tcmDiagnosisLists(
|
||||
buildDateCountRequestPayload({ completed_appointment: 1, has_appointment: '' }) as any
|
||||
),
|
||||
tcmDiagnosisLists(buildPendingAssignCountPayload() as any)
|
||||
tcmDiagnosisLists(buildPendingAssignCountPayload() as any),
|
||||
tcmDiagnosisLists(
|
||||
buildDateCountRequestPayload({ revisit_state: 'due', has_appointment: '' }) as any
|
||||
)
|
||||
])
|
||||
dateCounts.value = {
|
||||
[yesterdayStr.value]: yesterday?.count ?? 0,
|
||||
@@ -1094,6 +1209,7 @@ const fetchDateCounts = async () => {
|
||||
pendingBookingCount.value = noApt?.count ?? 0
|
||||
completedVisitCount.value = doneVisit?.count ?? 0
|
||||
pendingAssignCount.value = pending?.count ?? 0
|
||||
revisitDueCount.value = revisitDue?.count ?? 0
|
||||
} catch (e) {
|
||||
console.error('获取日期数量失败', e)
|
||||
}
|
||||
@@ -1252,12 +1368,11 @@ const handleTableSortChange = ({
|
||||
prop: string
|
||||
order: 'ascending' | 'descending' | null
|
||||
}) => {
|
||||
if (prop === 'unserved_days') {
|
||||
formData.sort_unserved_days =
|
||||
order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
|
||||
} else {
|
||||
formData.sort_unserved_days = ''
|
||||
}
|
||||
const dir: '' | 'asc' | 'desc' =
|
||||
order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
|
||||
// 按列 prop 分派;两种排序后端互斥,切换列时清掉另一列
|
||||
formData.sort_unserved_days = prop === 'unserved_days' ? dir : ''
|
||||
formData.sort_revisit_due = prop === 'revisit_due_date' ? dir : ''
|
||||
pager.page = 1
|
||||
getLists()
|
||||
}
|
||||
@@ -1311,6 +1426,9 @@ const handleReset = () => {
|
||||
formData.latest_assign_start_date = ''
|
||||
formData.latest_assign_end_date = ''
|
||||
formData.sort_unserved_days = ''
|
||||
formData.revisit_state = ''
|
||||
formData.revisit_days_bucket = ''
|
||||
formData.sort_revisit_due = ''
|
||||
formData.diagnosis_confirmed = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = ''
|
||||
@@ -1343,8 +1461,10 @@ const unservedDaysClass = (n: unknown) => {
|
||||
return 'unserved-green'
|
||||
}
|
||||
|
||||
// 行高亮:未确认诊单优先,其次未挂号
|
||||
// 行高亮优先级(方案 D3-c 默认 overdue_first):复诊超期/过号 > 未确认 > 未挂号
|
||||
const getRowClassName = ({ row }: { row: any }) => {
|
||||
const revisitCls = revisitRowClassName(revisitDueOf(row))
|
||||
if (revisitCls) return revisitCls
|
||||
if (!isDiagnosisConfirmed(row)) return 'row-unconfirmed'
|
||||
if (!row.has_appointment) return 'row-no-appointment'
|
||||
return ''
|
||||
@@ -1356,6 +1476,8 @@ const prescriptionRef = ref()
|
||||
const appointmentRef = ref()
|
||||
/** 从路由带 id 进入时,诊单弹窗为异步组件,需在 ref 就绪后再 open */
|
||||
const pendingRouteDiagnosisId = ref<number | null>(null)
|
||||
/** 路由 ?id=&action=appointment 深链(复诊到期弹窗「去挂号」):挂号弹窗同为异步组件,先暂存行再 open */
|
||||
const pendingRouteAppointmentRow = ref<Record<string, any> | null>(null)
|
||||
const userStore = useUserStore()
|
||||
|
||||
watch(
|
||||
@@ -1370,6 +1492,53 @@ watch(
|
||||
{ flush: 'post' }
|
||||
)
|
||||
|
||||
watch(
|
||||
[appointmentRef, pendingRouteAppointmentRow],
|
||||
() => {
|
||||
const row = pendingRouteAppointmentRow.value
|
||||
const opener = appointmentRef.value as { open?: (row: any) => void } | undefined
|
||||
if (!row || !opener?.open) return
|
||||
pendingRouteAppointmentRow.value = null
|
||||
handleAppointment(row)
|
||||
},
|
||||
{ flush: 'post' }
|
||||
)
|
||||
|
||||
/**
|
||||
* 深链打开挂号弹窗:优先用当前列表里的行(字段最全);不在本页时回退只读详情接口拼最小行
|
||||
* (appointment.vue open() 只读 patient_id / patient_name / gender_desc / age)。
|
||||
*/
|
||||
const openAppointmentFromRoute = async (diagnosisId: number) => {
|
||||
// 深链打开挂号弹窗前先校验挂号权限(与行内「预约」按钮 v-perms 同口径)
|
||||
if (!hasPermission(['tcm.diagnosis/guahao'])) {
|
||||
feedback.msgWarning('无挂号权限')
|
||||
return
|
||||
}
|
||||
const inList = (pager.lists as any[]).find((r) => Number(r?.id) === diagnosisId)
|
||||
if (inList) {
|
||||
pendingRouteAppointmentRow.value = inList
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await diagnosisReadonlyDetail({ id: diagnosisId })
|
||||
const diag = res?.diagnosis
|
||||
if (!diag || !diag.patient_id) {
|
||||
feedback.msgWarning('未找到该诊单或患者信息不完整,无法打开挂号')
|
||||
return
|
||||
}
|
||||
pendingRouteAppointmentRow.value = {
|
||||
...diag,
|
||||
id: diagnosisId,
|
||||
patient_id: diag.patient_id,
|
||||
patient_name: diag.patient_name || '',
|
||||
gender_desc: formatGender(diag.gender),
|
||||
age: diag.age ?? 0
|
||||
}
|
||||
} catch (e: any) {
|
||||
feedback.msgWarning(e?.msg || e?.message || '加载诊单失败,无法打开挂号')
|
||||
}
|
||||
}
|
||||
|
||||
const watchCallVisible = ref(false)
|
||||
const watchCallDiagnosisId = ref(0)
|
||||
|
||||
@@ -1614,13 +1783,13 @@ const handleConfirmAssign = async () => {
|
||||
feedback.msgWarning('请选择医助')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
assignLoading.value = true
|
||||
try {
|
||||
if (assignMode.value === 'single') {
|
||||
// 单独指派
|
||||
await tcmDiagnosisAssign({
|
||||
id: currentRow.value.id,
|
||||
await tcmDiagnosisAssign({
|
||||
id: currentRow.value.id,
|
||||
assistant_id: assignForm.value.assistant_id,
|
||||
is_inherit: assignForm.value.is_inherit ? 1 : 0
|
||||
})
|
||||
@@ -2220,22 +2389,57 @@ const goReadonly = (row: any) => {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 默认展示当天挂号,突出重点
|
||||
formData.appointment_date = todayStr.value
|
||||
// 字典与列表并行,避免 await 字典阻塞首屏列表(LCP)
|
||||
getDictOptions()
|
||||
getLists()
|
||||
scheduleDeferredDateCounts()
|
||||
if (String(route.query.revisit_state ?? '') === 'due') {
|
||||
// 复诊到期弹窗「查看全部」深链:直接激活「复诊到期」chip(内部会 getLists + fetchDateCounts)
|
||||
void handleRevisitDueTabClick()
|
||||
} else {
|
||||
// 默认展示当天挂号,突出重点
|
||||
formData.appointment_date = todayStr.value
|
||||
getLists()
|
||||
scheduleDeferredDateCounts()
|
||||
}
|
||||
|
||||
silentListPollTimer = setInterval(silentRefreshListsAndDateCounts, SILENT_LIST_POLL_MS)
|
||||
|
||||
const raw = route.query.id
|
||||
if (raw != null && raw !== '') {
|
||||
const num = Number(raw)
|
||||
if (!Number.isNaN(num)) pendingRouteDiagnosisId.value = num
|
||||
if (!Number.isNaN(num) && num > 0) {
|
||||
if (String(route.query.action ?? '') === 'appointment') {
|
||||
// 复诊到期弹窗「去挂号」深链:等首屏列表回来后再找行,找不到走详情接口
|
||||
void getListsPromiseForRoute().then(() => openAppointmentFromRoute(num))
|
||||
} else {
|
||||
pendingRouteDiagnosisId.value = num
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/** onMounted 里 getLists() 已发起;等待首屏列表 loading 结束(最多 8s)再找行,失败/超时不阻断 */
|
||||
const getListsPromiseForRoute = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (!pager.loading) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
let settled = false
|
||||
const finish = () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
stop()
|
||||
resolve()
|
||||
}
|
||||
const stop = watch(
|
||||
() => pager.loading,
|
||||
(loading) => {
|
||||
if (!loading) finish()
|
||||
}
|
||||
)
|
||||
setTimeout(finish, 8000)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (silentListPollTimer != null) {
|
||||
clearInterval(silentListPollTimer)
|
||||
@@ -2313,6 +2517,21 @@ onUnmounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.chip-revisit-due {
|
||||
margin-left: 8px;
|
||||
color: var(--el-color-danger);
|
||||
background: var(--el-color-danger-light-9);
|
||||
|
||||
&:hover {
|
||||
background: var(--el-color-danger-light-8);
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: #fff;
|
||||
background: var(--el-color-danger);
|
||||
}
|
||||
}
|
||||
|
||||
.chip-completed-visit {
|
||||
margin-left: 8px;
|
||||
color: var(--el-color-success);
|
||||
@@ -2451,6 +2670,14 @@ onUnmounted(() => {
|
||||
.latest-appointment-channel {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
.revisit-state-select {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
.revisit-days-bucket-select {
|
||||
width: 130px;
|
||||
}
|
||||
}
|
||||
|
||||
.list-card {
|
||||
@@ -2641,17 +2868,6 @@ onUnmounted(() => {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-prescribed {
|
||||
font-size: 13px;
|
||||
color: #4A5DFF;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.status-unprescribed {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
/* 未服务天数(T3):null=灰;>=7=红;3-6=橙;<=2=绿 */
|
||||
.unserved-days {
|
||||
display: inline-block;
|
||||
@@ -2696,33 +2912,6 @@ onUnmounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.followup-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
line-height: 1.35;
|
||||
|
||||
.followup-time {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.followup-doctor {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.followup-void-tag {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.followup-none {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.assistant-cell {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-secondary);
|
||||
@@ -2782,6 +2971,22 @@ onUnmounted(() => {
|
||||
:deep(.el-table__row.row-no-appointment:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-info-rgb), 0.08) 0%, transparent 100%) !important;
|
||||
}
|
||||
/* 复诊到期未挂号 / 过号未面诊:红色左边条(同 row-unconfirmed 结构,warning → danger) */
|
||||
:deep(.el-table__row.row-revisit-overdue) {
|
||||
border-left: 3px solid var(--el-color-danger);
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.06) 0%, transparent 100%) !important;
|
||||
}
|
||||
:deep(.el-table__row.row-revisit-overdue:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
/* 超期 ≥ severe_overdue_days:底色加深到 10%,悬停 14% */
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep) {
|
||||
border-left-color: #b91c1c;
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.14) 0%, transparent 100%) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.record-list {
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
formData.pending_assign !== '1' &&
|
||||
formData.pending_booking !== '1' &&
|
||||
formData.completed_appointment !== '1' &&
|
||||
formData.revisit_state === '' &&
|
||||
formData.appointment_date === tab.value
|
||||
}
|
||||
]"
|
||||
@@ -40,6 +41,13 @@
|
||||
待预约
|
||||
<em v-if="pendingBookingCount !== undefined">{{ pendingBookingCount }}</em>
|
||||
</span>
|
||||
<span
|
||||
:class="['dh5-chip', 'dh5-chip--revisit', { active: formData.revisit_state === 'due' }]"
|
||||
@click="handleRevisitDueTabClick"
|
||||
>
|
||||
复诊到期
|
||||
<em v-if="revisitDueCount !== undefined">{{ revisitDueCount }}</em>
|
||||
</span>
|
||||
<span
|
||||
:class="['dh5-chip', 'dh5-chip--done', { active: formData.completed_appointment === '1' }]"
|
||||
@click="handleCompletedVisitTabClick"
|
||||
@@ -170,13 +178,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 复诊块(仅已开方时显示) -->
|
||||
<div v-if="row.has_prescription" class="dh5-row dh5-row--followup">
|
||||
<!-- 复诊节点块(已开方或有复诊节点数据时显示;卡片头已有「已开方」标签,此处隐藏开方文案) -->
|
||||
<div v-if="row.has_prescription || hasRevisitDue(revisitDueOf(row))" class="dh5-row dh5-row--followup">
|
||||
<span class="dh5-row-key">复诊</span>
|
||||
<div class="dh5-row-val">
|
||||
<span>{{ row.followup_time_text || '—' }}</span>
|
||||
<span class="dh5-meta-doctor">{{ row.followup_doctor_name || '—' }}</span>
|
||||
<span v-if="row.followup_rx_voided" class="dh5-tag dh5-tag--gray">处方作废</span>
|
||||
<div class="dh5-row-val dh5-row-val--revisit">
|
||||
<revisit-node-cell
|
||||
compact
|
||||
:due="revisitDueOf(row)"
|
||||
:has-prescription="!!row.has_prescription"
|
||||
:followup-doctor-name="row.followup_doctor_name || ''"
|
||||
:prescribed-text="row.followup_rx_voided ? '处方作废' : ''"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -625,6 +637,13 @@ import {
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { defineAsyncComponent, computed, reactive, ref, onMounted, onUnmounted } from 'vue'
|
||||
import dayjs from 'dayjs'
|
||||
import RevisitNodeCell from './components/RevisitNodeCell.vue'
|
||||
import {
|
||||
hasRevisitDue,
|
||||
isRevisitDueHighlight,
|
||||
normalizeRevisitDue,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
const EditPopup = defineAsyncComponent(() => import('./edit.vue'))
|
||||
const DetailPopup = defineAsyncComponent(() => import('./detail.vue'))
|
||||
@@ -685,7 +704,9 @@ const formData = reactive({
|
||||
has_appointment: '' as '' | '0' | '1',
|
||||
pending_assign: '' as '' | '1',
|
||||
pending_booking: '' as '' | '1',
|
||||
completed_appointment: '' as '' | '1'
|
||||
completed_appointment: '' as '' | '1',
|
||||
/** 顶部「复诊到期」chip:due = 到期未挂号 ∪ 过号未面诊(后端 revisit_state) */
|
||||
revisit_state: '' as '' | 'due'
|
||||
})
|
||||
|
||||
const showMoreFilter = ref(false)
|
||||
@@ -740,6 +761,7 @@ const handleReset = () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
pager.page = 1
|
||||
getLists()
|
||||
fetchDateCounts()
|
||||
@@ -767,6 +789,7 @@ const handleDateTabClick = async (value: string) => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = value
|
||||
pager.page = 1
|
||||
@@ -778,6 +801,7 @@ const handlePendingBookingTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = '1'
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = '0'
|
||||
pager.page = 1
|
||||
@@ -789,6 +813,7 @@ const handleCompletedVisitTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = '1'
|
||||
formData.revisit_state = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
pager.page = 1
|
||||
@@ -800,6 +825,7 @@ const handlePendingAssignTabClick = async () => {
|
||||
formData.pending_assign = '1'
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
pager.page = 1
|
||||
@@ -807,9 +833,27 @@ const handlePendingAssignTabClick = async () => {
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
/** 顶部「复诊到期」chip:到期未挂号 ∪ 过号未面诊;后端按 revisit_state=due 过滤,排序默认药尽日升序 */
|
||||
const handleRevisitDueTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
formData.revisit_state = 'due'
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
const revisitDueCount = ref<number | undefined>(undefined)
|
||||
|
||||
/** 列表行 revisit_due → 规整对象(旧接口无字段时为 null,不渲染复诊块) */
|
||||
const revisitDueOf = (row: any): RevisitDue | null => normalizeRevisitDue(row?.revisit_due)
|
||||
|
||||
const fetchDateCounts = async () => {
|
||||
try {
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending] = await Promise.all([
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending, revisitDue] = await Promise.all([
|
||||
tcmDiagnosisLists({ appointment_date: yesterdayStr.value, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ appointment_date: dayBeforeStr.value, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ appointment_date: todayStr.value, page_no: 1, page_size: 1 }),
|
||||
@@ -818,7 +862,8 @@ const fetchDateCounts = async () => {
|
||||
tcmDiagnosisLists({ page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ has_appointment: 0, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ completed_appointment: 1, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ pending_assign: 1, page_no: 1, page_size: 1 })
|
||||
tcmDiagnosisLists({ pending_assign: 1, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ revisit_state: 'due', page_no: 1, page_size: 1 })
|
||||
])
|
||||
dateCounts.value = {
|
||||
[yesterdayStr.value]: yesterday?.count ?? 0,
|
||||
@@ -831,6 +876,7 @@ const fetchDateCounts = async () => {
|
||||
pendingBookingCount.value = noApt?.count ?? 0
|
||||
completedVisitCount.value = doneVisit?.count ?? 0
|
||||
pendingAssignCount.value = pending?.count ?? 0
|
||||
revisitDueCount.value = revisitDue?.count ?? 0
|
||||
} catch (e) {
|
||||
console.error('获取日期数量失败', e)
|
||||
}
|
||||
@@ -898,7 +944,9 @@ const isDiagnosisConfirmed = (row: any) => {
|
||||
return records.length > 0 && records.some((r: any) => r.is_confirmed == 1)
|
||||
}
|
||||
|
||||
// 卡片左边条优先级(同 PC 行高亮):复诊超期/过号 > 未确认 > 未挂号
|
||||
const getCardClass = (row: any) => {
|
||||
if (isRevisitDueHighlight(revisitDueOf(row))) return 'dh5-card--overdue'
|
||||
if (!isDiagnosisConfirmed(row)) return 'dh5-card--unconfirmed'
|
||||
if (!row.has_appointment) return 'dh5-card--noapt'
|
||||
return ''
|
||||
@@ -1582,6 +1630,8 @@ $dh5-card-bg: #ffffff;
|
||||
.dh5-chip--booking.active { background: $dh5-warn; }
|
||||
.dh5-chip--done.active { background: $dh5-success; }
|
||||
.dh5-chip--pending.active { background: $dh5-danger; }
|
||||
.dh5-chip--revisit { color: #b91c1c; background: rgba(239, 68, 68, 0.10); }
|
||||
.dh5-chip--revisit.active { color: #fff; background: $dh5-danger; }
|
||||
|
||||
.dh5-quick {
|
||||
display: flex;
|
||||
@@ -1675,6 +1725,12 @@ $dh5-card-bg: #ffffff;
|
||||
|
||||
.dh5-card--unconfirmed::before { background: $dh5-danger; }
|
||||
.dh5-card--noapt::before { background: $dh5-warn; }
|
||||
/* 复诊到期未挂号 / 过号未面诊:左边条同 danger,外框与底色轻微染红以区分「未确认」 */
|
||||
.dh5-card--overdue::before { background: $dh5-danger; }
|
||||
.dh5-card--overdue {
|
||||
border-color: rgba(239, 68, 68, 0.35);
|
||||
background: linear-gradient(90deg, rgba(239, 68, 68, 0.05) 0%, $dh5-card-bg 60%);
|
||||
}
|
||||
|
||||
.dh5-card-head {
|
||||
display: flex;
|
||||
@@ -1800,6 +1856,11 @@ $dh5-card-bg: #ffffff;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 复诊节点块:单元格组件自带多行布局,取消外层 flex 换行间距 */
|
||||
.dh5-row-val--revisit {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* 挂号块 - 状态色 */
|
||||
.dh5-row--apt {
|
||||
background: #fafbfc;
|
||||
|
||||
@@ -25,6 +25,17 @@
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<span v-else class="unserved-badge unserved-muted">从未打卡</span>
|
||||
<!-- 复诊节点徽标:第 N 诊 · 药尽 MM-DD · 超期 N 天(接口无 revisit_due 字段时不渲染) -->
|
||||
<el-tooltip
|
||||
v-if="revisitBadgeLabel"
|
||||
placement="bottom"
|
||||
:disabled="!revisitTooltipText"
|
||||
:content="revisitTooltipText"
|
||||
>
|
||||
<span :class="['unserved-badge', 'revisit-badge', revisitBadgeColorClass]">
|
||||
{{ revisitBadgeLabel }}
|
||||
</span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -156,6 +167,12 @@ import { diagnosisReadonlyDetail } from '@/api/tcm'
|
||||
import { getDoctorNotes } from '@/api/patient'
|
||||
import { formatGender } from '@/utils/diag-display'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
import {
|
||||
normalizeRevisitDue,
|
||||
revisitBadgeText,
|
||||
revisitStateColorClass,
|
||||
revisitTooltipLines
|
||||
} from '@/utils/revisitDue'
|
||||
import PatientInfoCard from './components/PatientInfoCard.vue'
|
||||
import PatientCaseCard from './components/PatientCaseCard.vue'
|
||||
import DailyMatrix from './components/DailyMatrix.vue'
|
||||
@@ -193,6 +210,17 @@ const unservedDays = computed<number | null>(() => {
|
||||
})
|
||||
const lastBloodAt = computed<string>(() => detail.value?.last_blood_record_at || '')
|
||||
|
||||
/** 复诊节点:readonlyDetail 顶层 revisit_due(兼容挂在 diagnosis 下);字段不存在 → null → 不渲染徽标 */
|
||||
const revisitDue = computed(() =>
|
||||
normalizeRevisitDue(detail.value?.revisit_due ?? detail.value?.diagnosis?.revisit_due)
|
||||
)
|
||||
const revisitBadgeLabel = computed(() => revisitBadgeText(revisitDue.value))
|
||||
const revisitBadgeColorClass = computed(() => {
|
||||
const due = revisitDue.value
|
||||
return due ? revisitStateColorClass(due.state) : 'unserved-muted'
|
||||
})
|
||||
const revisitTooltipText = computed(() => revisitTooltipLines(revisitDue.value).join(';'))
|
||||
|
||||
/**
|
||||
* 「未服务天数」着色规则(与 T3 列表一致):
|
||||
* null/undefined → 灰;>=7 → 红;3-6 → 橙;<=2 → 绿
|
||||
@@ -352,6 +380,13 @@ onMounted(fetchDetail)
|
||||
border-color: #fecaca;
|
||||
background: rgba(220, 38, 38, 0.08);
|
||||
}
|
||||
|
||||
/* 复诊节点徽标专用:已约 / 已联系 */
|
||||
&.unserved-blue {
|
||||
color: #4a5dff;
|
||||
border-color: #c7d2fe;
|
||||
background: rgba(74, 93, 255, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
|
||||
@@ -46,6 +46,8 @@ export default defineConfig(({ mode }) => {
|
||||
|
||||
return {
|
||||
base: '/admin/',
|
||||
// 临时 UI 预览可能共用 node_modules;主开发服务独立缓存,避免预构建互相覆盖。
|
||||
cacheDir: path.resolve(__dirname, 'node_modules/.vite-admin'),
|
||||
server: {
|
||||
port: 5555,
|
||||
host: '0.0.0.0',
|
||||
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
# IAM v2 关联管理与本人跨平台快捷登录
|
||||
|
||||
## 默认状态与部署次序
|
||||
|
||||
首次部署 `iam.v2_enabled`、`iam.v2_management_enabled`、`iam.v2_launch_enabled` 都默认 **false**。全局未启用时不登记新来源会话,原密码、企微、IAM 入站登录保持原路径。产生v2关联后,全局核心必须保持true以持续中央停用检查、签名事件和代际补偿;维护/回退优先关闭management与launch两个新流程开关,不能以关闭全局核心绕过这些检查。本文只描述源码;生产开关、迁移、真实浏览器及三端联调需另行验收。
|
||||
|
||||
1. 备份部署版本与配置,审查并执行 `server/database/migrations/20261029_iam_v2.sql`(按实际表前缀调整)。此迁移只加七张表及独立菜单/权限,不给现有角色自动授予权限,不改账号与角色。
|
||||
2. 中央先部署 v2 绑定墓碑、幂等恢复、固定来源回查、版本检查、源/目标访问授权、密码设置协议与签名事件。旧 v1 token 不得获得新管理权限。
|
||||
3. 向 IAM 注册 application `zyt` 的固定 HTTPS 回调;ZYT→ERP 固定目标 `zmxy-erp`;IAM 管理后台/员工工作台可进入本人 ZYT 或 ERP,不增加 ERP→ZYT 按钮。OIDC client 追加精确 self-link 回调,禁用任意重定向。
|
||||
4. 用一次性合成账号完成三端测试后再开启 v2。配置放服务器私密环境,不写仓库或日志。
|
||||
|
||||
```ini
|
||||
[IAM]
|
||||
V2_ENABLED = false
|
||||
V2_MANAGEMENT_ENABLED = false
|
||||
V2_LAUNCH_ENABLED = false
|
||||
V2_TOKEN = <dedicated-login-v2-credential-at-least-32-chars>
|
||||
V2_MANAGEMENT_TOKEN = <different-management-v2-credential-at-least-32-chars>
|
||||
V2_INTROSPECTION_TOKEN = <distinct-callback-credential-at-least-32-chars>
|
||||
V2_EVENT_SECRET = <distinct-HMAC-event-key-at-least-32-chars>
|
||||
ERP_URL = https://<ERP-origin>
|
||||
ERP_CALLBACK_URL = https://<ERP-origin>/basic-api/api/erp/iam/v2/launch/callback
|
||||
PORTAL_URL = https://<IAM-portal-origin>
|
||||
V2_SOURCES_JSON = {"iam-admin":"https://<IAM-origin>/admin/v1/iam/v2/launch/continue","iam-portal":"https://<IAM-origin>/portal/v2/launch/continue"}
|
||||
```
|
||||
|
||||
中央credentials数组分别注册:登录凭据 `V2_TOKEN` 仅 `binding:read,binding:self,password:setup,launch:issue,launch:accept`;管理凭据 `V2_MANAGEMENT_TOKEN` 仅 `identity:search,identity:create,binding:read,binding:manage`。identities/operations/audit/batch/jobs固定使用管理凭据,缺失时不fallback登录或v1凭据;target `zyt` 只接受 `iam-admin` / `iam-portal`。
|
||||
|
||||
`API_URL`、`PUBLIC_URL`、`ISSUER`、OIDC client 配置沿用原配置。`ERP_URL/PUBLIC_URL/PORTAL_URL` 是固定 origin,不接受浏览器 URL。新功能的 v2 凭据与原 `APPLICATION_TOKEN` 分离。
|
||||
|
||||
## 固定端点
|
||||
|
||||
源应用所有路径前缀 `/adminapi/iam/v2`:
|
||||
|
||||
- `POST /proofs/introspect`、`POST /sessions/check`:专用 Bearer callback credential,不接受业务 token 代替。回包为中央约定的原生 JSON,不包业务 envelope。
|
||||
- `POST /events/revocation`:`X-IAM-Signature=sha256=<HMAC-SHA256(raw-body)>`,`X-IAM-Event-ID` 必须等于 `body.id`;RFC3339 occurredAt、未来最多 60 秒,持久化 event ID + digest 幂等;耐久outbox旧时间事件仍可重试,不因超过5分钟被拒绝。旧 bindingVersion 只撤销旧/未知来源代际,不覆盖较新关联或另一员工的新会话;同业务token仍有新代际SID时保留token。历史本地无镜像时按签名事件externalAccountId或中央employeeId精确查询补齐映射,不从姓名/手机号猜测;无代际人员/授权事件在event handler回查当前中央状态后决定撤销,避免晚到事件踢掉重新授权会话。
|
||||
- `POST /launch/start`:同源、当前业务 token + 独立 HttpOnly source SID;只返回目标 `/iam/launch?source=zyt&intent=...`,在新标签页打开。
|
||||
- `GET /launch/continue?transaction_id=...&intent=...`:IAM 注册的固定来源 continuation;目标 prepare 必须原样附加 opaque intent。比对源 HttpOnly intent cookie、源 SID、源 sessionVersion、固定两应用 ID 后,隐藏表单 POST 到 **`ERP_CALLBACK_URL`**(生产公开反代前缀为 `/basic-api/api/erp/...`,必须与中央注册精确一致)。grant 和业务 token 均不进 URL。
|
||||
- `POST /self-link/start` → `GET /self-link/callback`:当前本地近期认证 + OIDC code/PKCE/nonce 证明 IAM 同一用户;后端提交已验证 ID token,中央独立验证。前端没有指定个人 employee ID 的能力。
|
||||
- `POST /password-setup` → `GET /password-continue?request_id=...&state=...`:只对本人已验证且待设置密码的 IAM 账号;中央初始返回 url/expiry/requestId,源 cookie + SID 绑定请求;continuation 隐藏表单 POST 到固定 `PORTAL_URL/portal/password-setup/authorize`。实际密码只在 IAM 页面输入。
|
||||
|
||||
用户 API 使用原业务 `{code,data,msg}` envelope。管理:accounts/identities/operations/audit/batch/jobs。每次 mutation 使用前端稳定 `Idempotency-Key`,自动 HTTP retry 关闭;中央按同一业务 payload 和 key 恢复已执行结果(proof 可刷新,不重复副作用)。operation/job 查询限定创建操作者及当前目标数据范围。
|
||||
|
||||
## 账号、会话与权限
|
||||
|
||||
- 新建来源会话保存独立浏览器 SID、原数据库 session ID、业务 token 的 SHA-256、账号凭据版本指纹、绑定employee/version快照、不可被续期更新的认证方法/时间、撤销版本。数据库会话轮换/到期、账号停用/删除、密码/企微关联/管理员标记改变立即使来源证明失效。
|
||||
- 密码登录登记前再次真正核对密码 hash,不接受开发免密开关。企微入口的 TLS 必须校验后才登记 `wecom`。旧会话首次通过密码验证,或用原企微入口重新登录后登记;普通未关联业务使用不受影响。OIDC 使用原始 `auth_time`,缺失时不算近期认证。
|
||||
- 每次管理写要求 5 分钟内认证、独立动作权限、现有 DataScope。权限:`iamV2/read|bind|create|unbind|rebind|batch`;不存在“未登记路由默认许可”的依赖。
|
||||
- root、管理员/系统管理员/超级管理员角色或持有 IAM 管理写权限的目标视为敏感账号;仅本地 root/管理员类角色具备对应动作权限并完成近期核验时,可提交单人待审操作。中央返回 pending + `PROTECTED_ACCOUNT_REVIEW_REQUIRED` + 固定 `/admin/iam/review?request=...`;界面新标签中央复核,批准后保持相同请求体/幂等键、新 proof 重试。无中央批准仍不执行,普通 IAM 管理角色不具备此特权。批量预检将其列为 review,不发送中央,不静默跳过核验。
|
||||
- 中央身份和授权是真源;本地绑定表是最长 30 秒快照。已关联账号的活跃业务请求在快照超时后回查;失权、版本变更、签名事件撤销来源 SID 和业务会话。服务不可用时相关受保护请求失败关闭。不宣称空闲客户端会在 30 秒内主动收到推送。
|
||||
- 解绑/换绑保留本地业务账号和历史记录。`iam_local_identity` 是开户幂等账本,不是历史绑定全量镜像,永不删除。v2 撤销墓碑拦截旧账本自动重绑;中央旧版 v1 必须同样维护墓碑。较旧或相同版本的 verified 状态不能覆盖本地 revoked。`binding_revoked.bindingVersion` 是旧代际撤销上界;人员停用/应用失权事件只撤销会话并过期快照,不建立永久绑定墓碑。中央审核的新显式绑定可恢复登录,但自动开户分支仍拒绝墓碑。
|
||||
- 管理列表来自所有可见本地账号并回查中央,首次展示历史绑定;按状态筛选基于已对账快照,未读取过的历史行应先在“全部”中分页核验。姓名/手机号不是自动合并依据。批量用明确 local ID/employee ID 映射预检。
|
||||
|
||||
|
||||
## IAM 管理后台/员工工作台 → ZYT target
|
||||
|
||||
中央注册 `zyt.launchUrl=PUBLIC_URL/admin/iam/launch`、`targetDeliveryUrl=PUBLIC_URL/adminapi/iam/v2/launch/callback`;`V2_SOURCES_JSON` 与中央两条 sourceContinueUrl 必须相同,来源只允许 iam-admin/iam-portal。
|
||||
|
||||
前端 `/admin/iam/launch` 先清除 URL 中的 intent/ticket,再调用 `POST /launch/prepare`。后端保存固定来源、PKCE、浏览器 hash 与已有本地账号,设置 HttpOnly Secure SameSite=None target cookie。中央 sourceContinueUrl 的 transaction_id 必须一致,后端追加原 opaque intent;已有 KC cookie 不是必要条件。
|
||||
|
||||
`POST /launch/callback` 核验固定来源 Origin、target cookie、单次事务后兑换 grant;已登录用户冲突在任何自动开户前拒绝。仍通过旧 IamAccountProvisioner 的持久账本/角色2开户,已有账号角色/密码不改。只读回查中央绑定完成后产生60秒一次票据。`POST /launch/exchange` 再比对当前 token 和独立 source cookie,成功才调用 LoginLogic 签发本地token,认证方法标记 iam_launch 并保留真实原authTime。账号不一致只显示显式退出当前浏览器并返回IAM重新发起,不静默替换。
|
||||
|
||||
目标来源代际保存在 `iam_v2_target_session`。活跃业务请求最长30秒调用中央 `/launch-authorizations/check`,仅检查employee/target授权与来源绑定代际,不把普通source logout当作全局登出。源 introspect/sessions-check 回调只查本地数据,绝不递归中央,避免中央state行锁死锁。
|
||||
|
||||
## 本地验证
|
||||
|
||||
```sh
|
||||
php server/tests/IamV2SourceTest.php
|
||||
php server/tests/IamV2TargetTest.php
|
||||
php server/tests/IamV2RouteContractTest.php
|
||||
NODE_PATH=admin/node_modules node server/tests/IamV2UiTest.mjs
|
||||
php server/tests/IamLoginTransactionTest.php
|
||||
php server/tests/IamProvisioningTest.php
|
||||
php server/tests/IamOidcClientTest.php
|
||||
NODE_PATH=admin/node_modules node server/tests/IamLoginUiContractTest.mjs
|
||||
```
|
||||
|
||||
SQLite 合成测试不加载生产 `.env`、不发网络、不修改真实用户、角色或授权。UI 测试编译四个组件并执行新标签页处理逻辑,不能替代三端真实浏览器(Cookie/SameSite/新标签页)验收。原前端全量 typecheck 存量 60 条诊断,需按基线比较,不能批量掩盖。
|
||||
|
||||
## 回退
|
||||
|
||||
已有v2状态时先将 `V2_MANAGEMENT_ENABLED=false`、`V2_LAUNCH_ENABLED=false`,保持 `V2_ENABLED=true` 和当前安全核心;管理写/个人关联密码写/新的委托事务停止,普通授权核验、事件和代际补偿继续。仅可回到同样保持这些核心能力的兼容版本,不能盲退到无v2检查的旧代码。只有从未激活、七表无v2业务状态且全局仍false的首次部署,才可还原本次原文件与原index。保留七张新表、旧开户账本、事件与审计记录、所有真实账号和业务数据。关闭新流程开关停止新的委托登录/管理证明,不撤回中央已执行的人事操作;错误关联通过有审计的显式解绑/换绑恢复,而非删表或恢复旧数据库。
|
||||
|
||||
## 2026-10-29 只读生产入口核对与发布步骤
|
||||
|
||||
本轮只读核验(未部署、未迁移、未开关):
|
||||
|
||||
- SSH 别名 `zyt`;Nginx vhost `/www/server/panel/vhost/nginx/admin.zhenyangtang.com.cn.conf` 的实际 root 是 `/www/wwwroot/zyt/server/public`,PHP include 为 `enable-php-82.conf`,现有 rewrite 经 `index.php?s=...` 进入 ThinkPHP。
|
||||
- 运行仓库 `/www/wwwroot/zyt` 的 HEAD 是 `e183e1cc62d3205576d5dfabd555e78bb86654c8`;它与开发基线 `bcd42a5c399904ec3f9454c6fe1a74bde511ca2c` 不同,禁止整树覆盖。首版9个原文件哈希与开发基线完全一致,17个新增路径未碰撞;本轮追加改动仍须对最终发布manifest重新核对。
|
||||
- PHP 二进制 `/www/server/php/82/bin/php` 为 8.2.35;MySQL CLI 为5.7.44(此处不是数据库服务器版本声明)。服务私密配置留在 `/www/wwwroot/zyt/server/.env`,本轮未读取或输出凭据。
|
||||
- 公网只读 `GET https://admin.zhenyangtang.com.cn/adminapi/iam/config` 返回 `code=1`、`enabled=true`、既有 `/adminapi/iam/start` 登录地址;v2 仍未发布。
|
||||
- `admin/scripts/release.mjs` 会先删除整个 `server/public/admin`。不要在生产直接运行 `npm run build`;它与 `docs/iam-quick-login.md` 要求的保留旧哈希资源冲突。仓库中的 Docker 示例不是当前 Nginx/PHP-FPM 运行入口,ERP ACR 发布脚本也不是 ZYT 发布入口。
|
||||
|
||||
得到发布授权后的受控步骤:
|
||||
|
||||
1. 从指定已提交版本的干净副本构建,运行完整 `scripts/test-iam-v2.sh`、基线差分与 `vite build`;只打包本次明确变更清单和前端构建,附各文件SHA256。不要携带 `.env`、`.local`、上传目录或开发库。
|
||||
2. 只读核对线上所有被替换文件与发布前manifest哈希、新增路径无碰撞;若不一致先重审,不覆盖他人的新发布。保留服务器原文件/静态index及独立备份目录,保存私密配置备份与正常数据库备份。
|
||||
3. 在确认实际表前缀后执行 `20261029_iam_v2.sql`,使用既有受保护的MySQL凭据方式,不能把口令放命令行/日志。MySQL DDL不因后面的事务自动回退;逐表验证七表/索引和菜单节点,保留旧开户账本。菜单不自动给业务角色授权。
|
||||
4. 中央先完成v2迁移、凭据/固定URL/回查注册、原生IAM本人入口和中央复核部署;ZYT新代码先保持 `V2_ENABLED=false`。配置完整的API/portal/ERP公开callback URL及两条来源映射,尤其ERP公开 `/basic-api` 前缀。
|
||||
5. 后端按审核清单更新;静态资源先增量加入旧资源目录,最后原子切换index.html,不删旧哈希文件。按实际OPcache配置处理源码重载,不把CLI `opcache_reset()`当成FPM已刷新,不重启无关服务。
|
||||
6. 先验证开关关闭时原登录/业务行为,再用授权测试账号开启v2验收:密码/企微→ERP、IAM管理后台本地session无KC cookie→ZYT/ERP、员工工作台→两端、同人/异人多标签、已有账号/角色2新开户、密码owner双阶段、敏感单人中央审批及批量跳过、签名事件/30秒补偿。逐项核对真实页面与后端会话,不以HTTP200代替登录验收。
|
||||
7. 初次未激活部署(全局false且七表空)可恢复发布前文件/index;一旦已有v2状态,回退优先只关闭管理/新登录两个开关、保持全局安全核心true,不盲退到旧代码;保留七表、事件、绑定历史、中央操作与所有业务数据。不要用整库恢复或删除IAM员工来回退代码。普通source logout按约定不是全局登出。
|
||||
|
||||
### 最终发布基线差异(追加)
|
||||
|
||||
最终32个变更路径核验:12个原文件中11个与开发基线相同,`admin/src/stores/modules/user.ts` 在线另有 `serverTimeOffsetMs` 状态、reset清理及 `web_consultation_policy.server_time` 的偏移计算;20个新增路径未发现碰撞。该生产逻辑必须保留。**当前以bcd基线生成的整包前端仅为本地构建验证,不直接用于生产发布。** 发布方应先获取/核验实际 `e183e1c` 及线上工作区差异,以其为发布副本应用本次IAM提交(保留时间偏移逻辑)再重新构建;不能通过覆盖生产user store或忽略差异来通过哈希校验。生产回退使用真实发布前备份,而非本地bcd基线副本。
|
||||
|
||||
### 保留生产前端的独立发布副本
|
||||
|
||||
只读补核了实际 `admin/src`、`admin/public`、index.html、package/lock、Vite/PostCSS/Tailwind、typings与TS配置,共710个输入,发现22个已变更文件和17个新增文件,无缺失或symlink。已有网页问诊/接诊、文字记录、复诊到期提醒/统计、处方订单、桌面下载等生产逻辑均按哈希快照保留。
|
||||
|
||||
独立前端副本位于 `/Users/long/Work/zyt-iam-v2-release-20261029`,分支 `codex/zyt-iam-v2-live-frontend`。它基于实际文件快照,而不是线上Git HEAD;仅应用10个受控IAM前端文件,705个非IAM生产输入逐字节不变。该副本仅用于前端构建,不使用其基线PHP目录发布后端。主实现树已三方保留生产user store的服务端时间偏移,并验证getUserInfo/reset行为。
|
||||
|
||||
没有读取生产.env:通过公开已部署JS核实 `baseUrl="https://admin.zhenyangtang.com.cn//"`、`timeout=60000`,最终构建显式使用 `VITE_APP_BASE_URL=https://admin.zhenyangtang.com.cn/` 与 `VITE_APP_REQUEST_TIMEOUT=60000` 保持一致。发布审查应结合 `frontend-production-manifest.json`、`production-frontend-drift.patch`、`release-frontend-manifest.json`、`public-build-config-match.json` 与最终构建包,不采用前面bcd基线的旧构建结果。生产原文件CRLF/尾空白保留原样,不为通过格式检查改写业务源文件。
|
||||
@@ -1,15 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
php server/tests/IamV2SourceTest.php
|
||||
php server/tests/IamV2TargetTest.php
|
||||
php server/tests/IamV2RouteContractTest.php
|
||||
NODE_PATH=admin/node_modules node server/tests/IamV2UiTest.mjs
|
||||
php server/tests/IamLoginTransactionTest.php
|
||||
php server/tests/IamProvisioningTest.php
|
||||
php server/tests/IamOidcClientTest.php
|
||||
NODE_PATH=admin/node_modules node server/tests/IamLoginUiContractTest.mjs
|
||||
php server/tests/AdminDesktopAuthContractTest.php
|
||||
php server/tests/AdminDesktopSessionBehaviorTest.php
|
||||
php server/tests/AdminMultiRoleRegressionTest.php
|
||||
php server/tests/DataScopeMultiRoleTest.php
|
||||
@@ -1,245 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\controller;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\service\iam\IamOidcClient;
|
||||
use app\adminapi\service\iam\v2\{IamV2Client, IamV2Source, IamV2Manager, IamV2Flow, IamV2Target};
|
||||
|
||||
/** Every endpoint authorizes itself. Never relies on legacy unregistered-route allow rules. */
|
||||
final class IamV2Controller extends BaseAdminController
|
||||
{
|
||||
public array $notNeedLogin = ['status', 'introspect', 'checkSession', 'revocation', 'launchContinue', 'selfCallback', 'passwordContinue', 'targetConfig', 'targetPrepare', 'targetCallback', 'targetExchange', 'targetReset'];
|
||||
private function invokeV2(callable $fn)
|
||||
{
|
||||
try {
|
||||
if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$action = strtolower((string) $this->request->action());
|
||||
if (in_array($action, ['operation','preflight','batch','retry','selfstart','passwordsetup'], true) && !IamV2Client::feature('management')) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
if (in_array($action, ['launchstart','targetprepare','targetexchange'], true) && !IamV2Client::feature('launch')) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$reads = ['status','accounts','identities','operationresult','audit','job','targetconfig'];
|
||||
$read = in_array(strtolower((string) $this->request->action()), $reads, true);
|
||||
if (($read && !$this->request->isGet()) || (!$read && !$this->request->isPost())) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
return $this->data($fn())->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return $this->fail($code, ['error' => ['code' => $code]], 0, 0)->header(['Cache-Control' => 'no-store']);
|
||||
}
|
||||
}
|
||||
private function session(bool $recent = false): array
|
||||
{
|
||||
if (!$this->request->isGet()) {
|
||||
$expected = IamV2Client::origin((string) Config::get('iam.public_url'));
|
||||
if ((string) $this->request->header('origin') !== $expected) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
return IamV2Source::current((string) $this->request->header('token', ''), $recent);
|
||||
}
|
||||
private function input(): array { return (array) $this->request->post(); }
|
||||
private function requestId(): string
|
||||
{
|
||||
$key = (string) $this->request->header('idempotency-key', '');
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $key)) { throw new RuntimeException('INVALID_IDEMPOTENCY_KEY'); }
|
||||
return 'zyt-' . $key;
|
||||
}
|
||||
private function serviceAuth(): void
|
||||
{
|
||||
$expected = (string) Config::get('iam.v2_introspection_token', '');
|
||||
if (!$this->request->isPost() || strlen($expected) < 32 || !hash_equals('Bearer ' . $expected, (string) $this->request->header('authorization', ''))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public function status()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$token = (string) $this->request->header('token', '');
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']);
|
||||
$fresh = false; try { $s = IamV2Source::current($token); $fresh = $s['auth_time'] >= time() - 300; } catch (\Throwable $e) { $s = null; }
|
||||
$b = (new IamV2Manager())->binding((int) $legacy['admin_id']);
|
||||
return ['enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'session_ready' => $s !== null, 'reauth_required' => !$fresh,
|
||||
'management_capabilities' => IamV2Source::capabilities((int) $legacy['admin_id']),
|
||||
'protected_review_operator' => IamV2Source::reviewOperator((int) $legacy['admin_id']),
|
||||
'protected_account' => IamV2Source::protectedAccount((int) $legacy['admin_id'])] + $b;
|
||||
});
|
||||
}
|
||||
public function reauth()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
if ((string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
$s = IamV2Source::reauth((string) $this->request->header('token', ''), (string) $this->request->post('password', ''));
|
||||
return ['expires_at' => $s['auth_time'] + 300];
|
||||
});
|
||||
}
|
||||
public function accounts() { return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false); return (new IamV2Manager())->accounts((array) $this->request->get(), (int) $s['admin_id']); }); }
|
||||
public function identities()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
$s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
$q = http_build_query(['q' => mb_substr((string) $this->request->get('q', ''), 0, 64), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20], '', '&', PHP_QUERY_RFC3986);
|
||||
return (new IamV2Client())->call('GET', '/identities?' . $q);
|
||||
});
|
||||
}
|
||||
public function operation() { return $this->invokeV2(fn() => (new IamV2Manager())->operation($this->session(true), $this->input(), $this->requestId())); }
|
||||
public function operationResult() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'operation', (string) $this->request->param('id'))); }
|
||||
public function audit()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
IamV2Source::scope((int) $s['admin_id'], [(int) $this->request->param('id')]);
|
||||
return (new IamV2Client())->call('GET', '/audit?' . http_build_query(['externalAccountId' => (string) (int) $this->request->param('id'), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20])); });
|
||||
}
|
||||
public function preflight() { return $this->invokeV2(fn() => (new IamV2Manager())->preflight($this->session(true), (array) $this->request->post('items', []))); }
|
||||
public function batch() { return $this->invokeV2(fn() => (new IamV2Manager())->batch($this->session(true), (string) $this->request->post('preview_id'), (array) $this->request->post('indexes', []), $this->requestId())); }
|
||||
public function job() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'job', (string) $this->request->param('id'))); }
|
||||
public function retry() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(true), 'job', (string) $this->request->param('id'), true, (array) $this->request->post('indexes', []))); }
|
||||
public function introspect()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input(); return IamV2Source::introspect((string) ($b['proof'] ?? ''), (string) ($b['purpose'] ?? ''), $b['transactionId'] ?? null); });
|
||||
}
|
||||
private function serviceResult(callable $fn)
|
||||
{
|
||||
try { if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); } if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); } return json($fn())->header(['Cache-Control' => 'no-store']); }
|
||||
catch (\Throwable $e) { return json(['active' => false], 403)->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function checkSession()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input();
|
||||
return IamV2Source::liveStatus((string) ($b['sessionId'] ?? ''), (int) ($b['sessionVersion'] ?? 0),
|
||||
(string) ($b['purpose'] ?? ''), (array) ($b['targetLocalIds'] ?? [])); });
|
||||
}
|
||||
public function launchStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
IamV2Source::check($s['session_id'], (int) $s['version']);
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('launch', $intent, ['sessionId' => $s['session_id'], 'sessionVersion' => $s['version']]);
|
||||
setcookie('ZYT_IAM_V2_INTENT', $intent, ['expires' => time() + 300, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return ['url' => IamV2Client::origin((string) Config::get('iam.erp_url')) . '/iam/launch?source=zyt&intent=' . $intent]; });
|
||||
}
|
||||
public function launchContinue()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('launch');
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$intent = (string) $this->request->get('intent', ''); $cookie = (string) ($_COOKIE['ZYT_IAM_V2_INTENT'] ?? '');
|
||||
if ($intent === '' || !hash_equals($cookie, $intent)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$flow = IamV2Flow::take('launch', $intent, $s['session_id']); IamV2Source::check($s['session_id'], (int) $flow['sessionVersion']);
|
||||
$tx = (string) $this->request->get('transaction_id', '');
|
||||
$transaction = $client->call('GET', '/launch-transactions/' . rawurlencode($tx));
|
||||
if (($transaction['sourceApplicationId'] ?? '') !== 'zyt' || ($transaction['targetApplicationId'] ?? '') !== 'zmxy-erp') { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
(new IamV2Manager($client))->assertLinked((int) $s['admin_id']);
|
||||
$grant = $client->call('POST', '/launch-grants', ['transactionId' => $tx, 'proof' => IamV2Source::proof($s, 'launch', [(int) $s['admin_id']], [], $tx)]);
|
||||
$erpOrigin = IamV2Client::origin((string) Config::get('iam.erp_url'));
|
||||
$delivery = IamV2Client::https((string) Config::get('iam.erp_callback_url') ?: $erpOrigin . '/api/erp/iam/v2/launch/callback');
|
||||
if (!in_array($delivery, [$erpOrigin . '/api/erp/iam/v2/launch/callback', $erpOrigin . '/basic-api/api/erp/iam/v2/launch/callback'], true)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
if (($grant['deliveryUrl'] ?? '') !== $delivery) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return response(IamV2Flow::form($delivery, ['transaction_id' => $tx, 'grant' => $grant['grant']]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=launch_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
private function selfConfig(): array { $c = (array) Config::get('iam'); $c['redirect_uri'] = IamV2Client::origin($c['public_url']) . '/adminapi/iam/v2/self-link/callback'; return $c; }
|
||||
public function selfStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $a = IamV2Source::admin((int) $s['admin_id']);
|
||||
if (IamV2Source::protectedAccount((int) $a['id'])) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
$b = (new IamV2Manager())->binding((int) $s['admin_id'], true);
|
||||
if (($b['binding']['state'] ?? '') === 'verified') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$state = bin2hex(random_bytes(32)); $nonce = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('self_link', $state, ['sessionId' => $s['session_id'], 'nonce' => $nonce, 'verifier' => $verifier, 'version' => $b['binding']['version'] ?? null]);
|
||||
return ['url' => (new IamOidcClient($this->selfConfig()))->authorizationUrl($state, $nonce, $verifier) . '&prompt=login&max_age=300']; });
|
||||
}
|
||||
public function selfCallback()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('self_link');
|
||||
$central = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$flow = IamV2Flow::take('self_link', (string) $this->request->get('state', ''), $s['session_id']);
|
||||
$oidc = new IamOidcClient($this->selfConfig()); $oidc->exchange((string) $this->request->get('code', ''), $flow['verifier'], $flow['nonce']);
|
||||
$proof = IamV2Source::proof($s, 'self_link', [(int) $s['admin_id']], [], null, ['oidcNonce' => $flow['nonce']]);
|
||||
$body = ['idToken' => $oidc->verifiedIdToken(), 'nonce' => $flow['nonce'], 'proof' => $proof, 'externalAccountId' => (string) $s['admin_id']];
|
||||
if ($flow['version'] !== null) { $body['expectedVersion'] = (int) $flow['version']; }
|
||||
$central->call('POST', '/self-link', $body);
|
||||
(new IamV2Manager($central))->binding((int) $s['admin_id'], true);
|
||||
return redirect('/admin/user/setting?iam_result=linked')->header(['Cache-Control' => 'no-store']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=link_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function passwordSetup()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $b = (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
if (!($b['employee']['passwordSetupPending'] ?? false)) { throw new RuntimeException('PASSWORD_ALREADY_SET'); }
|
||||
$result = (new IamV2Client())->call('POST', '/password-setup', ['proof' => IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']])]);
|
||||
$url = parse_url((string) ($result['url'] ?? '')); $portal = parse_url(IamV2Client::origin((string) Config::get('iam.portal_url')));
|
||||
if (!$url || ($url['scheme'] ?? '') !== 'https' || ($url['host'] ?? '') !== $portal['host'] || ($url['port'] ?? 443) !== ($portal['port'] ?? 443) || isset($url['user']) || isset($url['pass']) || ($url['path'] ?? '') !== '/portal/password-setup') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('password_setup', $intent, ['sessionId' => $s['session_id'], 'requestId' => $result['requestId']], 900);
|
||||
setcookie('ZYT_IAM_PASSWORD_INTENT', $intent, ['expires' => time() + 900, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return $result; });
|
||||
}
|
||||
public function passwordContinue()
|
||||
{
|
||||
try {
|
||||
IamV2Source::requirePurpose('password_setup');
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$f = IamV2Flow::take('password_setup', (string) ($_COOKIE['ZYT_IAM_PASSWORD_INTENT'] ?? ''), $s['session_id']);
|
||||
$id = (string) $this->request->get('request_id', ''); $state = (string) $this->request->get('state', '');
|
||||
if ($id !== $f['requestId'] || !preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $state)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$proof = IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']], [], $id, ['state' => $state]);
|
||||
$url = IamV2Client::origin((string) Config::get('iam.portal_url')) . '/portal/password-setup/authorize';
|
||||
return response(IamV2Flow::form($url, ['request_id' => $id, 'state' => $state, 'proof' => $proof]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'strict-origin']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=password_failed'); }
|
||||
}
|
||||
private function targetOrigin(): void
|
||||
{
|
||||
if (!$this->request->isPost() || (string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
public function targetConfig()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false, 'management_enabled' => false, 'launch_enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$source = (string) $this->request->get('source', 'iam-portal');
|
||||
return ['enabled' => IamV2Client::feature('launch'), 'global_enabled' => true, 'management_enabled' => IamV2Client::feature('management'), 'launch_enabled' => IamV2Client::feature('launch'), 'restart_url' => IamV2Client::origin((string) Config::get('iam.portal_url')) . ($source === 'iam-admin' ? '/admin' : '/portal')];
|
||||
});
|
||||
}
|
||||
public function targetPrepare()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
$out = (new IamV2Target())->prepare((string) $this->request->post('source', ''), (string) $this->request->post('intent', ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Target::COOKIE, $out['browser'], ['expires' => time() + 300, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['url' => $out['url']];
|
||||
});
|
||||
}
|
||||
public function targetCallback()
|
||||
{
|
||||
try {
|
||||
if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
$out = (new IamV2Target())->callback((string) $this->request->post('transaction_id', ''), (string) $this->request->post('grant', ''),
|
||||
(string) ($_COOKIE[IamV2Target::COOKIE] ?? ''), (string) $this->request->header('origin', ''));
|
||||
return redirect('/admin/iam/launch?' . http_build_query($out))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return redirect('/admin/iam/launch?iam_error=' . rawurlencode($code))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
}
|
||||
}
|
||||
public function targetExchange()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
return (new IamV2Target())->exchange((string) $this->request->post('ticket', ''), (string) ($_COOKIE[IamV2Target::COOKIE] ?? ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
});
|
||||
}
|
||||
public function targetReset()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
IamV2Source::revokeSession((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Source::COOKIE, '', ['expires' => 1, 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
setcookie(IamV2Target::COOKIE, '', ['expires' => 1, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['reset' => true];
|
||||
});
|
||||
}
|
||||
public function revocation()
|
||||
{
|
||||
return $this->serviceResult(fn() => \app\adminapi\service\iam\v2\IamV2Events::accept(
|
||||
(string) $this->request->getContent(), (string) $this->request->header('x-iam-signature', ''),
|
||||
(string) $this->request->header('x-iam-event-id', ''), (string) Config::get('iam.v2_event_secret', '')));
|
||||
}
|
||||
}
|
||||
@@ -38,15 +38,7 @@ class LoginController extends BaseAdminController
|
||||
public function account()
|
||||
{
|
||||
$params = (new LoginValidate())->post()->goCheck();
|
||||
$result = (new LoginLogic())->login($params);
|
||||
// Enroll only a genuinely checked password, never the debug bypass.
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
$a = \think\facade\Db::name('admin')->where('account', $params['account'])->find();
|
||||
if ($a && hash_equals((string) $a['password'], create_password((string) $params['password'], \think\facade\Config::get('project.unique_identification')))) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'password');
|
||||
}
|
||||
}
|
||||
return $this->data($result);
|
||||
return $this->data((new LoginLogic())->login($params));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,9 +158,6 @@ class LoginController extends BaseAdminController
|
||||
public function logout()
|
||||
{
|
||||
//退出登录情况特殊,只有成功的情况,也不需要token验证
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::revokeSession((string) ($_COOKIE[\app\adminapi\service\iam\v2\IamV2Source::COOKIE] ?? ''));
|
||||
}
|
||||
(new LoginLogic())->logout($this->adminInfo);
|
||||
return $this->success();
|
||||
}
|
||||
|
||||
@@ -69,22 +69,6 @@ class LoginMiddleware
|
||||
}
|
||||
}
|
||||
|
||||
// Active requests compensate missed central revocations within a 30-second cache window.
|
||||
// Local-only unlinked accounts and disabled installations keep their original behavior.
|
||||
if ($adminInfo && !$isNotNeedLogin && \app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
try { \app\adminapi\service\iam\v2\IamV2Target::compensate((string) $token); }
|
||||
catch (\Throwable $e) { return JsonService::fail('统一身份授权已失效或暂时不可用,请重新验证', [], 0); }
|
||||
$binding = \think\facade\Db::name('iam_v2_binding')->where('admin_id', $adminInfo['admin_id'])->find();
|
||||
if ($binding && $binding['state'] !== 'unlinked') {
|
||||
try {
|
||||
$b = (new \app\adminapi\service\iam\v2\IamV2Manager())->binding((int) $adminInfo['admin_id']);
|
||||
if (($b['binding']['state'] ?? '') !== 'verified' || !($b['access']['allowed'] ?? false) || ($b['employee']['status'] ?? '') !== 'active') {
|
||||
return JsonService::fail('统一账号关联已失效,请重新登录', [], -1);
|
||||
}
|
||||
} catch (\Throwable $e) { return JsonService::fail('统一身份服务暂时不可用,请稍后重试', [], 0); }
|
||||
}
|
||||
}
|
||||
|
||||
//给request赋值,用于控制器
|
||||
$request->adminInfo = $adminInfo;
|
||||
$request->adminId = $adminInfo['admin_id'] ?? 0;
|
||||
|
||||
@@ -222,10 +222,6 @@ class LoginLogic extends BaseLogic
|
||||
// 设置 token
|
||||
$adminInfo = AdminTokenService::setToken($admin->id, $terminal, $admin->multipoint_login);
|
||||
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($adminInfo['token'], 'wecom');
|
||||
}
|
||||
|
||||
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
|
||||
$avatar = FileService::getFileUrl($avatar);
|
||||
|
||||
@@ -283,8 +279,8 @@ class LoginLogic extends BaseLogic
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
|
||||
$result = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
use think\facade\Route;
|
||||
// Explicit method/path mapping; controller also fails closed for every v2 capability.
|
||||
Route::get('iam/v2/status', 'IamV2/status');
|
||||
Route::post('iam/v2/reauth', 'IamV2/reauth');
|
||||
Route::get('iam/v2/accounts', 'IamV2/accounts');
|
||||
Route::get('iam/v2/identities', 'IamV2/identities');
|
||||
Route::post('iam/v2/operations', 'IamV2/operation');
|
||||
Route::get('iam/v2/operations/:id', 'IamV2/operationResult');
|
||||
Route::get('iam/v2/accounts/:id/audit', 'IamV2/audit');
|
||||
Route::post('iam/v2/batch/preflight', 'IamV2/preflight');
|
||||
Route::post('iam/v2/batch', 'IamV2/batch');
|
||||
Route::get('iam/v2/jobs/:id', 'IamV2/job');
|
||||
Route::post('iam/v2/jobs/:id/retry', 'IamV2/retry');
|
||||
Route::post('iam/v2/proofs/introspect', 'IamV2/introspect');
|
||||
Route::post('iam/v2/sessions/check', 'IamV2/checkSession');
|
||||
Route::post('iam/v2/events/revocation', 'IamV2/revocation');
|
||||
Route::post('iam/v2/launch/start', 'IamV2/launchStart');
|
||||
Route::get('iam/v2/launch/continue', 'IamV2/launchContinue');
|
||||
Route::post('iam/v2/self-link/start', 'IamV2/selfStart');
|
||||
Route::get('iam/v2/self-link/callback', 'IamV2/selfCallback');
|
||||
Route::post('iam/v2/password-setup', 'IamV2/passwordSetup');
|
||||
Route::get('iam/v2/password-continue', 'IamV2/passwordContinue');
|
||||
|
||||
// ZYT as a target for the same person's IAM admin/portal session only.
|
||||
Route::get('iam/v2/launch/config', 'IamV2/targetConfig');
|
||||
Route::post('iam/v2/launch/prepare', 'IamV2/targetPrepare');
|
||||
Route::post('iam/v2/launch/callback', 'IamV2/targetCallback');
|
||||
Route::post('iam/v2/launch/exchange', 'IamV2/targetExchange');
|
||||
Route::post('iam/v2/launch/reset', 'IamV2/targetReset');
|
||||
@@ -41,11 +41,6 @@ final class IamAccountProvisioner
|
||||
if (($context['shouldCreateLocalAccount'] ?? null) !== true) {
|
||||
return IamLoginService::boundAdminId($context, $subject, $config['application_id']);
|
||||
}
|
||||
// A local tombstone blocks auto-creation, not an explicitly reviewed newer central binding.
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
$tombstone = Db::name('iam_v2_binding')->where('subject', $subject)->where('state', 'revoked')->find();
|
||||
if ($tombstone) { throw new RuntimeException('IAM_BINDING_REVOKED'); }
|
||||
}
|
||||
if (($context['externalAccountId'] ?? null) !== '') {
|
||||
throw new RuntimeException('统一账号绑定状态不一致');
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ final class IamLoginService
|
||||
$claims = $this->client->exchange($code, $transaction['verifier'], $transaction['nonce']);
|
||||
$this->verifiedAdmin($claims['sub']);
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
$this->transactions->put('ticket', $ticket, $browser, ['subject' => $claims['sub'], 'auth_time' => (int) ($claims['auth_time'] ?? 0)], 60);
|
||||
$this->transactions->put('ticket', $ticket, $browser, ['subject' => $claims['sub']], 60);
|
||||
return $ticket;
|
||||
}
|
||||
|
||||
@@ -79,15 +79,7 @@ final class IamLoginService
|
||||
$transaction = $this->transactions->consume('ticket', $ticket, $browser);
|
||||
// Recheck entitlement, binding and local status immediately before issuing the existing business token.
|
||||
$admin = $this->verifiedAdmin($transaction['subject']);
|
||||
// Reconcile/revoke the previous binding generation before minting the new token.
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
(new \app\adminapi\service\iam\v2\IamV2Manager())->assertLinked((int) $admin->id);
|
||||
}
|
||||
$result = (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'oidc', true, (int) ($transaction['auth_time'] ?? 0));
|
||||
}
|
||||
return $result;
|
||||
return (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
|
||||
}
|
||||
|
||||
public static function boundAdminId(array $context, string $subject, string $applicationId): int
|
||||
|
||||
@@ -14,13 +14,6 @@ final class IamOidcClient
|
||||
private array $config;
|
||||
private $transport;
|
||||
private ?array $discovery = null;
|
||||
private ?string $verifiedToken = null;
|
||||
|
||||
public function verifiedIdToken(): string
|
||||
{
|
||||
if ($this->verifiedToken === null) { throw new RuntimeException("IAM token not verified"); }
|
||||
return $this->verifiedToken;
|
||||
}
|
||||
|
||||
/** Transport signature: (method, url, headers, body): ['status'=>int, 'body'=>string]. */
|
||||
public function __construct(array $config, ?callable $transport = null)
|
||||
@@ -109,7 +102,6 @@ final class IamOidcClient
|
||||
|| (isset($claims['nbf']) && (!is_int($claims['nbf']) || $claims['nbf'] > $now))) {
|
||||
throw new RuntimeException('IAM ID token claims are invalid');
|
||||
}
|
||||
$this->verifiedToken = $response['id_token'];
|
||||
return $claims;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
|
||||
/** Dedicated v2 application credential; never falls back to the v1 provisioning token. */
|
||||
final class IamV2Client
|
||||
{
|
||||
public function __construct(private ?array $settings = null, private $transport = null)
|
||||
{
|
||||
$this->settings ??= (array) Config::get('iam', []);
|
||||
if (!self::enabled($this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
self::https((string) ($this->settings['api_url'] ?? ''));
|
||||
foreach (['public_url', 'erp_url'] as $field) { self::origin((string) ($this->settings[$field] ?? '')); }
|
||||
if (strlen((string) ($this->settings['v2_token'] ?? '')) < 32) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
}
|
||||
public static function enabled(?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
return filter_var($settings['v2_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function feature(string $feature, ?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
if (!in_array($feature, ['management', 'launch'], true)) { return false; }
|
||||
return self::enabled($settings) && filter_var($settings['v2_' . $feature . '_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function https(string $url): string
|
||||
{
|
||||
$p = parse_url($url);
|
||||
if (!$p || ($p['scheme'] ?? '') !== 'https' || empty($p['host']) || isset($p['user']) || isset($p['pass'])
|
||||
|| isset($p['fragment']) || isset($p['query']) || preg_match('/[\x00-\x20\x7f\\\\]/', $url)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return rtrim($url, '/');
|
||||
}
|
||||
public static function origin(string $url): string
|
||||
{
|
||||
$url = self::https($url);
|
||||
if ((parse_url($url, PHP_URL_PATH) ?? '') !== '') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $url;
|
||||
}
|
||||
public function call(string $method, string $path, array $body = [], ?string $key = null): array
|
||||
{
|
||||
if (!preg_match('#^/[a-zA-Z0-9/_?=&%.:-]+$#D', $path) || str_contains($path, '..')) { throw new RuntimeException('INVALID_PATH'); }
|
||||
$url = rtrim($this->settings['api_url'], '/') . '/internal/v2/applications/' . rawurlencode($this->settings['application_id'] ?? 'zyt') . $path;
|
||||
$management = preg_match('#^/(identities|operations|audit|batch|jobs)(/|[?]|$)#D', $path) === 1;
|
||||
$credential = (string) ($this->settings[$management ? 'v2_management_token' : 'v2_token'] ?? '');
|
||||
if (strlen($credential) < 32 || preg_match('/[\r\n]/', $credential)
|
||||
|| ($management && hash_equals((string) $this->settings['v2_token'], $credential))) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$headers = ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $credential];
|
||||
if ($method !== 'GET') {
|
||||
$headers[] = 'X-Request-ID: ' . bin2hex(random_bytes(16));
|
||||
$headers[] = 'Idempotency-Key: ' . ($key ?? bin2hex(random_bytes(24)));
|
||||
}
|
||||
$data = $method === 'GET' ? '' : json_encode($body, JSON_THROW_ON_ERROR);
|
||||
if ($this->transport) { $r = ($this->transport)($method, $url, $headers, $data); }
|
||||
else {
|
||||
$c = curl_init($url); $response = '';
|
||||
curl_setopt_array($c, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_WRITEFUNCTION => static function ($c, $chunk) use (&$response) {
|
||||
if (strlen($response) + strlen($chunk) > 2097152) { return 0; } $response .= $chunk; return strlen($chunk);
|
||||
}]);
|
||||
$ok = curl_exec($c); $r = ['status' => curl_getinfo($c, CURLINFO_RESPONSE_CODE), 'body' => $ok === false ? '' : $response]; curl_close($c);
|
||||
}
|
||||
$result = json_decode($r['body'] ?? '', true);
|
||||
if (!is_array($result)) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$operationEnvelope = isset($result['id']) && is_string($result['id'])
|
||||
&& in_array($result['status'] ?? '', ['pending', 'succeeded', 'failed', 'conflict'], true)
|
||||
&& preg_match('#^/(operations|jobs|batch)(/|$)#D', $path);
|
||||
if (($r['status'] ?? 0) < 200 || $r['status'] >= 300 || (isset($result['error']) && !$operationEnvelope)) {
|
||||
$code = $result['error']['code'] ?? 'SERVICE_UNAVAILABLE';
|
||||
throw new RuntimeException(preg_match('/^[A-Z_]{3,64}$/D', $code) ? $code : 'SERVICE_UNAVAILABLE');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Events
|
||||
{
|
||||
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null, ?callable $refresh = null, ?callable $locate = null, ?callable $generation = null): array
|
||||
{
|
||||
if (strlen($raw) > 65536 || strlen($secret) < 32 || !hash_equals('sha256=' . hash_hmac('sha256', $raw, $secret), $signature)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$event = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (empty($event['employeeId']) || $eventId === '' || strlen($eventId) > 128 || $eventId !== ($event['id'] ?? '') || !in_array('zyt', (array) ($event['applicationIds'] ?? []), true)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$occurredAt = (string) ($event['occurredAt'] ?? '');
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}T.*(Z|[+-][0-9]{2}:[0-9]{2})$/D', $occurredAt)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$stamp = strtotime($occurredAt);
|
||||
if (!$stamp || $stamp > time() + 60) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$customRevoke = $revoke !== null;
|
||||
$revoke ??= fn(int $id) => IamV2Manager::revoke($id);
|
||||
$refresh ??= fn(int $id) => (new IamV2Manager())->binding($id, true);
|
||||
$generation ??= $customRevoke ? fn(int $id, int $upper) => $revoke($id) : fn(int $id, int $upper) => IamV2Source::revokeGeneration($id, $upper, (string) $event['employeeId']);
|
||||
$locate ??= static function (array $event): array {
|
||||
if (($event['eventType'] ?? '') === 'binding_revoked' && isset($event['externalAccountId'])) {
|
||||
if (!is_string($event['externalAccountId']) || !preg_match('/^[1-9][0-9]{0,9}$/D', $event['externalAccountId'])) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return [(int) $event['externalAccountId']];
|
||||
}
|
||||
$reply = (new IamV2Client())->call('GET', '/bindings?' . http_build_query(['employeeId' => $event['employeeId'], 'page' => 1, 'pageSize' => 100], '', '&', PHP_QUERY_RFC3986));
|
||||
if (($reply['total'] ?? 0) > 100) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$ids = [];
|
||||
foreach ($reply['items'] ?? [] as $item) {
|
||||
if (($item['binding']['employeeId'] ?? '') !== $event['employeeId'] || ($item['binding']['applicationId'] ?? '') !== 'zyt') { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$external = (string) ($item['binding']['externalAccountId'] ?? '');
|
||||
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $external)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$ids[] = (int) $external;
|
||||
}
|
||||
return $ids;
|
||||
};
|
||||
return Db::transaction(function () use ($event, $eventId, $raw, $revoke, $refresh, $locate, $generation) {
|
||||
$existing = Db::name('iam_v2_event')->where('event_id', $eventId)->lock(true)->find();
|
||||
if ($existing) {
|
||||
if (!hash_equals($existing['digest'], hash('sha256', $raw))) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return ['accepted' => true, 'duplicate' => true];
|
||||
}
|
||||
Db::name('iam_v2_event')->insert(['event_id' => $eventId, 'digest' => hash('sha256', $raw), 'received_at' => time()]);
|
||||
$rows = Db::name('iam_v2_binding')->where('employee_id', (string) $event['employeeId'])->lock(true)->select()->toArray();
|
||||
if (!$rows && ($event['eventType'] ?? '') !== 'source_binding_revoked') {
|
||||
foreach ($locate($event) as $id) {
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$row) { $refresh($id); $row = Db::name('iam_v2_binding')->where('admin_id', $id)->find(); }
|
||||
if ($row) { $rows[] = $row; }
|
||||
}
|
||||
}
|
||||
foreach ($rows as $row) {
|
||||
$bindingEvent = ($event['eventType'] ?? '') === 'binding_revoked'
|
||||
|| in_array($event['reason'] ?? '', ['iam.v2.unbind', 'iam.v2.rebind'], true);
|
||||
// ZYT is source-only in this rollout; target-derived revocation belongs to ERP.
|
||||
if (($event['eventType'] ?? '') === 'source_binding_revoked') { continue; }
|
||||
$upper = isset($event['bindingVersion']) ? (int) $event['bindingVersion'] : null;
|
||||
if ($bindingEvent && $upper !== null && ($upper < (int) $row['version'] || $row['employee_id'] !== $event['employeeId'])) { $generation((int) $row['admin_id'], $upper); continue; }
|
||||
if (!$bindingEvent || $upper === null) {
|
||||
// Durable outbox delivery may be old. Current central state wins over a stale generic event.
|
||||
// A failed lookup rolls back event receipt, so the durable outbox can retry.
|
||||
$current = $refresh((int) $row['admin_id']);
|
||||
if (($current['binding']['state'] ?? '') === 'verified' && ($current['employee']['status'] ?? '') === 'active'
|
||||
&& ($current['access']['allowed'] ?? false)) { continue; }
|
||||
}
|
||||
$updates = ['checked_at' => 0];
|
||||
// Personnel disable/entitlement events invalidate sessions, not the binding itself.
|
||||
// A versioned binding event carries the OLD generation as its revocation upper bound.
|
||||
if ($bindingEvent && $upper !== null && $upper > 0) {
|
||||
$updates['state'] = 'revoked'; $updates['version'] = max((int) $row['version'], $upper);
|
||||
}
|
||||
Db::name('iam_v2_binding')->where('admin_id', $row['admin_id'])->update($updates);
|
||||
if ($bindingEvent && $upper !== null) { $generation((int) $row['admin_id'], $upper); }
|
||||
else { $revoke((int) $row['admin_id']); }
|
||||
}
|
||||
return ['accepted' => true];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Flow
|
||||
{
|
||||
public static function put(string $kind, string $secret, array $payload, int $ttl = 300): void
|
||||
{
|
||||
Db::name('iam_v2_flow')->insert(['flow_key' => hash('sha256', $kind . ':' . $secret), 'kind' => $kind,
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + $ttl, 'consumed' => 0]);
|
||||
}
|
||||
public static function peek(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', hash('sha256', $kind . ':' . $secret))->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
return $p;
|
||||
}
|
||||
public static function take(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
return Db::transaction(function () use ($kind, $secret, $sid) {
|
||||
$key = hash('sha256', $kind . ':' . $secret);
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', $key)->lock(true)->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if (Db::name('iam_v2_flow')->where('flow_key', $key)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return $p;
|
||||
});
|
||||
}
|
||||
public static function form(string $url, array $fields): string
|
||||
{
|
||||
$nonce = bin2hex(random_bytes(18));
|
||||
$escape = fn($s) => htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
$inputs = '';
|
||||
foreach ($fields as $name => $value) { $inputs .= '<input type="hidden" name="' . $escape($name) . '" value="' . $escape($value) . '">'; }
|
||||
$origin = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . (parse_url($url, PHP_URL_PORT) ? ':' . parse_url($url, PHP_URL_PORT) : '');
|
||||
return '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; base-uri \'none\'; form-action ' . $escape($origin) . '; script-src \'nonce-' . $nonce . '\'"><title>正在验证身份</title><form method="post" action="' . $escape($url) . '">' . $inputs . '<button>继续</button></form><script nonce="' . $nonce . '">document.forms[0].submit()</script>';
|
||||
}
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
|
||||
final class IamV2Manager
|
||||
{
|
||||
public function __construct(private ?IamV2Client $client = null) { $this->client ??= new IamV2Client(); }
|
||||
public function binding(int $id, bool $fresh = false): array
|
||||
{
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$fresh && $row && $row['checked_at'] > time() - 30) {
|
||||
$cached = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
$cached['checked_at'] = (int) $row['checked_at'];
|
||||
return $cached;
|
||||
}
|
||||
$result = $this->client->call('GET', '/bindings/by-external/' . $id);
|
||||
if (($result['binding']['externalAccountId'] ?? (string) $id) !== (string) $id) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($result['binding'] ?? null) {
|
||||
$b = $result['binding']; $employee = $result['employee'] ?? [];
|
||||
if (($b['applicationId'] ?? '') !== (string) Config::get('iam.application_id', 'zyt')
|
||||
|| !is_int($b['version'] ?? null) || $b['version'] < 1
|
||||
|| !in_array($b['state'] ?? '', ['verified','revoked','pending','conflict'], true)
|
||||
|| empty($employee['id']) || ($b['employeeId'] ?? '') !== $employee['id'] || empty($employee['oidcSubject'])) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
}
|
||||
$state = $result['binding']['state'] ?? 'unlinked';
|
||||
$version = (int) ($result['binding']['version'] ?? 0);
|
||||
if ($row && $row['state'] === 'revoked' && $state === 'verified' && $version <= (int) $row['version']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($row && (int) $row['version'] > $version) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$values = ['admin_id' => $id, 'employee_id' => $result['employee']['id'] ?? '', 'subject' => $result['employee']['oidcSubject'] ?? '',
|
||||
'state' => $state, 'version' => $version, 'payload' => json_encode($result, JSON_THROW_ON_ERROR), 'checked_at' => time()];
|
||||
if ($row) { Db::name('iam_v2_binding')->where('admin_id', $id)->update($values); }
|
||||
else { Db::name('iam_v2_binding')->insert($values); }
|
||||
$changed = $row && $row['state'] === 'verified' && (($row['employee_id'] ?? '') !== ($values['employee_id'] ?? '') || (int) $row['version'] !== $version);
|
||||
if ($state === 'revoked' || (($result['employee'] ?? null) && (($result['employee']['status'] ?? '') !== 'active' || !($result['access']['allowed'] ?? false)))) {
|
||||
self::revoke($id);
|
||||
} elseif ($changed) {
|
||||
IamV2Source::revokeGeneration($id, (int) $row['version'], (string) $row['employee_id']);
|
||||
}
|
||||
$result['checked_at'] = $values['checked_at'];
|
||||
return $result;
|
||||
}
|
||||
public static function revoke(int $id): void
|
||||
{
|
||||
IamV2Source::revokeAdmin($id);
|
||||
foreach (Db::name('admin_session')->where('admin_id', $id)->column('token') as $token) { AdminLogic::expireToken($token); }
|
||||
}
|
||||
public function assertLinked(int $id): array
|
||||
{
|
||||
$b = $this->binding($id, true);
|
||||
if (($b['binding']['state'] ?? '') !== 'verified') { throw new RuntimeException('NOT_LINKED'); }
|
||||
if (($b['employee']['status'] ?? '') !== 'active' || !($b['access']['allowed'] ?? false)) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return $b;
|
||||
}
|
||||
public function accounts(array $query, int $actor): array
|
||||
{
|
||||
$page = max(1, (int) ($query['page'] ?? 1)); $size = min(20, max(1, (int) ($query['pageSize'] ?? 20)));
|
||||
$db = Db::name('admin')->whereNull('delete_time');
|
||||
$visible = IamV2Source::visibleIds($actor);
|
||||
if ($visible !== null) { $db->whereIn('id', $visible ?: [0]); }
|
||||
if (($query['q'] ?? '') !== '') { $db->whereLike('account|name', '%' . mb_substr((string) $query['q'], 0, 64) . '%'); }
|
||||
if (($query['state'] ?? '') !== '') {
|
||||
$ids = Db::name('iam_v2_binding')->where('state', (string) $query['state'])->column('admin_id');
|
||||
if ($query['state'] === 'unknown') { $db->whereNotIn('id', Db::name('iam_v2_binding')->column('admin_id')); }
|
||||
else { $db->whereIn('id', $ids ?: [0]); }
|
||||
}
|
||||
$total = (clone $db)->count();
|
||||
$items = $db->field('id,account,name,disable,root')->page($page, $size)->select()->toArray();
|
||||
// Resolve department labels only for already-scoped rows, never broaden the account query.
|
||||
$departmentNames = [];
|
||||
if ($items !== []) {
|
||||
$links = Db::name('admin_dept')->whereIn('admin_id', array_column($items, 'id'))
|
||||
->field('admin_id,dept_id')->order('dept_id', 'asc')->select()->toArray();
|
||||
$ids = array_values(array_unique(array_column($links, 'dept_id')));
|
||||
$labels = $ids ? Db::name('dept')->whereIn('id', $ids)->whereNull('delete_time')->column('name', 'id') : [];
|
||||
foreach ($links as $link) {
|
||||
if (isset($labels[$link['dept_id']])) { $departmentNames[$link['admin_id']][$link['dept_id']] = (string) $labels[$link['dept_id']]; }
|
||||
}
|
||||
}
|
||||
foreach ($items as &$r) {
|
||||
$r['dept_names'] = array_values($departmentNames[$r['id']] ?? []);
|
||||
try { $r['iam'] = $this->binding((int) $r['id']); $r['iam']['state'] = $r['iam']['binding']['state'] ?? 'unlinked'; }
|
||||
catch (\Throwable $e) {
|
||||
$last = Db::name('iam_v2_binding')->where('admin_id', $r['id'])->value('checked_at');
|
||||
$reason = in_array($e->getMessage(), ['BINDING_CONFLICT','ACCOUNT_MISMATCH','ACCOUNT_DISABLED','NOT_AUTHORIZED'], true)
|
||||
? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
$r['iam'] = ['state' => 'unknown', 'error' => $reason, 'access' => ['allowed' => null, 'reason' => $reason],
|
||||
'checked_at' => (int) $last > 0 ? (int) $last : null];
|
||||
}
|
||||
}
|
||||
unset($r);
|
||||
return ['items' => $items, 'total' => $total];
|
||||
}
|
||||
public static function input(array $input): array
|
||||
{
|
||||
$kind = (string) ($input['kind'] ?? '');
|
||||
if (!in_array($kind, ['bind', 'create_and_bind', 'unbind', 'rebind', 'reconcile'], true)) { throw new RuntimeException('INVALID_OPERATION'); }
|
||||
$id = (int) ($input['user_id'] ?? 0);
|
||||
if ($id < 1 || strlen(trim((string) ($input['reason'] ?? ''))) < 3) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out = ['kind' => $kind, 'externalAccountId' => (string) $id, 'reason' => mb_strcut(trim($input['reason']), 0, 500, 'UTF-8')];
|
||||
if (isset($input['employee_id'])) { $out['employeeId'] = (string) $input['employee_id']; }
|
||||
if (isset($input['expected_version'])) { $out['expectedVersion'] = (int) $input['expected_version']; }
|
||||
if (in_array($kind, ['unbind','rebind'], true) && !isset($out['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($kind === 'create_and_bind') {
|
||||
$n = $input['new_employee'] ?? [];
|
||||
$out['newEmployee'] = ['username' => (string) ($n['username'] ?? ''), 'displayName' => (string) ($n['display_name'] ?? '')];
|
||||
if (!preg_match('/^[A-Za-z0-9_.@-]{3,64}$/D', $out['newEmployee']['username']) || trim($out['newEmployee']['displayName']) === '') { throw new RuntimeException('INVALID_INPUT'); }
|
||||
if (!empty($n['email'])) {
|
||||
if (!filter_var($n['email'], FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out['newEmployee']['email'] = $n['email'];
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
public static function cap(string $kind): string { return ['create_and_bind' => 'create', 'reconcile' => 'bind'][$kind] ?? $kind; }
|
||||
public function operation(array $session, array $input, string $requestId): array
|
||||
{
|
||||
$body = self::input($input); $target = (int) $body['externalAccountId']; $cap = self::cap($body['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$target], true, true);
|
||||
$current = $this->binding($target, true); $caps = ['iam:' . $cap];
|
||||
if ($body['kind'] === 'create_and_bind' && ($current['binding']['state'] ?? '') === 'revoked') {
|
||||
if (!isset($body['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$target], true, true); $caps[] = 'iam:rebind';
|
||||
}
|
||||
$body['proof'] = IamV2Source::proof($session, 'management', [$target], $caps, null, ['protectedReviewEligible' => IamV2Source::reviewOperator((int) $session['admin_id'])]);
|
||||
$op = $this->client->call('POST', '/operations', $body, $requestId);
|
||||
$op = $this->reviewLink($op);
|
||||
$this->remember('operation', (string) $op['id'], $session, [$target], $caps);
|
||||
if (($op['status'] ?? '') === 'succeeded') { $this->binding($target, true); }
|
||||
return $op;
|
||||
}
|
||||
private function reviewLink(array $operation): array
|
||||
{
|
||||
if (!isset($operation['reviewUrl'])) { return $operation; }
|
||||
$origin = IamV2Client::origin((string) Config::get('iam.portal_url'));
|
||||
$parts = parse_url((string) $operation['reviewUrl']);
|
||||
$fixed = parse_url($origin);
|
||||
if (!$parts || ($parts['scheme'] ?? '') !== 'https' || ($parts['host'] ?? '') !== $fixed['host']
|
||||
|| ($parts['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($parts['path'] ?? '') !== '/admin/iam/review'
|
||||
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($parts['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['request'] ?? null) !== ($operation['id'] ?? null)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $operation;
|
||||
}
|
||||
public function remember(string $kind, string $id, array $session, array $targets, array $caps = []): void
|
||||
{
|
||||
$key = hash('sha256', $kind . ':' . $id);
|
||||
$existing = Db::name('iam_v2_resource')->where('resource_key', $key)->find();
|
||||
if ($existing) { if ((int) $existing['actor_id'] !== (int) $session['admin_id']) { throw new RuntimeException('FORBIDDEN'); } return; }
|
||||
Db::name('iam_v2_resource')->insert(['resource_key' => $key, 'kind' => $kind, 'external_id' => $id, 'actor_id' => $session['admin_id'],
|
||||
'payload' => json_encode(['targets' => $targets, 'capabilities' => $caps]), 'created_at' => time()]);
|
||||
}
|
||||
public function owned(string $kind, string $id, array $session): array
|
||||
{
|
||||
$r = Db::name('iam_v2_resource')->where('resource_key', hash('sha256', $kind . ':' . $id))->where('actor_id', $session['admin_id'])->find();
|
||||
if (!$r) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$payload = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
IamV2Source::scope((int) $session['admin_id'], $payload['targets']);
|
||||
return $payload;
|
||||
}
|
||||
public function preflight(array $session, array $items): array
|
||||
{
|
||||
if (!$items || count($items) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
IamV2Source::authorize($session, 'batch'); $mapped = []; $targets = []; $caps = ['iam:batch']; $indexMap = []; $review = []; $itemCaps = [];
|
||||
foreach ($items as $index => $input) {
|
||||
try {
|
||||
$item = self::input($input); $id = (int) $item['externalAccountId']; $cap = self::cap($item['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$id]);
|
||||
$held = ['iam:' . $cap];
|
||||
if ($item['kind'] === 'create_and_bind' && (($this->binding($id, true)['binding']['state'] ?? '') === 'revoked')) {
|
||||
if (!isset($item['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$id]); $held[] = 'iam:rebind';
|
||||
}
|
||||
$indexMap[] = (int) $index; $mapped[] = $item; $targets[] = $id; $itemCaps[] = $held; $caps = array_merge($caps, $held);
|
||||
} catch (RuntimeException $e) {
|
||||
$review[] = ['index' => (int) $index, 'externalAccountId' => (string) ($input['user_id'] ?? ''),
|
||||
'status' => $e->getMessage() === 'PROTECTED_ACCOUNT_REVIEW_REQUIRED' ? 'review' : 'invalid', 'message' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
if (!$mapped) { return ['previewId' => null, 'items' => $review, 'expiresAt' => time()]; }
|
||||
$r = $this->client->call('POST', '/batch/preflight', ['items' => $mapped,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, array_values(array_unique($caps)))]);
|
||||
$this->remember('preview', (string) $r['previewId'], $session, $targets, $caps);
|
||||
$resource = hash('sha256', 'preview:' . $r['previewId']);
|
||||
$ready = [];
|
||||
foreach ($r['items'] as &$item) {
|
||||
$centralIndex = (int) $item['index'];
|
||||
if (!array_key_exists($centralIndex, $indexMap)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$item['index'] = $indexMap[$centralIndex];
|
||||
if ($item['status'] === 'ready') { $ready[] = $item['index']; }
|
||||
}
|
||||
unset($item);
|
||||
Db::name('iam_v2_resource')->where('resource_key', $resource)->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'indexMap' => $indexMap, 'ready' => $ready, 'itemCaps' => $itemCaps])]);
|
||||
$r['items'] = array_merge($r['items'], $review);
|
||||
usort($r['items'], fn($a, $b) => $a['index'] <=> $b['index']); return $r;
|
||||
}
|
||||
public function batch(array $session, string $preview, array $indexes, string $key): array
|
||||
{
|
||||
$scope = $this->owned('preview', $preview, $session);
|
||||
$indexes = array_values(array_unique(array_map('intval', $indexes)));
|
||||
if (!$indexes || array_diff($indexes, $scope['ready'] ?? [])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$indexes = array_map(fn($i) => array_search($i, $scope['indexMap'], true), $indexes);
|
||||
$targets = array_map(fn($i) => $scope['targets'][$i], $indexes); $caps = ['iam:batch']; $itemCaps = [];
|
||||
foreach ($indexes as $i) { $itemCaps[$i] = $scope['itemCaps'][$i] ?? $scope['capabilities']; $caps = array_merge($caps, $itemCaps[$i]); }
|
||||
$caps = array_values(array_unique($caps));
|
||||
foreach ($caps as $cap) { IamV2Source::authorize($session, substr($cap, 4), $targets); }
|
||||
$r = $this->client->call('POST', '/batch', ['previewId' => $preview, 'indexes' => $indexes,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, $caps)], $key);
|
||||
$this->remember('job', (string) $r['id'], $session, $targets, $caps);
|
||||
Db::name('iam_v2_resource')->where('resource_key', hash('sha256', 'job:' . $r['id']))->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'itemCaps' => $itemCaps, 'centralIndexes' => $indexes])]);
|
||||
return $r;
|
||||
}
|
||||
/** Public retry indexes are job.items positions, not original central preview indexes. */
|
||||
public static function retrySelection(array $job, array $positions = []): array
|
||||
{
|
||||
$items = $job['items'] ?? []; $central = $job['indexes'] ?? [];
|
||||
if ($positions === []) { $positions = array_keys($items); }
|
||||
$indexes = []; $targets = []; $caps = ['iam:batch'];
|
||||
foreach (array_unique($positions) as $position) {
|
||||
if (!is_int($position) || !isset($items[$position], $central[$position])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$item = $items[$position];
|
||||
if (!in_array($item['status'] ?? '', ['failed', 'pending'], true)) { continue; }
|
||||
$indexes[] = $central[$position]; $targets[] = (int) $item['externalAccountId']; $caps[] = 'iam:' . self::cap($item['kind']);
|
||||
}
|
||||
return ['indexes' => $indexes, 'targets' => $targets, 'capabilities' => array_values(array_unique($caps))];
|
||||
}
|
||||
public function result(array $session, string $kind, string $id, bool $retry = false, array $indexes = []): array
|
||||
{
|
||||
$scope = $this->owned($kind, $id, $session); IamV2Source::authorize($session, 'read', [], false);
|
||||
$path = ($kind === 'job' ? '/jobs/' : '/operations/') . rawurlencode($id);
|
||||
if ($retry) {
|
||||
$job = $this->client->call('GET', $path);
|
||||
// The saved mapping prevents the central endpoint changing this operation's target set.
|
||||
if (!isset($job['indexes'])) { $job['indexes'] = $scope['centralIndexes'] ?? []; }
|
||||
$selected = self::retrySelection($job, $indexes);
|
||||
if (!$selected['indexes']) { return $job; }
|
||||
if (array_diff($selected['targets'], array_map('intval', $scope['targets']))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
foreach ($selected['indexes'] as $i) { $selected['capabilities'] = array_merge($selected['capabilities'], $scope['itemCaps'][$i] ?? []); }
|
||||
$selected['capabilities'] = array_values(array_unique($selected['capabilities']));
|
||||
foreach ($selected['capabilities'] as $cap) { IamV2Source::authorize($session, substr($cap, 4), $selected['targets']); }
|
||||
$r = $this->client->call('POST', $path . '/retry', ['indexes' => $selected['indexes'],
|
||||
'proof' => IamV2Source::proof($session, 'management', $selected['targets'], $selected['capabilities'])]);
|
||||
$scope['targets'] = $selected['targets'];
|
||||
} else { $r = $this->client->call('GET', $path); }
|
||||
foreach ($scope['targets'] as $target) { $this->binding((int) $target, true); }
|
||||
return $kind === 'operation' ? $this->reviewLink($r) : $r;
|
||||
}
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\common\cache\AdminAccountSafeCache;
|
||||
|
||||
/** Browser source sessions are separate from legacy account/terminal shared business tokens. */
|
||||
final class IamV2Source
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_SESSION';
|
||||
public static function requirePurpose(string $purpose): void
|
||||
{
|
||||
$feature = in_array($purpose, ['management', 'self_link', 'password_setup'], true) ? 'management' : ($purpose === 'launch' ? 'launch' : null);
|
||||
if ($feature !== null && !IamV2Client::feature($feature)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
}
|
||||
public static function enroll(string $token, string $method, bool $cookie = true, ?int $authTime = null): array
|
||||
{
|
||||
if (!in_array($method, ['password', 'wecom', 'oidc', 'iam_launch'], true)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (in_array($method, ['oidc', 'iam_launch'], true) && $authTime !== null && ($authTime < 0 || $authTime > time() + 60)) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $legacy['admin_id']);
|
||||
$old = (string) ($_COOKIE[self::COOKIE] ?? '');
|
||||
if ($old !== '') { self::revokeSession($old); }
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $legacy['admin_id'])->where('state', 'verified')->find();
|
||||
$sid = bin2hex(random_bytes(32));
|
||||
$row = ['session_id' => $sid, 'admin_id' => (int) $legacy['admin_id'], 'business_session_id' => $legacy['id'],
|
||||
'token_hash' => hash('sha256', $token), 'account_stamp' => self::accountStamp($admin), 'auth_method' => $method, 'auth_time' => in_array($method, ['oidc', 'iam_launch'], true) ? max(0, $authTime ?? 0) : time(),
|
||||
'version' => 1, 'revoked' => 0, 'binding_version' => (int) ($binding['version'] ?? 0), 'employee_id' => $binding['employee_id'] ?? '', 'expires_at' => min((int) $legacy['expire_time'], time() + 43200)];
|
||||
Db::name('iam_v2_source_session')->insert($row);
|
||||
if ($cookie) {
|
||||
setcookie(self::COOKIE, $sid, ['expires' => $row['expires_at'], 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
$_COOKIE[self::COOKIE] = $sid;
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
private static function accountStamp(array $admin): string
|
||||
{
|
||||
return hash('sha256', json_encode([$admin['account'], $admin['password'], $admin['work_wechat_userid'] ?? '', (int) $admin['root']], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
public static function admin(int $id): array
|
||||
{
|
||||
$a = Db::name('admin')->where('id', $id)->find();
|
||||
if (!$a || (int) $a['disable'] !== 0 || !empty($a['delete_time'])) { throw new RuntimeException('ACCOUNT_DISABLED'); }
|
||||
return $a;
|
||||
}
|
||||
public static function current(string $token, bool $recent = false): array
|
||||
{
|
||||
$s = self::check((string) ($_COOKIE[self::COOKIE] ?? ''));
|
||||
if (!hash_equals($s['token_hash'], hash('sha256', $token))) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($recent && $s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
return $s;
|
||||
}
|
||||
public static function check(string $id, ?int $version = null): array
|
||||
{
|
||||
$s = Db::name('iam_v2_source_session')->where('session_id', $id)->find();
|
||||
if (!$s || (int) $s['revoked'] !== 0 || $s['expires_at'] <= time() || ($version !== null && (int) $s['version'] !== $version)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $s['admin_id']);
|
||||
if (!hash_equals($s['account_stamp'], self::accountStamp($admin))) { self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if (!$legacy || $legacy['expire_time'] <= time() || (int) $legacy['admin_id'] !== (int) $s['admin_id'] || !hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if ((int) ($s['binding_version'] ?? 0) > 0) {
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $s['admin_id'])->find();
|
||||
if ($binding && ($binding['state'] === 'revoked' || (int) $binding['version'] > (int) $s['binding_version'] || $binding['employee_id'] !== $s['employee_id'])) {
|
||||
self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
/** Service callback: local-only live authorization, safe while central holds its state lock. */
|
||||
public static function liveStatus(string $id, int $version, string $purpose = '', array $targets = []): array
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
$s = self::check($id, $version);
|
||||
$out = ['active' => true, 'actorLocalId' => (string) $s['admin_id'], 'sessionId' => $s['session_id'], 'sessionVersion' => (int) $s['version'],
|
||||
'authMethod' => $s['auth_method'], 'authTime' => (int) $s['auth_time'], 'expiresAt' => (int) $s['expires_at']];
|
||||
if ($purpose !== 'management') { return $out + ['protectedAccount' => self::protectedAccount((int) $s['admin_id'])]; }
|
||||
if ($s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (!$targets || count($targets) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
foreach ($targets as $target) {
|
||||
if (!is_string($target) || !preg_match('/^[1-9][0-9]{0,9}$/D', $target)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
}
|
||||
$caps = self::capabilities((int) $s['admin_id']);
|
||||
if (!$caps) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::scope((int) $s['admin_id'], $targets);
|
||||
$protected = false;
|
||||
foreach ($targets as $target) { self::admin((int) $target); $protected = self::protectedAccount((int) $target) || $protected; }
|
||||
$eligible = count($targets) === 1 && self::reviewOperator((int) $s['admin_id']);
|
||||
if ($protected && !$eligible) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
return $out + ['purpose' => 'management', 'capabilities' => array_map(fn($c) => 'iam:' . $c, $caps),
|
||||
'targetLocalIds' => $targets, 'protectedAccount' => $protected, 'protectedReviewEligible' => $eligible];
|
||||
}
|
||||
public static function reauth(string $token, string $password): array
|
||||
{
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy || $password === '' || strlen($password) > 256) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$a = self::admin((int) $legacy['admin_id']);
|
||||
$limiter = new AdminAccountSafeCache();
|
||||
if (!$limiter->isSafe()) { throw new RuntimeException('RATE_LIMITED'); }
|
||||
// Deliberately does NOT invoke LoginValidate's local-debug password bypass.
|
||||
if (!hash_equals((string) $a['password'], create_password($password, Config::get('project.unique_identification')))) {
|
||||
$limiter->record(); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
$limiter->relieve(); return self::enroll($token, 'password');
|
||||
}
|
||||
public static function capabilities(int $id): array
|
||||
{
|
||||
$admin = self::admin($id);
|
||||
$all = ['read', 'bind', 'create', 'unbind', 'rebind', 'batch'];
|
||||
if ((int) $admin['root'] === 1) { return $all; }
|
||||
$perms = AuthLogic::getAuthByAdminId($id);
|
||||
return array_values(array_filter($all, fn($p) => in_array('iamV2/' . $p, $perms, true)));
|
||||
}
|
||||
public static function reviewOperator(int $id): bool
|
||||
{
|
||||
$a = self::admin($id);
|
||||
if ((int) $a['root'] === 1) { return true; }
|
||||
$roles = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return $roles && Db::name('system_role')->whereIn('id', $roles)->whereIn('name', ['管理员', '系统管理员', '超级管理员'])->whereNull('delete_time')->count() > 0;
|
||||
}
|
||||
public static function protectedAccount(int $id): bool
|
||||
{
|
||||
return self::reviewOperator($id) || count(array_intersect(self::capabilities($id), ['bind','create','unbind','rebind','batch'])) > 0;
|
||||
}
|
||||
public static function visibleIds(int $id): ?array
|
||||
{
|
||||
$a = self::admin($id);
|
||||
$a['role_id'] = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return \app\common\service\DataScope\DataScopeService::getVisibleAdminIds($id, $a);
|
||||
}
|
||||
public static function scope(int $actor, array $targets): void
|
||||
{
|
||||
$visible = self::visibleIds($actor);
|
||||
if ($visible !== null && array_diff(array_map('intval', $targets), $visible)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public static function authorize(array $session, string $capability, array $targets = [], bool $recent = true, bool $protectedReview = false): void
|
||||
{
|
||||
if (!in_array($capability, self::capabilities((int) $session['admin_id']), true)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
if ($recent && $session['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
self::scope((int) $session['admin_id'], $targets);
|
||||
foreach ($targets as $id) {
|
||||
$target = self::admin((int) $id);
|
||||
// Single-target high-privilege requests may reach central review, never bypass it.
|
||||
if (self::protectedAccount((int) $id) && !($protectedReview && count($targets) === 1 && self::reviewOperator((int) $session['admin_id']))) {
|
||||
throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
}
|
||||
}
|
||||
}
|
||||
public static function proof(array $session, string $purpose, array $targets = [], array $capabilities = [], ?string $transaction = null, array $extra = []): string
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
self::check($session['session_id'], (int) $session['version']);
|
||||
$secret = bin2hex(random_bytes(32));
|
||||
$payload = ['applicationId' => (string) Config::get('iam.application_id', 'zyt'), 'actorLocalId' => (string) $session['admin_id'],
|
||||
'sessionId' => $session['session_id'], 'sessionVersion' => (int) $session['version'], 'authMethod' => $session['auth_method'],
|
||||
'authTime' => (int) $session['auth_time'], 'expiresAt' => time() + 60, 'capabilities' => $capabilities,
|
||||
'targetLocalIds' => array_map('strval', $targets), 'protectedAccount' => count(array_filter($targets, fn($id) => self::protectedAccount((int) $id))) > 0, 'transactionId' => $transaction];
|
||||
$payload += array_intersect_key($extra, array_flip(['oidcNonce', 'state', 'protectedReviewEligible']));
|
||||
Db::name('iam_v2_proof')->insert(['proof_hash' => hash('sha256', $secret), 'purpose' => $purpose, 'session_id' => $session['session_id'],
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + 60, 'consumed' => 0]);
|
||||
return $secret;
|
||||
}
|
||||
public static function introspect(string $proof, string $purpose, ?string $transaction = null): array
|
||||
{
|
||||
self::requirePurpose($purpose);
|
||||
// The central Go attestor serializes an absent transaction as an empty string.
|
||||
$transaction = $transaction === '' ? null : $transaction;
|
||||
return Db::transaction(function () use ($proof, $purpose, $transaction) {
|
||||
$hash = hash('sha256', $proof);
|
||||
$r = Db::name('iam_v2_proof')->where('proof_hash', $hash)->lock(true)->find();
|
||||
if (!$r || $r['purpose'] !== $purpose || $r['expires_at'] <= time() || (int) $r['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['transactionId'] ?? null) !== $transaction) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$session = self::check($p['sessionId'], (int) $p['sessionVersion']);
|
||||
$p['protectedReviewEligible'] = ($p['protectedReviewEligible'] ?? false) === true
|
||||
&& count($p['targetLocalIds']) === 1 && self::reviewOperator((int) $session['admin_id']);
|
||||
foreach ($p['capabilities'] as $cap) {
|
||||
if (!str_starts_with($cap, 'iam:')) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::authorize($session, substr($cap, 4), $p['targetLocalIds'], true, ($p['protectedReviewEligible'] ?? false) === true && count($p['targetLocalIds']) === 1);
|
||||
}
|
||||
// Target protection can change during the proof's short lifetime. Recompute it.
|
||||
$p['protectedAccount'] = count(array_filter($p['targetLocalIds'], fn($id) => self::protectedAccount((int) $id))) > 0;
|
||||
if (Db::name('iam_v2_proof')->where('proof_hash', $hash)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return ['active' => true] + $p;
|
||||
});
|
||||
}
|
||||
public static function revokeSession(string $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('session_id', $id)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
public static function revokeGeneration(int $id, int $upper, ?string $employeeId = null): void
|
||||
{
|
||||
$query = Db::name('iam_v2_source_session')->where('admin_id', $id)->where('binding_version', '<=', $upper);
|
||||
if ($employeeId !== null) { $query->where(function ($q) use ($employeeId) { $q->where('employee_id', $employeeId)->whereOr('binding_version', 0); }); }
|
||||
$sessions = $query->select()->toArray();
|
||||
foreach ($sessions as $s) { self::revokeSession($s['session_id']); }
|
||||
foreach ($sessions as $s) {
|
||||
$newer = Db::name('iam_v2_source_session')->where('token_hash', $s['token_hash'])->where('revoked', 0)->where('expires_at', '>', time())->find();
|
||||
if ($newer) { continue; }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if ($legacy && hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { \app\adminapi\logic\auth\AdminLogic::expireToken($legacy['token']); }
|
||||
}
|
||||
}
|
||||
public static function revokeAdmin(int $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('admin_id', $id)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
use app\adminapi\service\iam\{IamAccountProvisioner, IamOidcClient};
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
|
||||
/** ZYT target accepts only the person's own IAM admin/portal source, never ERP. */
|
||||
final class IamV2Target
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_TARGET';
|
||||
private array $settings;
|
||||
public function __construct(private ?IamV2Client $client = null, private $resolve = null, private $login = null)
|
||||
{
|
||||
$this->settings = (array) Config::get('iam');
|
||||
if (!IamV2Client::feature('launch', $this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$this->client ??= new IamV2Client();
|
||||
$this->resolve ??= fn(array $result) => $this->resolveAdmin($result);
|
||||
$this->login ??= function (int $id, array $authentication): array {
|
||||
$admin = IamV2Source::admin($id);
|
||||
$result = (array) (new LoginLogic())->login(['account' => $admin['account'], 'terminal' => AdminTerminalEnum::PC]);
|
||||
IamV2Source::enroll($result['token'], 'iam_launch', true, self::authTime($authentication['authTime'] ?? null));
|
||||
return $result;
|
||||
};
|
||||
}
|
||||
public static function authTime($value): int
|
||||
{
|
||||
$time = is_int($value) ? $value : (is_string($value) ? strtotime($value) : false);
|
||||
if (!$time || $time < 0 || $time > time() + 60) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
return $time;
|
||||
}
|
||||
private function registered(string $source): string
|
||||
{
|
||||
$sources = $this->settings['v2_sources'] ?? [];
|
||||
if (!in_array($source, ['iam-admin', 'iam-portal'], true) || !is_array($sources) || !isset($sources[$source])) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return IamV2Client::https((string) $sources[$source]);
|
||||
}
|
||||
public static function existing(string $token, string $sourceSession = ''): ?int
|
||||
{
|
||||
$id = null;
|
||||
if ($token !== '') {
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']); $id = (int) $legacy['admin_id'];
|
||||
}
|
||||
if ($sourceSession !== '') {
|
||||
try { $session = IamV2Source::check($sourceSession); } catch (RuntimeException $e) { $session = null; }
|
||||
if ($session) {
|
||||
if ($id !== null && $id !== (int) $session['admin_id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) $session['admin_id'];
|
||||
}
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
public function prepare(string $source, string $intent, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$registered = $this->registered($source);
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $intent)) { throw new RuntimeException('INVALID_REQUEST'); }
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
$browser = bin2hex(random_bytes(32)); $state = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
$tx = $this->client->call('POST', '/launch-transactions', ['sourceApplicationId' => $source, 'stateHash' => hash('sha256', $state),
|
||||
'codeChallenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=')]);
|
||||
$id = $tx['transactionId'] ?? '';
|
||||
if (!is_string($id) || !preg_match('/^[A-Za-z0-9_-]{1,128}$/D', $id)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$actual = parse_url((string) ($tx['sourceContinueUrl'] ?? '')); $fixed = parse_url($registered);
|
||||
if (!$actual || ($actual['scheme'] ?? '') !== $fixed['scheme'] || ($actual['host'] ?? '') !== $fixed['host']
|
||||
|| ($actual['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($actual['path'] ?? '') !== ($fixed['path'] ?? '')
|
||||
|| isset($actual['user']) || isset($actual['pass']) || isset($actual['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($actual['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['transaction_id'] ?? null) !== $id) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
IamV2Flow::put('target_launch', $id, ['sessionId' => hash('sha256', $browser), 'source' => $source, 'verifier' => $verifier,
|
||||
'stateHash' => hash('sha256', $state), 'expectedAdminId' => $existing]);
|
||||
return ['url' => $registered . '?' . http_build_query(['transaction_id' => $id, 'intent' => $intent], '', '&', PHP_QUERY_RFC3986), 'browser' => $browser];
|
||||
}
|
||||
public function callback(string $transaction, string $grant, string $browser, string $origin): array
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/D', $browser) || !preg_match('/^[A-Za-z0-9_-]{43}$/D', $grant)) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$flow = IamV2Flow::peek('target_launch', $transaction, hash('sha256', $browser));
|
||||
$source = parse_url($this->registered($flow['source']));
|
||||
$expectedOrigin = $source['scheme'] . '://' . $source['host'] . (isset($source['port']) ? ':' . $source['port'] : '');
|
||||
if ($origin !== $expectedOrigin) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
IamV2Flow::take('target_launch', $transaction, hash('sha256', $browser));
|
||||
$result = $this->client->call('POST', '/launch-grants/exchange', ['transactionId' => $transaction, 'grant' => $grant, 'codeVerifier' => $flow['verifier']]);
|
||||
$employee = $result['employee'] ?? []; $auth = $result['authentication'] ?? [];
|
||||
if (($employee['status'] ?? '') !== 'active' || !is_string($employee['oidcSubject'] ?? null) || $employee['oidcSubject'] === ''
|
||||
|| empty($employee['id']) || !($result['access']['allowed'] ?? false) || ($auth['sourceApplicationId'] ?? '') !== $flow['source']
|
||||
|| empty($auth['sessionId']) || !is_string($auth['authMethod'] ?? null) || $auth['authMethod'] === '' || !is_int($auth['sessionVersion'] ?? null) || $auth['sessionVersion'] < 1) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
self::authTime($auth['authTime'] ?? null);
|
||||
if ($flow['expectedAdminId'] !== null && (string) ($result['binding']['externalAccountId'] ?? '') !== (string) $flow['expectedAdminId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) ($this->resolve)($result);
|
||||
if ($id < 1 || ($flow['expectedAdminId'] !== null && $id !== (int) $flow['expectedAdminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
IamV2Source::admin($id);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $employee['oidcSubject']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('target_ticket', $ticket, ['sessionId' => hash('sha256', $browser), 'adminId' => $id, 'expectedAdminId' => $flow['expectedAdminId'],
|
||||
'employeeId' => $employee['id'], 'bindingVersion' => (int) $current['binding']['version'], 'source' => $flow['source'], 'authentication' => $auth], 60);
|
||||
return ['ticket' => $ticket, 'source' => $flow['source']];
|
||||
}
|
||||
private function resolveAdmin(array $result): int
|
||||
{
|
||||
$employee = $result['employee']; $subject = $employee['oidcSubject'];
|
||||
$client = new IamOidcClient($this->settings); $context = $client->provisioning($subject);
|
||||
if (($context['employee']['id'] ?? '') !== $employee['id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$binding = $result['binding'] ?? null;
|
||||
if ($binding && (($binding['applicationId'] ?? '') !== 'zyt' || ($binding['state'] ?? '') !== 'verified'
|
||||
|| (string) ($context['externalAccountId'] ?? '') !== (string) $binding['externalAccountId']
|
||||
|| (int) ($context['bindingVersion'] ?? 0) !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if (!$binding && ($context['externalAccountId'] ?? '') !== '') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$id = (new IamAccountProvisioner())->resolve($client, $this->settings, $subject);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $subject
|
||||
|| ($binding && (int) $current['binding']['version'] !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
return $id;
|
||||
}
|
||||
public function exchange(string $ticket, string $browser, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$flow = IamV2Flow::peek('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
if (($flow['expectedAdminId'] !== null && $existing !== (int) $flow['expectedAdminId']) || ($existing !== null && $existing !== (int) $flow['adminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$current = (new IamV2Manager($this->client))->assertLinked((int) $flow['adminId']);
|
||||
if (($current['employee']['id'] ?? '') !== $flow['employeeId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ((int) $current['binding']['version'] !== (int) $flow['bindingVersion']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Flow::take('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$result = ($this->login)((int) $flow['adminId'], $flow['authentication']);
|
||||
$hash = hash('sha256', $result['token']);
|
||||
$values = ['token_hash' => $hash, 'admin_id' => (int) $flow['adminId'], 'employee_id' => $flow['employeeId'],
|
||||
'source_application_id' => $flow['source'], 'source_binding_version' => (int) ($flow['authentication']['sourceBindingVersion'] ?? 0), 'checked_at' => time()];
|
||||
$old = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if ($old) { Db::name('iam_v2_target_session')->where('token_hash', $hash)->update($values); }
|
||||
else { Db::name('iam_v2_target_session')->insert($values); }
|
||||
return $result;
|
||||
}
|
||||
public static function compensate(string $token): void
|
||||
{
|
||||
$hash = hash('sha256', $token); $row = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if (!$row || $row['checked_at'] > time() - 30) { return; }
|
||||
$query = http_build_query(['employeeId' => $row['employee_id'], 'sourceApplicationId' => $row['source_application_id'],
|
||||
'sourceBindingVersion' => (int) $row['source_binding_version']], '', '&', PHP_QUERY_RFC3986);
|
||||
$check = (new IamV2Client())->call('GET', '/launch-authorizations/check?' . $query);
|
||||
if (!($check['allowed'] ?? false)) {
|
||||
Db::name('iam_v2_source_session')->where('token_hash', $hash)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
AdminLogic::expireToken($token); throw new RuntimeException('NOT_AUTHORIZED');
|
||||
}
|
||||
Db::name('iam_v2_target_session')->where('token_hash', $hash)->update(['checked_at' => time()]);
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,6 @@
|
||||
|
||||
// Optional integration: disabled installations never touch IAM or its transaction store.
|
||||
return [
|
||||
'v2_sources' => json_decode((string) env('iam.v2_sources_json', '{}'), true) ?: [],
|
||||
'v2_management_enabled' => env('iam.v2_management_enabled', false),
|
||||
'v2_launch_enabled' => env('iam.v2_launch_enabled', false),
|
||||
'v2_enabled' => env('iam.v2_enabled', false),
|
||||
'v2_management_token' => env('iam.v2_management_token', ''),
|
||||
'v2_token' => env('iam.v2_token', ''),
|
||||
'v2_introspection_token' => env('iam.v2_introspection_token', ''),
|
||||
'v2_event_secret' => env('iam.v2_event_secret', ''),
|
||||
'erp_callback_url' => env('iam.erp_callback_url', ''),
|
||||
'erp_url' => env('iam.erp_url', ''),
|
||||
'portal_url' => env('iam.portal_url', ''),
|
||||
'enabled' => env('iam.enabled', false),
|
||||
'issuer' => env('iam.issuer', ''),
|
||||
'client_id' => env('iam.client_id', 'zyt'),
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
-- Additive only. Preserve all seven tables and the legacy iam_local_identity ledger on rollback.
|
||||
-- Apply with configured table prefix (default zyt_). No existing roles/accounts are changed.
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_source_session (
|
||||
session_id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
admin_id INT UNSIGNED NOT NULL, business_session_id INT UNSIGNED NOT NULL,
|
||||
token_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
account_stamp CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
auth_method VARCHAR(16) NOT NULL, auth_time INT UNSIGNED NOT NULL,
|
||||
version INT UNSIGNED NOT NULL DEFAULT 1, revoked TINYINT NOT NULL DEFAULT 0,
|
||||
binding_version BIGINT UNSIGNED NOT NULL DEFAULT 0, employee_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
expires_at INT UNSIGNED NOT NULL, INDEX idx_admin (admin_id), INDEX idx_expiry (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_proof (
|
||||
proof_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
purpose VARCHAR(32) NOT NULL, session_id CHAR(64) NOT NULL, payload TEXT NOT NULL,
|
||||
expires_at INT UNSIGNED NOT NULL, consumed TINYINT NOT NULL DEFAULT 0, INDEX idx_expiry(expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_binding (
|
||||
admin_id INT UNSIGNED PRIMARY KEY, employee_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
subject VARCHAR(255) NOT NULL DEFAULT '', state VARCHAR(32) NOT NULL,
|
||||
version BIGINT UNSIGNED NOT NULL DEFAULT 0, payload MEDIUMTEXT NOT NULL,
|
||||
checked_at INT UNSIGNED NOT NULL DEFAULT 0, INDEX idx_employee(employee_id), INDEX idx_subject(subject)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_resource (
|
||||
resource_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
kind VARCHAR(32) NOT NULL, external_id VARCHAR(128) NOT NULL, actor_id INT UNSIGNED NOT NULL,
|
||||
payload MEDIUMTEXT NOT NULL, created_at INT UNSIGNED NOT NULL, INDEX idx_actor(actor_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_flow (
|
||||
flow_key CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
kind VARCHAR(32) NOT NULL, payload TEXT NOT NULL, expires_at INT UNSIGNED NOT NULL,
|
||||
consumed TINYINT NOT NULL DEFAULT 0, INDEX idx_expiry(expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_event (
|
||||
event_id VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY, digest CHAR(64) NOT NULL, received_at INT UNSIGNED NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS zyt_iam_v2_target_session (
|
||||
token_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
admin_id INT UNSIGNED NOT NULL, employee_id VARCHAR(128) NOT NULL,
|
||||
source_application_id VARCHAR(64) NOT NULL, source_binding_version BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
checked_at INT UNSIGNED NOT NULL DEFAULT 0, INDEX idx_admin(admin_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
START TRANSACTION;
|
||||
SET @iam_parent := (SELECT pid FROM zyt_system_menu WHERE component='permission/admin/index' LIMIT 1);
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT COALESCE(@iam_parent,0),'C','IAM关联管理','el-icon-Connection',85,'iamV2/read','identity-management','permission/identity/index','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/read');
|
||||
SET @iam_menu := (SELECT id FROM zyt_system_menu WHERE perms='iamV2/read' LIMIT 1);
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','绑定IAM','',0,'iamV2/bind','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/bind');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','创建并关联IAM','',0,'iamV2/create','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/create');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','解除IAM关联','',0,'iamV2/unbind','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/unbind');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','更换IAM关联','',0,'iamV2/rebind','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/rebind');
|
||||
INSERT INTO zyt_system_menu (pid,type,name,icon,sort,perms,paths,component,selected,params,is_cache,is_show,is_disable,create_time,update_time)
|
||||
SELECT @iam_menu,'A','批量IAM任务','',0,'iamV2/batch','','','','',0,1,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms='iamV2/batch');
|
||||
COMMIT;
|
||||
-- Deliberately no system_role_menu grants: assign capabilities explicitly after review.
|
||||
@@ -1,37 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
function requireContract(bool $condition, string $message): void { if (!$condition) { throw new RuntimeException($message); } }
|
||||
$root = dirname(__DIR__);
|
||||
$routes = file_get_contents($root . '/app/adminapi/route/app.php');
|
||||
$controller = file_get_contents($root . '/app/adminapi/controller/IamV2Controller.php');
|
||||
$source = file_get_contents($root . '/app/adminapi/service/iam/v2/IamV2Source.php');
|
||||
$client = file_get_contents($root . '/app/adminapi/service/iam/v2/IamV2Client.php');
|
||||
$config = file_get_contents($root . '/config/iam.php');
|
||||
foreach (['proofs/introspect','sessions/check','events/revocation','operations','batch/preflight','batch','launch/start','self-link/start','password-setup','launch/prepare','launch/callback','launch/exchange','launch/reset'] as $route) {
|
||||
requireContract(str_contains($routes,"Route::post('iam/v2/".$route."'"), 'POST registration ' . $route);
|
||||
}
|
||||
requireContract(str_contains($controller, "METHOD_NOT_ALLOWED"), 'default auto-route verbs checked');
|
||||
requireContract(str_contains($controller,"hash_equals('Bearer ' . \$expected"), 'source service secret constant-time');
|
||||
requireContract(str_contains($controller,'INVALID_ORIGIN'), 'browser mutation origin');
|
||||
requireContract(str_contains($source,"self::check(\$p['sessionId']"), 'proof checks live session');
|
||||
requireContract(str_contains($source,"self::authorize(\$session, substr(\$cap, 4)"), 'proof rechecks live permission');
|
||||
requireContract(str_contains($source,"self::scope((int) \$session['admin_id'], \$targets)"), 'target data scope');
|
||||
requireContract(str_contains($client,'CURLOPT_FOLLOWLOCATION => false') && str_contains($client,'CURLOPT_SSL_VERIFYPEER => true'), 'TLS fixed host no redirect');
|
||||
requireContract(str_contains($config,"'v2_enabled' => env('iam.v2_enabled', false)") && str_contains($config,"'v2_management_enabled' => env('iam.v2_management_enabled', false)") && str_contains($config,"'v2_launch_enabled' => env('iam.v2_launch_enabled', false)"), 'global and new-flow gates default OFF');
|
||||
requireContract(!str_contains($controller,"'token' =>"), 'no business token callback');
|
||||
requireContract(str_contains($controller,"verifiedIdToken()") && str_contains($controller,"'oidcNonce' =>"), 'self-link independently verifiable OIDC token and nonce');
|
||||
requireContract(!str_contains($controller,"request->post('employeeId'"), 'no browser chosen personal employee');
|
||||
$callback = substr($controller, strpos($controller, 'public function checkSession()'), strpos($controller, 'public function launchStart()') - strpos($controller, 'public function checkSession()'));
|
||||
requireContract(str_contains($callback, 'IamV2Source::liveStatus') && str_contains($source, "'sessionId' => \$s['session_id']") && str_contains($source, "'sessionVersion' => (int) \$s['version']"), 'live callback echoes actual SID/version');
|
||||
requireContract(!str_contains($callback, 'IamV2Manager') && !str_contains($callback, 'IamV2Client'), 'source callback never recursively calls central under state lock');
|
||||
$login = file_get_contents($root . '/app/adminapi/service/iam/IamLoginService.php');
|
||||
requireContract(strpos($login, '->assertLinked(') < strpos($login, '$result = (array) (new LoginLogic())->login'), 'binding sync precedes new token issuance');
|
||||
$provisioner = file_get_contents($root . '/app/adminapi/service/iam/IamAccountProvisioner.php');
|
||||
requireContract(strpos($provisioner, 'return IamLoginService::boundAdminId') < strpos($provisioner, 'IAM_BINDING_REVOKED'), 'explicit central binding precedes local auto-create tombstone');
|
||||
requireContract(str_contains($controller, "\$this->fail(\$code, ['error' => ['code' => \$code]], 0, 0)"), 'IAM structured errors suppress shared toast without changing other interfaces');
|
||||
foreach (['launchContinue' => 'private function selfConfig', 'passwordContinue' => 'private function targetOrigin'] as $method => $next) {
|
||||
$section = substr($controller, strpos($controller, 'public function ' . $method), strpos($controller, $next) - strpos($controller, 'public function ' . $method));
|
||||
requireContract(str_contains($section, 'IamV2Flow::form(') && str_contains($section, "'Referrer-Policy' => 'strict-origin'"), 'cross-origin source form must retain non-null Origin: ' . $method);
|
||||
}
|
||||
requireContract(str_contains(file_get_contents($root . '/app/adminapi/service/iam/v2/IamV2Target.php'), "if (\$origin !== \$expectedOrigin)"), 'target Origin matching stays strict');
|
||||
echo "PASS IamV2RouteContractTest: fixed POST callbacks, auto-route method gate, origin/service authentication, live proof authorization, target scope, dedicated TLS client, default-off, personal OIDC proof\n";
|
||||
@@ -1,203 +0,0 @@
|
||||
<?php
|
||||
/** Disposable SQLite only: no .env, provider calls or real identities. */
|
||||
declare(strict_types=1);
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
require dirname(__DIR__) . '/app/common.php';
|
||||
use think\facade\Db;
|
||||
use app\adminapi\service\iam\v2\{IamV2Source, IamV2Flow, IamV2Client, IamV2Manager, IamV2Events};
|
||||
function ok(bool $x, string $m): void { if (!$x) { throw new RuntimeException('FAIL ' . $m); } }
|
||||
function denies(callable $fn, string $message): void { try { $fn(); } catch (RuntimeException $e) { ok($e->getMessage() === $message, $message . ' got ' . $e->getMessage()); return; } throw new RuntimeException('accepted ' . $message); }
|
||||
$app = new think\App(dirname(__DIR__) . '/'); think\Container::setInstance($app);
|
||||
$file = tempnam(sys_get_temp_dir(), 'zyt-iamv2-');
|
||||
$cachePath = $file . '-cache/';
|
||||
$app->config->set(['default'=>'file','stores'=>['file'=>['type'=>'File','path'=>$cachePath]]], 'cache');
|
||||
$app->config->set(['default'=>'fixture','connections'=>['fixture'=>['type'=>'sqlite','database'=>$file,'prefix'=>'','fields_strict'=>true]]], 'database');
|
||||
$manager = new think\DbManager(); $manager->setConfig($app->config->get('database')); $app->instance('think\Db', $manager);
|
||||
$app->config->set(['data_scope'=>['enabled'=>false], 'unique_identification'=>'fixture'], 'project');
|
||||
$app->config->set(['application_id'=>'zyt','portal_url'=>'https://iam.example.test','v2_enabled'=>true,'v2_management_enabled'=>true,'v2_launch_enabled'=>true,'v2_introspection_token'=>str_repeat('c',32)], 'iam');
|
||||
try {
|
||||
foreach ([
|
||||
'CREATE TABLE admin (id INTEGER PRIMARY KEY,account TEXT,name TEXT,password TEXT,disable INTEGER,root INTEGER,multipoint_login INTEGER DEFAULT 1,delete_time INTEGER)',
|
||||
'CREATE TABLE admin_session (id INTEGER PRIMARY KEY,admin_id INTEGER,terminal INTEGER,token TEXT,expire_time INTEGER,update_time INTEGER)',
|
||||
'CREATE TABLE dept (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER)',
|
||||
'CREATE TABLE admin_dept (admin_id INTEGER,dept_id INTEGER)',
|
||||
'CREATE TABLE admin_role (admin_id INTEGER,role_id INTEGER)',
|
||||
'CREATE TABLE system_role (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER)',
|
||||
'CREATE TABLE system_role_menu (role_id INTEGER,menu_id INTEGER)',
|
||||
'CREATE TABLE system_menu (id INTEGER PRIMARY KEY,is_disable INTEGER,perms TEXT)',
|
||||
'CREATE TABLE iam_v2_source_session (session_id TEXT PRIMARY KEY,admin_id INTEGER,business_session_id INTEGER,token_hash TEXT,account_stamp TEXT,auth_method TEXT,auth_time INTEGER,version INTEGER,revoked INTEGER,binding_version INTEGER,employee_id TEXT,expires_at INTEGER)',
|
||||
'CREATE TABLE iam_v2_proof (proof_hash TEXT PRIMARY KEY,purpose TEXT,session_id TEXT,payload TEXT,expires_at INTEGER,consumed INTEGER)',
|
||||
'CREATE TABLE iam_v2_flow (flow_key TEXT PRIMARY KEY,kind TEXT,payload TEXT,expires_at INTEGER,consumed INTEGER)',
|
||||
'CREATE TABLE iam_v2_binding (admin_id INTEGER PRIMARY KEY,employee_id TEXT,subject TEXT,state TEXT,version INTEGER,payload TEXT,checked_at INTEGER)',
|
||||
'CREATE TABLE iam_v2_event (event_id TEXT PRIMARY KEY, digest TEXT, received_at INTEGER)',
|
||||
'CREATE TABLE iam_v2_resource (resource_key TEXT PRIMARY KEY,kind TEXT,external_id TEXT,actor_id INTEGER,payload TEXT,created_at INTEGER)',
|
||||
] as $sql) { Db::execute($sql); }
|
||||
Db::name('admin')->insertAll([['id'=>1,'account'=>'operator','name'=>'Synthetic Operator','password'=>'not-real','disable'=>0,'root'=>1],['id'=>2,'account'=>'employee','name'=>'Synthetic Employee','password'=>'not-real','disable'=>0,'root'=>0]]);
|
||||
Db::name('admin_session')->insertAll([['id'=>1,'admin_id'=>1,'terminal'=>1,'token'=>'fixture-token-1','expire_time'=>time()+3600],['id'=>2,'admin_id'=>2,'terminal'=>1,'token'=>'fixture-token-2','expire_time'=>time()+3600]]);
|
||||
denies(fn()=>IamV2Source::current('fixture-token-1'),'REAUTH_REQUIRED');
|
||||
$s1=IamV2Source::enroll('fixture-token-1','password',false); $s2=IamV2Source::enroll('fixture-token-1','password',false);
|
||||
ok($s1['session_id']!==$s2['session_id'],'independent browser sessions despite same business token');
|
||||
$_COOKIE[IamV2Source::COOKIE]=$s1['session_id'];
|
||||
ok(IamV2Source::current('fixture-token-1')['auth_method']==='password','immutable method');
|
||||
denies(fn()=>IamV2Source::current('fixture-token-2'),'ACCOUNT_MISMATCH');
|
||||
denies(fn()=>IamV2Source::enroll('fixture-token-1','legacy',false),'REAUTH_REQUIRED');
|
||||
IamV2Source::authorize($s1,'bind',[2]);
|
||||
denies(fn()=>IamV2Source::authorize($s1,'bind',[1]),'PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
$proof=IamV2Source::proof($s1,'launch',[1],[],'tx-fixture');
|
||||
ok(!str_contains(json_encode(Db::name('iam_v2_proof')->select()->toArray()),$proof),'proof plaintext never stored');
|
||||
denies(fn()=>IamV2Source::introspect($proof,'management','tx-fixture'),'TRANSACTION_EXPIRED');
|
||||
denies(fn()=>IamV2Source::introspect($proof,'launch','other'),'ACCOUNT_MISMATCH');
|
||||
$claims=IamV2Source::introspect($proof,'launch','tx-fixture');
|
||||
ok($claims['active'] && $claims['actorLocalId']==='1' && !isset($claims['token']),'service claims no business token');
|
||||
denies(fn()=>IamV2Source::introspect($proof,'launch','tx-fixture'),'TRANSACTION_EXPIRED');
|
||||
IamV2Flow::put('launch','intent',['sessionId'=>$s1['session_id']]);
|
||||
denies(fn()=>IamV2Flow::take('launch','intent',$s2['session_id']),'ACCOUNT_MISMATCH');
|
||||
IamV2Flow::take('launch','intent',$s1['session_id']); denies(fn()=>IamV2Flow::take('launch','intent',$s1['session_id']),'TRANSACTION_EXPIRED');
|
||||
$expired=IamV2Source::proof($s1,'launch'); Db::name('iam_v2_proof')->where('proof_hash',hash('sha256',$expired))->update(['expires_at'=>time()-1]);
|
||||
denies(fn()=>IamV2Source::introspect($expired,'launch'),'TRANSACTION_EXPIRED');
|
||||
$oldAuth=$s1['auth_time']; Db::name('admin_session')->where('id',1)->update(['update_time'=>time()+30,'expire_time'=>time()+7200]);
|
||||
ok(IamV2Source::check($s1['session_id'])['auth_time']===$oldAuth,'business renewal never freshens authentication');
|
||||
Db::name('admin')->where('id',1)->update(['disable'=>1]); denies(fn()=>IamV2Source::check($s1['session_id']),'ACCOUNT_DISABLED'); Db::name('admin')->where('id',1)->update(['disable'=>0]);
|
||||
Db::name('admin_session')->where('id',1)->update(['token'=>'rotated']); denies(fn()=>IamV2Source::check($s1['session_id']),'REAUTH_REQUIRED'); Db::name('admin_session')->where('id',1)->update(['token'=>'fixture-token-1']);
|
||||
IamV2Source::revokeSession($s1['session_id']); denies(fn()=>IamV2Source::check($s1['session_id']),'REAUTH_REQUIRED'); ok(IamV2Source::check($s2['session_id'])['revoked']===0,'revoking one browser preserves other independent session');
|
||||
$calls=[];$cfg=['v2_enabled'=>true,'v2_management_enabled'=>true,'v2_launch_enabled'=>true,'api_url'=>'https://iam.example.test/api','public_url'=>'https://zyt.example.test','erp_url'=>'https://erp.example.test','v2_token'=>str_repeat('v',32),'v2_management_token'=>str_repeat('m',32),'application_id'=>'zyt'];
|
||||
$client=new IamV2Client($cfg,function($method,$url,$headers,$body)use(&$calls){$calls[]=compact('method','url','headers','body');return ['status'=>200,'body'=>json_encode(['binding'=>null,'employee'=>null,'access'=>['allowed'=>false]])];});
|
||||
$service=new IamV2Manager($client);$service->binding(2);$service->binding(2);ok(count($calls)===1,'30 second read cache');
|
||||
Db::name('iam_v2_binding')->where('admin_id',2)->update(['checked_at'=>time()-31]);$service->binding(2);ok(count($calls)===2,'missed revocation compensation after 30 seconds');
|
||||
Db::name('dept')->insertAll([['id'=>10,'name'=>'Synthetic A','delete_time'=>null],['id'=>20,'name'=>'Synthetic B','delete_time'=>null],['id'=>30,'name'=>'Deleted Department','delete_time'=>time()]]);
|
||||
Db::name('admin_dept')->insertAll([['admin_id'=>1,'dept_id'=>10],['admin_id'=>1,'dept_id'=>20],['admin_id'=>1,'dept_id'=>30],['admin_id'=>2,'dept_id'=>20]]);
|
||||
$checkedAt=time()-5;Db::name('iam_v2_binding')->where('admin_id',2)->update(['checked_at'=>$checkedAt]);
|
||||
$listing=$service->accounts(['q'=>'employee'],1);ok(count($listing['items'])===1 && $listing['items'][0]['dept_names']===['Synthetic B'],'department labels for scoped account');
|
||||
ok($listing['items'][0]['iam']['checked_at']===$checkedAt,'cached successful check time is returned unchanged');
|
||||
$all=$service->accounts([],1);$byId=[];foreach($all['items']as$item)$byId[$item['id']]=$item;
|
||||
ok($byId[1]['dept_names']===['Synthetic A','Synthetic B'],'soft-deleted department is not displayed');
|
||||
$project=$app->config->get('project');$scoped=$project;$scoped['data_scope']['enabled']=true;$app->config->set($scoped,'project');
|
||||
$self=$service->accounts([],2);ok(count($self['items'])===1 && (int)$self['items'][0]['id']===2,'metadata does not widen existing data scope');$app->config->set($project,'project');
|
||||
$lastSuccess=time()-100;Db::name('iam_v2_binding')->where('admin_id',2)->update(['checked_at'=>$lastSuccess]);
|
||||
$offline=new IamV2Manager(new IamV2Client($cfg,fn()=>['status'=>503,'body'=>json_encode(['error'=>['code'=>'SERVICE_UNAVAILABLE']])]));
|
||||
$unknown=$offline->accounts(['q'=>'employee'],1)['items'][0]['iam'];
|
||||
ok($unknown['state']==='unknown' && $unknown['access']['allowed']===null && $unknown['checked_at']===$lastSuccess,'failed refresh never fabricates allowed access or successful timestamp');
|
||||
ok((int)Db::name('iam_v2_binding')->where('admin_id',2)->value('checked_at')===$lastSuccess,'failure preserves actual persisted check time');
|
||||
$invokeCallback=function($action,$body,$bearer=null,$method='POST')use($app){
|
||||
$request=(new think\Request())->withHeader(['authorization'=>$bearer??('Bearer '.str_repeat('c',32))])->withPost($body);
|
||||
$request->setMethod($method);$request->setAction($action);$request->setController('IamV2');$app->instance('request',$request);
|
||||
return (new app\adminapi\controller\IamV2Controller($app))->{$action}();
|
||||
};
|
||||
$request=(new think\Request())->withPost([]);$request->setMethod('POST');$request->setAction('launchStart');$app->instance('request',$request);
|
||||
$controller=new app\adminapi\controller\IamV2Controller($app);$method=new ReflectionMethod($controller,'invokeV2');$method->setAccessible(true);
|
||||
$response=$method->invoke($controller,static function(){throw new RuntimeException('NOT_LINKED');});$envelope=$response->getData();
|
||||
ok($envelope['code']===0 && $envelope['show']===0 && $envelope['data']['error']['code']==='NOT_LINKED','IAM structured failure silences only the global toast');
|
||||
$live=$invokeCallback('checkSession',['sessionId'=>$s2['session_id'],'sessionVersion'=>1]);$liveBody=$live->getData();
|
||||
ok($live->getCode()===200 && $liveBody['active'] && $liveBody['sessionId']===$s2['session_id'] && $liveBody['sessionVersion']===1,'actual source callback raw HTTP shape/SID/version');
|
||||
ok(!isset($liveBody['code']) && !isset($liveBody['data']),'callback is not business response envelope');
|
||||
$managed=$invokeCallback('checkSession',['sessionId'=>$s2['session_id'],'sessionVersion'=>1,'purpose'=>'management','targetLocalIds'=>['2']]);
|
||||
ok($managed->getData()['targetLocalIds']===['2'] && in_array('iam:bind',$managed->getData()['capabilities'],true),'live callback returns current management capabilities and scope');
|
||||
$invalid=$invokeCallback('checkSession',['sessionId'=>$s2['session_id'],'sessionVersion'=>1],'Bearer wrong');ok($invalid->getCode()===403 && !$invalid->getData()['active'],'callback dedicated credential required');
|
||||
$wireHTTP=IamV2Source::proof($s2,'management',[2],['iam:bind']);
|
||||
$actual=$invokeCallback('introspect',['proof'=>$wireHTTP,'purpose'=>'management','transactionId'=>'']);ok($actual->getCode()===200 && $actual->getData()['active'],'Go HTTP attestor body reaches actual controller');
|
||||
$replay=$invokeCallback('introspect',['proof'=>$wireHTTP,'purpose'=>'management','transactionId'=>'']);ok($replay->getCode()===403,'actual callback replay fails');
|
||||
$wire=IamV2Source::proof($s2,'management',[2],['iam:bind']);
|
||||
ok(IamV2Source::introspect($wire,'management','')['active'],'Go callback empty transactionId matches absent transaction');
|
||||
ok(IamV2Manager::cap('reconcile')==='bind','central reconcile capability contract');
|
||||
$normalSession=IamV2Source::enroll('fixture-token-2','password',false);
|
||||
$binding=['binding'=>['applicationId'=>'zyt','employeeId'=>'employee-fixture','state'=>'verified','version'=>2,'externalAccountId'=>'2'],'employee'=>['id'=>'employee-fixture','status'=>'active','oidcSubject'=>'subject-fixture'],'access'=>['allowed'=>true]];
|
||||
$firstLinkService=new IamV2Manager(new IamV2Client($cfg,fn()=>['status'=>200,'body'=>json_encode($binding)]));
|
||||
$firstLinkService->binding(2,true);
|
||||
ok(IamV2Source::check($normalSession['session_id'])['revoked']===0,'first association preserves authenticated local session');
|
||||
Db::name('iam_v2_binding')->where('admin_id',2)->update(['employee_id'=>'employee-fixture','state'=>'verified','version'=>2,'payload'=>json_encode($binding)]);
|
||||
$secret=str_repeat('e',32);$revoked=[];
|
||||
$event=['eventType'=>'binding_revoked','id'=>'evt-fixture','employeeId'=>'employee-fixture','applicationIds'=>['zyt'],'reason'=>'revoked','occurredAt'=>gmdate('Y-m-d\TH:i:s\Z'),'bindingVersion'=>1];
|
||||
$raw=json_encode($event);$sig='sha256='.hash_hmac('sha256',$raw,$secret);
|
||||
denies(fn()=>IamV2Events::accept($raw,'invalid','evt-fixture',$secret),'FORBIDDEN');
|
||||
denies(fn()=>IamV2Events::accept($raw,$sig,'another-event',$secret),'INVALID_EVENT');
|
||||
$revoke=function($id)use(&$revoked){$revoked[]=$id;};
|
||||
IamV2Events::accept($raw,$sig,'evt-fixture',$secret,$revoke,null,null,fn($id,$version)=>null);ok($revoked===[],'older event cannot revoke newer binding');
|
||||
ok(IamV2Events::accept($raw,$sig,'evt-fixture',$secret,$revoke)['duplicate'],'signed event idempotence');
|
||||
$event['id']='evt-new';$event['bindingVersion']=3;$raw=json_encode($event);$sig='sha256='.hash_hmac('sha256',$raw,$secret);
|
||||
IamV2Events::accept($raw,$sig,'evt-new',$secret,$revoke);ok($revoked===[2],'valid event revokes exact identity');
|
||||
$event['reason']='changed';$other=json_encode($event);denies(fn()=>IamV2Events::accept($other,'sha256='.hash_hmac('sha256',$other,$secret),'evt-new',$secret,$revoke),'INVALID_EVENT');
|
||||
$event['id']='future';$event['occurredAt']=gmdate('Y-m-d\TH:i:s\Z',time()+120);$future=json_encode($event);denies(fn()=>IamV2Events::accept($future,'sha256='.hash_hmac('sha256',$future,$secret),'future',$secret,$revoke),'TRANSACTION_EXPIRED');
|
||||
$binding['binding']['version']=3;
|
||||
$stale=new IamV2Manager(new IamV2Client($cfg,fn()=>['status'=>200,'body'=>json_encode($binding)]));
|
||||
denies(fn()=>$stale->binding(2,true),'BINDING_CONFLICT');
|
||||
Db::name('iam_v2_binding')->where('admin_id',2)->update(['state'=>'verified','version'=>3]);
|
||||
$statusEvent=['id'=>'evt-disabled','employeeId'=>'employee-fixture','applicationIds'=>['zyt'],'reason'=>'employee.disabled','occurredAt'=>gmdate('Y-m-d\TH:i:s\Z')];
|
||||
$statusRaw=json_encode($statusEvent);IamV2Events::accept($statusRaw,'sha256='.hash_hmac('sha256',$statusRaw,$secret),'evt-disabled',$secret,$revoke,fn()=>['binding'=>['state'=>'verified'],'employee'=>['status'=>'disabled'],'access'=>['allowed'=>false]]);
|
||||
ok(Db::name('iam_v2_binding')->where('admin_id',2)->value('state')==='verified','personnel/access revoke never creates permanent binding tombstone');
|
||||
$stale->binding(2,true); // restored access at same binding version is recoverable.
|
||||
$late=$statusEvent;$late['id']='evt-delayed';$late['occurredAt']=gmdate('Y-m-d\TH:i:s\Z',time()-86400);$lateRaw=json_encode($late);$revocationsBefore=count($revoked);
|
||||
IamV2Events::accept($lateRaw,'sha256='.hash_hmac('sha256',$lateRaw,$secret),'evt-delayed',$secret,$revoke,fn()=>['binding'=>['state'=>'verified'],'employee'=>['status'=>'active'],'access'=>['allowed'=>true]]);
|
||||
ok(count($revoked)===$revocationsBefore,'old durable generic event accepted without revoking reauthorized sessions');
|
||||
|
||||
$beforeUsers=Db::name('admin')->select()->toArray();$batchCalls=[];
|
||||
$batchClient=new IamV2Client($cfg,function($method,$url,$headers,$body)use(&$batchCalls){
|
||||
$data=json_decode($body,true);$batchCalls[]=$data;
|
||||
$claims=IamV2Source::introspect($data['proof'],'management');
|
||||
ok($claims['targetLocalIds']===['2'],'only authorized safe target in central proof');
|
||||
ok(in_array('iam:bind',$claims['capabilities'],true),'explicit binding capability');
|
||||
if(str_ends_with($url,'/batch/preflight'))return ['status'=>200,'body'=>json_encode(['previewId'=>'preview-fixture','items'=>[['index'=>0,'externalAccountId'=>'2','status'=>'ready']],'expiresAt'=>time()+300])];
|
||||
ok($data['indexes']===[0],'original selected index mapped to central filtered index');
|
||||
return ['status'=>200,'body'=>json_encode(['id'=>'job-fixture','status'=>'pending','items'=>[]])];
|
||||
});
|
||||
$batchService=new IamV2Manager($batchClient);
|
||||
$preview=$batchService->preflight($s2,[['kind'=>'bind','user_id'=>1,'employee_id'=>'protected','reason'=>'fixture'],['kind'=>'bind','user_id'=>2,'employee_id'=>'normal','reason'=>'fixture']]);
|
||||
ok($preview['items'][0]['status']==='review' && $preview['items'][1]['index']===1,'bulk protected skipped, original indexes retained');
|
||||
denies(fn()=>$batchService->batch($s2,'preview-fixture',[0],'fixture-key'),'INVALID_INPUT');
|
||||
$job=$batchService->batch($s2,'preview-fixture',[1],'fixture-key');ok($job['id']==='job-fixture','explicit safe selection starts job');
|
||||
ok(Db::name('admin')->select()->toArray()===$beforeUsers,'preflight/job orchestration never changes local accounts/roles');
|
||||
denies(fn()=>IamV2Manager::input(['kind'=>'rebind','user_id'=>2,'reason'=>'fixture']),'BINDING_CONFLICT');
|
||||
denies(fn()=>IamV2Manager::input(['kind'=>'create_and_bind','user_id'=>2,'reason'=>'fixture','new_employee'=>['username'=>'invalid /','display_name'=>'Name']]),'INVALID_INPUT');
|
||||
$newerSession=IamV2Source::enroll('fixture-token-2','password',false);
|
||||
IamV2Source::revokeGeneration(2,2);
|
||||
ok(IamV2Source::check($newerSession['session_id'])['binding_version']===3,'late older binding generation preserves newer source SID and shared business token');
|
||||
$normalSession=$newerSession;
|
||||
$reviewClient=new IamV2Client($cfg,function($method,$url,$headers,$body){
|
||||
if($method==='GET')return ['status'=>200,'body'=>json_encode(['binding'=>null,'employee'=>null,'access'=>['allowed'=>false]])];
|
||||
$data=json_decode($body,true);$claim=IamV2Source::introspect($data['proof'],'management','');
|
||||
ok($claim['protectedAccount']===true,'single protected source request remains marked for central review');
|
||||
return ['status'=>200,'body'=>json_encode(['id'=>'review-fixture','status'=>'pending','error'=>['code'=>'PROTECTED_ACCOUNT_REVIEW_REQUIRED'],'reviewUrl'=>'https://iam.example.test/admin/iam/review?request=review-fixture'])];
|
||||
});
|
||||
$review=(new IamV2Manager($reviewClient))->operation($s2,['kind'=>'bind','user_id'=>1,'employee_id'=>'employee-admin','reason'=>'verified fixture'],'stable-review-key');
|
||||
ok($review['status']==='pending' && isset($review['reviewUrl']),'root single operation reaches central pending review, not completion');
|
||||
$raceProof=IamV2Source::proof($s2,'management',[2],['iam:bind'],null,['protectedReviewEligible'=>true]);
|
||||
Db::name('system_menu')->insert(['id'=>7,'is_disable'=>0,'perms'=>'iamV2/bind']);
|
||||
Db::name('system_role_menu')->insert(['role_id'=>7,'menu_id'=>7]);Db::name('admin_role')->insert(['admin_id'=>2,'role_id'=>7]);
|
||||
ok(IamV2Source::introspect($raceProof,'management','')['protectedAccount']===true,'protection recomputed at callback after target privilege change');
|
||||
denies(fn()=>IamV2Source::authorize($normalSession,'bind',[1],true,true),'PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
ok(IamV2Source::liveStatus($normalSession['session_id'],1,'self_link')['protectedAccount']===true,'self-link callback reports live protection without requiring management capabilities');
|
||||
denies(fn()=>IamV2Source::liveStatus($normalSession['session_id'],1,'management',['1']),'PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
Db::name('system_role_menu')->where('role_id',7)->delete();
|
||||
denies(fn()=>IamV2Source::liveStatus($normalSession['session_id'],1,'management',['2']),'FORBIDDEN');
|
||||
|
||||
Db::name('admin')->where('id',1)->update(['password'=>'new-credential']);
|
||||
denies(fn()=>IamV2Source::check($s2['session_id']),'REAUTH_REQUIRED');
|
||||
ok((int) Db::name('iam_v2_source_session')->where('session_id',$s2['session_id'])->value('version')===2,'credential change increments source revocation version');
|
||||
$managementMissing=$cfg;unset($managementMissing['v2_management_token']);
|
||||
denies(fn()=>(new IamV2Client($managementMissing))->call('GET','/identities'),'SERVICE_UNAVAILABLE');
|
||||
$credentialCalls=[];$credentials=new IamV2Client($cfg,function($method,$url,$headers,$body)use(&$credentialCalls){$credentialCalls[]=$headers;return ['status'=>200,'body'=>'{}'];});
|
||||
$credentials->call('GET','/identities');$credentials->call('GET','/bindings/by-external/2');
|
||||
ok(in_array('Authorization: Bearer '.str_repeat('m',32),$credentialCalls[0],true) && in_array('Authorization: Bearer '.str_repeat('v',32),$credentialCalls[1],true),'management and login credentials strictly separated');
|
||||
Db::name('iam_v2_binding')->where('admin_id',2)->delete();
|
||||
$missing=$statusEvent;$missing['id']='evt-history';$missing['eventType']='binding_revoked';$missing['bindingVersion']=3;$missing['externalAccountId']='2';$missingRaw=json_encode($missing);$generations=[];
|
||||
$refreshHistory=function($id){$row=['admin_id'=>$id,'employee_id'=>'new-employee','subject'=>'new-subject','state'=>'verified','version'=>4,'payload'=>'{}','checked_at'=>time()];Db::name('iam_v2_binding')->insert($row);return ['binding'=>['state'=>'verified','version'=>4],'employee'=>['id'=>'new-employee','status'=>'active'],'access'=>['allowed'=>true]];};
|
||||
IamV2Events::accept($missingRaw,'sha256='.hash_hmac('sha256',$missingRaw,$secret),'evt-history',$secret,$revoke,$refreshHistory,fn($event)=>[(int)$event['externalAccountId']],function($id,$upper)use(&$generations){$generations[]=[$id,$upper];});
|
||||
ok($generations===[[2,3]] && Db::name('iam_v2_binding')->where('admin_id',2)->value('state')==='verified','historical unmapped rebind locates external ID without overwriting new generation');
|
||||
Db::name('admin')->insert(['id'=>4,'account'=>'old-generation','name'=>'Old generation','password'=>'fixture','disable'=>0,'root'=>0]);
|
||||
Db::name('admin_session')->insert(['id'=>4,'admin_id'=>4,'terminal'=>1,'token'=>'old-generation-token','expire_time'=>time()+3600]);
|
||||
$oldGeneration=IamV2Source::enroll('old-generation-token','password',false);
|
||||
IamV2Source::revokeGeneration(4,1,'old-employee');
|
||||
ok((int) Db::name('admin_session')->where('id',4)->value('expire_time')<=time(),'old generation without newer holder expires actual business session row');
|
||||
$gateSession=IamV2Source::enroll('fixture-token-1','password',false);
|
||||
$pendingProof=IamV2Source::proof($gateSession,'management',[2],['iam:bind']);
|
||||
$gateConfig=$app->config->get('iam');$gateConfig['v2_management_enabled']=false;$gateConfig['v2_launch_enabled']=false;$app->config->set($gateConfig,'iam');
|
||||
ok(IamV2Source::liveStatus($gateSession['session_id'],1)['active'],'closing new-flow gates preserves live-session validation');
|
||||
denies(fn()=>IamV2Source::proof($gateSession,'launch',[1]),'FEATURE_DISABLED');
|
||||
denies(fn()=>IamV2Source::introspect($pendingProof,'management',''),'FEATURE_DISABLED');
|
||||
denies(fn()=>IamV2Source::liveStatus($gateSession['session_id'],1,'management',['2']),'FEATURE_DISABLED');
|
||||
Db::name('admin')->where('id',1)->update(['disable'=>1]);denies(fn()=>IamV2Source::liveStatus($gateSession['session_id'],1),'ACCOUNT_DISABLED');
|
||||
ok(!IamV2Client::feature('management',['v2_enabled'=>true]) && !IamV2Client::feature('launch',['v2_enabled'=>true]),'new-flow gates default closed independently of global core');
|
||||
$legacy=$cfg; unset($legacy['v2_token']); $legacy['application_token']=str_repeat('l',32); denies(fn()=>new IamV2Client($legacy),'SERVICE_UNAVAILABLE');
|
||||
denies(fn()=>IamV2Client::https('https://iam.example.test/path?override=1'),'INVALID_FIXED_URL');
|
||||
} finally { @unlink($file); if (is_dir($cachePath)) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($cachePath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) { $path->isDir() ? rmdir($path->getPathname()) : unlink($path->getPathname()); } rmdir($cachePath); } }
|
||||
echo "PASS IamV2SourceTest: independent browser SID, legacy reauth, live DB, scope, protected accounts, single-use proof/intent, expiry, immutable authTime, disabled/rotated/revoked sessions, 30s compensation, signed event replay/digest/future/version, revoked tombstone, batch protected filtering/index mapping, selected-only execution, no local account mutation, credential-change revocation, central empty-tx/reconcile contract, first-link/session preservation, access restoration, protected single-review/ordinary denial/live target protection, separate credentials, durable events, historical mapping, generation-specific business expiry, maintenance gates retain revocation core and live self-link protection, scoped departments/real cached check time/unknown access, single-toast envelope\n";
|
||||
@@ -1,56 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/app/common.php';
|
||||
use think\facade\Db;
|
||||
use app\adminapi\service\iam\v2\{IamV2Client,IamV2Target,IamV2Source,IamV2Manager};
|
||||
function targetOK(bool $ok,string $message):void { if(!$ok)throw new RuntimeException('FAIL '.$message); }
|
||||
function targetReject(callable $fn,string $code):void { try{$fn();}catch(RuntimeException $e){targetOK($e->getMessage()===$code,$code.' got '.$e->getMessage());return;}throw new RuntimeException('accepted '.$code); }
|
||||
$app=new think\App(dirname(__DIR__).'/');think\Container::setInstance($app);$file=tempnam(sys_get_temp_dir(),'zyt-target-');
|
||||
$app->config->set(['default'=>'fixture','connections'=>['fixture'=>['type'=>'sqlite','database'=>$file,'prefix'=>'','fields_strict'=>true]]],'database');
|
||||
$db=new think\DbManager();$db->setConfig($app->config->get('database'));$app->instance('think\Db',$db);
|
||||
$config=['v2_enabled'=>true,'v2_management_enabled'=>true,'v2_launch_enabled'=>true,'api_url'=>'https://iam.example.test/api','public_url'=>'https://zyt.example.test','erp_url'=>'https://erp.example.test','application_id'=>'zyt','v2_token'=>str_repeat('v',32),
|
||||
'v2_sources'=>['iam-admin'=>'https://iam.example.test/admin/iam/launch/continue','iam-portal'=>'https://iam.example.test/portal/launch/continue']];$app->config->set($config,'iam');
|
||||
try {
|
||||
$ini=parse_ini_string('[IAM]'.PHP_EOL.'V2_SOURCES_JSON = '.json_encode($config['v2_sources']),true,INI_SCANNER_RAW);
|
||||
targetOK(json_decode($ini['IAM']['V2_SOURCES_JSON'],true)===$config['v2_sources'],'documented fixed source mapping parses through ThinkPHP INI scanner');
|
||||
foreach([
|
||||
'CREATE TABLE admin (id INTEGER PRIMARY KEY,account TEXT,name TEXT,password TEXT,disable INTEGER,root INTEGER,delete_time INTEGER)',
|
||||
'CREATE TABLE admin_session (id INTEGER PRIMARY KEY,admin_id INTEGER,token TEXT,expire_time INTEGER)',
|
||||
'CREATE TABLE iam_v2_source_session (session_id TEXT PRIMARY KEY,admin_id INTEGER,business_session_id INTEGER,token_hash TEXT,account_stamp TEXT,auth_method TEXT,auth_time INTEGER,version INTEGER,revoked INTEGER,binding_version INTEGER,employee_id TEXT,expires_at INTEGER)',
|
||||
'CREATE TABLE iam_v2_flow (flow_key TEXT PRIMARY KEY,kind TEXT,payload TEXT,expires_at INTEGER,consumed INTEGER)',
|
||||
'CREATE TABLE iam_v2_binding (admin_id INTEGER PRIMARY KEY,employee_id TEXT,subject TEXT,state TEXT,version INTEGER,payload TEXT,checked_at INTEGER)',
|
||||
'CREATE TABLE iam_v2_target_session (token_hash TEXT PRIMARY KEY,admin_id INTEGER,employee_id TEXT,source_application_id TEXT,source_binding_version INTEGER,checked_at INTEGER)'
|
||||
]as$sql)Db::execute($sql);
|
||||
Db::name('admin')->insertAll([['id'=>1,'account'=>'other','name'=>'Other','password'=>'synthetic','disable'=>0,'root'=>0],['id'=>2,'account'=>'employee','name'=>'Employee','password'=>'synthetic','disable'=>0,'root'=>0]]);
|
||||
Db::name('admin_session')->insertAll([['id'=>1,'admin_id'=>1,'token'=>'token-other','expire_time'=>time()+3600],['id'=>2,'admin_id'=>2,'token'=>'token-matching','expire_time'=>time()+3600]]);
|
||||
$count=0;$tx=[];$evil=false;$exchangeCalls=0;$resolveCalls=0;$loginCalls=0;$source='iam-admin';$authTime=time()-20;
|
||||
$employee=['id'=>'emp-fixture','status'=>'active','oidcSubject'=>'subject-fixture'];$binding=['id'=>'binding','applicationId'=>'zyt','externalAccountId'=>'2','employeeId'=>'emp-fixture','state'=>'verified','version'=>1];
|
||||
$client=new IamV2Client($config,function($method,$url,$headers,$body)use(&$count,&$tx,&$evil,&$exchangeCalls,&$source,$employee,$binding,$authTime){
|
||||
$b=json_decode($body,true);
|
||||
if(str_ends_with($url,'/launch-transactions')){$id='tx-'.(++$count);$source=$b['sourceApplicationId'];$tx[$id]=$b;return ['status'=>200,'body'=>json_encode(['transactionId'=>$id,'sourceContinueUrl'=>($evil?'https://evil.example.test': 'https://iam.example.test').($source==='iam-admin'?'/admin/iam/launch/continue':'/portal/launch/continue').'?transaction_id='.$id,'expiresAt'=>gmdate(DATE_RFC3339,time()+300)])];}
|
||||
if(str_ends_with($url,'/launch-grants/exchange')){$exchangeCalls++;targetOK(rtrim(strtr(base64_encode(hash('sha256',$b['codeVerifier'],true)),'+/','-_'),'=')===$tx[$b['transactionId']]['codeChallenge'],'target PKCE is consistent');return ['status'=>200,'body'=>json_encode(['employee'=>$employee,'binding'=>$binding,'access'=>['allowed'=>true],'authentication'=>['sourceApplicationId'=>$source,'sessionId'=>'native-source-session','sessionVersion'=>1,'authMethod'=>'password','authTime'=>gmdate(DATE_RFC3339,$authTime),'sourceBindingVersion'=>0]])];}
|
||||
if(str_contains($url,'/bindings/by-external/'))return ['status'=>200,'body'=>json_encode(['employee'=>$employee,'binding'=>$binding,'access'=>['allowed'=>true]])];
|
||||
throw new RuntimeException('UNEXPECTED_NETWORK');
|
||||
});
|
||||
$target=new IamV2Target($client,function($result)use(&$resolveCalls){$resolveCalls++;return 2;},function($id,$auth)use(&$loginCalls){$loginCalls++;IamV2Source::enroll('token-matching','iam_launch',false,IamV2Target::authTime($auth['authTime']));return ['token'=>'token-matching','is_paw'=>1,'need_bind_work_wechat'=>false];});
|
||||
$intent=str_repeat('i',43);targetReject(fn()=>$target->prepare('zmxy-erp',$intent,''),'NOT_AUTHORIZED');targetReject(fn()=>$target->prepare('iam-admin',$intent,'invalid'),'REAUTH_REQUIRED');
|
||||
$evil=true;targetReject(fn()=>$target->prepare('iam-admin',$intent,''),'INVALID_FIXED_URL');$evil=false;
|
||||
$start=$target->prepare('iam-admin',$intent,'');parse_str(parse_url($start['url'],PHP_URL_QUERY),$q);targetOK($q['intent']===$intent,'intent preserved in fixed continuation');$id=$q['transaction_id'];
|
||||
targetReject(fn()=>$target->callback($id,str_repeat('g',43),str_repeat('f',64),'https://iam.example.test'),'ACCOUNT_MISMATCH');
|
||||
targetReject(fn()=>$target->callback($id,str_repeat('g',43),$start['browser'],'https://evil.example.test'),'INVALID_ORIGIN');
|
||||
$ticket=$target->callback($id,str_repeat('g',43),$start['browser'],'https://iam.example.test');targetOK($resolveCalls===1,'same-identity resolver called once');
|
||||
targetReject(fn()=>$target->callback($id,str_repeat('g',43),$start['browser'],'https://iam.example.test'),'TRANSACTION_EXPIRED');
|
||||
targetReject(fn()=>$target->exchange($ticket['ticket'],$start['browser'],'token-other'),'ACCOUNT_MISMATCH');targetOK($loginCalls===0,'midflow account change does not issue token');
|
||||
$session=IamV2Source::enroll('token-other','password',false);
|
||||
targetReject(fn()=>$target->exchange($ticket['ticket'],$start['browser'],'',$session['session_id']),'ACCOUNT_MISMATCH');
|
||||
$result=$target->exchange($ticket['ticket'],$start['browser'],'token-matching');targetOK($result['token']==='token-matching'&&$loginCalls===1,'IAM local admin grant without KC cookie establishes target login');
|
||||
$local=Db::name('iam_v2_source_session')->where('auth_method','iam_launch')->find();targetOK((int)$local['auth_time']===$authTime,'original RFC3339 authentication age preserved');
|
||||
targetReject(fn()=>$target->exchange($ticket['ticket'],$start['browser'],'token-matching'),'TRANSACTION_EXPIRED');
|
||||
$other=$target->prepare('iam-portal',$intent,'token-other');parse_str(parse_url($other['url'],PHP_URL_QUERY),$q);
|
||||
targetReject(fn()=>$target->callback($q['transaction_id'],str_repeat('g',43),$other['browser'],'https://iam.example.test'),'ACCOUNT_MISMATCH');targetOK($resolveCalls===1,'preexisting mismatch rejects before local auto-provision');
|
||||
$selection=IamV2Manager::retrySelection(['indexes'=>[0,2],'items'=>[['status'=>'succeeded','externalAccountId'=>'1','kind'=>'bind'],['status'=>'failed','externalAccountId'=>'2','kind'=>'bind']]],[1]);
|
||||
targetOK($selection['indexes']===[2] && $selection['targets']===[2],'job item position translated to original noncontiguous preview index');
|
||||
targetReject(fn()=>IamV2Target::authTime(gmdate(DATE_RFC3339,time()+120)),'INVALID_AUTHENTICATION');
|
||||
echo "PASS IamV2TargetTest: native IAM admin/portal to ZYT without KC cookie, strict source allowlist, fixed continuation+intent, PKCE, browser/origin/replay checks, existing and midflow account mismatch, no duplicate provisioning, RFC3339 age, target lineage, noncontiguous retry index\n";
|
||||
} finally {@unlink($file);}
|
||||
@@ -1,58 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import vm from 'node:vm'
|
||||
import { createRequire } from 'node:module'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
const require = createRequire(import.meta.url), ts = require('typescript'), sfc = require('@vue/compiler-sfc')
|
||||
const root = process.env.IAM_UI_ROOT ? pathToFileURL(process.env.IAM_UI_ROOT.replace(/\/$/,'') + '/') : new URL('../../',import.meta.url)
|
||||
const files=['admin/src/components/iam-v2/launch.vue','admin/src/components/iam-v2/personal.vue','admin/src/views/permission/identity/index.vue','admin/src/views/account/iam-launch.vue']
|
||||
for(const file of files){
|
||||
const source=fs.readFileSync(new URL(file,root),'utf8'), {descriptor,errors}=sfc.parse(source,{filename:file})
|
||||
assert.deepEqual(errors,[])
|
||||
const script=sfc.compileScript(descriptor,{id:file})
|
||||
const template=sfc.compileTemplate({source:descriptor.template.content,filename:file,id:file,compilerOptions:{bindingMetadata:script.bindings}})
|
||||
assert.deepEqual(template.errors,[],file)
|
||||
}
|
||||
const source=fs.readFileSync(new URL(files[0],root),'utf8'), script=source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const js=ts.transpileModule(script,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText.replace(/^.*require\(.+\);?$/gm,'').replace(/^Object.defineProperty\(exports.*$/gm,'')
|
||||
async function scenario({enabled=true,launchEnabled=enabled,fail=false,blocked=false}={}){
|
||||
const events=[],tab={opener:'origin',location:{href:'about:blank'},close(){events.push('close')}},ref=v=>({value:v});let mounted
|
||||
const context={exports:{},vue_1:{ref,onMounted:f=>{mounted=f}},element_plus_1:{ElMessage:{warning:m=>events.push(m)}},iam_v2_1:{iamGet:async()=>({enabled,launch_enabled:launchEnabled,management_enabled:enabled}),iamPost:async(path)=>{events.push(path);assert.equal(tab.opener,null);if(fail)throw{error:{code:'REAUTH_REQUIRED'}};return{url:'https://erp.example.test/iam/launch?source=zyt&intent=opaque'}},identityError:()=> 'reauth'},window:{open:(url,target)=>{events.push(['open',url,target]);return blocked?null:tab}}}
|
||||
context.iam_v2_1.identityError=()=> 'reauth'
|
||||
vm.createContext(context);vm.runInContext(js,context);await mounted();return{context,events,tab}
|
||||
}
|
||||
let s=await scenario({enabled:false});assert.equal(vm.runInContext('enabled.value',s.context),false);assert.deepEqual(s.events,[])
|
||||
s=await scenario({enabled:true,launchEnabled:false});assert.equal(vm.runInContext('enabled.value',s.context),false);assert.deepEqual(s.events,[])
|
||||
s=await scenario();await vm.runInContext('launch()',s.context);assert.equal(s.events[0][0],'open');assert.equal(s.events[1],'/launch/start');assert.match(s.tab.location.href,/intent=opaque/);assert.equal(s.tab.opener,null)
|
||||
s=await scenario({fail:true});await vm.runInContext('launch()',s.context);assert.ok(s.events.includes('close'));assert.equal(vm.runInContext('busy.value',s.context),false)
|
||||
const management=fs.readFileSync(new URL(files[2],root),'utf8')
|
||||
assert.match(management,/核对本地账号/);assert.match(management,/核对 IAM 身份/);assert.match(management,/确认变更/)
|
||||
assert.match(management,/row.status === 'ready'/);assert.match(management,/batchConfirmed/);assert.match(management,/operationKey/)
|
||||
assert.match(management,/查询同一操作状态/);assert.match(management,/只重试失败\/待处理项/)
|
||||
const api=fs.readFileSync(new URL('admin/src/api/iam-v2.ts',root),'utf8');assert.match(api,/isOpenRetry: false/);assert.match(api,/Idempotency-Key/)
|
||||
assert.match(management,/中央复核/);assert.match(management,/noopener noreferrer/);assert.match(management,/submittedPayload/)
|
||||
const managerScript=management.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const managerJS=ts.transpileModule(managerScript,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText.replace(/^.*require\(.+\);?$/gm,'').replace(/^Object.defineProperty\(exports.*$/gm,'')
|
||||
const sent=[],ref=value=>({value}),managerContext={exports:{},console,crypto:{randomUUID:()=> 'stable-fixture-key'},vue_1:{ref,reactive:v=>v,computed:fn=>({get value(){return fn()}}),onMounted(){}},element_plus_1:{ElMessage:{success(){}}},iam_v2_1:{iamGet:async()=>({items:[],total:0}),identityError:()=> 'error',iamPost:async(path,body,key)=>{sent.push({body:JSON.stringify(body),key});return{id:'review',status:'pending',reviewUrl:'https://iam.example.test/admin/iam/review?request=review'}}}}
|
||||
vm.createContext(managerContext);vm.runInContext(managerJS,managerContext)
|
||||
vm.runInContext("operation.user_id=1; operation.employee_id='employee'; operation.reason='original reason'",managerContext)
|
||||
await vm.runInContext('submit()',managerContext);vm.runInContext("operation.reason='changed after review'",managerContext);await vm.runInContext('submit()',managerContext)
|
||||
assert.equal(sent[0].body,sent[1].body);assert.equal(sent[0].key,sent[1].key)
|
||||
const targetSource=fs.readFileSync(new URL(files[3],root),'utf8'),targetScript=targetSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const targetJS=ts.transpileModule(targetScript,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText.replace(/^.*require\(.+\);?$/gm,'').replace(/^Object.defineProperty\(exports.*$/gm,'')
|
||||
async function targetScenario(query,loginResult={is_paw:1}){
|
||||
const events=[];let mounted
|
||||
const c={exports:{},console,vue_1:{ref,onMounted:fn=>mounted=fn},vue_router_1:{useRoute:()=>({query}),useRouter:()=>({replace:async path=>events.push(['route',path])})},iam_v2_1:{identityError:e=>e.error.code,iamGet:async()=>{events.push(['config']);return{enabled:true,restart_url:'https://iam.example.test/admin'}},iamPost:async(path,body)=>{events.push(['post',path,body]);return{url:'https://iam.example.test/admin/v1/iam/v2/launch/continue?transaction_id=fixture&intent=opaque'}}},user_1:{default:()=>({iamLaunchLogin:async ticket=>{events.push(['login',ticket]);return loginResult}})},auth_1:{clearAuthInfo:()=>events.push(['clear'])},feedback_1:{default:{confirm:async()=>true}},window:{location:{pathname:'/admin/iam/launch',assign:url=>events.push(['assign',url])},history:{state:{},replaceState:()=>events.push(['clean'])}}}
|
||||
vm.createContext(c);vm.runInContext(targetJS,c);await mounted();return{events,c}
|
||||
}
|
||||
let targetFlow=await targetScenario({ticket:'one-use',source:'iam-admin'},{is_paw:0});assert.equal(targetFlow.events[0][0],'clean');assert.ok(targetFlow.events.some(x=>x[0]==='route'&&x[1]==='/change-password'))
|
||||
targetFlow=await targetScenario({ticket:'one-use',source:'iam-portal'},{is_paw:1,need_bind_work_wechat:true});assert.ok(targetFlow.events.some(x=>x[0]==='route'&&x[1]==='/bind-work-wechat'))
|
||||
targetFlow=await targetScenario({source:'iam-admin',intent:'i'.repeat(43)});assert.ok(targetFlow.events.some(x=>x[0]==='post'&&x[1]==='/launch/prepare'));assert.ok(targetFlow.events.some(x=>x[0]==='assign'))
|
||||
targetFlow=await targetScenario({source:'zmxy-erp',intent:'i'.repeat(43)});assert.ok(!targetFlow.events.some(x=>x[0]==='post'))
|
||||
targetFlow=await targetScenario({ticket:'one-use',iam_error:'ACCOUNT_MISMATCH'});assert.ok(!targetFlow.events.some(x=>x[0]==='login'));await vm.runInContext('switchAccount()',targetFlow.c);assert.ok(targetFlow.events.some(x=>x[0]==='post'&&x[1]==='/launch/reset'));assert.ok(targetFlow.events.some(x=>x[0]==='clear'))
|
||||
const storeSource=fs.readFileSync(new URL('admin/src/stores/modules/user.ts',root),'utf8')
|
||||
const storeJS=ts.transpileModule(storeSource,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText.replace(/^.*require\(.+\);?$/gm,'').replace(/^Object.defineProperty\(exports.*$/gm,'')
|
||||
const storeContext={exports:{},Date:{now:()=>500000},pinia_1:{defineStore:config=>config},auth_1:{getToken:()=> 'fixture',clearAuthInfo(){}},user_1:{getUserInfo:async()=>({user:{web_consultation_policy:{server_time:1000}},permissions:[],menu:[]})},router_1:{filterAsyncRoutes:r=>r}}
|
||||
vm.createContext(storeContext);vm.runInContext(storeJS,storeContext);const descriptor=storeContext.exports.default,state=descriptor.state()
|
||||
await descriptor.actions.getUserInfo.call(state);assert.equal(state.serverTimeOffsetMs,500000);descriptor.actions.resetState.call(state);assert.equal(state.serverTimeOffsetMs,0)
|
||||
console.log('PASS IamV2UiTest: 4 Vue components compile; default-off, explicit new tab, opener isolation, source-only POST, error closes tab, three-step confirm, batch ready-only, stable operation key, protected review retry snapshot, target URL cleanup/account mismatch/password-WeCom gates, production consultation server-time offset preservation')
|
||||
Reference in New Issue
Block a user