This commit is contained in:
Your Name
2026-11-26 15:46:20 +08:00
parent db6d327e91
commit be79e09c83
170 changed files with 21159 additions and 13217 deletions
+17 -3
View File
@@ -20,6 +20,7 @@ use app\common\model\auth\Admin;
use app\common\model\auth\AdminSession;
use app\common\model\auth\SystemRole;
use app\common\enum\AdminTerminalEnum;
use think\facade\Db;
/**
* 管理员token缓存
@@ -43,12 +44,15 @@ class AdminTokenCache extends BaseCache
//直接从缓存获取
$adminInfo = $this->get($this->prefix . $token);
if ($adminInfo) {
if ((int) ($adminInfo['terminal'] ?? 0) === AdminTerminalEnum::BCR) {
$terminal = (int) ($adminInfo['terminal'] ?? 0);
if (in_array($terminal, [AdminTerminalEnum::BCR, AdminTerminalEnum::WORKSTATION], true)) {
// 长会话每次请求查 DB;即使事务撤销后旧缓存尚未删除,也必须拒绝。
$session = AdminSession::where('token', $token)->where('expire_time', '>', time())->find();
$admin = $session ? Admin::where('id', $session->admin_id)->where('disable', 0)
->field('id,root,work_wechat_userid')->find() : null;
if (!$session || (int) $session->terminal !== AdminTerminalEnum::BCR
if (!$session || (int) $session->terminal !== $terminal
|| ($terminal === AdminTerminalEnum::WORKSTATION && ((int) $session->workstation_slot <= 0
|| (int) ($adminInfo['desktop_expires_at'] ?? 0) <= time()))
|| (int) $session->admin_id !== (int) $adminInfo['admin_id']
|| !$admin) {
$this->deleteAdminInfo($token);
@@ -93,7 +97,8 @@ class AdminTokenCache extends BaseCache
$admin = Admin::where('id', '=', $adminSession->admin_id)
->append(['role_id'])
->find();
if (!$admin || ((int) $adminSession->terminal === AdminTerminalEnum::BCR && (int) $admin->disable !== 0)) {
if (!$admin || (in_array((int) $adminSession->terminal, [AdminTerminalEnum::BCR, AdminTerminalEnum::WORKSTATION], true)
&& (int) $admin->disable !== 0)) {
return [];
}
@@ -122,6 +127,15 @@ class AdminTokenCache extends BaseCache
'login_ip' => request()->ip(),
'work_wechat_userid' => $admin->work_wechat_userid ?? '',
];
if ((int) $adminSession->terminal === AdminTerminalEnum::WORKSTATION) {
$row = Db::name('desktop_login_session')->where('id', $adminSession->workstation_slot)
->whereNull('logout_time')->where('due_time', '>', time())->field('expires_at,login_ip')->find();
if (!$row) {
return [];
}
$adminInfo['desktop_expires_at'] = (int) $row['expires_at'];
$adminInfo['login_ip'] = $row['login_ip'];
}
$this->set($this->prefix . $token, $adminInfo, new \DateTime(Date('Y-m-d H:i:s', $adminSession->expire_time)));
return $adminInfo;
}
@@ -27,6 +27,8 @@ class AdminTerminalEnum
const MOBILE = 2;
// BCR 原生录音应用:独立于通用手机后台及集团身份会话。
const BCR = 20;
// 医生桌面工作站。每个登录实例分别记录和结算。
const WORKSTATION = 21;
// 企业微信客服桌面软件。与网页端分开保存会话,桌面登录不会顶掉浏览器登录。
const WECOM_RPA = 7;
// 8 已被 AI 浏览器(app/mcp/service/ConsoleService::TERMINAL)占用,不要复用。
+44 -16
View File
@@ -15,7 +15,7 @@ use think\facade\Log;
class DifyChatService
{
/** @var array<int,string> */
private const ALLOWED_PROFILES = ['qwen', 'openai'];
private const ALLOWED_PROFILES = ['qwen', 'openai', 'doubao'];
private const MIN_TIMEOUT = 1;
@@ -74,7 +74,7 @@ class DifyChatService
return self::error('INVALID_PROFILE', '不支持的 AI 模型');
}
$baseUrl = trim((string) ($config['base_url'] ?? ''));
$baseUrl = self::profileBaseUrl($config, $modelConfig);
$rawApiKey = (string) ($modelConfig['api_key'] ?? '');
$apiKey = trim($rawApiKey);
if ($baseUrl === '' || $apiKey === '') {
@@ -112,10 +112,10 @@ class DifyChatService
$ancientBookSources = $evidenceOnly || $caseReferences ? [] : ClinicalKnowledgeReference::ancientBookSources($query);
try {
if (!$evidenceOnly) {
$query = $consultationReferences && ($options['response_contract'] ?? '') === 'live_consultation'
? ClinicalKnowledgeReference::augmentLiveConsultationQuery($query, (string) ($options['analysis_scope'] ?? 'authorized_case'))
: ($caseReferences ? ClinicalKnowledgeReference::augmentCaseQuery($query, $consultationReferences)
: ClinicalKnowledgeReference::augmentQueryWithAncientBookSources($query, $ancientBookSources));
$query = $consultationReferences && ($options['response_contract'] ?? '') === 'live_consultation'
? ClinicalKnowledgeReference::augmentLiveConsultationQuery($query, (string) ($options['analysis_scope'] ?? 'authorized_case'))
: ($caseReferences ? ClinicalKnowledgeReference::augmentCaseQuery($query, $consultationReferences)
: ClinicalKnowledgeReference::augmentQueryWithAncientBookSources($query, $ancientBookSources));
}
} catch (\RuntimeException $error) {
return self::error('SKILL_UNAVAILABLE', '临床 AI 参考资料不可用');
@@ -159,7 +159,8 @@ class DifyChatService
$user,
false,
$attempt['files'],
$attempt['omitted']
$attempt['omitted'],
self::openAiPayloadOptions($modelConfig)
);
$lastResponse = null;
$lastSpec = [];
@@ -286,7 +287,7 @@ class DifyChatService
return self::error('INVALID_PROFILE', '不支持的 AI 模型');
}
$baseUrl = trim((string) ($config['base_url'] ?? ''));
$baseUrl = self::profileBaseUrl($config, $modelConfig);
$rawApiKey = (string) ($modelConfig['api_key'] ?? '');
$apiKey = trim($rawApiKey);
if ($baseUrl === '' || $apiKey === '') {
@@ -320,10 +321,10 @@ class DifyChatService
$ancientBookSources = $evidenceOnly || $caseReferences ? [] : ClinicalKnowledgeReference::ancientBookSources($query);
try {
if (!$evidenceOnly) {
$query = $consultationReferences && ($options['response_contract'] ?? '') === 'live_consultation'
? ClinicalKnowledgeReference::augmentLiveConsultationQuery($query, (string) ($options['analysis_scope'] ?? 'authorized_case'))
: ($caseReferences ? ClinicalKnowledgeReference::augmentCaseQuery($query, $consultationReferences)
: ClinicalKnowledgeReference::augmentQueryWithAncientBookSources($query, $ancientBookSources));
$query = $consultationReferences && ($options['response_contract'] ?? '') === 'live_consultation'
? ClinicalKnowledgeReference::augmentLiveConsultationQuery($query, (string) ($options['analysis_scope'] ?? 'authorized_case'))
: ($caseReferences ? ClinicalKnowledgeReference::augmentCaseQuery($query, $consultationReferences)
: ClinicalKnowledgeReference::augmentQueryWithAncientBookSources($query, $ancientBookSources));
}
} catch (\RuntimeException $error) {
return self::error('SKILL_UNAVAILABLE', '临床 AI 参考资料不可用');
@@ -365,7 +366,8 @@ class DifyChatService
$user,
true,
$attempt['files'],
$attempt['omitted']
$attempt['omitted'],
self::openAiPayloadOptions($modelConfig)
);
$lastResponse = null;
$lastSpec = [];
@@ -849,7 +851,7 @@ class DifyChatService
if (preg_match('/^[a-zA-Z0-9_-]{1,128}$/', $taskId) !== 1 || $user === '') return false;
$config = config('prescription_ai') ?: [];
$model = self::resolveProfileConfig($config, $profile);
$base = trim((string) ($config['base_url'] ?? ''));
$base = is_array($model) ? self::profileBaseUrl($config, $model) : '';
$key = (string) ($model['api_key'] ?? '');
if (!self::isValidBaseUrl($base) || trim($key) === '' || strpbrk($key, "\r\n") !== false) return false;
$endpoint = self::buildEndpoint(rtrim($base, '/'), 'chat-messages');
@@ -1307,6 +1309,31 @@ class DifyChatService
return is_array($modelConfig) ? $modelConfig : null;
}
/**
* 模型可声明自己的上游地址(如豆包直连火山方舟),未声明时沿用共享的 Dify 地址。
*
* @param array<string,mixed> $config
* @param array<string,mixed> $modelConfig
*/
private static function profileBaseUrl(array $config, array $modelConfig): string
{
$own = trim((string) ($modelConfig['base_url'] ?? ''));
return $own !== '' ? $own : trim((string) ($config['base_url'] ?? ''));
}
/**
* 仅 OpenAI 兼容协议追加的模型参数。目前只有方舟的 thinking 开关。
*
* @param array<string,mixed> $modelConfig
* @return array<string,mixed>
*/
private static function openAiPayloadOptions(array $modelConfig): array
{
$thinking = (string) ($modelConfig['thinking'] ?? '');
return in_array($thinking, ['enabled', 'disabled', 'auto'], true)
? ['thinking' => ['type' => $thinking]] : [];
}
/**
* @param array<string,mixed> $inputs
* @param array<int,array<string,string>> $files 随请求送达的附件
@@ -1321,7 +1348,8 @@ class DifyChatService
string $user,
bool $streaming = false,
array $files = [],
array $omitted = []
array $omitted = [],
array $openAiOptions = []
): array {
$baseUrl = rtrim($baseUrl, '/');
$path = strtolower((string) (parse_url($baseUrl, PHP_URL_PATH) ?? ''));
@@ -1363,7 +1391,7 @@ class DifyChatService
['role' => 'user', 'content' => $openAiContent],
],
'stream' => $streaming,
],
] + $openAiOptions,
];
if (!$streaming) {
@@ -5,10 +5,11 @@ declare(strict_types=1);
namespace app\common\service;
/**
* Screenshot-only Dify transport. Reuses the configured assistant app, but never
* Screenshot-only model transport. Reuses the configured assistant app, but never
* enters clinical augmentation, OCR, history or protocol fallback. A rejected
* answer may be regenerated once from the same image within the total deadline.
* The private PHP upload is sent directly to Dify; no public storage is involved.
* Dify receives the private PHP upload directly; 豆包 (火山方舟) receives the same
* bytes inline as a data URI. No public storage is involved.
*/
final class DifyTongueScreenshotService
{
@@ -28,6 +29,24 @@ PROMPT;
$settings = self::settings($config, $model);
if (!function_exists('curl_init')) throw new \DomainException('截图分析服务暂不可用');
$deadline = microtime(true) + self::TIMEOUT_SECONDS;
$ask = $settings['protocol'] === 'openai'
? self::openAiAsker($image, $settings, $deadline)
: self::difyAsker($image, $settings, $deadline);
$answer = $ask(TongueScreenshotAnalysis::prompt());
try {
$analysis = TongueScreenshotAnalysis::parse($answer);
} catch (\DomainException $error) {
if ($deadline - microtime(true) < self::MIN_CORRECTION_SECONDS) throw $error;
// Only parser rejection permits one correction. Never replay the
// rejected answer, reset the budget, upload again or change models.
$analysis = TongueScreenshotAnalysis::parse($ask(TongueScreenshotAnalysis::prompt() . "\n" . self::CORRECTION_PROMPT));
}
return ['analysis' => $analysis, 'model' => $model, 'model_label' => $settings['label']];
}
/** Dify: upload the private image once, then every question references that same file. */
private static function difyAsker(TongueScreenshotImage $image, array $settings, float $deadline): \Closure
{
// No patient, diagnosis, admin ID, filename or historical conversation is sent.
$user = 'tongue-screenshot-' . bin2hex(random_bytes(16));
$upload = self::post($settings['base'] . '/files/upload', $settings, [
@@ -40,29 +59,43 @@ PROMPT;
}
// An upload failure can never become a text-only success. Both possible
// model calls use this same private image and anonymous request-local user.
$payload = [
'inputs' => (object) [],
'query' => TongueScreenshotAnalysis::prompt(),
'response_mode' => 'blocking',
'user' => $user,
'auto_generate_name' => false,
'files' => [['type' => 'image', 'transfer_method' => 'local_file', 'upload_file_id' => $upload['id']]],
];
$response = self::post($settings['base'] . '/chat-messages', $settings,
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), $deadline);
$answer = self::answer($response);
try {
$analysis = TongueScreenshotAnalysis::parse($answer);
} catch (\DomainException $error) {
if ($deadline - microtime(true) < self::MIN_CORRECTION_SECONDS) throw $error;
// Only parser rejection permits one correction. Never replay the
// rejected answer, reset the budget, upload again or change models.
$payload['query'] = TongueScreenshotAnalysis::prompt() . "\n" . self::CORRECTION_PROMPT;
$response = self::post($settings['base'] . '/chat-messages', $settings,
return static function (string $query) use ($settings, $deadline, $user, $upload): string {
$payload = [
'inputs' => (object) [],
'query' => $query,
'response_mode' => 'blocking',
'user' => $user,
'auto_generate_name' => false,
'files' => [['type' => 'image', 'transfer_method' => 'local_file', 'upload_file_id' => $upload['id']]],
];
return self::answer(self::post($settings['base'] . '/chat-messages', $settings,
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), $deadline));
};
}
/**
* OpenAI 兼容接口(豆包直连火山方舟):截图以 base64 data URI 内联,
* 不产生任何公开地址;同样不发送患者、诊单或账号标识。
*/
private static function openAiAsker(TongueScreenshotImage $image, array $settings, float $deadline): \Closure
{
$bytes = @file_get_contents($image->path());
if (!is_string($bytes) || $bytes === '') throw new \DomainException('截图无法读取,请重新截图');
$dataUri = 'data:image/jpeg;base64,' . base64_encode($bytes);
unset($bytes);
return static function (string $query) use ($settings, $deadline, $dataUri): string {
$payload = [
'model' => $settings['model'],
'messages' => [['role' => 'user', 'content' => [
['type' => 'text', 'text' => $query],
['type' => 'image_url', 'image_url' => ['url' => $dataUri]],
]]],
] + $settings['payload_options'];
$response = self::post($settings['base'], $settings,
json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), $deadline);
$analysis = TongueScreenshotAnalysis::parse(self::answer($response));
}
return ['analysis' => $analysis, 'model' => $model, 'model_label' => $settings['label']];
$content = $response['choices'][0]['message']['content'] ?? null;
return self::answer(['answer' => $content]);
};
}
private static function answer(array $response): string
@@ -75,11 +108,14 @@ PROMPT;
private static function settings(array $config, string $model): array
{
if (!in_array($model, ['qwen', 'openai'], true)) throw new \DomainException('截图分析模型无效');
if (!in_array($model, ['qwen', 'openai', 'doubao'], true)) throw new \DomainException('截图分析模型无效');
if (empty($config['enable'])) throw new \DomainException('AI 截图分析功能未启用');
// The selected profile owns both the image upload and chat. No cross-model fallback.
$profile = $config['models'][$model] ?? [];
$base = rtrim(trim((string) ($config['base_url'] ?? '')), '/');
// A profile with its own address (豆包 → 火山方舟) speaks OpenAI-compatible chat/completions.
$ownBase = rtrim(trim((string) ($profile['base_url'] ?? '')), '/');
$openAi = $ownBase !== '';
$base = $openAi ? $ownBase : rtrim(trim((string) ($config['base_url'] ?? '')), '/');
$key = trim((string) ($profile['api_key'] ?? ''));
$parts = parse_url($base);
if (!is_array($parts) || !in_array(strtolower($parts['scheme'] ?? ''), ['https', 'http'], true)
@@ -87,20 +123,30 @@ PROMPT;
|| isset($parts['query']) || isset($parts['fragment'])
|| preg_match('/[\x00-\x20\x7f]/', $base) || $key === ''
|| preg_match('/[\x00-\x1f\x7f]/', (string) ($profile['api_key'] ?? ''))
|| str_ends_with(strtolower($parts['path'] ?? ''), '/chat/completions')) {
|| str_ends_with(strtolower($parts['path'] ?? ''), '/chat/completions') !== $openAi
|| ($openAi && trim((string) ($profile['name'] ?? '')) === '')) {
throw new \DomainException('截图分析服务配置不完整');
}
if (str_ends_with($base, '/chat-messages')) $base = substr($base, 0, -strlen('/chat-messages'));
elseif (!str_ends_with($base, '/v1')) $base .= '/v1';
$caFile = (string) ($config['required_attachment_upload']['ca_file'] ?? '');
// Ark's chat/completions address is used as-is; only Dify bases are normalized.
if (!$openAi) {
if (str_ends_with($base, '/chat-messages')) $base = substr($base, 0, -strlen('/chat-messages'));
elseif (!str_ends_with($base, '/v1')) $base .= '/v1';
}
// The optional attachment CA bundle trusts the private Dify/attachment hosts;
// the public Ark endpoint always validates against the system trust store.
$caFile = $openAi ? '' : (string) ($config['required_attachment_upload']['ca_file'] ?? '');
if ($caFile !== '' && (!is_file($caFile) || !is_readable($caFile))) {
// Match the established attachment transport on other hosts: an
// optional stale CA path falls back to the system trust store.
// CURLOPT_SSL_VERIFYPEER/VERIFYHOST remain enabled below.
$caFile = '';
}
$label = $model === 'qwen' ? '千问' : 'GPT';
return ['base' => $base, 'key' => $key, 'ca_file' => $caFile, 'label' => $label];
$label = ['qwen' => '千问', 'openai' => 'GPT', 'doubao' => '豆包'][$model];
$thinking = (string) ($profile['thinking'] ?? '');
return ['base' => $base, 'key' => $key, 'ca_file' => $caFile, 'label' => $label,
'protocol' => $openAi ? 'openai' : 'dify', 'model' => trim((string) ($profile['name'] ?? '')),
'payload_options' => in_array($thinking, ['enabled', 'disabled', 'auto'], true)
? ['thinking' => ['type' => $thinking]] : []];
}
/** Exactly one bounded POST; redirects and ambient proxies must not receive credentials/images. */
@@ -71,26 +71,22 @@ final class AssistantServiceAlert
{
$actor = AssistantServiceAccess::actor($adminId);
$accounts = self::archiveAccounts();
$staff = [];
foreach (AssistantServiceAccess::assistantRows($adminId, $actor) as $row) {
$count = 0;
foreach ($accounts as $account) {
if ($account['name'] !== '' && $account['name'] === $row['name']) { $count += $account['conversations']; }
}
$wechat = trim((string) Db::name('admin')->where('id', $row['id'])->value('work_wechat_userid'));
foreach ($accounts as $account) {
if ($wechat !== '' && $account['external_id'] === $wechat) { $count += $account['conversations']; }
}
$staff[] = $row + ['conversations' => $count];
}
$owners = $accounts ? WecomArchiveScope::accountOwners() : [];
$staff = AssistantServiceAccess::assistantRows($adminId, $actor);
$visible = array_column($staff, 'id');
$counts = [];
$unmapped = [];
if (AssistantServiceAccess::visibleStaffIds($adminId, $actor) === null) {
$names = array_column($staff, 'name');
$wechatIds = array_map('strval', Db::name('admin')->whereIn('id', array_column($staff, 'id') ?: [0])->column('work_wechat_userid'));
foreach ($accounts as $account) {
if (!in_array($account['name'], $names, true) && !in_array($account['external_id'], $wechatIds, true)) { $unmapped[] = $account; }
$unrestricted = AssistantServiceAccess::visibleStaffIds($adminId, $actor) === null;
foreach ($accounts as $account) {
$owner = $owners[$account['external_id']] ?? 0;
if ($owner && in_array($owner, $visible, true)) {
$counts[$owner] = ($counts[$owner] ?? 0) + $account['conversations'];
} elseif ($unrestricted) {
$unmapped[] = $account;
}
}
foreach ($staff as &$row) { $row['conversations'] = $counts[$row['id']] ?? 0; }
unset($row);
return ['ready' => self::archiveReady(), 'staff' => $staff, 'accounts' => $unmapped];
}
@@ -117,6 +113,7 @@ final class AssistantServiceAlert
try {
$actor = AssistantServiceAccess::actor($adminId);
$allowed = self::allowedAccounts($p, $adminId, $actor);
if (!$allowed) { throw new DomainException('会话不存在或不在当前可见范围'); }
$thread = self::archiveMessages((string) $p['conversation_id']);
} catch (\PDOException $e) {
throw new DomainException('企微会话暂时读不出来,请稍后重试');
@@ -147,11 +144,11 @@ final class AssistantServiceAlert
if ($row['id'] === $staffId) { $visible = true; break; }
}
if (!$visible) { throw new DomainException('医助不存在、已停用或不在当前员工范围'); }
$name = trim((string) Db::name('admin')->where('id', $staffId)->value('name'));
$wechat = trim((string) Db::name('admin')->where('id', $staffId)->value('work_wechat_userid'));
$accounts = self::archiveAccounts();
$owners = $accounts ? WecomArchiveScope::accountOwners() : [];
$allowed = [];
foreach (self::archiveAccounts() as $row) {
if (($name !== '' && $row['name'] === $name) || ($wechat !== '' && $row['external_id'] === $wechat)) { $allowed[] = $row['external_id']; }
foreach ($accounts as $row) {
if (($owners[$row['external_id']] ?? 0) === $staffId) { $allowed[] = $row['external_id']; }
}
return array_values(array_unique($allowed));
}
@@ -212,7 +209,7 @@ final class AssistantServiceAlert
$actor = AssistantServiceAccess::actor($adminId, 'reviewQuality');
if (!self::alertReady()) { throw new DomainException('预警表尚未就绪,请先执行模块迁移'); }
$row = Db::name(self::TABLE)->where('id', $p['id'])->lock(true)->find();
if (!$row || !self::visible($row, $adminId, $actor)) { throw new DomainException('预警不存在或已不在当前范围'); }
if (!$row || !self::scoped($adminId, $actor)->where('a.id', (int) $row['id'])->find()) { throw new DomainException('预警不存在或已不在当前范围'); }
$now = time();
Db::name(self::TABLE)->where('id', (int) $row['id'])->update(['status' => $p['status'], 'reviewer_id' => $adminId,
'review_note' => $p['note'], 'reviewed_at' => $now, 'updated_at' => $now]);
@@ -243,6 +240,14 @@ final class AssistantServiceAlert
$state['source_version'] = 3;
$state['next_scan_at'] = 0;
}
$tenant = WecomArchiveScope::tenant();
if (($state['wecom_tenant'] ?? null) !== $tenant) {
$state['wecom_tenant'] = $tenant;
$state['wecom_cursor'] = '';
$state['wording_cursor'] = '';
$state['wording_next_at'] = 0;
$state['next_scan_at'] = 0;
}
$wording = $this->analyzeWording($state, $now);
$counts['created'] += $wording['created'];
if ((int) ($state['next_scan_at'] ?? 0) > $now && ($state['state'] ?? '') !== 'error') {
@@ -329,6 +334,7 @@ final class AssistantServiceAlert
/** @param array<string,mixed> $state @param array<int,string> $speakers @param array{scanned:int,created:int} $counts */
private function scanWecom(array &$state, array $speakers, int $now, int $limit, array &$counts): void
{
if (WecomArchiveScope::tenant() === '') { return; }
$cursor = (string) ($state['wecom_cursor'] ?? '');
for ($round = 0; $round < 100; $round++) {
$page = $this->wecomPage($cursor, $limit);
@@ -407,7 +413,7 @@ final class AssistantServiceAlert
if ($staffId <= 0 && $staffName === '') { return; }
if ($patientId <= 0 && $patientName === '') { return; }
foreach (self::hits($text) as $hit) {
$identity = ['channel' => $channel, 'source_id' => $sourceId, 'source_key' => $sourceKey, 'rule_code' => $hit['code']];
$identity = ['channel' => $channel, 'archive_tenant_id' => $channel === 'wecom' ? WecomArchiveScope::tenant() : '', 'source_id' => $sourceId, 'source_key' => $sourceKey, 'rule_code' => $hit['code']];
if (Db::name(self::TABLE)->where($identity)->find()) { continue; }
Db::name(self::TABLE)->insert($identity + ['staff_admin_id' => max(0, $staffId), 'patient_id' => max(0, $patientId),
'diagnosis_id' => $diagnosisId, 'external_staff' => $staffName, 'external_patient' => $patientName,
@@ -494,15 +500,27 @@ final class AssistantServiceAlert
private static function scoped(int $adminId, array $actor)
{
$sql = AssistantServiceAccess::patientQuery($adminId, $actor)->distinct(true)->field('d.patient_id')->buildSql();
$query = Db::name(self::TABLE)->alias('a');
if (AssistantServiceAccess::visibleStaffIds($adminId, $actor) !== null) {
return $query->whereRaw('a.patient_id IN ' . $sql);
}
return $query->where(static function ($nested) use ($sql): void {
$nested->whereRaw('a.patient_id IN ' . $sql)->whereOr(static function ($open): void {
$open->where('a.patient_id', 0)->where('a.channel', 'wecom');
$tenant = WecomArchiveScope::tenant();
$visible = AssistantServiceAccess::visibleStaffIds($adminId, $actor);
$query = Db::name(self::TABLE)->alias('a')->where(static function ($scope) use ($tenant, $visible): void {
$scope->where('a.channel', '<>', 'wecom');
if ($tenant === '') { return; }
$scope->whereOr(static function ($wecom) use ($tenant, $visible): void {
$wecom->where('a.channel', 'wecom')->where('a.archive_tenant_id', $tenant);
if ($visible !== null) {
if (!$visible) { $wecom->whereRaw('1=0'); }
else { $wecom->whereIn('a.staff_admin_id', $visible); }
}
});
});
return $query->where(static function ($patients) use ($sql, $visible): void {
$patients->whereRaw('a.patient_id IN ' . $sql);
if ($visible === null) {
$patients->whereOr(static function ($open): void {
$open->where('a.patient_id', 0)->where('a.channel', 'wecom');
});
}
});
}
private static function count($query, array $where): int
@@ -580,14 +598,6 @@ final class AssistantServiceAlert
return $names;
}
private static function visible(array $row, int $adminId, array $actor): bool
{
if ((int) $row['patient_id'] === 0 && (string) $row['channel'] === 'wecom') {
return AssistantServiceAccess::visibleStaffIds($adminId, $actor) === null;
}
return (bool) AssistantServiceAccess::patientQuery($adminId, $actor)->where('d.patient_id', (int) $row['patient_id'])->find();
}
private static function label(string $code): string
{
foreach (self::RULES as $rule) { if ($rule['code'] === $code) { return $rule['label']; } }
@@ -596,7 +606,7 @@ final class AssistantServiceAlert
private static function alertReady(): bool
{
return self::readable(self::TABLE, 'id,staff_admin_id,patient_id,diagnosis_id,channel,source_id,source_key,external_staff,external_patient,rule_code,rule_version,severity,snippet,status,reviewer_id,review_note,reviewed_at,occurred_at,created_at,updated_at');
return self::readable(self::TABLE, 'id,staff_admin_id,patient_id,diagnosis_id,channel,source_id,source_key,archive_tenant_id,external_staff,external_patient,rule_code,rule_version,severity,snippet,status,reviewer_id,review_note,reviewed_at,occurred_at,created_at,updated_at');
}
private static function imReady(): bool
@@ -628,6 +638,9 @@ final class AssistantServiceAlert
if (WecomArchiveSqlite::configured()) { return ['status' => 'available', 'note' => '本地企微归档只记员工发出的文字;对不上患者时仍保留会话名']; }
if (WecomArchiveHttp::configured()) { return ['status' => 'available', 'note' => '线上企微归档只记员工发出的文字;对不上患者时仍保留会话名']; }
$base = rtrim((string) config('assistant_service.wecom_archive_base_url', ''), '/');
if (($base !== '' || (string) config('assistant_service.wecom_archive_sqlite', '') !== '') && WecomArchiveScope::tenant() === '') {
return ['status' => 'not_connected', 'note' => '请配置本业务实例对应的归档租户'];
}
if ($base !== '') { return ['status' => 'not_connected', 'note' => '企微聊天归档地址已填写,还缺连接令牌']; }
return ['status' => 'not_connected', 'note' => '企微聊天归档尚未接入'];
}
@@ -739,7 +752,7 @@ final class AssistantServiceAlert
if ($staffId <= 0 && $staffName === '') { return 0; }
if ($patientId <= 0 && $patientName === '') { return 0; }
if ($staffId > 0 && !isset(self::speakers()[$staffId])) { return 0; }
$identity = ['channel' => 'wecom', 'source_id' => 0, 'source_key' => $sourceKey, 'rule_code' => 'inappropriate_wording'];
$identity = ['channel' => 'wecom', 'archive_tenant_id' => WecomArchiveScope::tenant(), 'source_id' => 0, 'source_key' => $sourceKey, 'rule_code' => 'inappropriate_wording'];
if (Db::name(self::TABLE)->where($identity)->find()) { return 0; }
$occurred = (int) ($item['sent_at_epoch'] ?? 0);
if ($occurred <= 0) { $occurred = self::epoch((string) ($item['sent_at'] ?? '')); }
@@ -769,6 +782,7 @@ final class AssistantServiceAlert
try {
if (!flock($handle, LOCK_EX)) { throw new RuntimeException('ALERT_STORAGE'); }
$json = json_encode(['cursor' => (int) ($state['cursor'] ?? 0), 'call_cursor' => (int) ($state['call_cursor'] ?? 0),
'wecom_tenant' => (string) ($state['wecom_tenant'] ?? ''),
'wecom_cursor' => substr((string) ($state['wecom_cursor'] ?? ''), 0, 200),
'wording_cursor' => substr((string) ($state['wording_cursor'] ?? ''), 0, 200),
'wording_next_at' => (int) ($state['wording_next_at'] ?? 0),
@@ -11,7 +11,7 @@ final class WecomArchiveHttp
{
public static function configured(): bool
{
return self::base() !== '' && self::token() !== '';
return WecomArchiveScope::tenant() !== '' && self::base() !== '' && self::token() !== '';
}
/** @return list<array{external_id:string,name:string,conversations:int}> */
@@ -74,28 +74,56 @@ final class WecomArchiveHttp
{
$base = self::base();
$token = self::token();
if ($base === '' || $token === '') { throw new RuntimeException('WECOM_ARCHIVE'); }
$tenant = WecomArchiveScope::tenant();
if ($tenant === '' || $base === '' || $token === '') { throw new RuntimeException('WECOM_ARCHIVE'); }
$url = $base . $path;
if ($query) { $url .= '?' . http_build_query($query); }
$handle = curl_init($url);
if ($handle === false) { throw new RuntimeException('WECOM_ARCHIVE'); }
curl_setopt_array($handle, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => ['Accept: application/json', 'X-Archive-Feed-Token: ' . $token]]);
$body = curl_exec($handle);
$code = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$attestedTenants = [];
$inHeaders = false;
$readHeader = static function ($handle, string $line) use (&$attestedTenants, &$inHeaders): int {
// CONNECT 和 1xx 可先于最终响应,租户声明只认最后一组响应头。
if (preg_match('/\AHTTP\/\S+\s+\d{3}\b/i', $line)) {
$attestedTenants = [];
$inHeaders = true;
} elseif (rtrim($line, "\r\n") === '') {
$inHeaders = false;
} elseif (stripos($line, 'X-Archive-Tenant:') === 0) {
$attestedTenants[] = $inHeaders ? trim(substr($line, strlen('X-Archive-Tenant:')), " \t\r\n") : '';
}
return strlen($line);
};
$options = [CURLOPT_HEADERFUNCTION => $readHeader, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => ['Accept: application/json', 'X-Archive-Feed-Token: ' . $token, 'X-Archive-Tenant: ' . $tenant]];
if (parse_url($base, PHP_URL_SCHEME) === 'http') { $options[CURLOPT_PROXY] = ''; }
try {
if (!curl_setopt_array($handle, $options)) { throw new RuntimeException('WECOM_ARCHIVE'); }
$body = curl_exec($handle);
$code = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
} finally { curl_close($handle); }
if ($code !== 200 || $attestedTenants !== [$tenant]) { throw new RuntimeException('WECOM_ARCHIVE'); }
$json = is_string($body) ? json_decode($body, true) : null;
if ($code !== 200 || !is_array($json)) { throw new RuntimeException('WECOM_ARCHIVE'); }
if (!is_array($json)) { throw new RuntimeException('WECOM_ARCHIVE'); }
return $json;
}
private static function base(): string
{
return rtrim((string) config('assistant_service.wecom_archive_base_url', ''), '/');
$url = rtrim((string) config('assistant_service.wecom_archive_base_url', ''), '/');
if ($url === '' || str_contains($url, '\\') || preg_match('/[\x00-\x20\x7f]/', $url)) { return ''; }
$parts = parse_url($url);
if (!$parts || empty($parts['host']) || isset($parts['user']) || isset($parts['pass'])
|| isset($parts['query']) || isset($parts['fragment'])) { return ''; }
$scheme = $parts['scheme'] ?? '';
if ($scheme === 'https') { return $url; }
$local = in_array(strtolower($parts['host']), ['localhost', '127.0.0.1', '[::1]'], true);
return $scheme === 'http' && $local ? $url : '';
}
private static function token(): string
{
return trim((string) config('assistant_service.wecom_archive_token', ''));
$token = (string) config('assistant_service.wecom_archive_token', '');
return preg_match('/\A[\x21-\x7e]{32,512}\z/D', $token) === 1 ? $token : '';
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace app\common\service\assistantservice;
use think\facade\Db;
final class WecomArchiveScope
{
/** 当前业务实例关联的归档租户,仅接受服务端配置。 */
public static function tenant(): string
{
$tenant = (string) config('assistant_service.wecom_archive_tenant', '');
return preg_match('/\A[A-Za-z0-9_-]{1,64}\z/D', $tenant) === 1 ? $tenant : '';
}
/** 企业微信账号必须唯一归属有效员工。重复、停用及未绑定账号不能授权。 */
public static function accountOwners(): array
{
$owners = [];
$rows = Db::name('admin')->whereNull('delete_time')
->field('id,work_wechat_userid,root,disable')->select()->toArray();
foreach ($rows as $row) {
$account = trim((string) $row['work_wechat_userid']);
if ($account === '') { continue; }
$owners[$account] = isset($owners[$account]) || (int) $row['root'] || (int) $row['disable']
? 0 : (int) $row['id'];
}
return $owners;
}
}
@@ -12,15 +12,15 @@ final class WecomArchiveSqlite
public static function configured(): bool
{
$path = (string) config('assistant_service.wecom_archive_sqlite', '');
return $path !== '' && is_file($path);
return WecomArchiveScope::tenant() !== '' && $path !== '' && is_file($path);
}
/** @return array{configured:bool,items:array<int,array<string,mixed>>,next_cursor:string,has_more:bool} */
public static function page(string $cursor, int $limit): array
{
$empty = ['configured' => true, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false];
$path = (string) config('assistant_service.wecom_archive_sqlite', '');
if ($path === '' || !is_file($path)) { return ['configured' => false, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false]; }
$pdo = self::connection();
if (!$pdo) { return ['configured' => false, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false]; }
$limit = max(1, min(200, $limit));
$cursorTime = '';
$cursorId = '';
@@ -29,16 +29,16 @@ final class WecomArchiveSqlite
if (count($parts) !== 2) { return $empty; }
[$cursorTime, $cursorId] = $parts;
}
$pdo = new \PDO('sqlite:' . $path, null, null, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
$sql = "SELECT m.id, substr(m.content,1,8000) AS content, m.sent_at, m.sent_at_epoch,
a.display_name AS staff_name, c.name AS patient_name
a.external_account_id, a.display_name AS staff_name, c.name AS patient_name,
c.id AS conversation_id, c.conversation_type, c.source_account_id
FROM archive_message m
JOIN archive_conversation c ON c.id = m.conversation_id
JOIN archive_source_account a ON a.id = m.source_account_id
WHERE m.direction = 'outbound' AND m.status = 'normal'
JOIN archive_conversation c ON c.id = m.conversation_id AND c.tenant_id = m.tenant_id AND c.source_account_id = m.source_account_id
JOIN archive_source_account a ON a.id = m.source_account_id AND a.tenant_id = m.tenant_id
WHERE m.tenant_id = ? AND m.direction = 'outbound' AND m.status = 'normal'
AND m.message_type IN ('text','文本') AND length(trim(m.content)) > 0
AND c.conversation_type IN ('direct_wechat','direct_wecom','group')";
$params = [];
$params = [WecomArchiveScope::tenant()];
if ($cursor !== '') {
$sql .= ' AND (m.sent_at, m.id) > (?, ?)';
$params[] = $cursorTime;
@@ -51,6 +51,11 @@ final class WecomArchiveSqlite
$hasMore = count($rows) > $limit;
if ($hasMore) { array_pop($rows); }
if (!$rows) { return $empty; }
$bindings = self::patientBindings($pdo, $rows);
foreach ($rows as &$row) {
$row += $bindings[$row['conversation_id']] ?? [];
}
unset($row);
$items = self::identify($rows);
$last = $rows[count($rows) - 1];
return ['configured' => true, 'items' => $items, 'has_more' => $hasMore,
@@ -60,21 +65,26 @@ final class WecomArchiveSqlite
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
public static function identify(array $rows): array
{
$staff = self::staffByUniqueName();
$patients = self::patientByUniqueName();
$staff = WecomArchiveScope::accountOwners();
$patientIds = array_values(array_filter(array_unique(array_map('intval', array_column($rows, 'patient_id')))));
$diagnoses = $patientIds ? Db::name('tcm_diagnosis')->whereNull('delete_time')->where('status', 1)
->whereIn('patient_id', $patientIds)->field('id,patient_id')->select()->toArray() : [];
$patients = [];
foreach ($diagnoses as $diagnosis) { $patients[(int) $diagnosis['patient_id']][(int) $diagnosis['id']] = true; }
$items = [];
foreach ($rows as $row) {
if (!is_array($row)) { continue; }
$staffName = trim((string) ($row['staff_name'] ?? ''));
$patientName = trim((string) ($row['patient_name'] ?? ''));
$person = $staff[$staffName] ?? 0;
$patient = $patients[$patientName] ?? ['patient_id' => 0, 'diagnosis_id' => 0];
$person = $staff[(string) ($row['external_account_id'] ?? '')] ?? 0;
$patientId = (int) ($row['patient_id'] ?? 0);
$diagnosisId = (int) ($row['diagnosis_id'] ?? 0);
$items[] = [
'id' => (string) ($row['id'] ?? ''),
'sent_at' => (string) ($row['sent_at'] ?? ''),
'sent_at_epoch' => (int) ($row['sent_at_epoch'] ?? 0),
'patient_id' => (int) $patient['patient_id'],
'diagnosis_id' => (int) $patient['diagnosis_id'],
'patient_id' => isset($patients[$patientId]) ? $patientId : 0,
'diagnosis_id' => isset($patients[$patientId][$diagnosisId]) ? $diagnosisId : 0,
'zyt_user_id' => (string) $person,
'staff_name' => $staffName,
'patient_name' => $patientName,
@@ -84,33 +94,33 @@ final class WecomArchiveSqlite
return $items;
}
/** @return array<string,int> */
private static function staffByUniqueName(): array
/** 仅接受同租户单聊中唯一入站对方的唯一有效主绑定。旧库没有绑定表时保留未归属。 */
private static function patientBindings(\PDO $pdo, array $rows): array
{
$map = [];
$rows = Db::name('admin')->where('root', 0)->where('disable', 0)->whereNull('delete_time')
->field('name, MIN(id) AS id, COUNT(*) AS people')->group('name')->select()->toArray();
$ids = [];
foreach ($rows as $row) {
$name = trim((string) ($row['name'] ?? ''));
if ($name !== '' && (int) $row['people'] === 1) { $map[$name] = (int) $row['id']; }
}
return $map;
}
/** @return array<string,array{patient_id:int,diagnosis_id:int}> */
private static function patientByUniqueName(): array
{
$map = [];
$rows = Db::name('tcm_diagnosis')->whereNull('delete_time')->where('status', 1)
->field('patient_name, MIN(patient_id) AS patient_id, MIN(id) AS diagnosis_id, COUNT(DISTINCT patient_id) AS people')
->group('patient_name')->select()->toArray();
foreach ($rows as $row) {
$name = trim((string) ($row['patient_name'] ?? ''));
if ($name !== '' && (int) $row['people'] === 1) {
$map[$name] = ['patient_id' => (int) $row['patient_id'], 'diagnosis_id' => (int) $row['diagnosis_id']];
if (in_array($row['conversation_type'], ['direct_wechat', 'direct_wecom'], true)) {
$ids[] = $row['conversation_id'];
}
}
return $map;
if (!$ids || !$pdo->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='archive_patient_binding'")->fetchColumn()) { return []; }
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$statement = $pdo->prepare("WITH peer AS (
SELECT m.tenant_id, m.conversation_id, MIN(m.sender_person_id) AS person_id
FROM archive_message m
JOIN archive_conversation c ON c.id = m.conversation_id AND c.tenant_id = m.tenant_id AND c.source_account_id = m.source_account_id
WHERE m.tenant_id = ? AND m.direction = 'inbound' AND m.conversation_id IN ($placeholders)
GROUP BY m.tenant_id, m.conversation_id
HAVING COUNT(*) = COUNT(NULLIF(m.sender_person_id, '')) AND COUNT(DISTINCT m.sender_person_id) = 1
)
SELECT peer.conversation_id, MIN(b.patient_id) AS patient_id, MIN(b.diagnosis_id) AS diagnosis_id
FROM peer
JOIN archive_person p ON p.id = peer.person_id AND p.tenant_id = peer.tenant_id
JOIN archive_patient_binding b ON b.tenant_id = peer.tenant_id AND b.person_id = peer.person_id
WHERE b.status = 'active' AND b.is_primary = 1
GROUP BY peer.conversation_id HAVING COUNT(*) = 1");
$statement->execute(array_merge([WecomArchiveScope::tenant()], $ids));
return $statement->fetchAll(\PDO::FETCH_UNIQUE | \PDO::FETCH_ASSOC);
}
/** @return list<array{external_id:string,name:string,conversations:int}> */
@@ -118,11 +128,14 @@ final class WecomArchiveSqlite
{
$pdo = self::connection();
if (!$pdo) { return []; }
$rows = $pdo->query("SELECT a.external_account_id, a.display_name, COUNT(c.id) AS conversations
$statement = $pdo->prepare("SELECT a.external_account_id, a.display_name, COUNT(c.id) AS conversations
FROM archive_source_account a
LEFT JOIN archive_conversation c ON c.source_account_id = a.id
LEFT JOIN archive_conversation c ON c.source_account_id = a.id AND c.tenant_id = a.tenant_id
WHERE a.tenant_id = ?
GROUP BY a.external_account_id, a.display_name
ORDER BY conversations DESC, a.external_account_id")->fetchAll(\PDO::FETCH_ASSOC);
ORDER BY conversations DESC, a.external_account_id");
$statement->execute([WecomArchiveScope::tenant()]);
$rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
$accounts = [];
foreach ($rows as $row) {
$accounts[] = ['external_id' => (string) $row['external_account_id'], 'name' => trim((string) $row['display_name']),
@@ -136,37 +149,24 @@ final class WecomArchiveSqlite
{
$pdo = self::connection();
if (!$pdo || $externalId === '') { return []; }
$statement = $pdo->prepare("SELECT c.id, c.name, c.conversation_type, c.last_message_at
$statement = $pdo->prepare("SELECT c.id, c.name, c.conversation_type, c.last_message_at,
(SELECT COUNT(*) FROM archive_message m WHERE m.tenant_id = c.tenant_id
AND m.conversation_id = c.id AND m.source_account_id = c.source_account_id) AS message_count,
(SELECT substr(m.content, 1, 80) FROM archive_message m WHERE m.tenant_id = c.tenant_id
AND m.conversation_id = c.id AND m.source_account_id = c.source_account_id
ORDER BY m.sent_at DESC, m.id DESC LIMIT 1) AS preview
FROM archive_conversation c
JOIN archive_source_account a ON a.id = c.source_account_id
WHERE a.external_account_id = ?
JOIN archive_source_account a ON a.id = c.source_account_id AND a.tenant_id = c.tenant_id
WHERE c.tenant_id = ? AND a.external_account_id = ?
ORDER BY c.last_message_at DESC, c.id DESC LIMIT 100");
$statement->execute([$externalId]);
$statement->execute([WecomArchiveScope::tenant(), $externalId]);
$rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
if (!$rows) { return []; }
$ids = array_map(static fn (array $row): string => (string) $row['id'], $rows);
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$counts = $pdo->prepare("SELECT conversation_id, COUNT(*) AS message_count FROM archive_message
WHERE conversation_id IN ($placeholders) GROUP BY conversation_id");
$counts->execute($ids);
$countById = [];
foreach ($counts->fetchAll(\PDO::FETCH_ASSOC) as $row) { $countById[(string) $row['conversation_id']] = (int) $row['message_count']; }
$latest = $pdo->prepare("SELECT conversation_id, MAX(sent_at) AS sent_at FROM archive_message
WHERE conversation_id IN ($placeholders) GROUP BY conversation_id");
$latest->execute($ids);
$previewById = [];
$preview = $pdo->prepare("SELECT substr(content, 1, 80) AS preview FROM archive_message
WHERE conversation_id = ? AND sent_at = ? ORDER BY id DESC LIMIT 1");
foreach ($latest->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$preview->execute([(string) $row['conversation_id'], (string) $row['sent_at']]);
$previewById[(string) $row['conversation_id']] = trim((string) ($preview->fetchColumn() ?: ''));
}
$items = [];
foreach ($rows as $row) {
$id = (string) $row['id'];
$items[] = ['id' => $id, 'name' => self::plainText((string) $row['name']),
'conversation_type' => (string) $row['conversation_type'], 'last_message_at' => (string) $row['last_message_at'],
'message_count' => $countById[$id] ?? 0, 'preview' => self::plainText($previewById[$id] ?? '')];
'message_count' => (int) $row['message_count'], 'preview' => self::plainText((string) $row['preview'])];
}
return $items;
}
@@ -176,18 +176,19 @@ final class WecomArchiveSqlite
{
$pdo = self::connection();
if (!$pdo || $conversationId === '') { return ['account' => '', 'messages' => []]; }
$account = $pdo->prepare("SELECT a.external_account_id FROM archive_conversation c
JOIN archive_source_account a ON a.id = c.source_account_id WHERE c.id = ?");
$account->execute([$conversationId]);
$externalId = (string) ($account->fetchColumn() ?: '');
$account = $pdo->prepare("SELECT a.external_account_id, a.id FROM archive_conversation c
JOIN archive_source_account a ON a.id = c.source_account_id AND a.tenant_id = c.tenant_id WHERE c.tenant_id = ? AND c.id = ?");
$account->execute([WecomArchiveScope::tenant(), $conversationId]);
$source = $account->fetch(\PDO::FETCH_ASSOC);
$externalId = (string) ($source['external_account_id'] ?? '');
if ($externalId === '') { return ['account' => '', 'messages' => []]; }
$statement = $pdo->prepare("SELECT m.id, m.sent_at, m.direction, m.message_type, substr(m.content, 1, 2000) AS content,
COALESCE(p.display_name, '') AS sender_name
FROM archive_message m
LEFT JOIN archive_person p ON p.id = m.sender_person_id
WHERE m.conversation_id = ?
LEFT JOIN archive_person p ON p.id = m.sender_person_id AND p.tenant_id = m.tenant_id
WHERE m.tenant_id = ? AND m.conversation_id = ? AND m.source_account_id = ?
ORDER BY m.sent_at ASC, m.id ASC LIMIT 200");
$statement->execute([$conversationId]);
$statement->execute([WecomArchiveScope::tenant(), $conversationId, $source['id']]);
$messages = [];
foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$messages[] = ['id' => (string) $row['id'], 'sent_at' => (string) $row['sent_at'], 'direction' => (string) $row['direction'],
@@ -207,8 +208,10 @@ final class WecomArchiveSqlite
private static function connection(): ?\PDO
{
$path = (string) config('assistant_service.wecom_archive_sqlite', '');
if ($path === '' || !is_file($path)) { return null; }
$pdo = new \PDO('sqlite:' . $path, null, null, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
return $pdo;
if (!self::configured()) { return null; }
return new \PDO('sqlite:' . $path, null, null, [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::SQLITE_ATTR_OPEN_FLAGS => \PDO::SQLITE_OPEN_READONLY,
]);
}
}
@@ -27,8 +27,9 @@ final class DoctorEsignIdentityService
public static function quickEnabled(): bool
{
return PrescriptionEsignService::enabled()
&& filter_var(Config::get('esign.doctor_quicksign_enabled', false), FILTER_VALIDATE_BOOLEAN);
$managed = PrescriptionCaSigningSettings::override();
return $managed ?? (PrescriptionEsignService::enabled()
&& filter_var(Config::get('esign.doctor_quicksign_enabled', false), FILTER_VALIDATE_BOOLEAN));
}
public static function status(int $actor): array
@@ -61,7 +62,13 @@ final class DoctorEsignIdentityService
return $pending;
}
}
$state = self::readiness($client, $snapshot, true, $quick === null)['state'];
$state = self::readiness(
$client,
$snapshot,
allowCertificateRecovery: true,
requireMobile: $quick === null,
reportUnconfirmedCertificate: true
)['state'];
if (isset($status) && $state['status'] !== 'ready') {
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
}
@@ -75,14 +82,14 @@ final class DoctorEsignIdentityService
self::assertUnchanged($scope, $quick);
}
self::assertUnchanged($scope, $snapshot);
return $state;
return $state + self::reviewerNameEntry($snapshot);
}
public static function start(int $actor, string $mobile): array
public static function start(int $actor, string $mobile, ?string $signerName = null): array
{
$scope = self::scope($actor);
$mobile = trim($mobile);
if (self::quickEnabled() && $mobile === '') {
if (self::quickEnabled() && $mobile === '' && $signerName === null) {
return self::startQuick($scope);
}
if (!self::validMobile($mobile)) {
@@ -90,15 +97,30 @@ final class DoctorEsignIdentityService
}
$mobileHash = self::mobileHash($scope, $mobile);
$snapshot = self::snapshot($scope);
$name = $snapshot['name'];
if ($signerName !== null) {
if (!self::reviewerNameEntry($snapshot)) {
throw new DomainException('仅未绑定签署身份的审核人可填写证件姓名');
}
$name = trim($signerName);
if (!preg_match('/^[\p{Han}A-Za-z][\p{Han}A-Za-z·()\-]{1,49}$/uD', $name)) {
throw new DomainException('请输入与本人证件一致的姓名');
}
}
if (self::hasLease($snapshot['flow'])) {
return self::processing();
}
$client = new EsignClient();
if (self::hasCurrentFlow($snapshot) && hash_equals($snapshot['flow']['mobile_hash'], $mobileHash)) {
$flow = $snapshot['flow'];
$sameSubject = $flow && $name === $snapshot['name'] && hash_equals($flow['mobile_hash'], $mobileHash);
if (self::hasCurrentFlow($snapshot) && ($sameSubject || $signerName !== null)) {
[$status, $person] = self::identityResult($client, $snapshot);
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
// A verified flow must finish binding under the name the provider verified.
if ($sameSubject || $status === 'SUCCESS') {
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
}
}
}
$state = self::readiness($client, $snapshot, true, !self::quickEnabled())['state'];
@@ -110,16 +132,17 @@ final class DoctorEsignIdentityService
$token = self::claim($scope, $snapshot);
try {
$accountId = $snapshot['account']['account_id'] ?? null;
$flow = $client->startDoctorIdentity($snapshot['name'], 'doctor-enrollment-' . $token, $mobile, $accountId);
$flow = $client->startDoctorIdentity($name, 'doctor-enrollment-' . $token, $mobile, $accountId);
self::finish($scope, $snapshot, $token, [
'doctor_name' => $snapshot['name'],
'doctor_name' => $name,
'account_id' => $accountId ?? '',
'flow_id' => $flow['flow_id'],
'auth_url' => $flow['auth_url'],
'mobile_hash' => $mobileHash,
'flow_started_at' => time(),
]);
return self::state('authenticating', '请完成医师实名认证') + ['auth_url' => $flow['auth_url']];
return self::state('authenticating', '请完成医师实名认证') + ['auth_url' => $flow['auth_url']]
+ self::reviewerNameEntry($snapshot);
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
@@ -281,7 +304,7 @@ final class DoctorEsignIdentityService
$token = self::claim($scope, $snapshot);
try {
$client = new EsignClient();
[$status, $person, $completedAt] = self::identityResult($client, $snapshot);
[$status, $person] = self::identityResult($client, $snapshot);
if ($status === 'INIT' || $status === 'ING') {
self::finish($scope, $snapshot, $token, []);
return self::pendingState($snapshot, $status, false);
@@ -293,8 +316,8 @@ final class DoctorEsignIdentityService
self::finish($scope, $snapshot, $token, null);
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
}
$providerExpiry = intdiv($client->willingnessValidity($snapshot['flow']['flow_id'])['expires_at'], 1000);
$expires = min($providerExpiry, min(time(), $completedAt) + self::QUICK_LIFETIME);
// 授权有效期以 e签宝返回为准(快捷签授权通常为 30 天)
$expires = intdiv($client->willingnessValidity($snapshot['flow']['flow_id'])['expires_at'], 1000);
}
if ($expires <= time()) {
self::finish($scope, $snapshot, $token, null);
@@ -367,32 +390,46 @@ final class DoctorEsignIdentityService
return ['name' => $signerName, 'idNo' => $ready['idNo'], 'mobile' => $ready['mobile']];
}
private static function readiness(EsignClient $client, array $snapshot, bool $allowCertificateRecovery = false, bool $requireMobile = true): array
{
private static function readiness(
EsignClient $client,
array $snapshot,
bool $allowCertificateRecovery = false,
bool $requireMobile = true,
bool $reportUnconfirmedCertificate = false
): array {
if (!$snapshot['account']) {
return ['state' => self::state('unbound', '请先完成医师实名认证')];
}
$idNo = self::accountDocument($client, $snapshot);
try {
[$start, $end] = self::certificatePeriod($client, $snapshot['account']['account_id']);
} catch (EsignProviderException $error) {
// The SDK does not define a distinct response code for no available certificate.
if (!$allowCertificateRecovery || !str_starts_with($error->providerCode, 'PROVIDER_')) {
} catch (EsignProviderException | DomainException $error) {
// A provider rejection can include the case where no certificate has been issued yet.
$allowRenewal = $allowCertificateRecovery && $error instanceof EsignProviderException
&& str_starts_with($error->providerCode, 'PROVIDER_');
if (!$reportUnconfirmedCertificate && !$allowRenewal) {
throw $error;
}
return ['state' => self::state('renewal_required', '暂时无法确认签署证书有效期,可重新查询或发起续期')];
$message = $allowRenewal ? '暂时无法确认签署证书有效期,可重新查询或发起续期' : '暂时无法确认签署证书有效期,请重新查询';
return ['state' => self::state('renewal_required', $message) + ['certificate_state' => 'unconfirmed']];
}
if ($start === 0 || $start > time() || $end <= time()) {
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
$now = time();
$valid = $start > 0 && $start <= $now && $end > $now;
$mobile = $valid && $requireMobile ? $client->authorizedMobile($snapshot['name'], $idNo) : null;
if (!$valid || $end <= time()) {
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', max(0, $end))
+ ['certificate_state' => 'renewal_required']];
}
$mobile = $requireMobile ? $client->authorizedMobile($snapshot['name'], $idNo) : null;
if ($requireMobile && !self::validMobile($mobile)) {
return ['state' => self::state('needs_mobile', '请完成实名手机号认证', $end)];
return ['state' => self::state('needs_mobile', '请完成实名手机号认证', $end) + ['certificate_state' => 'valid']];
}
if ($end <= time()) {
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
}
return ['state' => self::state('ready', '医师电子签署已就绪', $end), 'idNo' => $idNo, 'mobile' => $mobile];
return [
'state' => self::state('ready', '医师电子签署已就绪', $end) + ['certificate_state' => 'valid'],
'idNo' => $idNo,
'mobile' => $mobile,
];
}
private static function accountDocument(EsignClient $client, array $snapshot): string
@@ -415,14 +452,14 @@ final class DoctorEsignIdentityService
private static function certificatePeriod(EsignClient $client, string $accountId): array
{
$dates = $client->certificateValidity($accountId);
return [self::certificateTime($dates['startDate'] ?? ''), self::certificateTime($dates['endDate'] ?? '')];
return [self::certificateTime($dates['startDate'] ?? null), self::certificateTime($dates['endDate'] ?? null)];
}
/** SDK validity timestamps are local to the configured SDK timezone. */
private static function certificateTime(string $value): int
private static function certificateTime(mixed $value): int
{
if ($value === '') {
return 0;
if (!is_string($value) || !preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/D', $value)) {
throw new DomainException('暂时无法确认医师签署证书有效期,请稍后重试');
}
$zone = new DateTimeZone((string) Config::get('esign.sdk_timezone', 'Asia/Shanghai'));
$time = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $value, $zone);
@@ -476,7 +513,8 @@ final class DoctorEsignIdentityService
$quick = $snapshot['flow_table'] === self::QUICK_FLOW_TABLE;
if ($status === 'INIT' || $status === 'ING') {
$message = $quick ? '请完成快捷签人脸认证' : '请完成医师实名认证';
return self::state('authenticating', $message, 0, $quick) + ['auth_url' => $snapshot['flow']['auth_url']];
return self::state('authenticating', $message, 0, $quick) + ['auth_url' => $snapshot['flow']['auth_url']]
+ self::reviewerNameEntry($snapshot);
}
if ($status === 'SUCCESS') {
$needed = !$snapshot['account'] && $documentMissing;
@@ -506,18 +544,30 @@ final class DoctorEsignIdentityService
->whereNull('delete_time')->lock($lock)->value('name'));
$doctor = $actor > 0 && Db::name('admin_role')->where('admin_id', $actor)
->where('role_id', self::DOCTOR_ROLE_ID)->lock($lock)->value('admin_id');
if ($name === '' || (!$doctor && !(PrescriptionReviewEsignService::enabled()
&& PrescriptionReviewEsignService::canEnrollReviewer($actor)))) {
$reviewer = !$doctor && PrescriptionReviewEsignService::enabled()
&& PrescriptionReviewEsignService::canEnrollReviewer($actor);
if ($name === '' || (!$doctor && !$reviewer)) {
throw new DomainException('仅当前医师本人可使用医师电子签署认证');
}
$account = Db::name('doctor_esign_account')->where($scope)->lock($lock)->find();
$flow = Db::name($flowTable)->where($scope)->lock($lock)->find();
$name = PrescriptionEsignService::configuredSignerName(['doctor_name' => $name], $actor);
if ($reviewer) {
// Reviewers can have a display name unrelated to the legal name in the certificate.
$name = $account['doctor_name'] ?? (($flow['doctor_name'] ?? '') ?: $name);
}
return [
'name' => PrescriptionEsignService::configuredSignerName(['doctor_name' => $name], $actor),
'account' => Db::name('doctor_esign_account')->where($scope)->lock($lock)->find(),
'flow' => Db::name($flowTable)->where($scope)->lock($lock)->find(),
'flow_table' => $flowTable,
'name' => $name, 'account' => $account, 'flow' => $flow, 'flow_table' => $flowTable,
'reviewer' => $reviewer,
];
}
private static function reviewerNameEntry(array $snapshot): array
{
return $snapshot['reviewer'] && !$snapshot['account'] && $snapshot['flow_table'] === self::IDENTITY_FLOW_TABLE
? ['can_edit_signer_name' => true] : [];
}
private static function hasCurrentFlow(array $snapshot): bool
{
$flow = $snapshot['flow'];
@@ -96,7 +96,10 @@ final class EsignClient
public function __construct(?array $configuration = null, ?callable $transport = null, ?callable $clock = null)
{
$this->configuration = $configuration ?? (array) \think\facade\Config::get('esign', []);
$this->configuration = $configuration ?? array_replace(
(array) \think\facade\Config::get('esign', []),
['enabled' => PrescriptionEsignService::enabled()]
);
$this->transport = $transport !== null ? Closure::fromCallable($transport) : Closure::fromCallable([self::class, 'curlTransport']);
$this->clock = $clock !== null ? Closure::fromCallable($clock) : static fn (): int => (int) floor(microtime(true) * 1000);
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use app\common\service\ConfigService;
use DomainException;
use think\facade\Config;
use think\facade\Db;
final class PrescriptionCaSigningSettings
{
private const TYPE = 'esign';
private const NAME = 'ca_signing_enabled';
private const REQUEST_KEY = 'prescription_ca_signing_settings';
public static function override(): ?bool
{
$request = PHP_SAPI !== 'cli' ? request() : null;
$cached = $request?->middleware(self::REQUEST_KEY);
if (is_array($cached)) {
return $cached['enabled'];
}
$stored = ConfigService::get(self::TYPE, self::NAME, '');
$enabled = in_array($stored, [0, '0', 1, '1'], true) ? (bool) $stored : null;
$request?->withMiddleware([self::REQUEST_KEY => ['enabled' => $enabled]]);
return $enabled;
}
public static function setEnabled(bool $enabled, int $actor): void
{
Db::transaction(static function () use ($enabled, $actor): void {
// Serialize the first write as well as updates, since the shared config table
// does not require a unique type/name key.
$admins = Db::name('admin')->where('root', 1)->where('disable', 0)->whereNull('delete_time')
->order('id')->lock(true)->column('id');
if (!in_array($actor, array_map('intval', $admins), true)) {
throw new DomainException('仅超级管理员可以修改 CA 签名设置');
}
if ($enabled) {
$config = (array) Config::get('esign', []);
try {
(new EsignClient(array_replace($config, ['enabled' => true])))->assertConfigured();
} catch (EsignProviderException $error) {
throw new DomainException('请先检查 e签宝应用、SDK 地址和 CA 证书配置(' . $error->providerCode . ')');
}
}
ConfigService::set(self::TYPE, self::NAME, (int) $enabled);
});
if (PHP_SAPI !== 'cli') {
request()->withMiddleware([self::REQUEST_KEY => ['enabled' => $enabled]]);
}
}
}
@@ -70,6 +70,43 @@ final class PrescriptionEsignPolicy
}
}
public static function isPendingReview(array $row): bool
{
return in_array($row['audit_status'] ?? null, [0, '0'], true)
&& empty($row['void_status']) && empty($row['delete_time']);
}
public static function isAwaitingUpload(array $row): bool
{
return self::isPendingReview($row) && empty($row['review_submitted_at']);
}
public static function hasPrescriptionContent(array $row): bool
{
$herbs = $row['herbs'] ?? null;
if (is_string($herbs)) {
$herbs = json_decode($herbs, true);
}
return empty($row['is_system_auto']) && is_array($herbs) && $herbs !== [];
}
public static function isSubmittedForReview(array $row): bool
{
if (empty($row['id']) || !empty($row['void_status']) || !empty($row['delete_time'])) {
return false;
}
// Already approved prescriptions may still enter the business-order audit flow.
return in_array($row['audit_status'] ?? null, [1, '1'], true)
|| (self::isPendingReview($row) && (int) ($row['review_submitted_at'] ?? 0) > 0);
}
public static function assertReviewReady(array $row): void
{
if (!self::isSubmittedForReview($row)) {
throw new DomainException('请开方医生先上传处方,再进行审核');
}
}
public static function assertSigner(array $row, int $actor): void
{
if ($actor <= 0 || (int) ($row['creator_id'] ?? 0) !== $actor) {
@@ -20,10 +20,12 @@ final class PrescriptionEsignService
private const SMS_SEND_COOLDOWN_SECONDS = 60;
private const SMS_CODE_SECONDS = 900;
private const SMS_MAX_ATTEMPTS = 3;
private const REVIEW_SEAL_MAX_BYTES = 128 * 1024;
public static function enabled(): bool
{
return filter_var(Config::get('esign.enabled', false), FILTER_VALIDATE_BOOLEAN);
return PrescriptionCaSigningSettings::override()
?? filter_var(Config::get('esign.enabled', false), FILTER_VALIDATE_BOOLEAN);
}
public static function capability(): array
@@ -34,11 +36,10 @@ final class PrescriptionEsignService
+ ($enabled && self::usesDoctorQuick() ? ['verification_method' => 'quick'] : []);
}
private static function requiresSignature(array $row, bool $enabled): bool
public static function requiresSignature(array $row, bool $enabled): bool
{
return !empty($row['esign_required']) || ($enabled && ($row['esign_status'] ?? 'legacy') === 'legacy'
&& in_array($row['audit_status'] ?? null, [0, '0'], true)
&& empty($row['void_status']) && empty($row['delete_time']));
&& PrescriptionEsignPolicy::isPendingReview($row));
}
public static function status(int $id, int $actor, array $adminInfo): array
@@ -47,7 +48,9 @@ final class PrescriptionEsignService
if (!$model || !PrescriptionLogic::canViewPrescription($model, $actor, $adminInfo)) {
throw new DomainException('处方不存在或无权查看');
}
return self::describe($model->toArray(), $actor);
$row = $model->toArray();
return self::describe($row, $actor, true, (int) $row['creator_id'] === $actor
&& PrescriptionLogic::canSubmitForReview($actor, $adminInfo));
}
/** Read-only polling: never bind an account, change state or consume signing authorization. */
@@ -134,7 +137,7 @@ final class PrescriptionEsignService
'identity_details_required' => $detailsRequired];
}
public static function describe(array $row, int $actor): array
public static function describe(array $row, int $actor, bool $includeDetails = false, bool $maySubmitForReview = false): array
{
$enabled = self::enabled();
$enrolled = !empty($row['esign_required']);
@@ -147,7 +150,9 @@ final class PrescriptionEsignService
}
$sameApp = !$e || self::matchesEnvironment($e);
$isCreator = $actor > 0 && (int) ($row['creator_id'] ?? 0) === $actor;
$canSign = $enabled && $required && !$voided && $sameApp && $isCreator && empty($row['is_system_auto'])
$awaitingUpload = PrescriptionEsignPolicy::isAwaitingUpload($row);
$canSign = $enabled && $required && !$voided && $sameApp && $isCreator && !empty($row['review_submitted_at'])
&& self::hasUploadContent($row, $required)
&& (!$e || (int) $e['doctor_id'] === $actor);
$rawState = $state;
$quick = self::usesDoctorQuick();
@@ -192,16 +197,20 @@ final class PrescriptionEsignService
if ($message === '' && $required && !$voided && $state !== 'signed') {
if (!$enabled) {
$message = '电子签署尚未启用,请联系管理员';
} elseif (!self::hasUploadContent($row, $required)) {
$message = '请开方医生先补全处方药品和临床诊断并保存';
} elseif ($awaitingUpload) {
$message = '请开方医生先上传处方,再进行电子签署';
} elseif (!$isCreator) {
$message = '请开方医生本人完成电子签署';
} elseif (!empty($row['is_system_auto'])) {
$message = '请先补全处方,再进行电子签署';
}
}
$labels = ['legacy' => '历史手写签名', 'pending' => '待电子签署', 'authenticating' => '待医生核身',
'signing' => '签署中', 'signed' => '已电子签署', 'failed' => '签署未完成', 'uncertain' => '签署结果待核实', 'voided' => '已作废'];
$out = [
'enabled' => $enabled, 'required' => $required, 'status' => $state,
'review_required' => !empty($e['review_required']) || ($required && !$voided
&& in_array($row['audit_status'] ?? null, [0, '0'], true) && PrescriptionReviewEsignService::enabled()),
'status_label' => $labels[$state] ?? '待电子签署',
'environment' => $e['environment'] ?? Config::get('esign.environment', 'sandbox'),
'can_sign' => $canSign && !self::hasSignatureEvidence($e ?: [])
@@ -213,6 +222,11 @@ final class PrescriptionEsignService
'signature_time_source' => (string) ($e['signature_time_source'] ?? ''),
'issued_at' => (int) ($e['issued_at'] ?? 0),
'prescription_date' => (string) ($row['prescription_date'] ?? ''),
'review_submitted_at' => (int) ($row['review_submitted_at'] ?? 0),
'awaiting_upload' => $awaitingUpload,
'can_submit_for_review' => $maySubmitForReview && $isCreator && $awaitingUpload
&& self::hasUploadContent($row, $required),
'can_review_prescription' => PrescriptionEsignPolicy::isPendingReview($row) && self::canReview($row, $e ?: null),
];
if ($canResumeIdentity && !$quick && !empty($e['auth_url'])) {
$out['auth_url'] = $e['auth_url'];
@@ -231,26 +245,68 @@ final class PrescriptionEsignService
$out['status_label'] = $quick ? '待确认签名' : '待确认签署意愿';
}
}
return $out + PrescriptionReviewEsignService::describe($e ?: null);
if ($includeDetails && $out['can_download']) {
$out['doctor_signer_name'] = self::signerName($row, $e);
}
return $out + PrescriptionReviewEsignService::describe($e ?: null, $includeDetails ? $row : null);
}
public static function assertSignedById(int $id, bool $forDispensing = false, ?int $reviewer = null): void
public static function hasUploadContent(array $row, bool $required): bool
{
return PrescriptionEsignPolicy::hasPrescriptionContent($row)
&& (!$required || trim((string) ($row['clinical_diagnosis'] ?? '')) !== '');
}
public static function canReview(array $row, ?array $evidence = null): bool
{
try {
self::assertReviewReady($row, $evidence);
return true;
} catch (DomainException | \JsonException) {
return false;
}
}
public static function assertReviewReady(array $row, ?array $evidence = null): void
{
PrescriptionEsignPolicy::assertReviewReady($row);
if (!PrescriptionEsignPolicy::isPendingReview($row) || !self::requiresSignature($row, self::enabled())) {
return;
}
if ($evidence === null && !empty($row['esign_required']) && ($row['esign_status'] ?? '') === 'signed') {
$evidence = Db::name('prescription_esign')->where('prescription_id', (int) $row['id'])->find();
}
self::assertDoctorSignature($row, $evidence);
}
private static function assertDoctorSignature(array $row, ?array $evidence, bool $forDispensing = false): void
{
// Apply the active requirement without enrolling the prescription during review.
$row['esign_required'] = 1;
PrescriptionEsignPolicy::assertSigned($row, $evidence, $forDispensing);
self::readPdf((string) $evidence['signed_path'], (string) $evidence['signed_hash']);
}
// Audit and dispatch callers retain the prescription lock through their state write.
public static function assertSignedById(int $id, bool $forDispensing = false, ?int $reviewer = null, bool $orderApproval = false): void
{
// Audit/dispatch callers retain this lock through their state write.
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
if (!$row) {
throw new DomainException('处方不存在');
}
if ($forDispensing && (!empty($row['void_status']) || !empty($row['delete_time']))) {
throw new DomainException('处方已作废或删除,不能用于履约');
}
if ($reviewer !== null) {
PrescriptionEsignPolicy::assertReviewReady($row);
}
if (!self::requiresSignature($row, self::enabled())) {
return;
}
$e = empty($row['esign_required']) ? null : Db::name('prescription_esign')->where('prescription_id', $id)->find();
// Apply the active requirement without enrolling the prescription during review.
$row['esign_required'] = 1;
PrescriptionEsignPolicy::assertSigned($row, $e ?: null, $forDispensing);
self::readPdf((string) $e['signed_path'], (string) $e['signed_hash']);
self::assertDoctorSignature($row, $e ?: null, $forDispensing);
if ($forDispensing || $reviewer !== null) {
PrescriptionReviewEsignService::assertVerified($row, $e, $reviewer);
PrescriptionReviewEsignService::assertVerified($row, $e, $reviewer, $orderApproval);
}
}
@@ -353,7 +409,9 @@ final class PrescriptionEsignService
try {
$account = self::account($actor);
if ($account && $account['doctor_name'] !== $work['signer_name']) {
throw new DomainException('医师姓名已变更,请先由管理员核实签署账号');
// 账号可能以药师审核身份绑定了另一实名,此时不能用该证书签署他人名下的处方
throw new DomainException('当前账号的签署实名为「' . $account['doctor_name'] . '」,与处方医师「'
. $work['signer_name'] . '」不一致,请使用医师本人账号开方并签署');
}
if ($work['quick']) {
$accountId = $account['account_id'] ?? '';
@@ -858,7 +916,7 @@ final class PrescriptionEsignService
private static function usesDoctorQuick(): bool
{
return filter_var(Config::get('esign.doctor_quicksign_enabled', false), FILTER_VALIDATE_BOOLEAN);
return DoctorEsignIdentityService::quickEnabled();
}
private static function isSms(array $e): bool
@@ -991,6 +1049,9 @@ final class PrescriptionEsignService
throw new DomainException('此处方不属于电子签署流程');
}
PrescriptionEsignPolicy::assertSigner($row, $actor);
if (empty($row['review_submitted_at']) && ($row['esign_status'] ?? '') !== 'signed') {
throw new DomainException('请先上传处方,再进行电子签署');
}
if (trim((string) Admin::where('id', $actor)->value('name')) !== trim((string) $row['doctor_name'])) {
throw new DomainException('医师姓名已变更,请作废原处方后重新开方');
}
@@ -1088,7 +1149,7 @@ final class PrescriptionEsignService
private static function filePath(string $relative): string
{
if (!preg_match('#^\d+-[a-f0-9]{64}/(?:source(?:-issued)?|signed|review-signed)\.pdf$#D', $relative)) {
if (!preg_match('#^\d+-[a-f0-9]{64}/(?:(?:source(?:-issued)?|signed|review-signed)\.pdf|review-seal-[a-f0-9]{64}\.png)$#D', $relative)) {
throw new DomainException('签署文件引用无效');
}
return rtrim((string) Config::get('esign.storage_path', root_path() . 'storage/esign'), '/\\') . DIRECTORY_SEPARATOR . $relative;
@@ -1099,6 +1160,32 @@ final class PrescriptionEsignService
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > 20 * 1024 * 1024) {
throw new DomainException('签署服务返回的 PDF 无效或超出大小限制');
}
self::writeArchiveFile($relative, $bytes);
}
public static function writeReviewSeal(string $relative, string $png): void
{
if (!self::isReviewSeal($png)) {
throw new DomainException('审核签章图片无效');
}
self::writeArchiveFile($relative, $png);
}
public static function readReviewSeal(string $relative): ?string
{
$path = self::filePath($relative);
$png = is_file($path) ? file_get_contents($path, false, null, 0, self::REVIEW_SEAL_MAX_BYTES + 1) : false;
return $png !== false && self::isReviewSeal($png) ? $png : null;
}
private static function isReviewSeal(string $png): bool
{
return strlen($png) <= self::REVIEW_SEAL_MAX_BYTES && str_starts_with($png, "\x89PNG\r\n\x1a\n")
&& (getimagesizefromstring($png)[2] ?? null) === IMAGETYPE_PNG;
}
private static function writeArchiveFile(string $relative, string $bytes): void
{
$path = self::filePath($relative);
$dir = dirname($path);
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
@@ -99,7 +99,7 @@ final class PrescriptionPdf
if ($index === 0) {
$stream .= self::text('医师电子签章', 420, 104, 11);
if ($review) {
$stream .= self::text('审核电子签章', 420, 59, 11);
$stream .= self::text('药师审核', 420, 59, 11);
}
}
$stream .= self::text('处方快照 SHA-256', 45, 58, 8);
@@ -19,7 +19,9 @@ final class PrescriptionReviewEsignService
public static function enabled(): bool
{
return filter_var(Config::get('esign.review_enabled', false), FILTER_VALIDATE_BOOLEAN);
$managed = PrescriptionCaSigningSettings::override();
return $managed ?? (PrescriptionEsignService::enabled()
&& filter_var(Config::get('esign.review_enabled', false), FILTER_VALIDATE_BOOLEAN));
}
/** Recheck the live personnel record and grants, including for an existing binding. */
@@ -61,7 +63,7 @@ final class PrescriptionReviewEsignService
}
/** Called under the same prescription lock as approval or dispatch. */
public static function assertVerified(array $row, array $doctor, ?int $actor): void
public static function assertVerified(array $row, array $doctor, ?int $actor, bool $orderApproval = false): void
{
// Previously approved single-signature records retain their archived evidence.
if (empty($doctor['review_required']) && !($actor !== null && self::enabled())) {
@@ -71,31 +73,159 @@ final class PrescriptionReviewEsignService
if (!self::hasVerifiedReview($doctor, $review)) {
throw new DomainException('请由另一位有审核权限的人员完成处方审核电子签署');
}
if ($actor !== null && ($actor !== (int) $review['reviewer_id'] || !self::canEnrollReviewer($actor))) {
throw new DomainException('请由已签署此处方且仍有审核权限的审核人本人提交审核');
if ($actor !== null) {
if ($orderApproval) {
if (!self::canSubmitOrderAudit(self::reviewerAccess($actor))) {
throw new DomainException('当前账号没有业务订单处方审核权限');
}
} elseif ($actor !== (int) $review['reviewer_id'] || !self::canEnrollReviewer($actor)) {
throw new DomainException('请由已签署此处方且仍有审核权限的审核人本人提交审核');
}
}
PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
}
private static function canSubmitOrderAudit(array $admin): bool
{
return $admin && PrescriptionOrderLogic::canAuditPrescriptionOrder($admin)
&& self::hasGrant($admin, [self::ORDER_PERMISSION]);
}
private static function hasVerifiedReview(array $doctor, ?array $review): bool
{
return $review && $review['state'] === 'signed' && (int) $review['reviewer_id'] > 0
&& (int) $review['reviewer_id'] !== (int) $doctor['doctor_id']
&& $review['account_id'] !== '' && $review['account_id'] !== $doctor['account_id']
&& $review['environment'] === $doctor['environment'] && $review['app_id'] === $doctor['app_id']
&& hash_equals($doctor['signed_hash'], $review['doctor_pdf_hash'])
return self::matchesDoctor($doctor, $review) && $review['state'] === 'signed'
&& $review['sign_service_id'] !== '' && $review['signed_hash'] !== ''
&& (int) $review['signature_time'] > 0
&& (int) $review['signature_time'] >= (int) $doctor['signature_time'];
}
public static function describe(?array $doctor): array
private static function matchesDoctor(array $doctor, ?array $review): bool
{
if (empty($doctor['review_required']) || !($review = self::review((int) $doctor['prescription_id']))
|| !self::hasVerifiedReview($doctor, $review)) {
return $review && $doctor['signed_hash'] !== '' && (int) $review['reviewer_id'] > 0
&& (int) $review['reviewer_id'] !== (int) $doctor['doctor_id']
&& $review['account_id'] !== '' && $review['account_id'] !== $doctor['account_id']
&& $review['environment'] === $doctor['environment'] && $review['app_id'] === $doctor['app_id']
&& hash_equals($doctor['signed_hash'], $review['doctor_pdf_hash']);
}
public static function describe(?array $doctor, ?array $prescription = null): array
{
$required = !empty($doctor['review_required']);
$review = $required ? self::review((int) $doctor['prescription_id']) : null;
$verified = $doctor && self::hasVerifiedReview($doctor, $review);
$result = $prescription === null ? [] : ['signing_log' => self::signingLog($prescription, $doctor, $review, $verified)];
if ($required) {
$state = $review['state'] ?? 'pending';
$result['review_state'] = match (true) {
$verified => 'signed',
$review === null => 'pending',
!self::matchesDoctor($doctor, $review) => 'uncertain',
in_array($state, ['pending', 'failed', 'uncertain'], true) => $state,
in_array($state, ['signing', 'verifying'], true)
&& time() - (int) $review['update_time'] < self::VERIFY_LEASE_SECONDS => $state,
default => 'uncertain',
};
}
if (!$verified) {
return $result;
}
$result += ['review_signer_name' => $review['signer_name'], 'review_signature_time' => (int) $review['signature_time']];
if ($prescription !== null && ($seal = self::reviewSeal($doctor, $review)) !== null) {
$result['review_signature'] = 'data:image/png;base64,' . base64_encode($seal);
}
return $result;
}
/** Project the archived milestones and the latest persisted exception. */
private static function signingLog(array $prescription, ?array $doctor, ?array $review, bool $verifiedReview): array
{
if (!$doctor) {
return [];
}
return ['review_signer_name' => $review['signer_name'], 'review_signature_time' => (int) $review['signature_time']];
$events = [];
$add = static function (string $event, string $label, int $time, string $actor = '', string $source = 'system') use (&$events): void {
if ($time > 0) {
$events[] = ['event' => $event, 'label' => $label, 'time' => $time, 'source' => $source]
+ ($actor === '' ? [] : ['actor_name' => $actor]);
}
};
$doctorName = (string) (($doctor['signer_name'] ?? '') ?: ($prescription['doctor_name'] ?? ''));
$add('doctor_flow_created', '医师签署流程建立', (int) ($doctor['create_time'] ?? 0), $doctorName);
$add('issued', '开具确认', (int) ($doctor['issued_at'] ?? 0), $doctorName);
$verifiedAt = (int) ($doctor['signed_at'] ?? 0);
if ($verifiedAt > 0 && !empty($doctor['signed_path'])) {
$source = (string) ($doctor['signature_time_source'] ?? '');
if (in_array($source, ['tsa', 'local'], true)) {
$add('doctor_signed', '医师签署', (int) ($doctor['signature_time'] ?? 0), $doctorName, $source);
}
$add('doctor_verified', '医师签章验签通过', $verifiedAt);
}
$state = (string) ($prescription['esign_status'] ?? '');
if (in_array($state, ['failed', 'uncertain'], true)) {
$add('doctor_' . $state, $state === 'failed' ? '医师签署未完成' : '医师签署结果待核实',
(int) ($doctor['update_time'] ?? 0), $doctorName);
}
if (self::matchesDoctor($doctor, $review)) {
$reviewer = (string) ($review['signer_name'] ?? '');
$add('review_confirmed', '药师确认签署', (int) $review['confirmed_at'], $reviewer);
if ($verifiedReview) {
$add('review_signed', '药师签署', (int) $review['signature_time'], $reviewer, 'tsa');
$add('review_verified', '药师签章验签通过', (int) $review['update_time']);
} elseif (in_array($review['state'], ['failed', 'uncertain'], true)) {
$add('review_' . $review['state'], $review['state'] === 'failed' ? '药师签署未完成' : '药师签署结果待核实',
(int) $review['update_time'], $reviewer);
}
}
$auditState = (int) ($prescription['audit_status'] ?? 0);
if ($auditState === 1 || $auditState === 2) {
$add($auditState === 1 ? 'audit_approved' : 'audit_rejected', $auditState === 1 ? '处方审核通过' : '处方审核驳回',
(int) ($prescription['audit_time'] ?? 0), (string) ($prescription['audit_by_name'] ?? ''));
}
if (!empty($prescription['void_status'])) {
$add('voided', '处方作废', (int) ($prescription['void_time'] ?? 0), (string) ($prescription['void_by_name'] ?? ''));
}
usort($events, static fn (array $left, array $right): int => $left['time'] <=> $right['time']);
return $events;
}
private static function sealPath(array $doctor, array $review): string
{
return $doctor['prescription_id'] . '-' . $doctor['snapshot_hash'] . '/review-seal-' . $review['signed_hash'] . '.png';
}
/** Preview the exact seal from a verified signature. Existing archives need no re-signing. */
private static function reviewSeal(array $doctor, array $review): ?string
{
try {
$path = self::sealPath($doctor, $review);
$cached = PrescriptionEsignService::readReviewSeal($path);
if ($cached !== null || !PrescriptionEsignService::matchesEnvironment($doctor)) {
return $cached;
}
$source = PrescriptionEsignService::readPdf($doctor['signed_path'], $doctor['signed_hash']);
$pdf = PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
$signature = self::verifiedReviewSignature($source, $pdf, (new EsignClient())->verifyPdf($pdf), $doctor, $review);
if ($signature['time'] === (int) $review['signature_time']) {
return self::cacheSeal($path, $signature['seal']);
}
} catch (\Throwable) {
// The archived PDF and verified time are still available if the preview cannot be loaded.
}
return null;
}
private static function cacheSeal(string $path, string $seal): ?string
{
$png = base64_decode($seal, true);
if ($png === false || $png === '') {
return null;
}
try {
PrescriptionEsignService::writeReviewSeal($path, $png);
} catch (\Throwable) {
return null;
}
return $png;
}
public static function download(array $doctor): ?array
@@ -130,36 +260,47 @@ final class PrescriptionReviewEsignService
throw new DomainException('处方不存在或无权查看');
}
$doctor = empty($row['esign_required']) ? null : Db::name('prescription_esign')->where('prescription_id', $id)->find();
$required = !empty($row['esign_required']) && (self::enabled() || !empty($doctor['review_required']));
$required = !empty($doctor['review_required']) || (self::enabled()
&& PrescriptionEsignService::requiresSignature($row, PrescriptionEsignService::enabled()));
$review = $required && !empty($doctor['review_required']) ? self::review($id) : null;
$pending = empty($row['void_status']) && ($order
? (int) $order->prescription_audit_status === 0 && !in_array((int) $order->fulfillment_status, [3, 4], true)
: (int) $row['audit_status'] === 0);
$reviewer = $required && $pending ? self::reviewerAccess($actor) : [];
$grants = $order ? [self::ORDER_PERMISSION] : PrescriptionLogic::AUDIT_PERMISSIONS;
$reviewReady = PrescriptionEsignService::canReview($row, $doctor);
$reviewer = $required && $pending && $reviewReady ? self::reviewerAccess($actor) : [];
return ['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required,
'can_audit' => $pending && $reviewer && self::hasGrant($reviewer, $grants),
'review_ready' => $reviewReady,
'can_audit' => $order ? self::canSubmitOrderAudit($reviewer)
: ($reviewer && self::hasGrant($reviewer, PrescriptionLogic::AUDIT_PERMISSIONS)),
'order_audit' => $order !== null,
'reviewer' => $reviewer];
}
private static function describeContext(array $context, int $actor): array
{
['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required, 'can_audit' => $canAudit,
'reviewer' => $reviewer] = $context;
'review_ready' => $reviewReady,
'order_audit' => $orderAudit, 'reviewer' => $reviewer] = $context;
$differentPerson = $actor !== (int) $row['creator_id'];
$signed = $doctor && self::hasVerifiedReview($doctor, $review);
$own = (int) ($review['reviewer_id'] ?? 0) === $actor;
$active = $doctor && PrescriptionEsignService::matchesEnvironment($doctor);
$state = (string) ($review['state'] ?? 'pending');
$canWork = $canAudit && $differentPerson && $active && self::enabled()
&& DoctorEsignIdentityService::quickEnabled() && ($row['esign_status'] ?? '') === 'signed';
$account = $canWork ? PrescriptionEsignService::account($actor) : null;
$canApprove = $signed && $canAudit && ($orderAudit || $own) && ($row['esign_status'] ?? '') === 'signed';
$canSetup = !$signed && $canAudit && $differentPerson && (!$doctor || $active) && self::enabled()
&& DoctorEsignIdentityService::quickEnabled();
$canWork = $canSetup && $active && ($row['esign_status'] ?? '') === 'signed';
$account = $canSetup ? PrescriptionEsignService::account($actor) : null;
$stale = time() - (int) ($review['update_time'] ?? 0) >= self::VERIFY_LEASE_SECONDS;
$canRetry = $canAudit && $own && $active && PrescriptionEsignService::enabled() && !empty($review['signed_hash'])
&& ($state === 'uncertain' || (in_array($state, ['signing', 'verifying'], true) && $stale));
$message = match (true) {
PrescriptionEsignPolicy::isAwaitingUpload($row) => '请开方医生先上传处方,再进行审核。',
PrescriptionEsignPolicy::isPendingReview($row) && !$reviewReady => '请开方医生完成有效电子签署后再进行审核。',
!$required => '',
$signed => $own ? '审核签章已验签,可以提交通过。' : '请由已签署此处方的审核人本人提交审核。',
$canApprove => '医师和药师签章均已验签,可以提交审核通过。',
$signed && ($orderAudit || $own) => '当前账号或处方状态不允许提交审核。',
$signed => '请由已签署此处方的审核人本人提交审核。',
!$differentPerson => '请切换到另一位有权限的审核人账号。',
!$canAudit => '当前账号或处方状态不允许审核签署。',
($row['esign_status'] ?? '') !== 'signed' => '请开方医生先完成电子签署。',
@@ -173,8 +314,8 @@ final class PrescriptionReviewEsignService
return [
'required' => $required, 'state' => $signed ? 'signed' : $state,
'can_confirm' => $canWork && $account !== null && !$signed && in_array($state, ['pending', 'failed'], true),
'can_retry_verify' => $canRetry, 'can_approve' => !$required || ($signed && $own && $canAudit),
'can_setup' => $canWork,
'can_retry_verify' => $canRetry, 'can_approve' => $reviewReady && (!$required || $canApprove),
'can_setup' => $canSetup,
'actor_id' => $actor, 'actor_name' => (string) ($account['doctor_name'] ?? $reviewer['name'] ?? ''),
'signer_name' => $signed ? $review['signer_name'] : '',
'signature_time' => $signed ? (int) $review['signature_time'] : 0,
@@ -257,10 +398,12 @@ final class PrescriptionReviewEsignService
self::save($id, $token, ['sign_service_id' => $signed['sign_service_id']]);
$dual = $signed['pdf'];
PrescriptionEsignService::writePdf(self::path($doctor), $dual);
self::save($id, $token, ['signed_hash' => hash('sha256', $dual), 'state' => 'verifying']);
$work['signed_hash'] = hash('sha256', $dual);
self::save($id, $token, ['signed_hash' => $work['signed_hash'], 'state' => 'verifying']);
}
$time = self::verifyReview($source, $dual, $client->verifyPdf($dual), $doctor, $work);
self::save($id, $token, ['state' => 'signed', 'signature_time' => $time, 'error_message' => '']);
$signature = self::verifiedReviewSignature($source, $dual, $client->verifyPdf($dual), $doctor, $work);
self::cacheSeal(self::sealPath($doctor, $work), $signature['seal']);
self::save($id, $token, ['state' => 'signed', 'signature_time' => $signature['time'], 'error_message' => '']);
} catch (\Throwable $error) {
$definiteRejection = !$received && $error instanceof EsignProviderException && !($error instanceof EsignOutcomeUnknownException);
$details = $definiteRejection || $error instanceof DomainException ? $error->getMessage()
@@ -321,6 +464,12 @@ final class PrescriptionReviewEsignService
}
public static function verifyReview(string $source, string $dual, array $verified, array $doctor, array $proof): int
{
return self::verifiedReviewSignature($source, $dual, $verified, $doctor, $proof)['time'];
}
/** @return array{time:int,seal:string} */
private static function verifiedReviewSignature(string $source, string $dual, array $verified, array $doctor, array $proof): array
{
if (strlen($dual) <= strlen($source) || !str_starts_with($dual, $source)) {
throw new DomainException('双签原件未保留医生已签的原始文档,请联系管理员');
@@ -330,13 +479,15 @@ final class PrescriptionReviewEsignService
throw new DomainException('双签原件须包含两枚有效签章');
}
[$first, $second] = array_map([self::class, 'signature'], $entries);
[$original, $review] = $first['key'] === $proof['doctor_signature'] ? [$first, $second] : [$second, $first];
$originalIndex = $first['key'] === $proof['doctor_signature'] ? 0 : 1;
[$original, $review] = $originalIndex === 0 ? [$first, $second] : [$second, $first];
if ($original['key'] !== $proof['doctor_signature'] || $original['field'] === $review['field']
|| $original['certificate'] === $review['certificate']
|| $review['certificate'] !== $proof['reviewer_certificate'] || $review['name'] !== $proof['signer_name']
|| $review['time'] < max((int) $doctor['issued_at'], $original['time'])) {
throw new DomainException('医生与审核人签章、证书或时间顺序未通过核验');
}
return $review['time'];
$seal = $entries[1 - $originalIndex]['sealData'] ?? null;
return ['time' => $review['time'], 'seal' => is_string($seal) ? $seal : ''];
}
}