igengx
This commit is contained in:
@@ -4,3 +4,10 @@ BASE_URL = "https://ai.example.com/v1"
|
||||
QWEN_API_KEY = "replace-on-server"
|
||||
OPENAI_API_KEY = "replace-on-server"
|
||||
TIMEOUT = 90
|
||||
; 豆包:后端直连火山方舟 Ark(OpenAI 兼容 chat/completions),不经过 Dify
|
||||
; DOUBAO_API_KEY 即方舟控制台的 API Key;未配置时豆包会明确提示“该模型服务尚未完整配置”
|
||||
DOUBAO_API_KEY = ""
|
||||
; DOUBAO_MODEL = "doubao-seed-2-1-pro-260915"
|
||||
; DOUBAO_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"
|
||||
; 留空沿用模型默认深度思考;填 disabled 可缩短响应时间
|
||||
; DOUBAO_THINKING = disabled
|
||||
|
||||
@@ -15,7 +15,9 @@
|
||||
namespace app\adminapi\controller;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\adminapi\validate\LoginValidate;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
|
||||
/**
|
||||
* 管理员登录控制器
|
||||
@@ -41,6 +43,20 @@ class LoginController extends BaseAdminController
|
||||
return $this->data((new LoginLogic())->login($params));
|
||||
}
|
||||
|
||||
/** 工作站在线心跳 */
|
||||
public function desktopHeartbeat()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return $this->fail('请使用 POST 请求');
|
||||
}
|
||||
if ((int) ($this->adminInfo['terminal'] ?? 0) !== AdminTerminalEnum::WORKSTATION) {
|
||||
return $this->fail('请重新登录桌面工作站', [], -1);
|
||||
}
|
||||
$expiresAt = DesktopSessionService::update((string) $this->adminInfo['token'], 'heartbeat');
|
||||
return $expiresAt ? $this->data(['desktop_expires_at' => $expiresAt])
|
||||
: $this->fail('登录已过期,请重新登录', [], -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notes 获取企业微信登录配置(前端构造OAuth URL/扫码用)
|
||||
*/
|
||||
|
||||
@@ -16,7 +16,11 @@ namespace app\adminapi\controller\setting\system;
|
||||
|
||||
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\lists\setting\system\DesktopSessionLists;
|
||||
use app\adminapi\lists\setting\system\LogLists;
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use think\facade\Db;
|
||||
|
||||
/**
|
||||
* 系统日志
|
||||
@@ -35,4 +39,17 @@ class LogController extends BaseAdminController
|
||||
{
|
||||
return $this->dataLists(new LogLists());
|
||||
}
|
||||
}
|
||||
|
||||
public function desktopSessions()
|
||||
{
|
||||
// 未配置菜单时,通用中间件会放过未登记的接口。
|
||||
if ((int) ($this->adminInfo['root'] ?? 0) !== 1
|
||||
&& !in_array('setting.system.log/desktopSessions', AuthLogic::getAuthByAdminId($this->adminId), true)) {
|
||||
return $this->fail('权限不足,无法查看桌面登录记录');
|
||||
}
|
||||
|
||||
$lists = new DesktopSessionLists();
|
||||
DesktopSessionService::settleDue();
|
||||
return Db::transaction(fn () => $this->dataLists($lists));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,7 @@ use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\validate\tcm\PrescriptionValidate;
|
||||
use app\common\service\esign\DoctorEsignIdentityService;
|
||||
use app\common\service\esign\PrescriptionCaSigningSettings;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionReviewEsignService;
|
||||
|
||||
@@ -102,6 +103,27 @@ class PrescriptionController extends BaseAdminController
|
||||
return $this->data($detail);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notes 上传处方送审
|
||||
*/
|
||||
public function submitForReview()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return $this->fail('请使用 POST 上传处方');
|
||||
}
|
||||
$rawId = $this->request->post('id');
|
||||
$id = (is_int($rawId) || is_string($rawId))
|
||||
? filter_var($rawId, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
|
||||
if ($id === false) {
|
||||
return $this->fail('处方ID无效');
|
||||
}
|
||||
try {
|
||||
return $this->data(PrescriptionLogic::submitForReview($id, (int) $this->adminId, $this->adminInfo));
|
||||
} catch (\Throwable $error) {
|
||||
return $this->fail($error instanceof \DomainException ? $error->getMessage() : '处方上传失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @notes 审核处方(通过 / 驳回,驳回即作废)
|
||||
*/
|
||||
@@ -121,13 +143,8 @@ class PrescriptionController extends BaseAdminController
|
||||
|
||||
$msg = $params['action'] === 'reject' ? '已驳回并作废处方' : '审核通过';
|
||||
$wecom = PrescriptionLogic::consumeLastAuditWecomNotify();
|
||||
$data = [];
|
||||
if (is_array($wecom)) {
|
||||
$data['wecom_notify_ok'] = !empty($wecom['ok']);
|
||||
if (empty($wecom['ok']) && !empty($wecom['message'])) {
|
||||
$data['wecom_notify_hint'] = (string) $wecom['message'];
|
||||
}
|
||||
}
|
||||
// The audit is already committed. The notification diagnostic belongs in server logs.
|
||||
$data = $wecom === null ? [] : ['wecom_notify_ok' => !empty($wecom['ok'])];
|
||||
|
||||
return $this->success($msg, $data);
|
||||
}
|
||||
@@ -180,7 +197,11 @@ class PrescriptionController extends BaseAdminController
|
||||
if ($id <= 0) {
|
||||
return $this->fail('处方ID不能为空');
|
||||
}
|
||||
$ok = PrescriptionLogic::void($id, $this->adminId, $this->adminInfo);
|
||||
$pendingOnly = $this->request->post('pending_only', false, null);
|
||||
if (!is_bool($pendingOnly)) {
|
||||
return $this->fail('作废参数无效');
|
||||
}
|
||||
$ok = PrescriptionLogic::void($id, $this->adminId, $this->adminInfo, $pendingOnly);
|
||||
if (!$ok) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
@@ -191,6 +212,29 @@ class PrescriptionController extends BaseAdminController
|
||||
{
|
||||
return $this->data(PrescriptionEsignService::capability());
|
||||
}
|
||||
|
||||
/** @notes 修改处方 CA 签名设置 */
|
||||
public function esignSetConfig()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return $this->fail('请使用 POST 修改 CA 签名设置');
|
||||
}
|
||||
if ((int) ($this->adminInfo['root'] ?? 0) !== 1) {
|
||||
return $this->fail('仅超级管理员可以修改 CA 签名设置');
|
||||
}
|
||||
$enabled = $this->request->post('enabled', null, null);
|
||||
if (!is_bool($enabled)) {
|
||||
return $this->fail('CA 签名开关必须为布尔值');
|
||||
}
|
||||
try {
|
||||
PrescriptionCaSigningSettings::setEnabled($enabled, $this->adminId);
|
||||
return $this->data(PrescriptionEsignService::capability());
|
||||
} catch (\DomainException $error) {
|
||||
return $this->fail($error->getMessage());
|
||||
} catch (\Throwable) {
|
||||
return $this->fail('CA 签名设置暂时无法保存,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
public function esignStatus()
|
||||
{
|
||||
@@ -238,11 +282,11 @@ class PrescriptionController extends BaseAdminController
|
||||
if ($confirm ? !$this->request->isPost() : !$this->request->isGet()) {
|
||||
return $this->fail($confirm ? '请使用 POST 请求' : '请使用 GET 请求');
|
||||
}
|
||||
$params = $confirm ? $this->request->post() : $this->request->get();
|
||||
$params = $confirm ? $this->request->post(false) : $this->request->get();
|
||||
$id = (int) ($params['id'] ?? 0);
|
||||
$orderId = (int) ($params['order_id'] ?? 0);
|
||||
$actor = (int) $this->adminId;
|
||||
$verifyOnly = $params['verify_only'] ?? false;
|
||||
$verifyOnly = array_key_exists('verify_only', $params) ? $params['verify_only'] : false;
|
||||
if ($id <= 0 || $orderId < 0 || !is_bool($verifyOnly)) {
|
||||
return $this->fail('审核签署参数无效');
|
||||
}
|
||||
@@ -300,9 +344,16 @@ class PrescriptionController extends BaseAdminController
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
ignore_user_abort(true);
|
||||
$data = DoctorEsignIdentityService::complete((int) $this->adminId, $input);
|
||||
} else {
|
||||
$body = $this->request->post(false);
|
||||
$signerName = $body['signer_name'] ?? null;
|
||||
if (array_key_exists('signer_name', $body) && (!is_string($signerName) || strlen($signerName) > 200)) {
|
||||
return $this->fail('证件姓名格式无效');
|
||||
}
|
||||
$data = DoctorEsignIdentityService::start((int) $this->adminId, $input, $signerName);
|
||||
}
|
||||
return $this->data(DoctorEsignIdentityService::{$operation}((int) $this->adminId, $input))
|
||||
->header(['Cache-Control' => 'private, no-store']);
|
||||
return $this->data($data)->header(['Cache-Control' => 'private, no-store']);
|
||||
} catch (\Throwable $error) {
|
||||
return $this->fail($error instanceof \DomainException ? $error->getMessage() : '医师认证暂不可用,请稍后重试');
|
||||
}
|
||||
|
||||
@@ -78,20 +78,22 @@ class AuthMiddleware
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$adminAuthCache = new AdminAuthCache($request->adminInfo['admin_id']);
|
||||
|
||||
// 当前访问路径
|
||||
$accessUri = strtolower($request->controller() . '/' . $request->action());
|
||||
if ($accessUri === 'tcm.prescription/esignconfig') {
|
||||
return $next($request); // Logged-in clients only receive signing capability flags.
|
||||
}
|
||||
if ($accessUri === 'tcm.prescription/esignsetconfig') {
|
||||
return JsonService::fail('仅超级管理员可以修改 CA 签名设置');
|
||||
}
|
||||
|
||||
$adminAuthCache = new AdminAuthCache($request->adminInfo['admin_id']);
|
||||
|
||||
// Explicit gate: these new endpoints must not use unregistered-route bypass.
|
||||
if (str_starts_with($accessUri, 'tcm.prescription/esign')) {
|
||||
$action = substr($accessUri, strlen('tcm.prescription/'));
|
||||
if ($action === 'esignconfig') {
|
||||
return $next($request); // Only exposes enabled + environment, to logged-in users.
|
||||
}
|
||||
$uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
|
||||
$writes = ['tcm.prescription/add', 'tcm.prescription/edit', 'cf.prescription/add', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang'];
|
||||
$writes = PrescriptionLogic::REVIEW_SUBMIT_PERMISSIONS;
|
||||
$reads = array_merge($writes, ['tcm.prescription/detail', 'tcm.prescription/lists', 'cf.prescription/lists',
|
||||
'cf.prescription/detail', 'cf.prescription/audit', 'tcm.prescription/audit',
|
||||
'tcm.prescriptionorder/lists', 'tcm.prescriptionorder/detail', 'tcm.prescriptionorder/auditprescription']);
|
||||
@@ -275,6 +277,7 @@ class AuthMiddleware
|
||||
|
||||
$prescriptionWriteAliases = [
|
||||
'tcm.prescription/add' => PrescriptionLogic::PRESCRIBE_PERMISSIONS,
|
||||
'tcm.prescription/submitforreview' => PrescriptionLogic::REVIEW_SUBMIT_PERMISSIONS,
|
||||
'tcm.prescription/edit' => [
|
||||
'tcm.prescription/edit', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
@@ -351,6 +354,7 @@ class AuthMiddleware
|
||||
'tcm.prescription/delete',
|
||||
'tcm.prescription/void',
|
||||
'tcm.prescription/audit',
|
||||
'tcm.prescription/submitforreview',
|
||||
], true);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ class LoginMiddleware
|
||||
}
|
||||
|
||||
//token临近过期,自动续期
|
||||
if ($adminInfo) {
|
||||
if ($adminInfo && (int) ($adminInfo['terminal'] ?? 0) !== AdminTerminalEnum::WORKSTATION) {
|
||||
//获取临近过期自动续期时长
|
||||
$beExpireDuration = AdminTokenService::renewalWindow($adminInfo['terminal'] ?? 0);
|
||||
//token续期
|
||||
@@ -93,6 +93,9 @@ class LoginMiddleware
|
||||
|
||||
private static function isWorkWechatBindExemptAction($request): bool
|
||||
{
|
||||
if (strtolower($request->controller() . '/' . $request->action()) === 'login/desktopheartbeat') {
|
||||
return true;
|
||||
}
|
||||
if (LoginLogic::isWorkWechatBindExemptActionName((string) $request->action())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ class OperationLog
|
||||
{
|
||||
$request = request();
|
||||
$accessUri = strtolower($request->controller() . '/' . $request->action());
|
||||
// 在线时间已在会话表内记录,定时心跳不产生操作日志。
|
||||
if ($accessUri === 'login/desktopheartbeat') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Temporary visual observations and rejected upload parameters must never
|
||||
// enter the generic request/response audit log if this listener is enabled.
|
||||
@@ -126,7 +130,7 @@ class OperationLog
|
||||
private function stripLargeLogFields(array &$data): void
|
||||
{
|
||||
foreach ($data as $key => &$value) {
|
||||
if ($key === 'auth_url') {
|
||||
if (in_array($key, ['auth_url', 'review_signature', 'signing_log'], true)) {
|
||||
unset($data[$key]);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -205,7 +205,6 @@ class MyPatientOrderLists extends BaseAdminDataLists implements ListsSearchInter
|
||||
if ($prescriptionIds !== []) {
|
||||
$prescriptions = Prescription::whereIn('id', $prescriptionIds)
|
||||
->whereNull('delete_time')
|
||||
->field(['id', 'creator_id', 'doctor_name'])
|
||||
->select()
|
||||
->toArray();
|
||||
foreach ($prescriptions as $prescription) {
|
||||
@@ -285,6 +284,7 @@ class MyPatientOrderLists extends BaseAdminDataLists implements ListsSearchInter
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$prescription = $prescriptionMap[(int) ($row['prescription_id'] ?? 0)] ?? [];
|
||||
$row = PrescriptionOrderLogic::withReviewAvailability($row, $prescription);
|
||||
$doctorId = (int) ($prescription['creator_id'] ?? 0);
|
||||
$doctorName = trim((string) ($prescription['doctor_name'] ?? ''));
|
||||
$creatorId = (int) ($row['creator_id'] ?? 0);
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\lists\setting\system;
|
||||
|
||||
use app\adminapi\lists\BaseAdminDataLists;
|
||||
use app\common\lists\ListsExtendInterface;
|
||||
use app\common\lists\Traits\HasDataScopeFilter;
|
||||
use app\common\service\DataScope\DataScopeService;
|
||||
use app\common\service\JsonService;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use think\db\Query;
|
||||
use think\facade\Db;
|
||||
|
||||
class DesktopSessionLists extends BaseAdminDataLists implements ListsExtendInterface
|
||||
{
|
||||
use HasDataScopeFilter;
|
||||
|
||||
private Query $sessions;
|
||||
private DateTimeImmutable $now;
|
||||
private string $daySecondsSql;
|
||||
private ?array $summary = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->now = new DateTimeImmutable('now', new DateTimeZone('Asia/Shanghai'));
|
||||
$date = $this->request->get('date', $this->now->format('Y-m-d'));
|
||||
$day = is_string($date) && preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date)
|
||||
? DateTimeImmutable::createFromFormat('!Y-m-d', $date, $this->now->getTimezone())
|
||||
: false;
|
||||
if (!$day || $day->format('Y-m-d') !== $date) {
|
||||
JsonService::throw('请选择有效的查询日期');
|
||||
}
|
||||
$keyword = $this->request->get('keyword', '');
|
||||
if (!is_string($keyword)) {
|
||||
JsonService::throw('请填写账号或姓名');
|
||||
}
|
||||
|
||||
$start = $day->getTimestamp();
|
||||
$end = $day->modify('+1 day')->getTimestamp();
|
||||
$now = $this->now->getTimestamp();
|
||||
// 所有会话最迟到下一次 05:00。用前一日下界限制登录时间索引的扫描范围。
|
||||
$this->sessions = Db::name('desktop_login_session')
|
||||
->where('login_time', '>=', $day->modify('-1 day')->getTimestamp())
|
||||
->where('login_time', '<', $end)
|
||||
->where('login_time', '<=', $now)
|
||||
// 同秒登录退出也应保留在登录当日,午夜退出归入前一天。
|
||||
->whereRaw("(login_time >= {$start} OR COALESCE(logout_time, {$now}) > {$start})");
|
||||
$this->daySecondsSql = "LEAST(COALESCE(logout_time, {$now}), {$end}) - GREATEST(login_time, {$start})";
|
||||
|
||||
if (trim($keyword) !== '') {
|
||||
$pattern = '%' . strtr(trim($keyword), ['!' => '!!', '%' => '!%', '_' => '!_']) . '%';
|
||||
$this->sessions->whereRaw("(account LIKE ? ESCAPE '!' OR name LIKE ? ESCAPE '!')", [$pattern, $pattern]);
|
||||
}
|
||||
if ((int) ($this->adminInfo['root'] ?? 0) !== 1) {
|
||||
$this->adminInfo['role_id'] = DataScopeService::roleIdsOf($this->adminId);
|
||||
}
|
||||
$this->applyDataScopeByOwner($this->sessions, 'admin_id');
|
||||
}
|
||||
|
||||
public function lists(): array
|
||||
{
|
||||
$rows = (clone $this->sessions)
|
||||
->field('id,admin_id,account,name,login_time,logout_time,end_reason,duration_seconds')
|
||||
->fieldRaw("({$this->daySecondsSql}) AS day_seconds")
|
||||
->order(['login_time' => 'desc', 'id' => 'desc'])
|
||||
->limit($this->limitOffset, $this->limitLength)->select()->toArray();
|
||||
foreach ($rows as &$row) {
|
||||
$login = (int) $row['login_time'];
|
||||
$logout = $row['logout_time'];
|
||||
$row['status'] = $logout === null ? 'online' : $row['end_reason'];
|
||||
$row['status_label'] = match ($row['status']) {
|
||||
'online' => '在线',
|
||||
'logout' => '已退出',
|
||||
'replaced' => '重新登录',
|
||||
'timeout' => '连接超时',
|
||||
'daily_cutoff' => '每日下线',
|
||||
'revoked' => '登录已撤销',
|
||||
default => '已结束',
|
||||
};
|
||||
$row['duration_seconds'] = $logout === null
|
||||
? $this->now->getTimestamp() - $login : (int) $row['duration_seconds'];
|
||||
$row['day_seconds'] = (int) $row['day_seconds'];
|
||||
$row['login_time'] = $this->now->setTimestamp($login)->format('Y-m-d H:i:s');
|
||||
$row['logout_time'] = $logout === null
|
||||
? null : $this->now->setTimestamp((int) $logout)->format('Y-m-d H:i:s');
|
||||
unset($row['end_reason']);
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
private function summary(): array
|
||||
{
|
||||
return $this->summary ??= (clone $this->sessions)
|
||||
->fieldRaw("COUNT(*) AS session_count, COALESCE(SUM({$this->daySecondsSql}), 0) AS day_seconds")
|
||||
->find();
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return (int) $this->summary()['session_count'];
|
||||
}
|
||||
|
||||
public function extend(): array
|
||||
{
|
||||
return ['total_day_seconds' => (int) $this->summary()['day_seconds']];
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,8 @@ use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\model\tcm\Prescription;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use think\db\Query;
|
||||
|
||||
/**
|
||||
* 处方列表
|
||||
@@ -157,7 +159,16 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
$query->whereIn('audit_status', [0, 2]);
|
||||
break;
|
||||
case 'pending':
|
||||
$query->where('audit_status', '=', 0);
|
||||
$esignEnabled = PrescriptionEsignService::enabled();
|
||||
$query->where('audit_status', '=', 0)->where('review_submitted_at', '>', 0)->where('void_status', '=', 0)
|
||||
->where(static function (Query $q) use ($esignEnabled): void {
|
||||
$q->where('esign_status', 'signed')->whereOr(static function (Query $legacy) use ($esignEnabled): void {
|
||||
$legacy->where('esign_required', 0);
|
||||
if ($esignEnabled) {
|
||||
$legacy->where('esign_status', '<>', 'legacy');
|
||||
}
|
||||
});
|
||||
});
|
||||
break;
|
||||
case 'rejected':
|
||||
$query->where('audit_status', '=', 2);
|
||||
@@ -167,6 +178,18 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
}
|
||||
}
|
||||
|
||||
private function buildFilteredQuery(): Query
|
||||
{
|
||||
$query = Prescription::where($this->searchWhere)->whereNull('delete_time');
|
||||
$this->applyAuditFilter($query);
|
||||
$this->applySourceFilter($query);
|
||||
$this->applyVisibilityScope($query);
|
||||
$this->applyCreatorIdsFilter($query);
|
||||
$this->applyDataScopeByOwnerColumns($query, ['creator_id', 'assistant_id']);
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* 来源:system=系统代开(is_system_auto=1),manual=手工(0 或空)
|
||||
*/
|
||||
@@ -230,18 +253,13 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
*/
|
||||
public function lists(): array
|
||||
{
|
||||
$query = Prescription::where($this->searchWhere);
|
||||
$this->applyAuditFilter($query);
|
||||
$this->applySourceFilter($query);
|
||||
$this->applyVisibilityScope($query);
|
||||
$this->applyCreatorIdsFilter($query);
|
||||
$this->applyDataScopeByOwnerColumns($query, ['creator_id', 'assistant_id']);
|
||||
$query = $this->buildFilteredQuery();
|
||||
|
||||
// 全局置顶:有业务订单且处方药材为空白/重复
|
||||
$candidateIds = (clone $query)->whereNull('delete_time')->column('id');
|
||||
$candidateIds = (clone $query)->column('id');
|
||||
$riskIds = $this->collectRiskPrescriptionIds(is_array($candidateIds) ? $candidateIds : []);
|
||||
|
||||
$listQuery = $query->whereNull('delete_time');
|
||||
$listQuery = $query;
|
||||
if ($riskIds !== []) {
|
||||
$riskIdStr = implode(',', array_map('intval', $riskIds));
|
||||
$listQuery->orderRaw("CASE WHEN id IN ({$riskIdStr}) THEN 0 ELSE 1 END ASC");
|
||||
@@ -257,7 +275,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
$rejectedRx = [];
|
||||
$bizRejectRemark = [];
|
||||
$hasBizOrderRx = [];
|
||||
$hasReleasedOrderRx = [];
|
||||
$ordersByPrescription = [];
|
||||
if ($rxIds !== []) {
|
||||
$bizRejectRows = PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->where('prescription_audit_status', 2)
|
||||
@@ -280,13 +298,12 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
|
||||
$orders = PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->whereNull('delete_time')
|
||||
->field(['prescription_id', 'fulfillment_status'])
|
||||
->select();
|
||||
->field(['prescription_id', 'fulfillment_status', 'prescription_audit_status', 'payment_slip_audit_status'])
|
||||
->select()->toArray();
|
||||
foreach ($orders as $order) {
|
||||
$prescriptionId = (int) $order->prescription_id;
|
||||
if (in_array((int) $order->fulfillment_status, PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) {
|
||||
$hasReleasedOrderRx[$prescriptionId] = true;
|
||||
} else {
|
||||
$prescriptionId = (int) $order['prescription_id'];
|
||||
$ordersByPrescription[$prescriptionId][] = $order;
|
||||
if (!in_array((int) $order['fulfillment_status'], PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) {
|
||||
$hasBizOrderRx[$prescriptionId] = true;
|
||||
}
|
||||
}
|
||||
@@ -302,13 +319,16 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
|
||||
// 处理字段格式
|
||||
$voidAccess = $lists === [] ? [] : PrescriptionLogic::getVoidAccess($this->adminId, $this->adminInfo);
|
||||
$maySubmit = in_array($this->adminId, array_map('intval', array_column($lists, 'creator_id')), true)
|
||||
&& PrescriptionLogic::canSubmitForReview($this->adminId, $this->adminInfo);
|
||||
foreach ($lists as &$item) {
|
||||
$rid = (int) $item['id'];
|
||||
$item['can_void'] = empty($item['void_status']) && empty($hasBizOrderRx[$rid])
|
||||
$item['can_void'] = empty($item['void_status'])
|
||||
&& PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess)
|
||||
&& (empty($hasReleasedOrderRx[$rid]) || PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($rid) === null);
|
||||
&& !PrescriptionLogic::hasBlockingVoidOrder($item, $ordersByPrescription[$rid] ?? [])
|
||||
&& (empty($ordersByPrescription[$rid]) || PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($rid) === null);
|
||||
$item['can_restore_rejected'] = PrescriptionLogic::canRestoreRejected($item);
|
||||
$item['esign'] = \app\common\service\esign\PrescriptionEsignService::describe($item, (int) $this->adminId);
|
||||
$item = PrescriptionLogic::withSigningStatus($item, $this->adminId, $maySubmit);
|
||||
// 设置默认值
|
||||
$item['usage_time'] = $item['usage_time'] ?? '饭前';
|
||||
$item['usage_way'] = $item['usage_way'] ?? '温水送服';
|
||||
@@ -343,13 +363,6 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
$query = Prescription::where($this->searchWhere);
|
||||
$this->applyAuditFilter($query);
|
||||
$this->applySourceFilter($query);
|
||||
$this->applyVisibilityScope($query);
|
||||
$this->applyCreatorIdsFilter($query);
|
||||
$this->applyDataScopeByOwnerColumns($query, ['creator_id', 'assistant_id']);
|
||||
|
||||
return $query->whereNull('delete_time')->count();
|
||||
return $this->buildFilteredQuery()->count();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -667,7 +667,6 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
|
||||
if ($prescriptionIds !== []) {
|
||||
$prescriptions = \app\common\model\tcm\Prescription::whereIn('id', $prescriptionIds)
|
||||
->whereNull('delete_time')
|
||||
->field(['id', 'creator_id', 'doctor_name', 'phone', 'assistant_id'])
|
||||
->select()
|
||||
->toArray();
|
||||
$doctorIds = [];
|
||||
@@ -681,7 +680,7 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
|
||||
'doctor_name' => $doctorName,
|
||||
'phone' => (string) ($rx['phone'] ?? ''),
|
||||
'assistant_id' => (int) ($rx['assistant_id'] ?? 0),
|
||||
];
|
||||
] + $rx;
|
||||
if ($doctorId > 0) {
|
||||
$doctorIds[] = $doctorId;
|
||||
}
|
||||
@@ -781,6 +780,7 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
|
||||
// 添加开方人姓名、处方登记手机(与业务订单收货手机比对用)
|
||||
$item['doctor_name'] = $rxId > 0 ? ($prescriptionCreators[$rxId]['doctor_name'] ?? '') : '';
|
||||
$item['prescription_phone'] = $rxId > 0 ? ($prescriptionCreators[$rxId]['phone'] ?? '') : '';
|
||||
$item = PrescriptionOrderLogic::withReviewAvailability($item, $prescriptionCreators[$rxId] ?? []);
|
||||
}
|
||||
unset($item);
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ namespace app\adminapi\logic;
|
||||
use app\common\logic\BaseLogic;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\service\FileService;
|
||||
use think\facade\Config;
|
||||
use think\facade\Cache;
|
||||
@@ -144,6 +145,9 @@ class LoginLogic extends BaseLogic
|
||||
'root' => (int) ($admin->root ?? 0),
|
||||
'work_wechat_userid' => (string) ($admin->work_wechat_userid ?? ''),
|
||||
]);
|
||||
if ((int) $params['terminal'] === AdminTerminalEnum::WORKSTATION) {
|
||||
$row['desktop_expires_at'] = $adminInfo['desktop_expires_at'];
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
@@ -226,7 +230,7 @@ class LoginLogic extends BaseLogic
|
||||
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
|
||||
$avatar = FileService::getFileUrl($avatar);
|
||||
|
||||
return [
|
||||
$row = [
|
||||
'name' => $adminInfo['name'],
|
||||
'avatar' => $avatar,
|
||||
'role_name' => $adminInfo['role_name'],
|
||||
@@ -235,6 +239,10 @@ class LoginLogic extends BaseLogic
|
||||
// 企微扫码登录即已绑定 userid
|
||||
'need_bind_work_wechat' => false,
|
||||
];
|
||||
if ((int) $terminal === AdminTerminalEnum::WORKSTATION) {
|
||||
$row['desktop_expires_at'] = $adminInfo['desktop_expires_at'];
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -347,7 +355,7 @@ class LoginLogic extends BaseLogic
|
||||
$admin->is_paw = 1;
|
||||
Db::transaction(static function () use ($admin) {
|
||||
$admin->save();
|
||||
AdminTokenService::revokeBcrSessions((int) $admin->id);
|
||||
AdminTokenService::revokeNativeSessions((int) $admin->id);
|
||||
});
|
||||
|
||||
// 使当前 token 过期,要求重新登录
|
||||
|
||||
@@ -17,6 +17,8 @@ namespace app\adminapi\logic\auth;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\service\DoctorWebConsultationPolicy;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\cache\AdminAuthCache;
|
||||
use app\common\enum\YesNoEnum;
|
||||
use app\common\logic\BaseLogic;
|
||||
@@ -121,6 +123,8 @@ class AdminLogic extends BaseLogic
|
||||
{
|
||||
Db::startTrans();
|
||||
try {
|
||||
// 与工作站签发共用账号锁,停用或更换角色时能看到此前签发的全部终端。
|
||||
Admin::where('id', $params['id'])->field('id')->lock(true)->find();
|
||||
// 处理资质图片:如果是数组则转为JSON字符串
|
||||
$qualificationImages = '';
|
||||
if (isset($params['qualification_images'])) {
|
||||
@@ -178,7 +182,7 @@ class AdminLogic extends BaseLogic
|
||||
|
||||
Admin::update($data);
|
||||
if (isset($data['password'])) {
|
||||
AdminTokenService::revokeBcrSessions((int) $params['id']);
|
||||
AdminTokenService::revokeNativeSessions((int) $params['id']);
|
||||
}
|
||||
|
||||
// 删除旧的关联信息
|
||||
@@ -223,7 +227,7 @@ class AdminLogic extends BaseLogic
|
||||
{
|
||||
Db::startTrans();
|
||||
try {
|
||||
$admin = Admin::findOrEmpty($params['id']);
|
||||
$admin = Admin::where('id', $params['id'])->lock(true)->findOrEmpty();
|
||||
if ($admin->root == YesNoEnum::YES) {
|
||||
throw new \Exception("超级管理员不允许被删除");
|
||||
}
|
||||
@@ -270,6 +274,9 @@ class AdminLogic extends BaseLogic
|
||||
if (empty($adminSession)) {
|
||||
return false;
|
||||
}
|
||||
if ((int) $adminSession->terminal === AdminTerminalEnum::WORKSTATION) {
|
||||
return (bool) DesktopSessionService::update((string) $token, 'revoked');
|
||||
}
|
||||
|
||||
$time = time();
|
||||
$adminSession->expire_time = $time;
|
||||
@@ -362,7 +369,7 @@ class AdminLogic extends BaseLogic
|
||||
return Db::transaction(static function () use ($data) {
|
||||
$admin = Admin::update($data);
|
||||
if (isset($data['password'])) {
|
||||
AdminTokenService::revokeBcrSessions((int) $data['id']);
|
||||
AdminTokenService::revokeNativeSessions((int) $data['id']);
|
||||
}
|
||||
return $admin;
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -51,7 +51,7 @@ class PatientAiReportLogic extends BaseLogic
|
||||
private const PROMPT_VERSION = 'patient-longitudinal-report-tcm-four-diagnoses-v7';
|
||||
|
||||
/** @var array<int,string> */
|
||||
private const MODEL_KEYS = ['qwen', 'openai'];
|
||||
private const MODEL_KEYS = ['qwen', 'openai', 'doubao'];
|
||||
|
||||
private const MAX_RESPONSE_BYTES = 65536;
|
||||
|
||||
@@ -174,7 +174,7 @@ class PatientAiReportLogic extends BaseLogic
|
||||
array $adminInfo
|
||||
): ?array {
|
||||
if (!in_array($modelKey, self::MODEL_KEYS, true)) {
|
||||
self::setError('AI模型仅支持qwen或openai');
|
||||
self::setError('AI模型仅支持qwen、openai或doubao');
|
||||
return null;
|
||||
}
|
||||
if (!self::hasPermission($adminId, $adminInfo, self::PERMISSION_READ)) {
|
||||
@@ -1664,7 +1664,7 @@ class PatientAiReportLogic extends BaseLogic
|
||||
|
||||
$authorized = array_fill_keys(array_map('intval', $diagnosisIds), true);
|
||||
$versionById = [];
|
||||
$modelVersions = ['qwen' => 0, 'openai' => 0];
|
||||
$modelVersions = array_fill_keys(self::MODEL_KEYS, 0);
|
||||
foreach (array_reverse($rows) as $row) {
|
||||
$model = strtolower(trim((string) ($row['model_key'] ?? '')));
|
||||
if (!array_key_exists($model, $modelVersions)) {
|
||||
@@ -1675,7 +1675,7 @@ class PatientAiReportLogic extends BaseLogic
|
||||
}
|
||||
|
||||
$reports = [];
|
||||
$latestByModel = ['qwen' => null, 'openai' => null];
|
||||
$latestByModel = array_fill_keys(self::MODEL_KEYS, null);
|
||||
$generatedReport = null;
|
||||
foreach ($rows as $row) {
|
||||
$sourceDiagnosisIds = array_values(array_filter(array_map(
|
||||
|
||||
@@ -29,7 +29,7 @@ class PrescriptionLibraryAiLogic extends BaseLogic
|
||||
private const PERMISSION_EDIT = 'tcm.prescriptionlibrary/editaireport';
|
||||
|
||||
/** @var array<int,string> */
|
||||
private const MODEL_KEYS = ['qwen', 'openai'];
|
||||
private const MODEL_KEYS = ['qwen', 'openai', 'doubao'];
|
||||
|
||||
/** @var array<string,string> */
|
||||
private const TEXT_REPORT_SECTIONS = [
|
||||
|
||||
@@ -28,6 +28,7 @@ class PrescriptionLogic
|
||||
public const PRESCRIBE_PERMISSIONS = [
|
||||
'tcm.prescription/add', 'cf.prescription/add', 'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
];
|
||||
public const REVIEW_SUBMIT_PERMISSIONS = [...self::PRESCRIBE_PERMISSIONS, 'tcm.prescription/edit', 'cf.prescription/edit'];
|
||||
public const VOID_MANAGE_PERMISSIONS = ['tcm.prescription/void', 'cf.prescription/del'];
|
||||
public const AUDIT_PERMISSIONS = ['tcm.prescription/audit', 'cf.prescription/audit'];
|
||||
|
||||
@@ -188,18 +189,67 @@ class PrescriptionLogic
|
||||
&& (int) ($row['audit_by'] ?? 0) > 0 && (int) $row['audit_by'] === (int) ($row['void_by'] ?? 0)
|
||||
&& (empty($row['esign_required']) || ($row['esign_status'] ?? 'pending') === 'pending');
|
||||
}
|
||||
|
||||
public static function canSubmitForReview(int $adminId, array $adminInfo): bool
|
||||
{
|
||||
return $adminId > 0 && ((int) ($adminInfo['root'] ?? 0) === 1
|
||||
|| array_intersect(self::REVIEW_SUBMIT_PERMISSIONS, array_map('strtolower', AuthLogic::getAuthByAdminId($adminId))) !== []);
|
||||
}
|
||||
|
||||
public static function withSigningStatus(array $row, int $adminId, bool $maySubmit, bool $details = false): array
|
||||
{
|
||||
$row['esign'] = PrescriptionEsignService::describe($row, $adminId, $details, $maySubmit);
|
||||
$row['review_submitted_at'] = $row['esign']['review_submitted_at'];
|
||||
$row['can_submit_for_review'] = $row['esign']['can_submit_for_review'];
|
||||
$row['can_review_prescription'] = $row['esign']['can_review_prescription'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
public static function submitForReview(int $id, int $adminId, array $adminInfo): array
|
||||
{
|
||||
if (!self::canSubmitForReview($adminId, $adminInfo)) {
|
||||
throw new \DomainException('无权限上传处方');
|
||||
}
|
||||
|
||||
return Db::transaction(static function () use ($id, $adminId): array {
|
||||
$prescription = Prescription::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$prescription || (int) $prescription->creator_id !== $adminId) {
|
||||
throw new \DomainException('处方不存在或非本人开具');
|
||||
}
|
||||
|
||||
$row = $prescription->toArray();
|
||||
$required = PrescriptionEsignService::requiresSignature($row, PrescriptionEsignService::enabled());
|
||||
if (!empty($row['void_status']) || !PrescriptionEsignService::hasUploadContent($row, $required)) {
|
||||
throw new \DomainException('请确认处方未作废并已补全内容');
|
||||
}
|
||||
$submittedAt = (int) ($row['review_submitted_at'] ?? 0);
|
||||
if ($submittedAt <= 0) {
|
||||
if (!PrescriptionEsignPolicy::isPendingReview($row)) {
|
||||
throw new \DomainException('当前处方状态不可上传');
|
||||
}
|
||||
$submittedAt = time();
|
||||
if (!$prescription->save(['review_submitted_at' => $submittedAt])) {
|
||||
throw new \DomainException('处方上传未完成,请重试');
|
||||
}
|
||||
}
|
||||
|
||||
return ['review_submitted_at' => $submittedAt, 'can_submit_for_review' => false];
|
||||
});
|
||||
}
|
||||
|
||||
private static function withActionAvailability(array $row, int $viewerAdminId, array $viewerAdminInfo): array
|
||||
{
|
||||
$id = (int) $row['id'];
|
||||
// 与列表和创建校验一致:已取消 / 已退款的订单保留历史关联,但不再占用处方。
|
||||
$hasBizOrder = PrescriptionOrder::where('prescription_id', $id)
|
||||
$orders = PrescriptionOrder::where('prescription_id', $id)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->count() > 0;
|
||||
->field(['fulfillment_status', 'prescription_audit_status', 'payment_slip_audit_status'])
|
||||
->select()->toArray();
|
||||
$hasBizOrder = array_filter($orders, static fn (array $order): bool =>
|
||||
!in_array((int) $order['fulfillment_status'], PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) !== [];
|
||||
$row['has_prescription_order'] = $hasBizOrder ? 1 : 0;
|
||||
$row['can_restore_rejected'] = self::canRestoreRejected($row);
|
||||
$row['can_void'] = !$hasBizOrder && empty($row['void_status'])
|
||||
$row['can_void'] = empty($row['void_status']) && !self::hasBlockingVoidOrder($row, $orders)
|
||||
&& self::hasVoidAccess(
|
||||
$row,
|
||||
$viewerAdminId,
|
||||
@@ -211,6 +261,24 @@ class PrescriptionLogic
|
||||
return $row;
|
||||
}
|
||||
|
||||
/** Pending prescriptions can be voided while any active order is still waiting for both reviews. */
|
||||
public static function hasBlockingVoidOrder(array $prescription, array $orders): bool
|
||||
{
|
||||
foreach ($orders as $order) {
|
||||
$fulfillmentStatus = (int) ($order['fulfillment_status'] ?? -1);
|
||||
if (in_array($fulfillmentStatus, PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) {
|
||||
continue;
|
||||
}
|
||||
if ($fulfillmentStatus !== 1
|
||||
|| !in_array($order['prescription_audit_status'] ?? null, [0, '0'], true)
|
||||
|| !in_array($order['payment_slip_audit_status'] ?? null, [0, '0'], true)
|
||||
|| !PrescriptionEsignPolicy::isPendingReview($prescription)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function generateSn(): string
|
||||
{
|
||||
return 'RX' . date('Ymd') . str_pad((string)mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
|
||||
@@ -648,6 +716,7 @@ class PrescriptionLogic
|
||||
'is_system_auto' => 0,
|
||||
// 开方医生修改后重新进入待审核
|
||||
'audit_status' => 0,
|
||||
'review_submitted_at' => 0,
|
||||
'audit_time' => null,
|
||||
'audit_by' => null,
|
||||
'audit_by_name' => '',
|
||||
@@ -790,7 +859,7 @@ class PrescriptionLogic
|
||||
'patient_name' => $patientName,
|
||||
'phone' => $phone,
|
||||
'gender' => $gender,
|
||||
]);
|
||||
] + (PrescriptionEsignPolicy::isPendingReview($prescription->toArray()) ? ['review_submitted_at' => 0] : []));
|
||||
|
||||
$latestPo = PrescriptionOrder::where('prescription_id', $rxId)
|
||||
->whereNull('delete_time')
|
||||
@@ -881,7 +950,8 @@ class PrescriptionLogic
|
||||
return null;
|
||||
}
|
||||
$arr = $row->toArray();
|
||||
$arr['esign'] = PrescriptionEsignService::describe($arr, $viewerAdminId);
|
||||
$arr = self::withSigningStatus($arr, $viewerAdminId,
|
||||
(int) $row->creator_id === $viewerAdminId && self::canSubmitForReview($viewerAdminId, $viewerAdminInfo), true);
|
||||
$arr['gender_desc'] = $arr['gender'] == 1 ? '男' : '女';
|
||||
|
||||
$bizPo = PrescriptionOrder::where('prescription_id', $id)
|
||||
@@ -942,7 +1012,7 @@ class PrescriptionLogic
|
||||
if (!$row || (int) ($row->void_status ?? 0) === 1 || (int) ($row->audit_status ?? 1) !== 0) {
|
||||
return null;
|
||||
}
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId, false, $adminId);
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId, false, $adminId, orderApproval: true);
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = time();
|
||||
$row->audit_by = $adminId;
|
||||
@@ -1046,6 +1116,7 @@ class PrescriptionLogic
|
||||
}
|
||||
|
||||
if ($action === 'reject') {
|
||||
PrescriptionEsignService::assertReviewReady($row->toArray());
|
||||
if (trim($remark) === '') {
|
||||
self::setError('驳回时请填写审核意见');
|
||||
|
||||
@@ -1166,10 +1237,9 @@ class PrescriptionLogic
|
||||
$rows,
|
||||
static fn (array $row): bool => self::canViewPrescription($row, $viewerAdminId, $viewerAdminInfo)
|
||||
));
|
||||
return array_map(static function (array $row) use ($viewerAdminId): array {
|
||||
$row['esign'] = PrescriptionEsignService::describe($row, $viewerAdminId);
|
||||
return $row;
|
||||
}, $visible);
|
||||
$maySubmit = in_array($viewerAdminId, array_map('intval', array_column($visible, 'creator_id')), true)
|
||||
&& self::canSubmitForReview($viewerAdminId, $viewerAdminInfo);
|
||||
return array_map(static fn (array $row): array => self::withSigningStatus($row, $viewerAdminId, $maySubmit), $visible);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1206,8 +1276,8 @@ class PrescriptionLogic
|
||||
return null;
|
||||
}
|
||||
|
||||
$result = $row->toArray();
|
||||
$result['esign'] = PrescriptionEsignService::describe($result, $viewerAdminId);
|
||||
$result = self::withSigningStatus($row->toArray(), $viewerAdminId,
|
||||
(int) $row->creator_id === $viewerAdminId && self::canSubmitForReview($viewerAdminId, $viewerAdminInfo));
|
||||
return self::withActionAvailability($result, $viewerAdminId, $viewerAdminInfo);
|
||||
}
|
||||
|
||||
@@ -1348,7 +1418,7 @@ class PrescriptionLogic
|
||||
/**
|
||||
* 作废处方
|
||||
*/
|
||||
public static function void(int $id, int $adminId, array $adminInfo): bool
|
||||
public static function void(int $id, int $adminId, array $adminInfo, bool $pendingOnly = false): bool
|
||||
{
|
||||
self::setError('');
|
||||
try {
|
||||
@@ -1362,7 +1432,7 @@ class PrescriptionLogic
|
||||
|
||||
return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
|
||||
$id,
|
||||
static fn (): bool => self::voidLocked($id, $adminId, $adminInfo, $access)
|
||||
static fn (array $orders): bool => self::voidLocked($id, $adminId, $adminInfo, $access, $pendingOnly, $orders)
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
if (self::getError() === '') {
|
||||
@@ -1372,7 +1442,7 @@ class PrescriptionLogic
|
||||
}
|
||||
}
|
||||
|
||||
private static function voidLocked(int $id, int $adminId, array $adminInfo, array $access): bool
|
||||
private static function voidLocked(int $id, int $adminId, array $adminInfo, array $access, bool $pendingOnly, array $orders): bool
|
||||
{
|
||||
$row = Prescription::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$row || !self::hasVoidAccess($row->toArray(), $adminId, $adminInfo, $access)) {
|
||||
@@ -1383,13 +1453,12 @@ class PrescriptionLogic
|
||||
self::setError('该处方已作废');
|
||||
return false;
|
||||
}
|
||||
$rxId = (int) ($row->id ?? 0);
|
||||
$bizCount = (int) PrescriptionOrder::where('prescription_id', $rxId)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->count();
|
||||
if ($bizCount > 0) {
|
||||
self::setError('该处方已存在业务订单,无法作废');
|
||||
if ($pendingOnly && !PrescriptionEsignPolicy::isPendingReview($row->toArray())) {
|
||||
self::setError('处方审核状态已变化,请刷新列表后查看');
|
||||
return false;
|
||||
}
|
||||
if (self::hasBlockingVoidOrder($row->toArray(), $orders)) {
|
||||
self::setError('关联业务订单的审核或履约状态不允许作废此处方');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -60,16 +60,33 @@ class PrescriptionOrderLogic
|
||||
return self::$error;
|
||||
}
|
||||
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false, ?int $reviewer = null): bool
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false, ?int $orderAuditor = null): bool
|
||||
{
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing, $reviewer);
|
||||
PrescriptionEsignService::assertSignedById(
|
||||
(int) $order->prescription_id, $forDispensing, $orderAuditor, orderApproval: $orderAuditor !== null
|
||||
);
|
||||
return true;
|
||||
} catch (\DomainException $e) {
|
||||
self::$error = $e->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function assertPrescriptionReviewReady(PrescriptionOrder $order): void
|
||||
{
|
||||
$rx = Db::name('tcm_prescription')->where('id', (int) $order->prescription_id)->lock(true)->find();
|
||||
PrescriptionEsignService::assertReviewReady($rx ?: []);
|
||||
}
|
||||
|
||||
public static function withReviewAvailability(array $order, array $rx): array
|
||||
{
|
||||
$order['review_submitted_at'] = (int) ($rx['review_submitted_at'] ?? 0);
|
||||
$order['can_review_prescription'] = (int) ($order['prescription_audit_status'] ?? -1) === 0
|
||||
&& !in_array((int) ($order['fulfillment_status'] ?? 0), [3, 4], true)
|
||||
&& PrescriptionEsignService::canReview($rx);
|
||||
return $order;
|
||||
}
|
||||
|
||||
private static function assertTrackingAuditApproved(PrescriptionOrder $order): bool
|
||||
{
|
||||
@@ -1284,6 +1301,8 @@ class PrescriptionOrderLogic
|
||||
}
|
||||
}
|
||||
|
||||
$arr = self::withReviewAvailability($arr, $arr['prescription'] ?? []);
|
||||
|
||||
$canHerbs = self::canViewPrescriptionHerbsInOrderDetail($adminInfo);
|
||||
$arr['prescription_detail_herbs_visible'] = $canHerbs;
|
||||
if (! $canHerbs && isset($arr['prescription']) && is_array($arr['prescription'])) {
|
||||
@@ -2329,21 +2348,7 @@ class PrescriptionOrderLogic
|
||||
|
||||
try {
|
||||
$order->save();
|
||||
|
||||
// 撤回订单后,将关联的处方审核状态改回"待审核"
|
||||
$prescriptionId = (int) $order->prescription_id;
|
||||
if ($prescriptionId > 0) {
|
||||
Prescription::where('id', $prescriptionId)
|
||||
->whereNull('delete_time')
|
||||
->update([
|
||||
'audit_status' => 0, // 0=待审核
|
||||
'audit_time' => null,
|
||||
'audit_by' => null,
|
||||
'audit_by_name' => '',
|
||||
'audit_remark' => '',
|
||||
'update_time' => time(),
|
||||
]);
|
||||
}
|
||||
self::resetPrescriptionReview((int) $order->prescription_id);
|
||||
} catch (\Throwable $e) {
|
||||
self::$error = $e->getMessage();
|
||||
|
||||
@@ -2427,6 +2432,9 @@ class PrescriptionOrderLogic
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
if ($action === 'reject') {
|
||||
self::assertPrescriptionReviewReady($order);
|
||||
}
|
||||
|
||||
if ($action === 'approve') {
|
||||
$order->prescription_audit_status = 1;
|
||||
@@ -2673,26 +2681,7 @@ class PrescriptionOrderLogic
|
||||
}
|
||||
|
||||
// 同步撤回处方表的审核状态
|
||||
$prescriptionId = (int) $order->prescription_id;
|
||||
if ($prescriptionId > 0) {
|
||||
try {
|
||||
$prescription = Prescription::where('id', $prescriptionId)->whereNull('delete_time')->find();
|
||||
if ($prescription) {
|
||||
$prescription->audit_status = 0;
|
||||
$prescription->audit_remark = '';
|
||||
$prescription->audit_time = null;
|
||||
$prescription->audit_by = null;
|
||||
$prescription->audit_by_name = '';
|
||||
$prescription->save();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// 记录日志但不影响主流程
|
||||
Log::error('撤回处方审核时同步处方表失败: ' . $e->getMessage(), [
|
||||
'prescription_id' => $prescriptionId,
|
||||
'order_id' => $id
|
||||
]);
|
||||
}
|
||||
}
|
||||
self::resetPrescriptionReview((int) $order->prescription_id);
|
||||
|
||||
self::writeLog((int) $order->id, $adminId, $adminInfo, 'revoke_rx_audit', '撤回处方审核,状态重置为待审核');
|
||||
|
||||
@@ -2704,6 +2693,21 @@ class PrescriptionOrderLogic
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function resetPrescriptionReview(int $prescriptionId): void
|
||||
{
|
||||
if ($prescriptionId > 0) {
|
||||
Prescription::where('id', $prescriptionId)->whereNull('delete_time')->update([
|
||||
'audit_status' => 0,
|
||||
'review_submitted_at' => 0,
|
||||
'audit_time' => null,
|
||||
'audit_by' => null,
|
||||
'audit_by_name' => '',
|
||||
'audit_remark' => '',
|
||||
'update_time' => time(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 撤回支付单审核:将已通过/已驳回的支付单审核重置为待审核
|
||||
*
|
||||
@@ -2871,10 +2875,16 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
$oldRx = (int) $order->prescription_audit_status;
|
||||
if ($newRx === 1 && $newRx !== $oldRx && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
if ($newRx !== $oldRx) {
|
||||
if ($newRx === 1 && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
if ($newRx === 2) {
|
||||
self::assertPrescriptionReviewReady($order);
|
||||
}
|
||||
if ($newRx === 0) {
|
||||
self::resetPrescriptionReview((int) $order->prescription_id);
|
||||
}
|
||||
$order->prescription_audit_status = $newRx;
|
||||
$changeParts[] = '处方审核:' . self::auditStatusLabelForLog($oldRx)
|
||||
. ' → ' . self::auditStatusLabelForLog($newRx);
|
||||
@@ -5982,13 +5992,16 @@ class PrescriptionOrderLogic
|
||||
$changes['辅方袋数'] = [$oldAuxDosageBagCount, $auxDosageBagCount, '袋'];
|
||||
}
|
||||
}
|
||||
$changes['订单服用天数'] = [$oldMedDays, $medDays, '天'];
|
||||
$parts = [];
|
||||
foreach ($changes as $label => [$oldValue, $newValue, $unit]) {
|
||||
if ($oldValue !== $newValue) {
|
||||
$parts[] = sprintf('%s %d%s → %d%s', $label, $oldValue, $unit, $newValue, $unit);
|
||||
}
|
||||
}
|
||||
$prescriptionChanged = $parts !== [];
|
||||
if ($oldMedDays !== $medDays) {
|
||||
$parts[] = sprintf('订单服用天数:%d → %d', $oldMedDays, $medDays);
|
||||
}
|
||||
if ($parts === []) {
|
||||
return true;
|
||||
}
|
||||
@@ -6010,6 +6023,9 @@ class PrescriptionOrderLogic
|
||||
}
|
||||
$rxUpdates['aux_usage'] = $auxUsage;
|
||||
}
|
||||
if ($prescriptionChanged && PrescriptionEsignPolicy::isPendingReview($rx->toArray())) {
|
||||
$rxUpdates['review_submitted_at'] = 0;
|
||||
}
|
||||
$rx->save($rxUpdates);
|
||||
|
||||
$order->medication_days = $medDays;
|
||||
|
||||
@@ -21,7 +21,7 @@ final class TongueScreenshotLogic extends BaseLogic
|
||||
throw new \DomainException('截图分析请求包含不支持的字段');
|
||||
}
|
||||
$model = array_key_exists('model', $params) ? $params['model'] : 'qwen';
|
||||
if (!is_string($model) || !in_array($model, ['qwen', 'openai'], true)) {
|
||||
if (!is_string($model) || !in_array($model, ['qwen', 'openai', 'doubao'], true)) {
|
||||
throw new \DomainException('截图分析模型无效');
|
||||
}
|
||||
$rawId = $params['id'] ?? null;
|
||||
|
||||
@@ -42,7 +42,13 @@ class AdminTokenService
|
||||
(int) $terminal === AdminTerminalEnum::BCR ? 86400 * 150 : 3600);
|
||||
}
|
||||
|
||||
/** 与改密同一事务调用;只撤销 BCR,会话有效性由 DB 决定,旧缓存不能续活。 */
|
||||
/** 改密撤销原生终端的独立凭据。 */
|
||||
public static function revokeNativeSessions(int $adminId): void
|
||||
{
|
||||
self::revokeBcrSessions($adminId);
|
||||
DesktopSessionService::closeForAdmin($adminId, 'revoked');
|
||||
}
|
||||
|
||||
public static function revokeBcrSessions(int $adminId): void
|
||||
{
|
||||
AdminSession::where('admin_id', $adminId)->where('terminal', AdminTerminalEnum::BCR)
|
||||
@@ -63,6 +69,9 @@ class AdminTokenService
|
||||
*/
|
||||
public static function setToken($adminId, $terminal, $multipointLogin = 1)
|
||||
{
|
||||
if ((int) $terminal === AdminTerminalEnum::WORKSTATION) {
|
||||
return DesktopSessionService::open((int) $adminId);
|
||||
}
|
||||
$time = time();
|
||||
$adminSession = AdminSession::where([['admin_id', '=', $adminId], ['terminal', '=', $terminal]])->find();
|
||||
|
||||
@@ -113,6 +122,9 @@ class AdminTokenService
|
||||
if ($adminSession->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if ((int) $adminSession->terminal === AdminTerminalEnum::WORKSTATION) {
|
||||
return false; // 只有桌面心跳可以续租,不能跨过每天 05:00。
|
||||
}
|
||||
if ((int) $adminSession->terminal === AdminTerminalEnum::BCR) {
|
||||
$previousExpiry = (int) $adminSession->expire_time;
|
||||
if ($previousExpiry <= $time || !Admin::where('id', $adminSession->admin_id)
|
||||
@@ -153,6 +165,9 @@ class AdminTokenService
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((int) $adminSession->terminal === AdminTerminalEnum::WORKSTATION) {
|
||||
return (bool) DesktopSessionService::update((string) $token, 'logout');
|
||||
}
|
||||
// 其他终端保留多处登录的原有退出语义。
|
||||
// BCR 必须注销;同账号多台 BCR 复用一个 token 时,这些设备会一起失效。
|
||||
if ((int) $adminSession->terminal !== AdminTerminalEnum::BCR
|
||||
|
||||
@@ -88,7 +88,7 @@ final class AssistantRequestControl
|
||||
/** Atomic ownership record immediately before this generation's first POST execution. */
|
||||
public function beginSubmission(string $profile, string $user): string
|
||||
{
|
||||
if (!in_array($profile, ['qwen', 'openai'], true) || strlen($user) > 128) throw new \RuntimeException('Invalid submission scope');
|
||||
if (!in_array($profile, ['qwen', 'openai', 'doubao'], true) || strlen($user) > 128) throw new \RuntimeException('Invalid submission scope');
|
||||
$token = bin2hex(random_bytes(12));
|
||||
return $this->update(static function (array &$state) use ($profile, $user, $token): string {
|
||||
if (!self::canStartState($state)) throw new \RuntimeException('UPSTREAM_CLEANUP_PENDING');
|
||||
@@ -198,7 +198,7 @@ final class AssistantRequestControl
|
||||
|
||||
public function bindTask(string $profile, string $user, string $taskId, string $workflowRunId = '', string $submissionId = ''): void
|
||||
{
|
||||
if (!in_array($profile, ['qwen', 'openai'], true)
|
||||
if (!in_array($profile, ['qwen', 'openai', 'doubao'], true)
|
||||
|| !self::validUpstreamId($taskId) || strlen($user) > 128
|
||||
|| ($workflowRunId !== '' && !self::validUpstreamId($workflowRunId))) {
|
||||
throw new \RuntimeException('Invalid upstream task identity');
|
||||
@@ -573,7 +573,7 @@ final class AssistantRequestControl
|
||||
$task = $target['upstream'] ?? [];
|
||||
if (!is_array($task) || !is_string($task['task_id'] ?? null) || !self::validUpstreamId($task['task_id'])
|
||||
|| !is_string($task['workflow_run_id'] ?? null) || !self::validUpstreamId($task['workflow_run_id'])
|
||||
|| !in_array($task['profile'] ?? '', ['qwen', 'openai'], true)
|
||||
|| !in_array($task['profile'] ?? '', ['qwen', 'openai', 'doubao'], true)
|
||||
|| !is_string($task['user'] ?? null) || strlen($task['user']) > 128
|
||||
|| !is_int($task['generation'] ?? null) || $task['generation'] <= 0) return null;
|
||||
return ['profile' => $task['profile'], 'user' => $task['user'], 'task_id' => $task['task_id'],
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\service;
|
||||
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\service\JsonService;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use think\facade\Db;
|
||||
|
||||
/** 医生工作站每次登录单独计时,认证记录与历史记录在同一事务内更新。 */
|
||||
final class DesktopSessionService
|
||||
{
|
||||
public const HEARTBEAT_GRACE = 180;
|
||||
|
||||
public static function nextCutoff(int $time): int
|
||||
{
|
||||
$local = (new DateTimeImmutable('@' . $time))->setTimezone(new DateTimeZone('Asia/Shanghai'));
|
||||
$cutoff = $local->setTime(5, 0);
|
||||
return ($cutoff <= $local ? $cutoff->modify('+1 day') : $cutoff)->getTimestamp();
|
||||
}
|
||||
|
||||
public static function open(int $adminId): array
|
||||
{
|
||||
return Db::transaction(static function () use ($adminId): array {
|
||||
// 即使还没有任何会话行,账号锁也能串行化单点登录的首次并发签发。
|
||||
$admin = Admin::where('id', $adminId)->lock(true)->find();
|
||||
if (!$admin || (int) $admin['disable'] !== 0) {
|
||||
JsonService::throw('账号不存在或已禁用');
|
||||
}
|
||||
if (!(int) $admin['multipoint_login']) {
|
||||
self::closeForAdmin($adminId, 'replaced');
|
||||
}
|
||||
$now = time();
|
||||
$cutoff = self::nextCutoff($now);
|
||||
$due = min($cutoff, $now + self::HEARTBEAT_GRACE);
|
||||
$slot = Db::name('desktop_login_session')->insertGetId([
|
||||
'admin_id' => $adminId, 'account' => $admin['account'], 'name' => $admin['name'],
|
||||
'login_time' => $now, 'last_seen_time' => $now, 'expires_at' => $cutoff,
|
||||
'due_time' => $due, 'login_ip' => request()->ip(),
|
||||
]);
|
||||
$token = bin2hex(random_bytes(16));
|
||||
Db::name('admin_session')->insert([
|
||||
'admin_id' => $adminId, 'terminal' => AdminTerminalEnum::WORKSTATION,
|
||||
'workstation_slot' => $slot, 'token' => $token, 'expire_time' => $due, 'update_time' => $now,
|
||||
]);
|
||||
$info = (new AdminTokenCache())->setAdminInfo($token);
|
||||
if (!$info) {
|
||||
// 签发若恰好跨过 05:00,与认证行一起回滚。
|
||||
JsonService::throw('登录已到期,请重新登录', [], -1);
|
||||
}
|
||||
return $info;
|
||||
});
|
||||
}
|
||||
|
||||
/** 在改密、停用及单点重登事务内调用。其他终端不访问工作站历史表。 */
|
||||
public static function closeForAdmin(int $adminId, string $reason): void
|
||||
{
|
||||
$tokens = Db::name('admin_session')->where('admin_id', $adminId)
|
||||
->where('terminal', AdminTerminalEnum::WORKSTATION)->order('id')->column('token');
|
||||
foreach ($tokens as $token) {
|
||||
self::update((string) $token, $reason);
|
||||
}
|
||||
}
|
||||
|
||||
/** 心跳返回固定的 05:00 截止时间;手工退出或撤销返回结束时间。过期凭据不能续活。 */
|
||||
public static function update(string $token, string $action): int
|
||||
{
|
||||
return Db::transaction(static function () use ($token, $action): int {
|
||||
$auth = Db::name('admin_session')->where('token', $token)
|
||||
->where('terminal', AdminTerminalEnum::WORKSTATION)->lock(true)->find();
|
||||
if (!$auth) {
|
||||
return 0;
|
||||
}
|
||||
$row = Db::name('desktop_login_session')->where('id', $auth['workstation_slot'])
|
||||
->whereNull('logout_time')->lock(true)->find();
|
||||
if (!$row) {
|
||||
return 0;
|
||||
}
|
||||
$now = time();
|
||||
$reason = $action;
|
||||
$end = $now;
|
||||
if ((int) $auth['expire_time'] < (int) $row['due_time'] && (int) $auth['expire_time'] <= $now) {
|
||||
// 兼容通过通用账号管理入口撤销凭据的情形。
|
||||
$reason = 'revoked';
|
||||
$end = min($now, (int) $auth['update_time']);
|
||||
} elseif ((int) $row['due_time'] <= $now) {
|
||||
$cutoffReached = (int) $row['due_time'] === (int) $row['expires_at'];
|
||||
$reason = $cutoffReached ? 'daily_cutoff' : 'timeout';
|
||||
$end = $cutoffReached ? (int) $row['expires_at'] : (int) $row['last_seen_time'];
|
||||
} elseif ($action === 'heartbeat') {
|
||||
$due = min((int) $row['expires_at'], $now + self::HEARTBEAT_GRACE);
|
||||
Db::name('desktop_login_session')->where('id', $row['id'])->update([
|
||||
'last_seen_time' => $now, 'due_time' => $due, 'duration_seconds' => $now - (int) $row['login_time'],
|
||||
]);
|
||||
Db::name('admin_session')->where('id', $auth['id'])->update(['expire_time' => $due, 'update_time' => $now]);
|
||||
return (int) $row['expires_at'];
|
||||
} elseif ($action === 'settle') {
|
||||
// 扫描与锁行之间可能已收到心跳。
|
||||
return 0;
|
||||
}
|
||||
$end = max((int) $row['login_time'], $end);
|
||||
Db::name('desktop_login_session')->where('id', $row['id'])->update([
|
||||
'logout_time' => $end, 'duration_seconds' => $end - (int) $row['login_time'], 'end_reason' => $reason,
|
||||
]);
|
||||
Db::name('admin_session')->where('id', $auth['id'])->delete();
|
||||
return $action === 'heartbeat' ? 0 : $end;
|
||||
});
|
||||
}
|
||||
|
||||
/** 定时任务及报表入口共用;到期时间取已落库的界线,不受任务迟到的影响。 */
|
||||
public static function settleDue(): int
|
||||
{
|
||||
$settled = 0;
|
||||
$now = time();
|
||||
Db::name('admin_session')->where('terminal', AdminTerminalEnum::WORKSTATION)
|
||||
->where('workstation_slot', '>', 0)->where('expire_time', '<=', $now)->field('id,token')
|
||||
->chunk(200, static function ($rows) use (&$settled) {
|
||||
foreach ($rows as $row) {
|
||||
if (self::update((string) $row['token'], 'settle')) {
|
||||
$settled++;
|
||||
}
|
||||
}
|
||||
}, 'id');
|
||||
return $settled;
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ class LoginValidate extends BaseValidate
|
||||
protected $rule = [
|
||||
'terminal' => 'require|in:' . AdminTerminalEnum::PC . ',' . AdminTerminalEnum::MOBILE
|
||||
. ',' . AdminTerminalEnum::WECOM_RPA . ',' . AdminTerminalEnum::WECOM_RPA_MOBILE
|
||||
. ',' . AdminTerminalEnum::BCR,
|
||||
. ',' . AdminTerminalEnum::BCR . ',' . AdminTerminalEnum::WORKSTATION,
|
||||
'account' => 'require',
|
||||
'password' => 'require|password',
|
||||
];
|
||||
|
||||
@@ -1,113 +1,113 @@
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | likeadmin快速开发前后端分离管理后台(PHP版)
|
||||
// +----------------------------------------------------------------------
|
||||
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
|
||||
// | 开源版本可自由商用,可去除界面版权logo
|
||||
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
|
||||
// | github下载:https://github.com/likeshop-github/likeadmin
|
||||
// | 访问官网:https://www.likeadmin.cn
|
||||
// | likeadmin团队 版权所有 拥有最终解释权
|
||||
// +----------------------------------------------------------------------
|
||||
// | author: likeadminTeam
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace app\adminapi\validate\tcm;
|
||||
|
||||
use app\common\model\tcm\Diagnosis;
|
||||
use app\common\validate\BaseValidate;
|
||||
|
||||
/**
|
||||
* 中医辨房病因诊单验证
|
||||
* Class DiagnosisValidate
|
||||
* @package app\adminapi\validate\tcm
|
||||
*/
|
||||
class DiagnosisValidate extends BaseValidate
|
||||
{
|
||||
protected $rule = [
|
||||
'id' => 'require|checkDiagnosis',
|
||||
'patient_name' => 'require|length:1,50',
|
||||
'id_card' => 'length:15,18',
|
||||
'phone' => 'require|mobile',
|
||||
'gender' => 'require|in:0,1',
|
||||
'age' => 'require|number|between:0,150',
|
||||
'diagnosis_type' => 'require',
|
||||
'local_hospital_name' => 'require|max:255',
|
||||
'status' => 'in:0,1',
|
||||
'show_card' => 'in:0,1',
|
||||
'create_source' => 'max:32',
|
||||
'current_medications' => 'max:2000',
|
||||
'tongue_images' => 'array',
|
||||
'report_files' => 'array',
|
||||
'diabetes_discovery_year' => 'max:50',
|
||||
'start_date' => 'date',
|
||||
'end_date' => 'date|checkDateRange',
|
||||
'diagnosis_id' => 'require|integer|checkDiagnosisId',
|
||||
'tracking_content' => 'require|length:1,1000',
|
||||
'revisit_slot_start_offset' => 'integer|between:0,20',
|
||||
'report_id' => 'number|gt:0',
|
||||
'content' => 'max:12000',
|
||||
<?php
|
||||
// +----------------------------------------------------------------------
|
||||
// | likeadmin快速开发前后端分离管理后台(PHP版)
|
||||
// +----------------------------------------------------------------------
|
||||
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
|
||||
// | 开源版本可自由商用,可去除界面版权logo
|
||||
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
|
||||
// | github下载:https://github.com/likeshop-github/likeadmin
|
||||
// | 访问官网:https://www.likeadmin.cn
|
||||
// | likeadmin团队 版权所有 拥有最终解释权
|
||||
// +----------------------------------------------------------------------
|
||||
// | author: likeadminTeam
|
||||
// +----------------------------------------------------------------------
|
||||
|
||||
namespace app\adminapi\validate\tcm;
|
||||
|
||||
use app\common\model\tcm\Diagnosis;
|
||||
use app\common\validate\BaseValidate;
|
||||
|
||||
/**
|
||||
* 中医辨房病因诊单验证
|
||||
* Class DiagnosisValidate
|
||||
* @package app\adminapi\validate\tcm
|
||||
*/
|
||||
class DiagnosisValidate extends BaseValidate
|
||||
{
|
||||
protected $rule = [
|
||||
'id' => 'require|checkDiagnosis',
|
||||
'patient_name' => 'require|length:1,50',
|
||||
'id_card' => 'length:15,18',
|
||||
'phone' => 'require|mobile',
|
||||
'gender' => 'require|in:0,1',
|
||||
'age' => 'require|number|between:0,150',
|
||||
'diagnosis_type' => 'require',
|
||||
'local_hospital_name' => 'require|max:255',
|
||||
'status' => 'in:0,1',
|
||||
'show_card' => 'in:0,1',
|
||||
'create_source' => 'max:32',
|
||||
'current_medications' => 'max:2000',
|
||||
'tongue_images' => 'array',
|
||||
'report_files' => 'array',
|
||||
'diabetes_discovery_year' => 'max:50',
|
||||
'start_date' => 'date',
|
||||
'end_date' => 'date|checkDateRange',
|
||||
'diagnosis_id' => 'require|integer|checkDiagnosisId',
|
||||
'tracking_content' => 'require|length:1,1000',
|
||||
'revisit_slot_start_offset' => 'integer|between:0,20',
|
||||
'report_id' => 'number|gt:0',
|
||||
'content' => 'max:12000',
|
||||
'task' => 'require|in:summary,case_analysis,glucose_trend,lifestyle_advice,tcm_pattern,prescription_review,prescription_generate,medication_review,exam_review,complication_risk,guideline_review,custom,live_consultation,live_review',
|
||||
'prompt' => 'max:500',
|
||||
'model' => 'in:qwen,openai',
|
||||
'patient_id' => 'integer|gt:0',
|
||||
];
|
||||
|
||||
protected $message = [
|
||||
'id.require' => '参数缺失',
|
||||
'patient_name.require' => '请输入患者姓名',
|
||||
'patient_name.length' => '患者姓名长度须在1-50位字符',
|
||||
'id_card.length' => '身份证号长度不正确',
|
||||
'id_card.require' => '请输入身份证号',
|
||||
'phone.require' => '请输入手机号',
|
||||
'phone.mobile' => '手机号格式不正确',
|
||||
'gender.require' => '请选择性别',
|
||||
'gender.in' => '性别参数错误',
|
||||
'age.require' => '请输入年龄',
|
||||
'age.number' => '年龄必须为数字',
|
||||
'age.between' => '年龄范围0-150',
|
||||
'diagnosis_type.require' => '请选择诊断类型',
|
||||
'local_hospital_name.require' => '请输入当地就诊医院名称',
|
||||
'local_hospital_name.max' => '当地就诊医院名称最多255个字符',
|
||||
'status.in' => '状态参数错误',
|
||||
'create_source.max' => '渠道来源长度不能超过32个字符',
|
||||
'current_medications.max' => '在用药物最多2000个字符',
|
||||
'diabetes_discovery_year.max' => '发现糖尿病患病史最多50个字符',
|
||||
'start_date.date' => '开始日期格式不正确',
|
||||
'end_date.date' => '结束日期格式不正确',
|
||||
'diagnosis_id.require' => '诊单ID不能为空',
|
||||
'tracking_content.require' => '跟踪备注内容不能为空',
|
||||
'tracking_content.length' => '跟踪备注最多1000个字符',
|
||||
'report_id.require' => '报告ID不能为空',
|
||||
'report_id.number' => '报告ID必须为数字',
|
||||
'report_id.gt' => '报告ID必须大于0',
|
||||
'content.require' => '报告内容不能为空',
|
||||
'content.max' => '报告内容最多12000个字符',
|
||||
'task.require' => '请选择 AI 助手任务',
|
||||
'task.in' => 'AI 助手任务不受支持',
|
||||
'prompt.max' => '问题最多500个字符',
|
||||
'model.in' => 'AI模型仅支持qwen或openai',
|
||||
'patient_id.require' => '患者ID不能为空',
|
||||
'patient_id.integer' => '患者ID必须为整数',
|
||||
'patient_id.gt' => '患者ID必须大于0',
|
||||
];
|
||||
|
||||
public function sceneAdd()
|
||||
{
|
||||
// 全局规则里混有跟踪备注、AI 助手字段;新增诊单只去掉这些无关校验。
|
||||
// 不要改成 only([...]):add 还会写入现病史等多选字段,only 会把它们从请求里丢掉。
|
||||
return $this->remove('id', true)
|
||||
->remove('diagnosis_id', true)
|
||||
->remove('tracking_content', true)
|
||||
->remove('task', true)
|
||||
->remove('prompt', true)
|
||||
->remove('model', true)
|
||||
->remove('report_id', true)
|
||||
->remove('content', true);
|
||||
}
|
||||
|
||||
public function sceneEdit()
|
||||
{
|
||||
'prompt' => 'max:500',
|
||||
'model' => 'in:qwen,openai,doubao',
|
||||
'patient_id' => 'integer|gt:0',
|
||||
];
|
||||
|
||||
protected $message = [
|
||||
'id.require' => '参数缺失',
|
||||
'patient_name.require' => '请输入患者姓名',
|
||||
'patient_name.length' => '患者姓名长度须在1-50位字符',
|
||||
'id_card.length' => '身份证号长度不正确',
|
||||
'id_card.require' => '请输入身份证号',
|
||||
'phone.require' => '请输入手机号',
|
||||
'phone.mobile' => '手机号格式不正确',
|
||||
'gender.require' => '请选择性别',
|
||||
'gender.in' => '性别参数错误',
|
||||
'age.require' => '请输入年龄',
|
||||
'age.number' => '年龄必须为数字',
|
||||
'age.between' => '年龄范围0-150',
|
||||
'diagnosis_type.require' => '请选择诊断类型',
|
||||
'local_hospital_name.require' => '请输入当地就诊医院名称',
|
||||
'local_hospital_name.max' => '当地就诊医院名称最多255个字符',
|
||||
'status.in' => '状态参数错误',
|
||||
'create_source.max' => '渠道来源长度不能超过32个字符',
|
||||
'current_medications.max' => '在用药物最多2000个字符',
|
||||
'diabetes_discovery_year.max' => '发现糖尿病患病史最多50个字符',
|
||||
'start_date.date' => '开始日期格式不正确',
|
||||
'end_date.date' => '结束日期格式不正确',
|
||||
'diagnosis_id.require' => '诊单ID不能为空',
|
||||
'tracking_content.require' => '跟踪备注内容不能为空',
|
||||
'tracking_content.length' => '跟踪备注最多1000个字符',
|
||||
'report_id.require' => '报告ID不能为空',
|
||||
'report_id.number' => '报告ID必须为数字',
|
||||
'report_id.gt' => '报告ID必须大于0',
|
||||
'content.require' => '报告内容不能为空',
|
||||
'content.max' => '报告内容最多12000个字符',
|
||||
'task.require' => '请选择 AI 助手任务',
|
||||
'task.in' => 'AI 助手任务不受支持',
|
||||
'prompt.max' => '问题最多500个字符',
|
||||
'model.in' => 'AI模型仅支持qwen、openai或doubao',
|
||||
'patient_id.require' => '患者ID不能为空',
|
||||
'patient_id.integer' => '患者ID必须为整数',
|
||||
'patient_id.gt' => '患者ID必须大于0',
|
||||
];
|
||||
|
||||
public function sceneAdd()
|
||||
{
|
||||
// 全局规则里混有跟踪备注、AI 助手字段;新增诊单只去掉这些无关校验。
|
||||
// 不要改成 only([...]):add 还会写入现病史等多选字段,only 会把它们从请求里丢掉。
|
||||
return $this->remove('id', true)
|
||||
->remove('diagnosis_id', true)
|
||||
->remove('tracking_content', true)
|
||||
->remove('task', true)
|
||||
->remove('prompt', true)
|
||||
->remove('model', true)
|
||||
->remove('report_id', true)
|
||||
->remove('content', true);
|
||||
}
|
||||
|
||||
public function sceneEdit()
|
||||
{
|
||||
return $this->only(['id', 'patient_name', 'id_card', 'phone', 'gender', 'age', 'diagnosis_date', 'diagnosis_type', 'syndrome_type', 'marital_status', 'height', 'weight', 'region', 'systolic_pressure', 'diastolic_pressure', 'fasting_blood_sugar', 'diabetes_discovery_year', 'local_hospital_diagnosis', 'local_hospital_name', 'past_history', 'symptoms', 'tongue_coating', 'pulse', 'treatment_principle', 'prescription', 'doctor_advice', 'remark', 'current_medications', 'status', 'show_card', 'create_source'])
|
||||
// 脱敏或被业务锁定的基本信息可省略,省略表示保留原值;显式提交仍需非空且格式有效。
|
||||
->remove(['patient_name' => 'require', 'phone' => 'require', 'gender' => 'require', 'age' => 'require'])
|
||||
@@ -123,28 +123,28 @@ class DiagnosisValidate extends BaseValidate
|
||||
return $this->message[$field . '.require'];
|
||||
}
|
||||
|
||||
public function sceneId()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneReadonlyDetail()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneTrackingWindow()
|
||||
{
|
||||
return $this->only(['id', 'start_date', 'end_date']);
|
||||
}
|
||||
|
||||
/** 新增跟踪备注:诊单ID + 备注内容 */
|
||||
public function sceneAddTrackingNote()
|
||||
{
|
||||
return $this->only(['diagnosis_id', 'tracking_content']);
|
||||
}
|
||||
|
||||
/** 拉取跟踪备注列表:诊单ID */
|
||||
public function sceneId()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneReadonlyDetail()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneTrackingWindow()
|
||||
{
|
||||
return $this->only(['id', 'start_date', 'end_date']);
|
||||
}
|
||||
|
||||
/** 新增跟踪备注:诊单ID + 备注内容 */
|
||||
public function sceneAddTrackingNote()
|
||||
{
|
||||
return $this->only(['diagnosis_id', 'tracking_content']);
|
||||
}
|
||||
|
||||
/** 拉取跟踪备注列表:诊单ID */
|
||||
public function sceneTrackingNotes()
|
||||
{
|
||||
return $this->only(['diagnosis_id']);
|
||||
@@ -161,54 +161,54 @@ class DiagnosisValidate extends BaseValidate
|
||||
}
|
||||
|
||||
public function sceneGenerateQrcode()
|
||||
{
|
||||
return $this->only(['diagnosis_id', 'doctor_id', 'patient_id', 'share_user_id', 'mini_program_path'])
|
||||
// The global diagnosis_id rule is required for diagnosis APIs, but
|
||||
// video QR codes identify the doctor instead. Keep diagnosis_id
|
||||
// optional here while still validating it when it is supplied.
|
||||
->remove('diagnosis_id', 'require')
|
||||
->append('patient_id', 'require|integer|checkQrcodeIds')
|
||||
->append('share_user_id', 'require|integer')
|
||||
->append('doctor_id', 'integer');
|
||||
}
|
||||
|
||||
public function sceneGenerateOrderQrcode()
|
||||
{
|
||||
return $this->only([]);
|
||||
}
|
||||
|
||||
public function sceneFillIdCard()
|
||||
{
|
||||
return $this->only(['id', 'id_card'])
|
||||
->append('id', 'require')
|
||||
->append('id_card', 'require|length:15,18');
|
||||
}
|
||||
|
||||
public function sceneGuahaoLogList()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
/** 业务订单 tab:设置复诊接诊率统计起始偏移 */
|
||||
public function sceneSetRevisitSlotStartOffset()
|
||||
{
|
||||
return $this->only(['id', 'revisit_slot_start_offset'])
|
||||
->append('revisit_slot_start_offset', 'require|integer|between:0,20');
|
||||
}
|
||||
|
||||
public function sceneAiReports()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneAiAssistant()
|
||||
{
|
||||
return $this->only(['id', 'task', 'prompt']);
|
||||
}
|
||||
|
||||
{
|
||||
return $this->only(['diagnosis_id', 'doctor_id', 'patient_id', 'share_user_id', 'mini_program_path'])
|
||||
// The global diagnosis_id rule is required for diagnosis APIs, but
|
||||
// video QR codes identify the doctor instead. Keep diagnosis_id
|
||||
// optional here while still validating it when it is supplied.
|
||||
->remove('diagnosis_id', 'require')
|
||||
->append('patient_id', 'require|integer|checkQrcodeIds')
|
||||
->append('share_user_id', 'require|integer')
|
||||
->append('doctor_id', 'integer');
|
||||
}
|
||||
|
||||
public function sceneGenerateOrderQrcode()
|
||||
{
|
||||
return $this->only([]);
|
||||
}
|
||||
|
||||
public function sceneFillIdCard()
|
||||
{
|
||||
return $this->only(['id', 'id_card'])
|
||||
->append('id', 'require')
|
||||
->append('id_card', 'require|length:15,18');
|
||||
}
|
||||
|
||||
public function sceneGuahaoLogList()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
/** 业务订单 tab:设置复诊接诊率统计起始偏移 */
|
||||
public function sceneSetRevisitSlotStartOffset()
|
||||
{
|
||||
return $this->only(['id', 'revisit_slot_start_offset'])
|
||||
->append('revisit_slot_start_offset', 'require|integer|between:0,20');
|
||||
}
|
||||
|
||||
public function sceneAiReports()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneAiAssistant()
|
||||
{
|
||||
return $this->only(['id', 'task', 'prompt', 'model']);
|
||||
}
|
||||
|
||||
public function sceneAiAssistantStream()
|
||||
{
|
||||
return $this->only(['id', 'task', 'prompt', 'request_id', 'call_record_id', 'transcription_session_id'])
|
||||
return $this->only(['id', 'task', 'prompt', 'model', 'request_id', 'call_record_id', 'transcription_session_id'])
|
||||
->append('task', 'checkLiveAssistantIdentity')
|
||||
->append('request_id', 'checkAssistantRequestId');
|
||||
}
|
||||
@@ -233,136 +233,136 @@ class DiagnosisValidate extends BaseValidate
|
||||
? true : 'AI请求标识无效';
|
||||
}
|
||||
|
||||
public function sceneAiAnalysis()
|
||||
{
|
||||
return $this->only(['id', 'model'])
|
||||
->remove('id', 'checkDiagnosis')
|
||||
->append('id', 'integer|gt:0|checkAiAnalysisPayload');
|
||||
}
|
||||
|
||||
public function scenePatientAiReports()
|
||||
{
|
||||
return $this->only(['patient_id'])
|
||||
->append('patient_id', 'require|integer|gt:0|checkPatientAiReportsPayload');
|
||||
}
|
||||
|
||||
public function sceneGeneratePatientAiReport()
|
||||
{
|
||||
return $this->only(['patient_id', 'model'])
|
||||
->append('patient_id', 'require|integer|gt:0|checkGeneratePatientAiReportPayload')
|
||||
->append('model', 'require|in:qwen,openai');
|
||||
}
|
||||
|
||||
public function sceneGenerateAiReports()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneEditAiReport()
|
||||
{
|
||||
return $this->only(['id', 'report_id', 'content'])
|
||||
->append('report_id', 'require|number|gt:0')
|
||||
->append('content', 'require|max:12000');
|
||||
}
|
||||
|
||||
protected function checkDiagnosis($value)
|
||||
{
|
||||
$diagnosis = Diagnosis::findOrEmpty($value);
|
||||
if ($diagnosis->isEmpty()) {
|
||||
return '诊单不存在';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 校验 diagnosis_id 字段(addTrackingNote 等场景使用,避开 id 字段) */
|
||||
protected function checkDiagnosisId($value)
|
||||
{
|
||||
$diagnosis = Diagnosis::findOrEmpty($value);
|
||||
if ($diagnosis->isEmpty()) {
|
||||
return '诊单不存在';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** end_date 不能早于 start_date */
|
||||
protected function checkDateRange($value, $rule, $data = [])
|
||||
{
|
||||
$start = $data['start_date'] ?? '';
|
||||
if ($start && $value && strtotime($value) < strtotime($start)) {
|
||||
return '结束日期不能早于开始日期';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 视频场景需 doctor_id,确认诊单需 diagnosis_id */
|
||||
protected function checkQrcodeIds($value, $rule, $data = [])
|
||||
{
|
||||
$page = $data['mini_program_path'] ?? '';
|
||||
$hasDoctor = !empty($data['doctor_id']);
|
||||
$hasDiagnosis = !empty($data['diagnosis_id']);
|
||||
if ($page === 'pages/login/login') {
|
||||
return $hasDoctor ? true : '视频二维码需传挂号医生ID';
|
||||
}
|
||||
return $hasDiagnosis ? true : '诊单ID不能为空';
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 智能分析仅接受诊单 ID 和可选的固定模型键。客户端不得提供
|
||||
* provider、凭据、上游地址、提示词等服务端配置或控制字段。
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param mixed $rule
|
||||
* @param array<string,mixed> $data
|
||||
* @return bool|string
|
||||
*/
|
||||
protected function checkAiAnalysisPayload($value, $rule, array $data = [])
|
||||
{
|
||||
if (!array_key_exists('id', $data)) {
|
||||
return 'AI智能分析请求缺少id参数';
|
||||
}
|
||||
|
||||
$extraFields = array_diff(array_keys($data), ['id', 'model']);
|
||||
if ($extraFields !== []) {
|
||||
return 'AI智能分析请求仅允许id及可选model参数';
|
||||
}
|
||||
|
||||
if (array_key_exists('model', $data)) {
|
||||
$model = $data['model'];
|
||||
if (!is_string($model) || !in_array($model, ['qwen', 'openai'], true)) {
|
||||
return 'AI模型仅支持qwen或openai';
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
protected function checkPatientAiReportsPayload($value, $rule, array $data = [])
|
||||
{
|
||||
if (!array_key_exists('patient_id', $data)) {
|
||||
return '请求缺少patient_id参数';
|
||||
}
|
||||
$extraFields = array_diff(array_keys($data), ['patient_id']);
|
||||
return $extraFields === [] ? true : '请求仅允许patient_id参数';
|
||||
}
|
||||
|
||||
/**
|
||||
* 患者报告生成端点只接受稳定患者ID与服务端模型白名单键。
|
||||
* provider、凭据、BASE_URL、提示词和任意来源正文均不得由客户端注入。
|
||||
*
|
||||
* @param array<string,mixed> $data
|
||||
*/
|
||||
protected function checkGeneratePatientAiReportPayload($value, $rule, array $data = [])
|
||||
{
|
||||
if (!array_key_exists('patient_id', $data) || !array_key_exists('model', $data)) {
|
||||
return '请求缺少patient_id或model参数';
|
||||
}
|
||||
$extraFields = array_diff(array_keys($data), ['patient_id', 'model']);
|
||||
if ($extraFields !== []) {
|
||||
return '请求仅允许patient_id和model参数';
|
||||
}
|
||||
if (!is_string($data['model']) || !in_array($data['model'], ['qwen', 'openai'], true)) {
|
||||
return 'AI模型仅支持qwen或openai';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public function sceneAiAnalysis()
|
||||
{
|
||||
return $this->only(['id', 'model'])
|
||||
->remove('id', 'checkDiagnosis')
|
||||
->append('id', 'integer|gt:0|checkAiAnalysisPayload');
|
||||
}
|
||||
|
||||
public function scenePatientAiReports()
|
||||
{
|
||||
return $this->only(['patient_id'])
|
||||
->append('patient_id', 'require|integer|gt:0|checkPatientAiReportsPayload');
|
||||
}
|
||||
|
||||
public function sceneGeneratePatientAiReport()
|
||||
{
|
||||
return $this->only(['patient_id', 'model'])
|
||||
->append('patient_id', 'require|integer|gt:0|checkGeneratePatientAiReportPayload')
|
||||
->append('model', 'require|in:qwen,openai,doubao');
|
||||
}
|
||||
|
||||
public function sceneGenerateAiReports()
|
||||
{
|
||||
return $this->only(['id']);
|
||||
}
|
||||
|
||||
public function sceneEditAiReport()
|
||||
{
|
||||
return $this->only(['id', 'report_id', 'content'])
|
||||
->append('report_id', 'require|number|gt:0')
|
||||
->append('content', 'require|max:12000');
|
||||
}
|
||||
|
||||
protected function checkDiagnosis($value)
|
||||
{
|
||||
$diagnosis = Diagnosis::findOrEmpty($value);
|
||||
if ($diagnosis->isEmpty()) {
|
||||
return '诊单不存在';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 校验 diagnosis_id 字段(addTrackingNote 等场景使用,避开 id 字段) */
|
||||
protected function checkDiagnosisId($value)
|
||||
{
|
||||
$diagnosis = Diagnosis::findOrEmpty($value);
|
||||
if ($diagnosis->isEmpty()) {
|
||||
return '诊单不存在';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** end_date 不能早于 start_date */
|
||||
protected function checkDateRange($value, $rule, $data = [])
|
||||
{
|
||||
$start = $data['start_date'] ?? '';
|
||||
if ($start && $value && strtotime($value) < strtotime($start)) {
|
||||
return '结束日期不能早于开始日期';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 视频场景需 doctor_id,确认诊单需 diagnosis_id */
|
||||
protected function checkQrcodeIds($value, $rule, $data = [])
|
||||
{
|
||||
$page = $data['mini_program_path'] ?? '';
|
||||
$hasDoctor = !empty($data['doctor_id']);
|
||||
$hasDiagnosis = !empty($data['diagnosis_id']);
|
||||
if ($page === 'pages/login/login') {
|
||||
return $hasDoctor ? true : '视频二维码需传挂号医生ID';
|
||||
}
|
||||
return $hasDiagnosis ? true : '诊单ID不能为空';
|
||||
}
|
||||
|
||||
/**
|
||||
* AI 智能分析仅接受诊单 ID 和可选的固定模型键。客户端不得提供
|
||||
* provider、凭据、上游地址、提示词等服务端配置或控制字段。
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param mixed $rule
|
||||
* @param array<string,mixed> $data
|
||||
* @return bool|string
|
||||
*/
|
||||
protected function checkAiAnalysisPayload($value, $rule, array $data = [])
|
||||
{
|
||||
if (!array_key_exists('id', $data)) {
|
||||
return 'AI智能分析请求缺少id参数';
|
||||
}
|
||||
|
||||
$extraFields = array_diff(array_keys($data), ['id', 'model']);
|
||||
if ($extraFields !== []) {
|
||||
return 'AI智能分析请求仅允许id及可选model参数';
|
||||
}
|
||||
|
||||
if (array_key_exists('model', $data)) {
|
||||
$model = $data['model'];
|
||||
if (!is_string($model) || !in_array($model, ['qwen', 'openai', 'doubao'], true)) {
|
||||
return 'AI模型仅支持qwen、openai或doubao';
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
protected function checkPatientAiReportsPayload($value, $rule, array $data = [])
|
||||
{
|
||||
if (!array_key_exists('patient_id', $data)) {
|
||||
return '请求缺少patient_id参数';
|
||||
}
|
||||
$extraFields = array_diff(array_keys($data), ['patient_id']);
|
||||
return $extraFields === [] ? true : '请求仅允许patient_id参数';
|
||||
}
|
||||
|
||||
/**
|
||||
* 患者报告生成端点只接受稳定患者ID与服务端模型白名单键。
|
||||
* provider、凭据、BASE_URL、提示词和任意来源正文均不得由客户端注入。
|
||||
*
|
||||
* @param array<string,mixed> $data
|
||||
*/
|
||||
protected function checkGeneratePatientAiReportPayload($value, $rule, array $data = [])
|
||||
{
|
||||
if (!array_key_exists('patient_id', $data) || !array_key_exists('model', $data)) {
|
||||
return '请求缺少patient_id或model参数';
|
||||
}
|
||||
$extraFields = array_diff(array_keys($data), ['patient_id', 'model']);
|
||||
if ($extraFields !== []) {
|
||||
return '请求仅允许patient_id和model参数';
|
||||
}
|
||||
if (!is_string($data['model']) || !in_array($data['model'], ['qwen', 'openai', 'doubao'], true)) {
|
||||
return 'AI模型仅支持qwen、openai或doubao';
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
|
||||
final class DesktopSessionSettle extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('desktop-session:settle')->setDescription('结算已到期的医生工作站登录记录');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output): int
|
||||
{
|
||||
$output->writeln('已结算工作站会话 ' . DesktopSessionService::settleDue() . ' 条');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+17
-3
@@ -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)占用,不要复用。
|
||||
|
||||
@@ -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 : ''];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ return [
|
||||
'alert_enabled' => filter_var(env('assistant_service.ALERT_ENABLED', false), FILTER_VALIDATE_BOOLEAN),
|
||||
'alert_interval_seconds' => max(5, min(3600, (int) env('assistant_service.ALERT_INTERVAL_SECONDS', 60))),
|
||||
'alert_batch_size' => max(1, min(500, (int) env('assistant_service.ALERT_BATCH_SIZE', 200))),
|
||||
// 企微客服归档(im.zhenyangtang.cn)。只拉员工发出且已绑定患者的文字。
|
||||
// 医助工作台归档和员工预警。对接配置见 server/docs/wecom-archive.md。
|
||||
// 每个业务实例只关联一个归档租户;该租户的患者 ID 必须来自本实例。
|
||||
'wecom_archive_tenant' => (string) env('assistant_service.WECOM_ARCHIVE_TENANT', ''),
|
||||
'wecom_archive_sqlite' => (string) env('assistant_service.WECOM_ARCHIVE_SQLITE', ''),
|
||||
'wecom_archive_base_url' => rtrim((string) env('assistant_service.WECOM_ARCHIVE_BASE_URL', ''), '/'),
|
||||
'wecom_archive_token' => (string) env('assistant_service.WECOM_ARCHIVE_TOKEN', ''),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
return [
|
||||
// 指令定义
|
||||
'commands' => [
|
||||
'desktop-session:settle' => 'app\\command\\DesktopSessionSettle',
|
||||
'esign:setup' => 'app\\command\\EsignSetup',
|
||||
'assistant-service:daily' => 'app\\command\\AssistantServiceDaily',
|
||||
'assistant-service:alert' => 'app\\command\\AssistantServiceAlert',
|
||||
|
||||
@@ -125,5 +125,24 @@ return [
|
||||
env('prescription_ai.openai_api_key', '')
|
||||
),
|
||||
],
|
||||
/**
|
||||
* 豆包:直连火山方舟 Ark 的 OpenAI 兼容 chat/completions,不经过 Dify。
|
||||
* 只能内联图片(按 URL 由方舟拉取),PDF 等文档会被明确标记为不支持的附件。
|
||||
* THINKING 留空则沿用模型默认的深度思考;填 disabled 可关闭以缩短响应时间。
|
||||
*/
|
||||
'doubao' => [
|
||||
'name' => (string) env('prescription_ai.DOUBAO_MODEL', 'doubao-seed-2-1-pro-260915'),
|
||||
'label' => '豆包',
|
||||
'base_url' => rtrim((string) env(
|
||||
'prescription_ai.DOUBAO_BASE_URL',
|
||||
'https://ark.cn-beijing.volces.com/api/v3/chat/completions'
|
||||
), '/'),
|
||||
'max_files' => (int) env('prescription_ai.DOUBAO_MAX_FILES', 10),
|
||||
'thinking' => strtolower(trim((string) env('prescription_ai.DOUBAO_THINKING', ''))),
|
||||
'api_key' => (string) env(
|
||||
'prescription_ai.DOUBAO_API_KEY',
|
||||
env('prescription_ai.ARK_API_KEY', '')
|
||||
),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
SET @has_review_submitted_at = (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'zyt_tcm_prescription'
|
||||
AND COLUMN_NAME = 'review_submitted_at'
|
||||
);
|
||||
SET @ddl = IF(@has_review_submitted_at = 0,
|
||||
'ALTER TABLE `zyt_tcm_prescription` ADD COLUMN `review_submitted_at` int unsigned NOT NULL DEFAULT 0 COMMENT ''医生提交处方审核时间(Unix 秒)''',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@@ -0,0 +1,55 @@
|
||||
-- 工作站每次登录独立计时。旧终端默认 workstation_slot=0,继续按账号/终端唯一。
|
||||
CREATE TABLE IF NOT EXISTS zyt_desktop_login_session (
|
||||
id bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
admin_id int unsigned NOT NULL,
|
||||
account varchar(128) NOT NULL,
|
||||
name varchar(128) NOT NULL,
|
||||
login_ip varchar(45) NOT NULL,
|
||||
login_time int unsigned NOT NULL,
|
||||
last_seen_time int unsigned NOT NULL,
|
||||
expires_at int unsigned NOT NULL COMMENT '北京时间下一次 05:00',
|
||||
due_time int unsigned NOT NULL COMMENT '当前心跳租约与 05:00 中的较早时间',
|
||||
logout_time int unsigned DEFAULT NULL,
|
||||
duration_seconds int unsigned NOT NULL DEFAULT 0,
|
||||
end_reason varchar(20) NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_desktop_admin_time (admin_id,login_time),
|
||||
KEY idx_desktop_login_time (login_time),
|
||||
KEY idx_desktop_due (logout_time,due_time)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='医生工作站登录时长';
|
||||
|
||||
SET @ddl = IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE()
|
||||
AND table_name='zyt_admin_session' AND column_name='workstation_slot'),
|
||||
'SELECT 1', 'ALTER TABLE zyt_admin_session ADD workstation_slot bigint unsigned NOT NULL DEFAULT 0');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @ddl = IF(EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema=DATABASE()
|
||||
AND table_name='zyt_admin_session' AND index_name='uk_admin_terminal_slot'),
|
||||
'SELECT 1', 'ALTER TABLE zyt_admin_session ADD UNIQUE KEY uk_admin_terminal_slot (admin_id,terminal,workstation_slot)');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @ddl = IF(EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema=DATABASE()
|
||||
AND table_name='zyt_admin_session' AND index_name='idx_terminal_expiry'),
|
||||
'SELECT 1', 'ALTER TABLE zyt_admin_session ADD KEY idx_terminal_expiry (terminal,expire_time)');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @old_indexes = (SELECT GROUP_CONCAT(CONCAT('DROP INDEX `', REPLACE(i.index_name, '`', '``'), '`') SEPARATOR ', ')
|
||||
FROM (SELECT index_name FROM information_schema.statistics
|
||||
WHERE table_schema=DATABASE() AND table_name='zyt_admin_session' AND non_unique=0 AND index_name<>'PRIMARY'
|
||||
GROUP BY index_name HAVING GROUP_CONCAT(column_name ORDER BY seq_in_index) IN ('admin_id,terminal','terminal,admin_id')) i);
|
||||
SET @ddl = IF(@old_indexes IS NULL, 'SELECT 1', CONCAT('ALTER TABLE zyt_admin_session ', @old_indexes));
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
INSERT INTO zyt_dev_crontab
|
||||
(name,type,`system`,remark,command,params,status,expression,last_time,create_time,update_time)
|
||||
SELECT '工作站登录会话结算',1,1,'结算掉线和每日 05:00 截止的会话','desktop-session:settle','',1,'* * * * *',
|
||||
UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
|
||||
WHERE NOT EXISTS (SELECT 1 FROM zyt_dev_crontab WHERE command='desktop-session:settle' AND delete_time IS NULL);
|
||||
@@ -0,0 +1,28 @@
|
||||
-- 在系统日志旁新增桌面登录记录,并继承已有系统日志的查看权限。
|
||||
START TRANSACTION;
|
||||
|
||||
SET @desktop_log_source = (
|
||||
SELECT id FROM zyt_system_menu WHERE perms = 'setting.system.log/lists' ORDER BY id LIMIT 1
|
||||
);
|
||||
INSERT INTO zyt_system_menu
|
||||
(pid, type, name, icon, sort, perms, paths, component, selected, params, is_cache, is_show, is_disable, create_time, update_time)
|
||||
SELECT COALESCE(src.pid, (SELECT id FROM zyt_system_menu WHERE type = 'M' AND name = '系统维护' ORDER BY id LIMIT 1), 0),
|
||||
'C', '桌面登录记录', '', COALESCE(src.sort, 90), 'setting.system.log/desktopSessions',
|
||||
'desktop_sessions', 'setting/system/desktop_sessions', '', '', 0, 1, COALESCE(src.is_disable, 0), UNIX_TIMESTAMP(), UNIX_TIMESTAMP()
|
||||
FROM (SELECT @desktop_log_source AS id) source_id
|
||||
LEFT JOIN zyt_system_menu src ON src.id = source_id.id
|
||||
WHERE NOT EXISTS (SELECT 1 FROM zyt_system_menu WHERE perms = 'setting.system.log/desktopSessions');
|
||||
|
||||
-- 仅在首次创建菜单时继承角色,重跑迁移时保留管理员之后手工调整的授权。
|
||||
SET @desktop_log_created = ROW_COUNT();
|
||||
INSERT INTO zyt_system_role_menu (role_id, menu_id)
|
||||
SELECT DISTINCT grant_row.role_id, target.id
|
||||
FROM zyt_system_role_menu grant_row
|
||||
JOIN zyt_system_menu target ON target.perms = 'setting.system.log/desktopSessions'
|
||||
WHERE @desktop_log_created = 1
|
||||
AND grant_row.menu_id = @desktop_log_source
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM zyt_system_role_menu existing WHERE existing.role_id = grant_row.role_id AND existing.menu_id = target.id
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,9 @@
|
||||
# 医助工作台的企微归档对接
|
||||
|
||||
每个业务后台实例使用一个归档租户。在服务端配置的 `[ASSISTANT_SERVICE]` 节中设置 `WECOM_ARCHIVE_TENANT`,填写归档端实际的 `tenant_id`。归档端绑定的员工和患者必须属于本业务实例的身份体系。多个独立租户分别配置对接实例。
|
||||
|
||||
- HTTP 对接使用 `WECOM_ARCHIVE_BASE_URL` 和 `WECOM_ARCHIVE_TOKEN`。生产地址必须使用 HTTPS,原有远端 HTTP 地址需要切换到 HTTPS。归档端在 `ARCHIVE_STAFF_FEED_GRANTS` 中为该租户登记令牌的 SHA-256,业务端保存相应的原始高熵令牌。客户端同时发送令牌和租户声明,并核对成功响应中的唯一 `X-Archive-Tenant` 是否与配置完全一致。旧版归档服务缺少该响应头,需先升级。仅本机回环地址支持 HTTP 联调。
|
||||
- 本地读取使用 `WECOM_ARCHIVE_SQLITE` 指向归档 SQLite 文件。文件存在时优先读取本地库,按同一个 `WECOM_ARCHIVE_TENANT` 查询。
|
||||
- 员工归属使用后台唯一绑定的 `work_wechat_userid` 对应归档的 `external_account_id`。显示名仅供展示。单聊中有唯一入站对方和唯一有效主患者绑定时,预警才使用在本业务库能核验的患者 ID。受限员工还需同时具有员工和患者的可见权限。无法确认归属的会话由具有全员工范围的角色查看。
|
||||
|
||||
预警模块升级时,在已具备 `source_key` 和 `external_staff` 等既有字段的业务库执行 [归档租户迁移](../sql/1.9.20261110/05_assistant_service_alert_tenant.sql),按实例核对表前缀。迁移保留已有记录,历史企微预警的租户为空,业务接口将其隐藏。重新扫描后按经核验的租户写入预警。切换租户会重置企微扫描和用词检查游标。关闭租户配置后,企微预警查询和归档读取均关闭。
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 现有业务库升级和新库建表后均执行一次。空值表示历史记录未经租户验证。
|
||||
ALTER TABLE `zyt_assistant_service_alert`
|
||||
ADD COLUMN `archive_tenant_id` varchar(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '' AFTER `source_key`,
|
||||
DROP INDEX `uk_channel_source_rule`,
|
||||
ADD UNIQUE KEY `uk_channel_source_rule` (`channel`,`archive_tenant_id`,`source_id`,`source_key`,`rule_code`);
|
||||
@@ -10,11 +10,13 @@ use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
|
||||
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
|
||||
use app\common\service\assistantservice\AssistantServiceAccess as Access;
|
||||
use app\common\service\assistantservice\AssistantServiceAlert as Alert;
|
||||
use app\common\service\assistantservice\WecomArchiveSqlite as Archive;
|
||||
use think\Container;
|
||||
use think\facade\Db;
|
||||
|
||||
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) { throw new RuntimeException('需要隔离测试 SQLite 扩展'); }
|
||||
new think\App();
|
||||
$temporary = sys_get_temp_dir() . '/assistant-alert-test-' . bin2hex(random_bytes(6));
|
||||
new think\App($temporary);
|
||||
set_exception_handler(static function (Throwable $e): void { fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1); });
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true]]]);
|
||||
@@ -26,7 +28,7 @@ $config->set($settings, 'assistant_service');
|
||||
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
$tables = [
|
||||
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
|
||||
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,work_wechat_userid TEXT DEFAULT "",root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
|
||||
'admin_role' => 'admin_id INTEGER,role_id INTEGER', 'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
|
||||
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
|
||||
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
|
||||
@@ -36,7 +38,7 @@ $tables = [
|
||||
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER DEFAULT 0,from_account TEXT COLLATE NOCASE,to_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
|
||||
'tcm_call_record' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,caller_id INTEGER,caller_type TEXT,callee_id INTEGER,callee_type TEXT,start_time INTEGER,duration INTEGER,delete_time INTEGER NULL',
|
||||
'tcm_call_transcript_segment' => 'id INTEGER PRIMARY KEY,call_record_id INTEGER,speaker_user_id TEXT,speaker_role TEXT,text TEXT,create_time INTEGER',
|
||||
'assistant_service_alert' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,staff_admin_id INTEGER,patient_id INTEGER,diagnosis_id INTEGER DEFAULT 0,channel TEXT,source_id INTEGER,source_key TEXT NOT NULL DEFAULT "",external_staff TEXT NOT NULL DEFAULT "",external_patient TEXT NOT NULL DEFAULT "",rule_code TEXT,rule_version INTEGER,severity TEXT,snippet TEXT,status TEXT DEFAULT "open",reviewer_id INTEGER DEFAULT 0,review_note TEXT DEFAULT "",reviewed_at INTEGER DEFAULT 0,occurred_at INTEGER,created_at INTEGER,updated_at INTEGER,UNIQUE(channel,source_id,source_key,rule_code)',
|
||||
'assistant_service_alert' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,staff_admin_id INTEGER,patient_id INTEGER,diagnosis_id INTEGER DEFAULT 0,channel TEXT,source_id INTEGER,source_key TEXT NOT NULL DEFAULT "",archive_tenant_id TEXT NOT NULL DEFAULT "",external_staff TEXT NOT NULL DEFAULT "",external_patient TEXT NOT NULL DEFAULT "",rule_code TEXT,rule_version INTEGER,severity TEXT,snippet TEXT,status TEXT DEFAULT "open",reviewer_id INTEGER DEFAULT 0,review_note TEXT DEFAULT "",reviewed_at INTEGER DEFAULT 0,occurred_at INTEGER,created_at INTEGER,updated_at INTEGER,UNIQUE(channel,archive_tenant_id,source_id,source_key,rule_code)',
|
||||
];
|
||||
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
|
||||
Db::name('admin')->insertAll([['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => '甲', 'root' => 0],
|
||||
@@ -52,7 +54,6 @@ Db::name('tcm_diagnosis')->insertAll([
|
||||
['id' => 102, 'patient_id' => 301, 'assistant_id' => 12, 'patient_name' => '域外患者', 'phone' => '', 'status' => 1],
|
||||
]);
|
||||
$clock = (new DateTimeImmutable('2026-11-10 11:00:00', new DateTimeZone('Asia/Shanghai')))->getTimestamp();
|
||||
$temporary = sys_get_temp_dir() . '/assistant-alert-test-' . bin2hex(random_bytes(6));
|
||||
$scanner = new Alert($temporary, static function () use (&$clock): int { return $clock; });
|
||||
$checks = 0;
|
||||
$ok = static function (bool $pass, string $message) use (&$checks): void { if (!$pass) { throw new RuntimeException($message); } $checks++; };
|
||||
@@ -151,6 +152,7 @@ try {
|
||||
$configure(['alert_enabled' => true, 'alert_batch_size' => 1]);
|
||||
$ok($scanner->tick()['created'] === 1 && $scanner->tick()['state'] === 'waiting', '一批只处理设定条数,下一条等下一轮');
|
||||
$clock += 61;
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_tenant' => 'tenant-a']);
|
||||
$wecom = new Alert($temporary, static function () use (&$clock): int { return $clock; }, static function (string $cursor): array {
|
||||
if ($cursor !== '') { return ['configured' => true, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false]; }
|
||||
return ['configured' => true, 'has_more' => false, 'next_cursor' => '2026-11-10T03:00:00Z|m1', 'items' => [[
|
||||
@@ -162,26 +164,65 @@ try {
|
||||
$ok($fed['created'] === 1 && (int) Db::name('assistant_service_alert')->where('channel', 'wecom')->where('source_key', 'm1:201')->count() === 1, '企微归档里员工发出且已绑定患者的文字进入预警');
|
||||
$local = $temporary . '/archive.db';
|
||||
$archive = new PDO('sqlite:' . $local);
|
||||
$archive->exec('CREATE TABLE archive_source_account (id TEXT PRIMARY KEY, display_name TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_conversation (id TEXT PRIMARY KEY, conversation_type TEXT, name TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_message (id TEXT PRIMARY KEY, conversation_id TEXT, source_account_id TEXT, content TEXT, direction TEXT, status TEXT, message_type TEXT, sent_at TEXT, sent_at_epoch INTEGER)');
|
||||
$archive->exec("INSERT INTO archive_source_account VALUES ('a1','甲'),('a2','外来客服')");
|
||||
$archive->exec("INSERT INTO archive_conversation VALUES ('c1','direct_wecom','合成甲'),('c2','direct_wecom','未建档')");
|
||||
$archive->exec("INSERT INTO archive_message VALUES ('local1','c1','a1','加我微信','outbound','normal','文本','2026-11-10T03:00:00+00:00',1794268800),('local2','c2','a2','私下转账给我','outbound','normal','文本','2026-11-10T03:01:00+00:00',1794268860)");
|
||||
Db::name('admin')->where('id', 11)->update(['work_wechat_userid' => 'staff-a']);
|
||||
Db::name('admin')->where('id', 12)->update(['work_wechat_userid' => 'staff-b']);
|
||||
$archive->exec('CREATE TABLE archive_source_account (id TEXT PRIMARY KEY, tenant_id TEXT, external_account_id TEXT, display_name TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_conversation (id TEXT PRIMARY KEY, tenant_id TEXT, source_account_id TEXT, conversation_type TEXT, name TEXT, last_message_at TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_message (id TEXT PRIMARY KEY, conversation_id TEXT, source_account_id TEXT, content TEXT, direction TEXT, status TEXT, message_type TEXT, sent_at TEXT, sent_at_epoch INTEGER, tenant_id TEXT, sender_person_id TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_person (id TEXT PRIMARY KEY, tenant_id TEXT, display_name TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_patient_binding (tenant_id TEXT, person_id TEXT, patient_id INTEGER, diagnosis_id INTEGER, status TEXT, is_primary INTEGER)');
|
||||
$archive->exec("INSERT INTO archive_source_account VALUES ('a1','tenant-a','staff-a','甲'),('a2','tenant-a','unbound','外来客服'),('a3','tenant-a','staff-b','甲'),('b1','tenant-b','staff-a','甲')");
|
||||
$archive->exec("INSERT INTO archive_conversation VALUES ('c1','tenant-a','a1','direct_wecom','合成甲','3'),('c2','tenant-a','a2','direct_wecom','未建档','3'),('c3','tenant-a','a3','direct_wecom','合成甲','3'),('cb','tenant-b','b1','direct_wecom','乙','3'),('bad','tenant-b','a1','direct_wecom','域外','3')");
|
||||
$archive->exec("INSERT INTO archive_person VALUES ('p1','tenant-a','合成甲'),('pb','tenant-b','其他租户')");
|
||||
$archive->exec("INSERT INTO archive_patient_binding VALUES ('tenant-a','p1',201,101,'active',1),('tenant-b','p1',301,102,'active',1)");
|
||||
$archive->exec("INSERT INTO archive_message VALUES
|
||||
('local1','c1','a1','加我微信','outbound','normal','文本','2026-11-10T03:00:00+00:00',1794268800,'tenant-a','pb'),
|
||||
('local2','c2','a2','私下转账给我','outbound','normal','文本','2026-11-10T03:01:00+00:00',1794268860,'tenant-a',NULL),
|
||||
('peer','c1','a1','合成入站','inbound','normal','文本','2026-11-09',1794268700,'tenant-a','p1'),
|
||||
('foreign','cb','b1','加我微信','outbound','normal','文本','2026-11-09',1794268700,'tenant-b','pb'),
|
||||
('foreign-link','c1','b1','范围外','outbound','normal','文本','2099-01',1794268700,'tenant-b','pb'),
|
||||
('mismatch','c1','a3','其他员工','outbound','normal','文本','2099-02',1794268700,'tenant-a',NULL)");
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => '']);
|
||||
$ok(!Archive::configured() && !Archive::page('', 5)['configured'] && Archive::accounts() === []
|
||||
&& Archive::conversations('staff-a') === [] && Archive::messages('c1')['messages'] === [], '未绑定租户时本地归档关闭');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => 'tenant-a']);
|
||||
$directory = Alert::wecomDirectory(11);
|
||||
$ok($directory['ready'] && count($directory['staff']) === 1 && $directory['staff'][0]['conversations'] === 1
|
||||
&& !$directory['accounts'], '按员工范围和稳定账号计算目录,显示名重合不增加计数');
|
||||
$chats = Alert::wecomChats(['assistant_id' => 11], 11)['conversations'];
|
||||
$ok(array_column($chats, 'id') === ['c1'] && $chats[0]['message_count'] === 2 && $chats[0]['preview'] === '加我微信', '会话计数和预览仅包含本租户该员工的消息');
|
||||
$ok(array_column(Alert::wecomMessages(['assistant_id' => 11, 'conversation_id' => 'c1'], 11)['messages'], 'sender_name') === ['合成甲', ''], '正文只含本账号消息,跨租户发言人不显示');
|
||||
$deny(static fn () => Alert::wecomMessages(['assistant_id' => 11, 'conversation_id' => 'c3'], 11), '同名员工不能查看他人正文');
|
||||
$deny(static fn () => Alert::wecomChats(['assistant_id' => 12], 11), '越过部门的医助不可选');
|
||||
$deny(static fn () => Alert::wecomChats(['account' => 'staff-b'], 11), '受限员工不能直接指定账号');
|
||||
$deny(static fn () => Alert::wecomMessages(['account' => 'staff-a', 'conversation_id' => 'cb'], 1), '全范围管理员也不能凭 ID 查看其他租户正文');
|
||||
Db::name('admin')->where('id', 12)->update(['work_wechat_userid' => 'staff-a']);
|
||||
$ok(!Alert::wecomChats(['assistant_id' => 11], 11)['conversations'] && Alert::wecomDirectory(11)['staff'][0]['conversations'] === 0, '稳定账号归属重复时拒绝受限访问');
|
||||
Db::name('admin')->where('id', 11)->update(['work_wechat_userid' => '']);
|
||||
$ok(!Alert::wecomChats(['assistant_id' => 11], 11)['conversations'], '缺少绑定不能按同名查看');
|
||||
Db::name('admin')->where('id', 11)->update(['work_wechat_userid' => 'staff-a']);
|
||||
Db::name('admin')->where('id', 12)->update(['work_wechat_userid' => 'staff-b']);
|
||||
$page = Archive::page('', 1);
|
||||
$ok($page['has_more'] && $page['items'][0]['id'] === 'local1' && $page['items'][0]['patient_id'] === 201
|
||||
&& array_column(Archive::page($page['next_cursor'], 10)['items'], 'id') === ['local2'], '定时分页只含归属租户的发出文字,患者来自明确绑定');
|
||||
$archive->exec("INSERT INTO archive_patient_binding VALUES ('tenant-a','p1',301,102,'active',1)");
|
||||
$ok(Archive::page('', 1)['items'][0]['patient_id'] === 0, '多个有效主绑定不会被用于授权');
|
||||
$archive->exec("DELETE FROM archive_patient_binding WHERE tenant_id='tenant-a' AND patient_id=301");
|
||||
$legacy = Archive::identify([['id' => 'legacy', 'staff_name' => '甲', 'patient_name' => '合成甲']])[0];
|
||||
$ok($legacy['patient_id'] === 0 && $legacy['zyt_user_id'] === '0', '旧版 HTTP 只带名字时保留未归属');
|
||||
$saved = json_decode((string) file_get_contents($temporary . '/scan.json'), true);
|
||||
$saved['wecom_cursor'] = '';
|
||||
$saved['next_scan_at'] = 0;
|
||||
file_put_contents($temporary . '/scan.json', json_encode($saved));
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local]);
|
||||
$localScan = (new Alert($temporary, static function () use (&$clock): int { return $clock; }))->tick();
|
||||
$ok($localScan['created'] === 2 && (int) Db::name('assistant_service_alert')->where('source_key', 'local1:201')->value('staff_admin_id') === 11, '本地归档按姓名对上医助和患者');
|
||||
$ok($localScan['created'] === 2 && (int) Db::name('assistant_service_alert')->where('source_key', 'local1:201')->value('staff_admin_id') === 11, '本地归档依照稳定账号与明确绑定关联医助和患者');
|
||||
$loose = null;
|
||||
foreach ($list([], 1)['lists'] as $row) { if (($row['patient_name'] ?? '') === '未建档') { $loose = $row; } }
|
||||
$ok($loose && $loose['staff']['name'] === '外来客服' && $loose['patient_id'] === 0, '对不上的本地会话仍给不受限账号查看');
|
||||
$hiddenLocal = false;
|
||||
foreach ($list([], 13)['lists'] as $row) { if ((int) ($row['patient_id'] ?? 1) === 0) { $hiddenLocal = true; } }
|
||||
$ok(!$hiddenLocal, '部门主管看不到没有患者归属的企微会话');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_wording_enabled' => true, 'wecom_wording_interval_seconds' => 60, 'wecom_wording_batch_size' => 6]);
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => 'tenant-a', 'wecom_wording_enabled' => true, 'wecom_wording_interval_seconds' => 60, 'wecom_wording_batch_size' => 6]);
|
||||
$saved = json_decode((string) file_get_contents($temporary . '/scan.json'), true);
|
||||
$saved['wording_next_at'] = 0;
|
||||
$saved['wording_cursor'] = '';
|
||||
@@ -192,12 +233,32 @@ try {
|
||||
});
|
||||
$judged = $wording->tick();
|
||||
$ok($judged['created'] === 1 && (int) Db::name('assistant_service_alert')->where('rule_code', 'inappropriate_wording')->count() === 1, '模型指出且原文确实存在的用词才进入预警');
|
||||
$owned = Db::name('assistant_service_alert')->where('source_key', 'local1:201')->find();
|
||||
$foreignStaff = $owned;
|
||||
unset($foreignStaff['id']);
|
||||
$foreignStaff['source_key'] = 'foreign-staff';
|
||||
$foreignStaff['staff_admin_id'] = 12;
|
||||
$outsideId = (int) Db::name('assistant_service_alert')->insertGetId($foreignStaff);
|
||||
$legacyAlert = $foreignStaff;
|
||||
$legacyAlert['archive_tenant_id'] = '';
|
||||
$legacyId = (int) Db::name('assistant_service_alert')->insertGetId($legacyAlert);
|
||||
$ok(!in_array($outsideId, array_column($list(['page_size' => 50], 11)['lists'], 'id'), true), '患者可见也不能查看范围外员工的归档预警');
|
||||
$deny(static fn () => $review(['id' => $outsideId, 'status' => 'confirmed', 'note' => 'test'], 13), '复核校验当前员工范围');
|
||||
$deny(static fn () => $review(['id' => $legacyId, 'status' => 'confirmed', 'note' => 'test'], 1), '历史未标记租户的归档预警不可按 ID 复核');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => 'tenant-b']);
|
||||
$otherScan = $scanner->tick();
|
||||
$ok($otherScan['created'] === 1 && Db::name('assistant_service_alert')->where('archive_tenant_id', 'tenant-b')->count() === 1, '切换租户后两个扫描游标重新起步');
|
||||
$ok(!in_array((int) $owned['id'], array_column($list(['page_size' => 50], 1)['lists'], 'id'), true), '切换租户后全范围账号也看不到原租户预警');
|
||||
$deny(static fn () => $review(['id' => (int) $owned['id'], 'status' => 'confirmed', 'note' => 'test'], 1), '旧租户预警无法按 ID 复核');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_tenant' => '']);
|
||||
$ok(!in_array('wecom', array_column($list(['page_size' => 50], 1)['lists'], 'channel'), true), '清除租户配置时历史归档预警全部关闭');
|
||||
Db::execute('DROP TABLE test_assistant_service_alert');
|
||||
$missing = $list();
|
||||
$ok($missing['schema_ready'] === false && $missing['lists'] === [] && $missing['summary']['open'] === 0, '缺表时显示未就绪,不把空列表当成没有风险');
|
||||
$ok($scanner->tick()['state'] === 'unavailable', '缺表时扫描停止并说明未就绪');
|
||||
echo 'ASSISTANT_SERVICE_ALERT assertions=' . $checks . ' PASS sqlite=memory real_access=1 flock=1 model=0 network=0' . PHP_EOL;
|
||||
} finally {
|
||||
unset($archive);
|
||||
if (is_dir($temporary)) {
|
||||
foreach (glob($temporary . '/*') ?: [] as $file) { @unlink($file); }
|
||||
@rmdir($temporary);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\controller\setting\system\LogController;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\Request;
|
||||
use think\facade\Db;
|
||||
|
||||
// 直接调用报表控制器,使用隔离的内存库,不加载项目环境。
|
||||
$app = new think\App(sys_get_temp_dir() . '/desktop-session-report-test');
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => [
|
||||
'test' => ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_'],
|
||||
]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
think\Model::setDb($manager);
|
||||
$config = new think\Config();
|
||||
$config->set(['lists' => ['page_size' => 20, 'page_size_max' => 100],
|
||||
'data_scope' => ['enabled' => true]], 'project');
|
||||
$app->instance('config', $config);
|
||||
think\Validate::maker(static fn ($validate) => $validate->setRequest(request()));
|
||||
|
||||
foreach ([
|
||||
'admin_role' => 'admin_id INTEGER, role_id INTEGER',
|
||||
'admin_dept' => 'admin_id INTEGER, dept_id INTEGER',
|
||||
'system_role' => 'id INTEGER PRIMARY KEY, name TEXT, data_scope INTEGER, delete_time INTEGER',
|
||||
'system_menu' => 'id INTEGER PRIMARY KEY, perms TEXT, is_disable INTEGER DEFAULT 0',
|
||||
'system_role_menu' => 'role_id INTEGER, menu_id INTEGER',
|
||||
'admin_session' => 'id INTEGER PRIMARY KEY, workstation_slot INTEGER, terminal INTEGER, token TEXT, expire_time INTEGER, update_time INTEGER',
|
||||
'desktop_login_session' => 'id INTEGER PRIMARY KEY, admin_id INTEGER, account TEXT, name TEXT, login_time INTEGER,
|
||||
logout_time INTEGER NULL, last_seen_time INTEGER, due_time INTEGER, expires_at INTEGER, duration_seconds INTEGER, end_reason TEXT',
|
||||
] as $table => $fields) {
|
||||
Db::execute("CREATE TABLE test_{$table} ({$fields})");
|
||||
}
|
||||
$pdo = Db::connect()->getPdo();
|
||||
$pdo->sqliteCreateFunction('LEAST', 'min', 2);
|
||||
$pdo->sqliteCreateFunction('GREATEST', 'max', 2);
|
||||
Db::execute("INSERT INTO test_system_role VALUES (10,'医助',4,NULL),(12,'主管',3,NULL),(13,'系统管理员',1,NULL)");
|
||||
Db::execute('INSERT INTO test_admin_role VALUES (20,10),(21,10),(30,12)');
|
||||
Db::execute('INSERT INTO test_admin_dept VALUES (20,1),(21,2),(30,1)');
|
||||
Db::execute("INSERT INTO test_system_menu VALUES (1,'setting.system.log/desktopSessions',0)");
|
||||
Db::execute('INSERT INTO test_system_role_menu VALUES (10,1),(12,1)');
|
||||
|
||||
$tz = new DateTimeZone('Asia/Shanghai');
|
||||
$start = (new DateTimeImmutable('2024-01-02', $tz))->getTimestamp();
|
||||
$insert = static function (int $id, int $owner, int $login, ?int $logout, string $reason, ?int $lastSeen = null): void {
|
||||
$lastSeen ??= $logout ?? $login;
|
||||
Db::name('desktop_login_session')->insert([
|
||||
'id' => $id, 'admin_id' => $owner, 'account' => 'staff' . $owner,
|
||||
'name' => $owner === 20 ? '张医生' : '王医生', 'login_time' => $login, 'logout_time' => $logout,
|
||||
'expires_at' => DesktopSessionService::nextCutoff($login), 'last_seen_time' => $lastSeen,
|
||||
'due_time' => min(DesktopSessionService::nextCutoff($login), $lastSeen + DesktopSessionService::HEARTBEAT_GRACE),
|
||||
'duration_seconds' => $lastSeen - $login, 'end_reason' => $reason,
|
||||
]);
|
||||
};
|
||||
$insert(1, 20, $start - 1800, $start + 1800, 'logout');
|
||||
$insert(2, 20, $start - 200, $start, 'logout');
|
||||
$insert(3, 20, $start, $start, 'replaced');
|
||||
$insert(4, 21, $start + 1200, $start + 2400, 'revoked');
|
||||
$insert(5, 20, $start + 10, null, '', $start + 70);
|
||||
$insert(6, 20, $start + 86400 - 600, $start + 86400 + 1200, 'logout');
|
||||
$due = $start + 70 + DesktopSessionService::HEARTBEAT_GRACE;
|
||||
Db::name('admin_session')->insert(['workstation_slot' => 5, 'terminal' => AdminTerminalEnum::WORKSTATION,
|
||||
'token' => 'expired-test-session', 'expire_time' => $due, 'update_time' => $start + 70]);
|
||||
|
||||
$query = static function (int $viewer, array $params = [], bool $root = false) use ($app): array {
|
||||
$request = (new Request())->withServer(['REQUEST_METHOD' => 'GET'])->withGet($params);
|
||||
$request->adminId = $viewer;
|
||||
// 模拟变更前缓存仍为管理员的情况,数据范围须依据当前角色。
|
||||
$request->adminInfo = ['admin_id' => $viewer, 'role_id' => [13], 'root' => (int) $root];
|
||||
$app->instance('request', $request);
|
||||
try {
|
||||
return (new LogController($app))->desktopSessions()->getData();
|
||||
} catch (think\exception\HttpResponseException $error) {
|
||||
return $error->getResponse()->getData();
|
||||
}
|
||||
};
|
||||
$expect = static function (bool $ok, string $message): void {
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$params = ['date' => '2024-01-02'];
|
||||
$expect($query(99, $params)['code'] === 0, '无菜单权限不能读取报表');
|
||||
$report = $query(1, $params, true)['data'];
|
||||
$expect($report['count'] === 5 && array_column($report['lists'], 'id') === [6,4,5,3,1],
|
||||
'午夜结束应算在前一天、同秒登录退出算在当天,按登录时间倒序');
|
||||
$expect($report['extend']['total_day_seconds'] === 3660, '合计使用自然日内的实际交集');
|
||||
$rows = array_column($report['lists'], null, 'id');
|
||||
$expect($rows[1]['duration_seconds'] === 3600 && $rows[1]['day_seconds'] === 1800
|
||||
&& $rows[1]['login_time'] === '2024-01-01 23:30:00' && $rows[1]['logout_time'] === '2024-01-02 00:30:00',
|
||||
'跨午夜分摊时保留会话完整时长与北京时间');
|
||||
$expect($rows[5]['status'] === 'timeout' && $rows[5]['status_label'] === '连接超时'
|
||||
&& $rows[5]['duration_seconds'] === 60 && $rows[5]['day_seconds'] === 60, '查询可补结算掉线会话');
|
||||
$expect($query(1, ['date' => '2024-01-03'], true)['data']['extend']['total_day_seconds'] === 1200,
|
||||
'跨次日的会话仅计次日部分');
|
||||
$own = $query(20, $params + ['apply_data_scope' => 0, 'page_size' => 1, 'page_no' => 2])['data'];
|
||||
$expect($own['count'] === 4 && $own['extend']['total_day_seconds'] === 2460
|
||||
&& array_column($own['lists'], 'id') === [5], '本人视图的列表、分页计数与合计使用相同范围');
|
||||
$team = $query(30, $params + ['keyword' => '医生'])['data'];
|
||||
$expect($team['count'] === 4 && $team['extend']['total_day_seconds'] === 2460, '主管仅可查询同部门历史');
|
||||
$other = $query(30, $params + ['keyword' => 'staff21'])['data'];
|
||||
$expect($other['count'] === 0 && $other['extend']['total_day_seconds'] === 0, '域外账号搜索不能泄漏计数或汇总');
|
||||
$expect($query(1, $params + ['keyword' => '王医生'], true)['data']['count'] === 1, '按姓名快照搜索');
|
||||
$expect($query(1, $params + ['keyword' => '%'], true)['data']['count'] === 0, '按字面匹配特殊字符');
|
||||
$expect($query(1, ['date' => '2024-02-30'], true)['code'] === 0, '拒绝无效日期');
|
||||
|
||||
$current = time();
|
||||
$insert(7, 20, $current - 10, null, '', $current);
|
||||
$live = $query(20)['data'];
|
||||
$expect($live['count'] === 1 && $live['lists'][0]['status'] === 'online' && $live['lists'][0]['logout_time'] === null
|
||||
&& $live['lists'][0]['duration_seconds'] >= 10, '默认查询北京时间今天,进行中会话实时计时');
|
||||
echo "DesktopSessionReportTest OK\n";
|
||||
@@ -40,7 +40,7 @@ analysisRoutingExpect(
|
||||
'public business logic rejects model names before loading a diagnosis'
|
||||
);
|
||||
analysisRoutingExpect(
|
||||
'AI模型仅支持qwen或openai',
|
||||
'AI模型仅支持qwen、openai或doubao',
|
||||
DiagnosisAiLogic::getError(),
|
||||
'business logic returns a fixed non-secret invalid-model error'
|
||||
);
|
||||
|
||||
@@ -84,8 +84,8 @@ assistantStreamExpect(
|
||||
'request validation and diagnosis authorization precede early start; aggregation follows it'
|
||||
);
|
||||
assistantStreamExpect(
|
||||
str_contains($validate, "return \$this->only(['id', 'task', 'prompt']);"),
|
||||
'stream reuses the strict id/task/prompt assistant scene'
|
||||
str_contains($validate, "return \$this->only(['id', 'task', 'prompt', 'model']);"),
|
||||
'stream reuses the strict id/task/prompt/model assistant scene'
|
||||
);
|
||||
assistantStreamExpect(
|
||||
str_contains($logic, 'self::PERMISSION_ASSISTANT')
|
||||
|
||||
@@ -347,6 +347,61 @@ try {
|
||||
&& $GLOBALS['tongueCalls'][0][CURLOPT_URL] === 'https://dify.fixture.test/v1/files/upload', 'existing Dify base URL forms supported');
|
||||
}
|
||||
|
||||
// 豆包直连火山方舟:同一张截图以 data URI 内联,单次 chat/completions,不经过 Dify 上传。
|
||||
$arkUrl = 'https://ark.fixture.test/api/v3/chat/completions';
|
||||
$doubaoProfile = ['api_key' => 'fixture-only-ark-secret', 'label' => '豆包', 'name' => 'doubao-fixture-model', 'base_url' => $arkUrl];
|
||||
$arkReply = static fn (string $content, int $seconds = 0): array => ['seconds' => $seconds,
|
||||
'body' => json_encode(['choices' => [['message' => ['role' => 'assistant', 'content' => $content]]]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)];
|
||||
$reset([$arkReply($correctedAnswer)]);
|
||||
$GLOBALS['tongueConfig']['models']['doubao'] = $doubaoProfile;
|
||||
$GLOBALS['tongueReadableCa'] = __FILE__;
|
||||
$GLOBALS['tongueConfig']['required_attachment_upload']['ca_file'] = __FILE__;
|
||||
$file = $upload(); $filePath = $file->getRealPath(); $bytes = file_get_contents($filePath); $digest = hash('sha256', $bytes);
|
||||
$result = $controller(array_replace($body, ['model' => 'doubao']), ['file' => $file]);
|
||||
$expect($result['code'] === 1 && $result['data'] === ['request_id' => $body['request_id'], 'diagnosis_id' => 41,
|
||||
'image_sha256' => $digest, 'analysis' => $valid, 'model' => 'doubao', 'model_label' => '豆包'], 'doubao returns the same response contract');
|
||||
$expect(count($GLOBALS['tongueCalls']) === 1 && $GLOBALS['tongueClosed'] === 1 && !is_file($filePath), 'doubao performs one model call, no Dify upload, and removes the JPEG');
|
||||
$arkCall = $GLOBALS['tongueCalls'][0];
|
||||
$arkPayload = json_decode($arkCall[CURLOPT_POSTFIELDS], true);
|
||||
$expect($arkCall[CURLOPT_URL] === $arkUrl && in_array('Authorization: Bearer fixture-only-ark-secret', $arkCall[CURLOPT_HTTPHEADER], true)
|
||||
&& !str_contains($arkCall[CURLOPT_POSTFIELDS], 'fixture-only-secret'), 'doubao uses its own Ark endpoint and key, never the Dify credentials');
|
||||
$expect($arkPayload['model'] === 'doubao-fixture-model' && count($arkPayload['messages']) === 1
|
||||
&& $arkPayload['messages'][0]['content'][0] === ['type' => 'text', 'text' => \app\common\service\TongueScreenshotAnalysis::prompt()]
|
||||
&& $arkPayload['messages'][0]['content'][1] === ['type' => 'image_url', 'image_url' => ['url' => 'data:image/jpeg;base64,' . base64_encode($bytes)]]
|
||||
&& !isset($arkPayload['thinking']), 'exact screenshot bytes are inlined beside the fixed prompt; thinking follows the model default');
|
||||
$expect(!str_contains($arkCall[CURLOPT_POSTFIELDS], 'patient-secret') && !str_contains($arkCall[CURLOPT_POSTFIELDS], $body['request_id'])
|
||||
&& !isset($arkCall[CURLOPT_CAINFO]) && $arkCall[CURLOPT_SSL_VERIFYPEER] === true && $arkCall[CURLOPT_SSL_VERIFYHOST] === 2
|
||||
&& $arkCall[CURLOPT_FOLLOWLOCATION] === false && $arkCall[CURLOPT_PROXY] === '' && $arkCall[CURLOPT_TIMEOUT_MS] === 50000,
|
||||
'no patient identifiers; public Ark TLS ignores the private attachment CA and keeps every transport protection');
|
||||
|
||||
$reset([$arkReply($rejectedAnswer, 6), $arkReply($correctedAnswer)]);
|
||||
$GLOBALS['tongueConfig']['models']['doubao'] = $doubaoProfile + ['thinking' => 'disabled'];
|
||||
$expect($controller(array_replace($body, ['model' => 'doubao']), ['file' => $upload()])['code'] === 1
|
||||
&& count($GLOBALS['tongueCalls']) === 2, 'doubao parser rejection permits exactly one correction');
|
||||
[$arkFirst, $arkCorrection] = array_map(static fn (array $call): array => json_decode($call[CURLOPT_POSTFIELDS], true), $GLOBALS['tongueCalls']);
|
||||
$expect($arkFirst['thinking'] === ['type' => 'disabled'] && $arkCorrection['thinking'] === ['type' => 'disabled']
|
||||
&& $arkCorrection['messages'][0]['content'][1] === $arkFirst['messages'][0]['content'][1]
|
||||
&& str_starts_with($arkCorrection['messages'][0]['content'][0]['text'], $arkFirst['messages'][0]['content'][0]['text'] . "\n")
|
||||
&& !str_contains($GLOBALS['tongueCalls'][1][CURLOPT_POSTFIELDS], $rejectedMarker)
|
||||
&& $GLOBALS['tongueCalls'][1][CURLOPT_TIMEOUT_MS] === 44000, 'correction resends the same image with the fixed rules, configured thinking and the remaining deadline only');
|
||||
|
||||
foreach ([['status' => 401, 'body' => '{"error":{"message":"fixture-only-ark-secret invalid"}}'], ['body' => '{}'],
|
||||
['body' => '{"choices":[{"message":{"content":null}}]}'], ['body' => 'not-json']] as $arkFailure) {
|
||||
$reset([$arkFailure]); $GLOBALS['tongueConfig']['models']['doubao'] = $doubaoProfile;
|
||||
$file = $upload(); $failed = $controller(array_replace($body, ['model' => 'doubao']), ['file' => $file]);
|
||||
$expect($failed['code'] === 0 && count($GLOBALS['tongueCalls']) === 1 && !is_file($file->getPathname())
|
||||
&& !str_contains(json_encode($failed), 'fixture-only-ark-secret'), 'doubao transport or envelope failure is safe and never retried');
|
||||
}
|
||||
foreach ([['api_key' => ''], ['name' => ''], ['base_url' => 'https://ark.fixture.test/api/v3'],
|
||||
['base_url' => 'http://user:[EMAIL]/api/v3/chat/completions']] as $brokenDoubao) {
|
||||
$reset(); $GLOBALS['tongueConfig']['models']['doubao'] = array_replace($doubaoProfile, $brokenDoubao);
|
||||
$expect($controller(array_replace($body, ['model' => 'doubao']), ['file' => $upload()])['code'] === 0
|
||||
&& $GLOBALS['tongueCalls'] === [], 'incomplete doubao configuration fails before network');
|
||||
}
|
||||
$reset();
|
||||
$expect($controller(array_replace($body, ['model' => 'doubao']), ['file' => $upload()])['code'] === 0
|
||||
&& $GLOBALS['tongueCalls'] === [], 'an unconfigured doubao profile never falls back to Dify');
|
||||
|
||||
// Real auth middleware, with menu lookup deliberately explosive: exact shared grant only.
|
||||
$route = new class {
|
||||
public array $adminInfo = ['admin_id' => 7, 'root' => 0, 'login_ip' => '127.0.0.1'];
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\validate\tcm\DiagnosisValidate;
|
||||
|
||||
function diagnosisAddSceneExpect(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
fwrite(STDERR, "FAIL: {$message}\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
$validateSource = file_get_contents(
|
||||
dirname(__DIR__) . '/app/adminapi/validate/tcm/DiagnosisValidate.php'
|
||||
);
|
||||
diagnosisAddSceneExpect(is_string($validateSource), 'DiagnosisValidate source is readable');
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "->remove('task', true)"),
|
||||
'add scene strips the AI assistant task rule'
|
||||
);
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "return \$this->only(['id', 'task', 'prompt']);"),
|
||||
'aiAssistant scene still requires a task'
|
||||
);
|
||||
|
||||
$addPayload = [
|
||||
'patient_name' => '张三',
|
||||
'phone' => '13800138000',
|
||||
'gender' => 1,
|
||||
'age' => 50,
|
||||
'diagnosis_type' => 'follow_up',
|
||||
'local_hospital_name' => '某医院',
|
||||
];
|
||||
|
||||
$addScene = (new DiagnosisValidate())->scene('add');
|
||||
$addOk = $addScene->check($addPayload);
|
||||
diagnosisAddSceneExpect(
|
||||
$addOk === true,
|
||||
'add scene accepts a diagnosis payload without an AI assistant task'
|
||||
. ($addOk ? '' : '; got: ' . $addScene->getError())
|
||||
);
|
||||
|
||||
echo "Diagnosis add-scene validation: OK\n";
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\validate\tcm\DiagnosisValidate;
|
||||
|
||||
function diagnosisAddSceneExpect(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
fwrite(STDERR, "FAIL: {$message}\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
$validateSource = file_get_contents(
|
||||
dirname(__DIR__) . '/app/adminapi/validate/tcm/DiagnosisValidate.php'
|
||||
);
|
||||
diagnosisAddSceneExpect(is_string($validateSource), 'DiagnosisValidate source is readable');
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "->remove('task', true)"),
|
||||
'add scene strips the AI assistant task rule'
|
||||
);
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "return \$this->only(['id', 'task', 'prompt', 'model']);"),
|
||||
'aiAssistant scene still requires a task'
|
||||
);
|
||||
|
||||
$addPayload = [
|
||||
'patient_name' => '张三',
|
||||
'phone' => '13800138000',
|
||||
'gender' => 1,
|
||||
'age' => 50,
|
||||
'diagnosis_type' => 'follow_up',
|
||||
'local_hospital_name' => '某医院',
|
||||
];
|
||||
|
||||
$addScene = (new DiagnosisValidate())->scene('add');
|
||||
$addOk = $addScene->check($addPayload);
|
||||
diagnosisAddSceneExpect(
|
||||
$addOk === true,
|
||||
'add scene accepts a diagnosis payload without an AI assistant task'
|
||||
. ($addOk ? '' : '; got: ' . $addScene->getError())
|
||||
);
|
||||
|
||||
echo "Diagnosis add-scene validation: OK\n";
|
||||
|
||||
@@ -14,8 +14,11 @@ namespace app\common\service\esign {
|
||||
public static array $identity = ['status' => 'INIT'];
|
||||
public static int $starts = 0;
|
||||
public static int $creates = 0;
|
||||
public static string $newAccountId = 'bound-account';
|
||||
public static string $requestedName = '';
|
||||
public static ?string $mobile = null;
|
||||
public static bool $expired = false;
|
||||
public static ?\Closure $checkCertificate = null;
|
||||
public static ?\Closure $duringStart = null;
|
||||
public static ?\Closure $duringRecipientLookup = null;
|
||||
public static ?string $account = null;
|
||||
@@ -29,6 +32,7 @@ namespace app\common\service\esign {
|
||||
{
|
||||
++self::$starts;
|
||||
self::$account = $accountId;
|
||||
self::$requestedName = $name;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
@@ -71,7 +75,7 @@ namespace app\common\service\esign {
|
||||
throw new \RuntimeException('Identity proof mismatch');
|
||||
}
|
||||
++self::$creates;
|
||||
return 'bound-account';
|
||||
return self::$newAccountId;
|
||||
}
|
||||
|
||||
public function signingAccount(string $accountId): array
|
||||
@@ -82,6 +86,9 @@ namespace app\common\service\esign {
|
||||
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
if (self::$checkCertificate) {
|
||||
return (self::$checkCertificate)($accountId);
|
||||
}
|
||||
return ['startDate' => '2024-01-01 08:00:00',
|
||||
'endDate' => self::$expired ? '2024-02-01 08:00:00' : '2099-01-01 08:00:00'];
|
||||
}
|
||||
@@ -107,6 +114,7 @@ namespace {
|
||||
use app\common\service\esign\DoctorEsignAuthorizationRequired;
|
||||
use app\common\service\esign\DoctorEsignIdentityService as Enrollment;
|
||||
use app\common\service\esign\EsignClient as Provider;
|
||||
use app\common\service\esign\EsignProviderException;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
@@ -128,7 +136,8 @@ namespace {
|
||||
Db::execute($sql);
|
||||
Db::execute($sql);
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER,root INTEGER DEFAULT 0)');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER,role_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_esign_account (doctor_id INTEGER,environment TEXT,app_id TEXT,account_id TEXT,
|
||||
doctor_name TEXT,create_time INTEGER,UNIQUE(doctor_id,environment,app_id))');
|
||||
@@ -145,7 +154,7 @@ namespace {
|
||||
$throws = static function (callable $operation, string $expected, string $message) use ($assert): void {
|
||||
try {
|
||||
$operation();
|
||||
} catch (DomainException $error) {
|
||||
} catch (Throwable $error) {
|
||||
$assert(is_a($error, $expected), $message);
|
||||
return;
|
||||
}
|
||||
@@ -155,7 +164,8 @@ namespace {
|
||||
$phone = '13800000000';
|
||||
$assert(Enrollment::status(1)['enabled'] === false, 'SMS enrollment defaults off');
|
||||
$config->set(['doctor_sms_enabled' => true], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'doctor starts unbound');
|
||||
$unbound = Enrollment::status(1);
|
||||
$assert($unbound['status'] === 'unbound' && !isset($unbound['certificate_state']), 'doctor starts unbound');
|
||||
$throws(static fn () => Enrollment::status(3), DomainException::class, 'non-physician denied');
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, ''), DoctorEsignIdentityRequired::class, 'setup-required reason distinguishes an unbound doctor');
|
||||
|
||||
@@ -180,14 +190,46 @@ namespace {
|
||||
$assert($pending['status'] === 'binding_required' && $pending['identity_details_required'] && !isset($pending['auth_url'])
|
||||
&& Provider::$creates === 0, 'successful polling exposes only safe metadata and accepts masked identity as supplemental');
|
||||
$assert(Enrollment::complete(1, 'bad-input')['identity_details_required'] && Provider::$creates === 0, 'invalid supplemental number never reaches SDK');
|
||||
$assert(Enrollment::complete(1, Provider::DOCUMENT)['status'] === 'needs_mobile' && Provider::$creates === 1,
|
||||
$withoutMobile = Enrollment::complete(1, Provider::DOCUMENT);
|
||||
$assert($withoutMobile['status'] === 'needs_mobile' && $withoutMobile['certificate_state'] === 'valid' && Provider::$creates === 1,
|
||||
'successful provider proof binds without signing, but an absent provider authorization is not ready');
|
||||
$assert(Db::name('doctor_esign_identity')->count() === 0 && !str_contains(json_encode(Db::name('doctor_esign_account')->find()), Provider::DOCUMENT),
|
||||
'completed enrollment clears hosted URL and does not persist identity number');
|
||||
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class, 'willingness requires a current authorized mobile');
|
||||
|
||||
$boundAccount = Db::name('doctor_esign_account')->where('doctor_id', 1)->find();
|
||||
Provider::$checkCertificate = static function (string $accountId) use ($assert): array {
|
||||
$assert($accountId === 'bound-account', 'certificate query uses the current signing account');
|
||||
return ['startDate' => '2098-01-01 08:00:00', 'endDate' => '2099-01-01 08:00:00'];
|
||||
};
|
||||
$futureCertificate = Enrollment::status(1);
|
||||
$assert($futureCertificate['status'] === 'renewal_required' && $futureCertificate['certificate_state'] === 'renewal_required',
|
||||
'certificate validity must have already started');
|
||||
Provider::$checkCertificate = static fn () => ['startDate' => '2024-01-01 08:00:00', 'endDate' => '2024-01-01 08:00:00'];
|
||||
$assert(Enrollment::status(1)['certificate_state'] === 'renewal_required', 'an empty validity period cannot authorize signing');
|
||||
Provider::$checkCertificate = static fn () => ['startDate' => '2024-02-30 08:00:00', 'endDate' => '2099-01-01 08:00:00'];
|
||||
$badCertificate = Enrollment::status(1);
|
||||
$assert($badCertificate['status'] === 'renewal_required' && $badCertificate['certificate_state'] === 'unconfirmed'
|
||||
&& $badCertificate['cert_expires_at'] === 0, 'unparseable dates cannot establish certificate validity');
|
||||
$throws(static fn () => Enrollment::start(1, $phone), DomainException::class, 'malformed dates cannot begin renewal');
|
||||
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'TIMEOUT');
|
||||
$timeout = Enrollment::status(1);
|
||||
$assert($timeout['certificate_state'] === 'unconfirmed' && $timeout['cert_expires_at'] === 0 && !isset($timeout['auth_url'])
|
||||
&& !str_contains(json_encode($timeout), 'TIMEOUT'), 'a transient query failure reports uncertainty without provider data');
|
||||
$throws(static fn () => Enrollment::start(1, $phone), EsignProviderException::class, 'a transient failure preserves the retry path');
|
||||
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'PROVIDER_123');
|
||||
$providerRejection = Enrollment::status(1);
|
||||
$assert($providerRejection['certificate_state'] === 'unconfirmed' && $providerRejection['cert_expires_at'] === 0
|
||||
&& !str_contains(json_encode($providerRejection), 'PROVIDER_123') && Provider::$starts === 1
|
||||
&& Db::name('doctor_esign_account')->where('doctor_id', 1)->find() === $boundAccount
|
||||
&& Db::name('doctor_esign_identity')->count() === 0, 'recheck does not initiate or mutate enrollment on provider rejection');
|
||||
Provider::$checkCertificate = null;
|
||||
$assert(Enrollment::status(1)['certificate_state'] === 'valid', 'a later recheck can confirm the existing certificate');
|
||||
Provider::$expired = true;
|
||||
$assert(Enrollment::status(1)['status'] === 'renewal_required', 'expired provider certificate requires renewal');
|
||||
$expired = Enrollment::status(1);
|
||||
$assert($expired['status'] === 'renewal_required' && $expired['certificate_state'] === 'renewal_required',
|
||||
'expired provider certificate requires renewal');
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account', 'renewal reuses canonical account');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
@@ -195,7 +237,8 @@ namespace {
|
||||
Provider::$expired = false;
|
||||
$assert(Enrollment::status(1)['identity_details_required'] === false, 'a bound account needs no supplemental input');
|
||||
$ready = Enrollment::complete(1);
|
||||
$assert($ready['status'] === 'ready' && $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
$assert($ready['status'] === 'ready' && $ready['certificate_state'] === 'valid'
|
||||
&& $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
'same account becomes ready with certificate date in configured SDK timezone');
|
||||
$assert(!str_contains(json_encode($ready), $phone) && !str_contains(json_encode($ready), Provider::DOCUMENT), 'status never returns provider identity');
|
||||
$recipient = Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account');
|
||||
@@ -207,6 +250,15 @@ namespace {
|
||||
Provider::$mobile = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'PROVIDER_123');
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account',
|
||||
'explicit renewal on provider rejection reuses the canonical account');
|
||||
Provider::$checkCertificate = null;
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['certificate_state'] === 'valid' && Provider::$creates === 1,
|
||||
'successful same-account recheck does not create another account');
|
||||
|
||||
$assert(!Enrollment::quickEnabled(), 'quick-sign is disabled by default');
|
||||
$config->set(['doctor_sms_enabled' => false, 'doctor_quicksign_enabled' => true], 'esign');
|
||||
$quickReady = Enrollment::status(1);
|
||||
@@ -240,9 +292,9 @@ namespace {
|
||||
'provider face verification alone does not activate grant');
|
||||
$quickGranted = Enrollment::complete(1);
|
||||
$assert($quickGranted['status'] === 'ready' && !$quickGranted['quicksign_authorizing']
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 3 * 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& !str_contains(json_encode($quickGranted), 'quick-proof') && !str_contains(json_encode($quickGranted), Provider::DOCUMENT),
|
||||
'confirmed provider proof is capped to 24 hours and remains server-only');
|
||||
'confirmed provider proof follows provider expiry and remains server-only');
|
||||
$quickRow = Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->find();
|
||||
$assert($quickRow['flow_id'] === 'quick-proof-1' && $quickRow['auth_url'] === null
|
||||
&& Db::name('doctor_esign_identity')->count() === 0 && Provider::$creates === 1, 'grant clears its hosted link and keeps enrollment untouched');
|
||||
@@ -271,7 +323,7 @@ namespace {
|
||||
Provider::$willingnessValid = false;
|
||||
$spent = Enrollment::status(1);
|
||||
$assert($spent['quicksign_expires_at'] === 0 && $spent['quicksign_remaining_times'] === 0
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready',
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready' && $spent['certificate_state'] === 'valid',
|
||||
'provider exhaustion leaves certificate enrollment valid and reports the spent grant');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider cancellation/exhaustion blocks dispatch');
|
||||
@@ -291,5 +343,33 @@ namespace {
|
||||
$assert(Enrollment::start(1, '')['quicksign_authorizing'] && Provider::$quickStarts === 2, 'expired grant permits a new standalone grant');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['quicksign_expires_at'] === $now + 120, 'provider validity is preserved when shorter than the local bound');
|
||||
|
||||
$config->set(['review_enabled' => true], 'esign');
|
||||
Db::name('admin')->insert(['id' => 4, 'name' => 'admin', 'root' => 1]);
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$newAccountId = 'reviewer-account';
|
||||
$startsBeforeReview = Provider::$starts;
|
||||
$assert(Enrollment::status(4)['can_edit_signer_name'] === true, 'an unbound reviewer can supply a separate legal name');
|
||||
$throws(static fn () => Enrollment::start(2, $phone, Provider::NAME), DomainException::class,
|
||||
'the reviewer-only input does not override a physician roster name');
|
||||
$throws(static fn () => Enrollment::start(4, $phone, '<姓名>'), DomainException::class,
|
||||
'invalid names are rejected before contacting eSign');
|
||||
$oldReview = Enrollment::start(4, $phone);
|
||||
$newReview = Enrollment::start(4, $phone, Provider::NAME);
|
||||
$assert($newReview['auth_url'] !== $oldReview['auth_url'] && Provider::$requestedName === Provider::NAME
|
||||
&& Enrollment::status(4)['can_edit_signer_name'] && Provider::$starts === $startsBeforeReview + 2,
|
||||
'correcting an unfinished reviewer name requests a new provider URL');
|
||||
$assert(Enrollment::start(4, $phone, Provider::NAME) === $newReview && Provider::$starts === $startsBeforeReview + 2,
|
||||
'resubmitting the same name and number restores the pending flow');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
|
||||
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => Provider::DOCUMENT]];
|
||||
$assert(Enrollment::start(4, $phone, '错误姓名')['status'] === 'binding_required' && Provider::$starts === $startsBeforeReview + 2,
|
||||
'an already verified identity cannot be replaced on retry');
|
||||
$assert(Enrollment::complete(4)['status'] === 'ready'
|
||||
&& Db::name('doctor_esign_account')->where('doctor_id', 4)->value('doctor_name') === Provider::NAME
|
||||
&& Db::name('admin')->where('id', 4)->value('name') === 'admin',
|
||||
'verified legal name is saved only to the reviewer signing account');
|
||||
$throws(static fn () => Enrollment::start(4, $phone, '不同姓名'), DomainException::class,
|
||||
'a verified signing account cannot be renamed through enrollment');
|
||||
echo "Doctor eSign enrollment: $checks checks passed (SQLite and provider doubles)\n";
|
||||
}
|
||||
|
||||
@@ -2,6 +2,16 @@
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
final class PrescriptionReviewEsignService
|
||||
{
|
||||
public static array $calls = [];
|
||||
public static function confirm(int $id, int $orderId, int $actor, array $info, bool $verifyOnly): array
|
||||
{
|
||||
self::$calls[] = [$id, $orderId, $actor, $verifyOnly];
|
||||
return ['state' => 'signed'];
|
||||
}
|
||||
}
|
||||
|
||||
final class PrescriptionEsignService
|
||||
{
|
||||
public static array $calls = [];
|
||||
@@ -33,6 +43,30 @@ namespace app\common\model {
|
||||
public function save(): bool { self::$saved[] = $this->fields; return true; }
|
||||
}
|
||||
}
|
||||
namespace app\adminapi\logic\tcm {
|
||||
final class PrescriptionLogic
|
||||
{
|
||||
public static bool $auditOk = true;
|
||||
public static ?array $notice = null;
|
||||
|
||||
public static function audit(int $id, string $action, string $remark, int $actor, array $info): bool
|
||||
{
|
||||
return self::$auditOk;
|
||||
}
|
||||
|
||||
public static function getError(): string
|
||||
{
|
||||
return '无审核权限';
|
||||
}
|
||||
|
||||
public static function consumeLastAuditWecomNotify(): ?array
|
||||
{
|
||||
$notice = self::$notice;
|
||||
self::$notice = null;
|
||||
return $notice;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace app\adminapi\controller {
|
||||
class BaseAdminController
|
||||
{
|
||||
@@ -40,8 +74,17 @@ namespace app\adminapi\controller {
|
||||
public int $adminId = 7;
|
||||
public array $adminInfo = ['admin_id' => 7, 'name' => '测试医师'];
|
||||
public function isNotNeedLogin(): bool { return false; }
|
||||
protected function data(array $data): array { return ['code' => 1, 'data' => $data]; }
|
||||
protected function data(array $data): \ArrayObject
|
||||
{
|
||||
return new class(['code' => 1, 'data' => $data]) extends \ArrayObject {
|
||||
public function header(array $headers): self { return $this; }
|
||||
};
|
||||
}
|
||||
protected function fail(string $message): array { return ['code' => 0, 'msg' => $message]; }
|
||||
protected function success(string $message, array $data = []): array
|
||||
{
|
||||
return ['code' => 1, 'msg' => $message, 'data' => $data];
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
@@ -68,7 +111,7 @@ namespace {
|
||||
|
||||
think\Container::getInstance()->instance('request', $request);
|
||||
$response = new class($result) {
|
||||
public function __construct(private array $result) {}
|
||||
public function __construct(private \ArrayObject $result) {}
|
||||
public function getContent(): string { return json_encode($this->result); }
|
||||
};
|
||||
(new app\adminapi\listener\OperationLog())->handle($response);
|
||||
@@ -93,6 +136,24 @@ namespace {
|
||||
$expect($controller->esignStart()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$starts) === 1, 'invalid replacement flag cannot change identity flow');
|
||||
}
|
||||
|
||||
foreach ([false, true] as $verifyOnly) {
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost([
|
||||
'id' => 42, 'order_id' => 5, 'actor_id' => 7, 'verify_only' => $verifyOnly,
|
||||
]);
|
||||
$expect($controller->esignReviewConfirm()['code'] === 1, 'review accepts a JSON boolean without the global trim filter');
|
||||
}
|
||||
$expect(app\common\service\esign\PrescriptionReviewEsignService::$calls === [[42, 5, 7, false], [42, 5, 7, true]],
|
||||
'review confirmation preserves the explicit sign versus verify choice');
|
||||
foreach ([null, 'false', 'true', 0, 1, []] as $invalid) {
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost([
|
||||
'id' => 42, 'actor_id' => 7, 'verify_only' => $invalid,
|
||||
]);
|
||||
$expect($controller->esignReviewConfirm()['code'] === 0, 'malformed review flag never dispatches');
|
||||
}
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'actor_id' => 8, 'verify_only' => false]);
|
||||
$expect($controller->esignReviewConfirm()['code'] === 0
|
||||
&& count(app\common\service\esign\PrescriptionReviewEsignService::$calls) === 2, 'actor mismatch cannot dispatch review');
|
||||
|
||||
$code = '023941';
|
||||
$mobile = '13800000000';
|
||||
$authUrl = 'https://smlt.esign.cn/example/private-auth-url';
|
||||
@@ -123,5 +184,26 @@ namespace {
|
||||
$expect(!str_contains($entry, $mobile) && !str_contains($entry, $number) && !str_contains($entry, $code)
|
||||
&& !str_contains($audit['result'], 'private-auth-url'), "$action audit omits signing secrets and authorization URL");
|
||||
}
|
||||
echo "eSign identity controller/privacy: $checks checks passed (isolated doubles, no DB/network)\n";
|
||||
$auditRequest = (new app\Request())->setMethod('POST');
|
||||
$controller->request = $auditRequest;
|
||||
think\Container::getInstance()->instance('request', $auditRequest);
|
||||
think\Validate::maker(static function (think\Validate $validate) use ($auditRequest, $app): void {
|
||||
$validate->setRequest($auditRequest);
|
||||
$validate->setLang(new think\Lang($app));
|
||||
});
|
||||
foreach (['approve' => '审核通过', 'reject' => '已驳回并作废处方'] as $action => $message) {
|
||||
$auditRequest->withPost(['id' => 42, 'action' => $action, 'remark' => '虚构测试']);
|
||||
app\adminapi\logic\tcm\PrescriptionLogic::$notice = [
|
||||
'ok' => false, 'errcode' => 81013, 'message' => 'user & party & tag all invalid, private provider diagnostic',
|
||||
];
|
||||
$expect($controller->audit() === ['code' => 1, 'msg' => $message, 'data' => ['wecom_notify_ok' => false]],
|
||||
"$action stays successful and never exposes a WeCom notification error");
|
||||
}
|
||||
app\adminapi\logic\tcm\PrescriptionLogic::$notice = ['ok' => true];
|
||||
$auditRequest->withPost(['id' => 42, 'action' => 'approve']);
|
||||
$expect($controller->audit()['data'] === ['wecom_notify_ok' => true], 'successful delivery status remains available');
|
||||
app\adminapi\logic\tcm\PrescriptionLogic::$auditOk = false;
|
||||
$expect($controller->audit() === ['code' => 0, 'msg' => '无审核权限'], 'actual audit denial is still returned');
|
||||
|
||||
echo "eSign identity and prescription audit controller/privacy: $checks checks passed (isolated doubles, no DB/network)\n";
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ patientSecurityExpect(
|
||||
'invalid model is rejected before database or network access'
|
||||
);
|
||||
patientSecurityExpect(
|
||||
PatientAiReportLogic::getError() === 'AI模型仅支持qwen或openai',
|
||||
PatientAiReportLogic::getError() === 'AI模型仅支持qwen、openai或doubao',
|
||||
'invalid model error is fixed and secret-free'
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\controller\tcm\PrescriptionController;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\Request;
|
||||
use app\common\service\esign\EsignClient;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use think\facade\Db;
|
||||
|
||||
$app = new think\App();
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$defaults = ['enabled' => true, 'environment' => 'sandbox', 'doctor_quicksign_enabled' => false,
|
||||
'review_enabled' => false, 'app_id' => 'fixture', 'app_secret' => 'fixture-secret',
|
||||
'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service'];
|
||||
$config->set($defaults, 'esign');
|
||||
$app->instance('config', $config);
|
||||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,root INTEGER,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::name('admin')->insertAll([['id' => 1, 'root' => 1], ['id' => 2, 'root' => 0]]);
|
||||
|
||||
$checks = 0;
|
||||
$expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
$checks++;
|
||||
};
|
||||
$invoke = static function (string $method, string $action, array $post, int $actor = 1, int $root = 1) use ($app): array {
|
||||
$request = (new Request())->withServer(['REMOTE_ADDR' => '127.0.0.1', 'REQUEST_METHOD' => $method])
|
||||
->setMethod($method)->setController('tcm.Prescription')->setAction($action)->withPost($post)->filter('trim');
|
||||
$request->adminInfo = ['admin_id' => $actor, 'root' => $root, 'login_ip' => '127.0.0.1'];
|
||||
$app->instance('request', $request);
|
||||
$controller = new PrescriptionController($app);
|
||||
$request->controllerObject = $controller;
|
||||
$response = (new AuthMiddleware())->handle($request, static fn () => $controller->{$action}());
|
||||
return json_decode($response->getContent(), true, flags: JSON_THROW_ON_ERROR);
|
||||
};
|
||||
|
||||
$read = static fn () => $invoke('GET', 'esignConfig', [], 2, 0);
|
||||
$save = static fn (bool $enabled) => $invoke('POST', 'esignSetConfig', ['enabled' => $enabled]);
|
||||
$expect($read()['data'] === ['enabled' => true, 'environment' => 'sandbox'], 'ordinary accounts read the .env fallback');
|
||||
$expect($invoke('GET', 'esignSetConfig', [])['code'] === 0, 'GET cannot change the policy');
|
||||
$expect($invoke('POST', 'esignSetConfig', ['enabled' => false], 2, 0)['code'] === 0, 'middleware denies a non-root writer');
|
||||
$expect($invoke('POST', 'esignSetConfig', ['enabled' => false], 2, 1)['code'] === 0, 'stale root claims cannot write');
|
||||
foreach ([[], ['enabled' => 'false'], ['enabled' => 0], ['enabled' => [true]]] as $malformed) {
|
||||
$expect($invoke('POST', 'esignSetConfig', $malformed)['code'] === 0, 'only a JSON boolean can switch modes');
|
||||
}
|
||||
$expect(Db::name('config')->count() === 0, 'rejected setting changes leave storage untouched');
|
||||
|
||||
$expect($save(false)['data'] === ['enabled' => false, 'environment' => 'sandbox']
|
||||
&& $read()['data']['enabled'] === false && !(new EsignClient())->isEnabled(), 'explicit off overrides enabled .env for clients and SDK');
|
||||
$legacy = ['id' => 17, 'audit_status' => 0, 'review_submitted_at' => 123, 'esign_status' => 'legacy'];
|
||||
$expect(!PrescriptionEsignService::requiresSignature($legacy, PrescriptionEsignService::enabled())
|
||||
&& PrescriptionEsignService::canReview($legacy), 'uploaded handwritten prescriptions use ordinary review');
|
||||
$draft = array_replace($legacy, ['esign_required' => 1, 'esign_status' => 'pending']);
|
||||
$expect(!PrescriptionEsignService::canReview($draft), 'CA-enrolled drafts cannot pass as handwritten');
|
||||
|
||||
$config->set(array_replace($defaults, ['enabled' => false, 'app_secret' => '']), 'esign');
|
||||
$expect($save(true)['code'] === 0 && $read()['data']['enabled'] === false, 'invalid SDK config leaves the previous setting active');
|
||||
$config->set(array_replace($defaults, ['enabled' => false]), 'esign');
|
||||
$enabled = $save(true)['data'];
|
||||
$expect($enabled === ['enabled' => true, 'environment' => 'sandbox', 'review_enabled' => true, 'verification_method' => 'quick'],
|
||||
'explicit on enables quick signing and pharmacist CA independently of previous rollout flags');
|
||||
$expect($read()['data'] === $enabled && (new EsignClient())->isEnabled(), 'saved setting is observed across requests and by SDK');
|
||||
$expect(!PrescriptionEsignService::canReview($legacy), 'eligible unsigned draft must satisfy the CA signature after enablement');
|
||||
$expect($save(true)['data'] === $enabled && Db::name('config')->count() === 1, 'repeated saves keep one setting record');
|
||||
|
||||
echo "Prescription CA setting: {$checks} checks passed (isolated SQLite and offline SDK configuration)\n";
|
||||
@@ -187,6 +187,7 @@ namespace app\common\service\esign {
|
||||
'signature' => ['signatureName' => 'Signature2', 'validate' => true,
|
||||
'signDate' => gmdate('Y-m-d H:i:s', max(time() + 28800, strtotime($original['signature']['signDate'] . ' UTC'))), 'timeFrom' => 'tsa'],
|
||||
'cert' => ['cn' => '测试审核人', 'issuerCN' => 'Test CA', 'sn' => 'b2'],
|
||||
'sealData' => 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/J5cAAAAASUVORK5CYII=',
|
||||
], $original];
|
||||
return ['pdf' => $dual, 'sign_service_id' => 'review-sign-1'];
|
||||
}
|
||||
@@ -196,6 +197,7 @@ namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\adminapi\lists\tcm\PrescriptionLists;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\service\esign\PrescriptionEsignService as Service;
|
||||
@@ -234,19 +236,27 @@ namespace {
|
||||
'esign_required', 'esign_status', 'is_system_auto', 'delete_time', 'doctor_signature', 'update_time',
|
||||
'create_time', 'template_id', 'is_shared', 'visible_role_ids', 'assistant_id',
|
||||
'audit_status', 'audit_time', 'audit_by', 'audit_by_name', 'audit_remark',
|
||||
'void_status', 'void_time', 'void_by', 'void_by_name',
|
||||
'void_status', 'void_time', 'void_by', 'void_by_name', 'review_submitted_at',
|
||||
]));
|
||||
$columns = array_map(static fn ($field) => match ($field) {
|
||||
'id' => 'id INTEGER PRIMARY KEY',
|
||||
'void_status' => 'void_status INTEGER NOT NULL DEFAULT 0',
|
||||
'review_submitted_at' => 'review_submitted_at INTEGER NOT NULL DEFAULT 0',
|
||||
default => $field . ' TEXT',
|
||||
}, $fields);
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription (' . implode(',', $columns) . ')');
|
||||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER,disable INTEGER DEFAULT 0,root INTEGER DEFAULT 0)');
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription_order (
|
||||
id INTEGER PRIMARY KEY, prescription_id INTEGER, prescription_audit_status INTEGER,
|
||||
fulfillment_status INTEGER, delete_time INTEGER, diagnosis_id INTEGER, creator_id INTEGER, create_time INTEGER
|
||||
prescription_audit_remark TEXT, payment_slip_audit_status INTEGER DEFAULT 0,
|
||||
fulfillment_status INTEGER, delete_time INTEGER, diagnosis_id INTEGER, creator_id INTEGER,
|
||||
create_time INTEGER, update_time INTEGER
|
||||
)');
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription_order_pay_order (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, pay_order_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_pharmacy_submission_claim (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, source_revision INTEGER, status TEXT)');
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription_order_log (id INTEGER PRIMARY KEY, prescription_order_id INTEGER,
|
||||
admin_id INTEGER, admin_name TEXT, action TEXT, summary TEXT, create_time INTEGER)');
|
||||
Db::name('admin')->insert(['id' => 1, 'name' => '测试医师']);
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql')
|
||||
. file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_identity.sql')
|
||||
@@ -269,12 +279,13 @@ namespace {
|
||||
}
|
||||
Db::execute('CREATE UNIQUE INDEX uk_doctor ON zyt_doctor_esign_account(doctor_id,environment,app_id)');
|
||||
Db::execute('ALTER TABLE zyt_prescription_esign ADD review_required INTEGER NOT NULL DEFAULT 0');
|
||||
$new = static function (int $id): void {
|
||||
$new = static function (int $id, bool $uploaded = true): void {
|
||||
Db::name('tcm_prescription')->insert([
|
||||
'id' => $id, 'sn' => 'RX-TEST-' . $id, 'creator_id' => 1, 'doctor_name' => '测试医师',
|
||||
'patient_name' => '虚构测试患者', 'gender' => 1, 'age' => 30, 'phone' => '13800000000',
|
||||
'clinical_diagnosis' => '仅用于软件测试', 'herbs' => json_encode([['name' => '测试药材', 'dosage' => 10, 'unit' => 'g']], JSON_UNESCAPED_UNICODE),
|
||||
'prescription_date' => '2026-11-17', 'esign_required' => 1, 'esign_status' => 'pending', 'void_status' => 0,
|
||||
'review_submitted_at' => $uploaded ? time() : 0,
|
||||
]);
|
||||
};
|
||||
$new(1);
|
||||
@@ -700,7 +711,7 @@ namespace {
|
||||
48 => ['clinical_diagnosis' => ''],
|
||||
];
|
||||
foreach ($legacyCases as $id => $values) {
|
||||
$new($id);
|
||||
$new($id, false);
|
||||
Db::name('tcm_prescription')->where('id', $id)->update($values + [
|
||||
'esign_required' => 0, 'esign_status' => 'legacy', 'audit_status' => 0,
|
||||
'doctor_signature' => 'original-handwritten-signature',
|
||||
@@ -713,6 +724,15 @@ namespace {
|
||||
Service::assertSignedById(41, true);
|
||||
$assert(!$disabled['enabled'] && !$disabled['required'] && $disabled['status'] === 'legacy' && !$disabled['can_sign'],
|
||||
'disabled rollout keeps an unenrolled pending prescription compatible');
|
||||
$assert($disabled['can_submit_for_review'] === true && $disabled['review_submitted_at'] === 0,
|
||||
'prescriptions created without required e-sign can still be submitted');
|
||||
$legacySubmission = PrescriptionLogic::submitForReview(47, 1, $root);
|
||||
$assert($legacySubmission['review_submitted_at'] > 0 && $legacySubmission['can_submit_for_review'] === false,
|
||||
'legacy submission records the first upload under existing signature configuration');
|
||||
$assert(Service::status(47, 2, $root)['can_review_prescription']
|
||||
&& PrescriptionLogic::audit(47, 'reject', '测试驳回', 1, $root)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 47)->value('void_status') === 1,
|
||||
'an uploaded handwritten prescription is reviewable while eSign is disabled');
|
||||
$alreadyEnrolled = Service::status(5, 1, $root);
|
||||
$assert($alreadyEnrolled['required'] && !$alreadyEnrolled['can_sign']
|
||||
&& str_contains($alreadyEnrolled['message'], '尚未启用'), 'disabled rollout explains blocked enrolled signing');
|
||||
@@ -720,27 +740,38 @@ namespace {
|
||||
$config->set($settings, 'esign');
|
||||
$draft = Db::name('tcm_prescription')->find(41);
|
||||
$pending = Service::status(41, 1, $root);
|
||||
$assert($pending['required'] && $pending['status'] === 'pending' && $pending['can_sign']
|
||||
&& !$pending['can_resume_identity'], 'unenrolled pending prescription enters eSign for its doctor');
|
||||
$assert($pending['required'] && $pending['status'] === 'pending' && !$pending['can_sign']
|
||||
&& $pending['awaiting_upload'] && $pending['can_submit_for_review'] && !$pending['can_review_prescription']
|
||||
&& !$pending['can_resume_identity'], 'unenrolled pending prescription offers upload before eSign');
|
||||
$other = Service::status(41, 2, $root);
|
||||
$assert($other['required'] && !$other['can_sign'] && str_contains($other['message'], '开方医生'),
|
||||
'auditor can see that the doctor needs to sign');
|
||||
$assert($other['required'] && !$other['can_sign'] && $other['awaiting_upload'] && !$other['can_submit_for_review']
|
||||
&& !$other['can_review_prescription'] && str_contains($other['message'], '上传处方'),
|
||||
'auditor can see that the doctor needs to upload');
|
||||
$throws(fn () => Service::start(41, 2, $root), 'auditor cannot enroll a different doctor’s pending prescription');
|
||||
$assert(Service::identityStatus(41, 1, $root)['identity_status'] === 'UNAVAILABLE',
|
||||
'pending legacy identity status waits for enrollment');
|
||||
$throws(fn () => Service::complete(41, 1, $root), 'unenrolled draft cannot complete signing before starting');
|
||||
$startsBeforeUpload = Fake::$starts;
|
||||
$throws(fn () => Service::start(41, 1, $root), 'doctor cannot start prescription signing before upload');
|
||||
$throws(fn () => Service::identityStatus(41, 1, $root), 'identity status cannot resume before upload');
|
||||
$throws(fn () => Service::complete(41, 1, $root), 'doctor cannot complete signing before upload');
|
||||
$assert(PrescriptionLogic::audit(41, 'approve', '', 1, $root) === false
|
||||
&& str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual approval blocks an unenrolled pending prescription');
|
||||
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual approval blocks an unsubmitted prescription');
|
||||
$assert(PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署')
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方')
|
||||
&& (int) Db::name('tcm_prescription_order')->where('id', 41)->value('prescription_audit_status') === 0,
|
||||
'business order approval blocks an unenrolled pending prescription');
|
||||
'business order approval blocks an unsubmitted prescription');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(41, 2, $root), 'another doctor cannot upload on behalf of the owner');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(42, 1, $root), 'closed historical prescription cannot get a new upload timestamp');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(44, 1, $root), 'system-generated blank prescription cannot upload');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(45, 1, $root), 'voided prescription cannot upload');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(46, 1, $root), 'deleted prescription cannot upload');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(48, 1, $root), 'a prescription awaiting eSign must have a clinical diagnosis before upload');
|
||||
$assert($draft === Db::name('tcm_prescription')->find(41)
|
||||
&& !Db::name('prescription_esign')->where('prescription_id', 41)->find(), 'status and audit checks never enroll or change the draft');
|
||||
&& Fake::$starts === $startsBeforeUpload && !Db::name('prescription_esign')->where('prescription_id', 41)->find(),
|
||||
'blocked checks neither contact the signing provider nor change the draft');
|
||||
|
||||
foreach ([42, 43, 45, 46] as $id) {
|
||||
$historical = Service::describe(Db::name('tcm_prescription')->find($id), 1);
|
||||
$assert(!$historical['required'] && $historical['status'] === 'legacy' && !$historical['can_sign'],
|
||||
$assert(!$historical['required'] && $historical['status'] === 'legacy' && !$historical['can_sign']
|
||||
&& !$historical['awaiting_upload'] && !$historical['can_review_prescription'],
|
||||
'approved, rejected, voided and deleted legacy cases are never auto-enrolled');
|
||||
$throws(fn () => Service::start($id, 1, $root), 'closed historical prescription cannot be enrolled by signing');
|
||||
}
|
||||
@@ -752,9 +783,32 @@ namespace {
|
||||
$throws(fn () => Service::start(48, 1, $root), 'invalid legacy contents fail before enrollment');
|
||||
$assert((int) Db::name('tcm_prescription')->where('id', 48)->value('esign_required') === 0
|
||||
&& !Db::name('prescription_esign')->where('prescription_id', 48)->find(), 'failed preparation keeps the draft unmodified');
|
||||
$assert(PrescriptionLogic::audit(47, 'reject', '测试驳回', 1, $root)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 47)->value('void_status') === 1,
|
||||
'unsigned pending prescription remains correctable through rejection');
|
||||
$submission = PrescriptionLogic::submitForReview(41, 1, $root);
|
||||
$assert($submission['review_submitted_at'] > 0 && $submission['can_submit_for_review'] === false
|
||||
&& PrescriptionLogic::submitForReview(41, 1, $root) === $submission,
|
||||
'doctor upload persists once before signing and is idempotent');
|
||||
$uploaded = Service::status(41, 1, $root);
|
||||
$assert($uploaded['can_sign'] && !$uploaded['awaiting_upload'] && !$uploaded['can_review_prescription']
|
||||
&& !$uploaded['can_submit_for_review'] && $uploaded['review_submitted_at'] === $submission['review_submitted_at'],
|
||||
'upload enables doctor signing while the prescription remains unavailable for review');
|
||||
$pendingList = static fn () => new class($root) extends PrescriptionLists {
|
||||
public function __construct(array $adminInfo)
|
||||
{
|
||||
$this->adminId = 1;
|
||||
$this->adminInfo = $adminInfo;
|
||||
$this->params = ['audit_filter' => 'pending'];
|
||||
$this->searchWhere = [['id', 'in', [41, 42, 44, 48]]];
|
||||
$this->limitOffset = 0;
|
||||
$this->limitLength = 20;
|
||||
}
|
||||
};
|
||||
$list = $pendingList();
|
||||
$assert($list->count() === 0 && $list->lists() === [],
|
||||
'pending review filter excludes uploaded but unsigned prescriptions from both results and count');
|
||||
$assert(PrescriptionLogic::audit(41, 'reject', '测试驳回', 1, $root) === false
|
||||
&& str_contains(PrescriptionLogic::getError(), '电子签署')
|
||||
&& PrescriptionOrderLogic::auditPrescription(41, 'reject', '测试驳回', 1, $root) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署'), 'existing review entry points require doctor signature after upload');
|
||||
|
||||
$started = Service::start(41, 1, $root);
|
||||
$frozen = Db::name('tcm_prescription')->find(41);
|
||||
@@ -764,10 +818,32 @@ namespace {
|
||||
&& $evidence['snapshot_hash'] === Policy::hash($draft) && is_file($dir . '/pdf/' . $evidence['source_path']),
|
||||
'starting eSign freezes the same prescription and preserves its handwritten data');
|
||||
$throws(fn () => Policy::assertMutable($frozen), 'newly enrolled draft is frozen before approval');
|
||||
$assert(Service::complete(41, 1, $root)['status'] === 'signed', 'the enrolled doctor can sign the existing prescription');
|
||||
$signedStatus = Service::complete(41, 1, $root);
|
||||
$signedRx = PrescriptionLogic::withSigningStatus(Db::name('tcm_prescription')->find(41), 2, false);
|
||||
$assert($signedStatus['status'] === 'signed' && $signedStatus['can_review_prescription']
|
||||
&& $signedRx['can_review_prescription'] && $signedRx['esign']['can_review_prescription']
|
||||
&& !$signedStatus['can_submit_for_review'] && $signedStatus['review_submitted_at'] === $submission['review_submitted_at']
|
||||
&& (int) $signedRx['audit_status'] === 0, 'verified signing makes the existing upload available for review without approving it');
|
||||
$list = $pendingList();
|
||||
$assert($list->count() === 1 && array_map('intval', array_column($list->lists(), 'id')) === [41],
|
||||
'pending review filter includes the signed prescription in the actual page and count');
|
||||
$archivePath = $dir . '/pdf/' . Db::name('prescription_esign')->where('prescription_id', 41)->value('signed_path');
|
||||
$archived = file_get_contents($archivePath);
|
||||
file_put_contents($archivePath, $archived . 'changed');
|
||||
$assert(!Service::status(41, 1, $root)['can_review_prescription']
|
||||
&& !PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0],
|
||||
Db::name('tcm_prescription')->find(41))['can_review_prescription']
|
||||
&& !PrescriptionLogic::audit(41, 'reject', '测试驳回', 1, $root)
|
||||
&& !PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root),
|
||||
'a missing or modified original blocks review status and mutations');
|
||||
$assert(!$pendingList()->lists()[0]['can_review_prescription'],
|
||||
'a row with a stored signed state still needs an intact archive to allow review');
|
||||
file_put_contents($archivePath, $archived);
|
||||
$assert(PrescriptionLogic::audit(41, 'approve', '', 1, $root)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 41)->value('audit_status') === 1,
|
||||
'the same prescription can be approved after verified eSign');
|
||||
$assert(PrescriptionLogic::submitForReview(41, 1, $root) === $submission,
|
||||
'a retry after approval still returns the existing upload receipt');
|
||||
$throws(fn () => Service::assertSignedById(41, true), 'sandbox enrollment permits approval but still blocks formal dispensing');
|
||||
|
||||
$new(49);
|
||||
@@ -797,6 +873,7 @@ namespace {
|
||||
$before = Fake::$signs;
|
||||
$assert(Service::retryVerification(49, 2, $root)['status'] === 'signed' && Fake::$signs === $before,
|
||||
'archive verification uses the frozen signer after configuration changes without signing again');
|
||||
PrescriptionLogic::submitForReview(49, 2, $root);
|
||||
$assert(PrescriptionLogic::audit(49, 'approve', '', 1, $root)
|
||||
&& !empty(Service::download(49, 2, $root)['sha256']), 'verified alias prescription can be audited and downloaded');
|
||||
$assert(PrescriptionLogic::consumeLastAuditWecomNotify() === null, 'a sandbox audit does not send a live WeCom notification');
|
||||
@@ -897,7 +974,6 @@ namespace {
|
||||
Db::execute('INSERT INTO zyt_doctor_appointment VALUES (40, 10, 1, 3)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_note (id INTEGER PRIMARY KEY, diagnosis_id INTEGER, delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_diagnosis_view_records (id INTEGER PRIMARY KEY, diagnosis_id INTEGER, user_id INTEGER, delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_pharmacy_submission_claim (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, source_revision INTEGER, status TEXT)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_medicine (id INTEGER PRIMARY KEY, name TEXT, status INTEGER, delete_time INTEGER)');
|
||||
Db::execute("INSERT INTO zyt_doctor_medicine VALUES (1, '测试药材', 1, NULL)");
|
||||
|
||||
@@ -908,8 +984,11 @@ namespace {
|
||||
$permissionAlias = new \ReflectionMethod(AuthMiddleware::class, 'matchPermissionAlias');
|
||||
foreach (PrescriptionLogic::PRESCRIBE_PERMISSIONS as $grant) {
|
||||
$assert($permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/void', [$grant]), 'prescribing grants permit the void route');
|
||||
$assert($permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/submitforreview', [$grant]), 'prescribing grants permit the upload route');
|
||||
}
|
||||
$assert(!$permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/void', ['cf.prescription/lists']), 'read permission grants no void route');
|
||||
$assert(!$permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/submitforreview', ['cf.prescription/lists']), 'read permission grants no upload route');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(41, 3, $readOnly), 'read-only accounts cannot upload prescriptions');
|
||||
$assert(PrescriptionLogic::detail(2, 1, $doctor)['can_void'], 'creator can void signed prescription through detail');
|
||||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||||
$assert((int) $appointmentPrescription['id'] === 2 && $appointmentPrescription['can_void'] === true
|
||||
@@ -966,10 +1045,38 @@ namespace {
|
||||
&& (int) $reissued['audit_status'] === 0 && Db::name('prescription_esign')->where('prescription_id', $newId)->count() === 0,
|
||||
'reissue gets a new serial number and its own pending signature and audit');
|
||||
if ($previousState === 'pending') {
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update(['esign_required' => 0, 'esign_status' => 'legacy']);
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update([
|
||||
'esign_required' => 0, 'esign_status' => 'legacy', 'is_system_auto' => 1, 'herbs' => '[]',
|
||||
]);
|
||||
Db::name('tcm_prescription_order')->insert([
|
||||
'id' => 2041, 'prescription_id' => $newId, 'fulfillment_status' => 1,
|
||||
'prescription_audit_status' => 0, 'payment_slip_audit_status' => 1,
|
||||
]);
|
||||
$assert(!PrescriptionLogic::detail($newId, 1, $doctor)['can_void']
|
||||
&& !PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true),
|
||||
'an approved payment audit still blocks void from the issued list');
|
||||
Db::name('tcm_prescription_order')->where('id', 2041)->update(['payment_slip_audit_status' => 0]);
|
||||
$linkedBefore = Db::name('tcm_prescription_order')->find(2041);
|
||||
$assert(PrescriptionLogic::detail($newId, 1, $doctor)['can_void'],
|
||||
'blank pending prescription can be voided before either linked order audit');
|
||||
}
|
||||
$assert(PrescriptionLogic::void($newId, 1, $doctor) && !PrescriptionLogic::edit(['id' => $newId], 1),
|
||||
if ($previousState === 'signed') {
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update(['audit_status' => 1]);
|
||||
$assert(!PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true)
|
||||
&& str_contains(PrescriptionLogic::getError(), '审核状态已变化')
|
||||
&& (int) Db::name('tcm_prescription')->where('id', $newId)->value('void_status') === 0,
|
||||
'a stale issued-list action cannot void a prescription that has since been approved');
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update(['audit_status' => 0]);
|
||||
}
|
||||
$assert(PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true) && !PrescriptionLogic::edit(['id' => $newId], 1),
|
||||
'a manually voided record cannot be edited back into use');
|
||||
if ($previousState === 'pending') {
|
||||
$assert(Db::name('tcm_prescription_order')->find(2041) === $linkedBefore
|
||||
&& PrescriptionOrderLogic::auditPrescription(2041, 'approve', '', 1, $root) === false,
|
||||
'void preserves the linked order and blocks order approval on the voided prescription');
|
||||
$throws(fn () => Service::assertSignedById($newId, true),
|
||||
'voided handwritten prescription cannot be dispatched through a linked order');
|
||||
}
|
||||
$oldId = $newId;
|
||||
}
|
||||
$auditRejected = ['audit_status' => 2, 'void_status' => 1, 'audit_time' => 100, 'void_time' => 100,
|
||||
@@ -1096,6 +1203,13 @@ namespace {
|
||||
Fake::$expiredWillingness = false;
|
||||
$new(88);
|
||||
Service::start(88, 1, $doctor);
|
||||
Db::name('tcm_prescription')->where('id', 88)->update(['audit_status' => 0, 'review_submitted_at' => 0]);
|
||||
$inFlight = Service::status(88, 1, $doctor);
|
||||
$assert($inFlight['can_submit_for_review'] && !$inFlight['can_resume_identity'] && !isset($inFlight['auth_url']),
|
||||
'a signing session prepared before upload is gated until the doctor uploads');
|
||||
$throws(fn () => Service::complete(88, 1, $doctor), 'a pre-existing signing session cannot confirm without upload');
|
||||
PrescriptionLogic::submitForReview(88, 1, $doctor);
|
||||
$assert(Service::status(88, 1, $doctor)['can_resume_identity'], 'upload unlocks a retained doctor signing session');
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replacement-account']);
|
||||
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update([
|
||||
'account_id' => 'replacement-account', 'flow_id' => 'replacement-grant',
|
||||
@@ -1108,19 +1222,60 @@ namespace {
|
||||
'renewed authorization can prepare an existing prescription without automatic signing');
|
||||
|
||||
$config->set(['review_enabled' => true] + $config->get('esign'), 'esign');
|
||||
Db::name('tcm_prescription')->where('id', 84)->update(['audit_status' => 0]);
|
||||
Db::name('tcm_prescription')->where('id', 84)->update(['audit_status' => 0, 'review_submitted_at' => 0]);
|
||||
Db::name('admin')->insert(['id' => 22, 'name' => '测试审核人', 'root' => 1]);
|
||||
Db::name('admin')->insert(['id' => 23, 'name' => '另一位测试审核人', 'root' => 1]);
|
||||
Db::name('admin')->insert(['id' => 23, 'name' => '另一位测试审核人']);
|
||||
Db::name('admin')->insert(['id' => 24, 'name' => '仅查看订单']);
|
||||
$orderAuditMenu = Db::name('system_menu')->insertGetId(['perms' => Review::ORDER_PERMISSION]);
|
||||
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => $orderAuditMenu]);
|
||||
Db::name('admin_role')->insert(['admin_id' => 23, 'role_id' => 3]);
|
||||
$auditor = ['root' => 1, 'admin_id' => 22, 'name' => '测试审核人'];
|
||||
$otherAuditor = ['root' => 1, 'admin_id' => 23, 'name' => '另一位测试审核人'];
|
||||
$otherAuditor = ['root' => 0, 'admin_id' => 23, 'name' => '另一位测试审核人', 'role_id' => [3]];
|
||||
$reviewerAccount = ['doctor_id' => 22, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||||
'doctor_name' => '测试审核人', 'account_id' => 'reviewer-account'];
|
||||
Db::name('doctor_esign_account')->insert($reviewerAccount + ['create_time' => time()]);
|
||||
Db::name('doctor_esign_quicksign')->insert($reviewerAccount + [
|
||||
'flow_id' => 'stored-reviewer-authorization', 'expires_at' => time() + 3600, 'flow_started_at' => time(),
|
||||
]);
|
||||
$new(89, false);
|
||||
Db::name('tcm_prescription')->where('id', 89)->update(['esign_required' => 0, 'esign_status' => 'legacy', 'audit_status' => 0]);
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 89, 'prescription_id' => 89, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
$waitingForDoctor = Review::status(89, 89, 22, $auditor);
|
||||
$assert($waitingForDoctor['required'] && !$waitingForDoctor['can_setup']
|
||||
&& !$waitingForDoctor['can_confirm'] && !$waitingForDoctor['can_approve']
|
||||
&& str_contains($waitingForDoctor['message'], '上传处方'),
|
||||
'order audit and reviewer signing wait for the doctor to upload');
|
||||
$throws(fn () => Review::confirm(89, 89, 22, $auditor, false), 'reviewer cannot sign an unenrolled pending prescription');
|
||||
PrescriptionLogic::submitForReview(89, 1, $doctor);
|
||||
$waitingForSignature = Review::status(89, 89, 22, $auditor);
|
||||
$assert($waitingForSignature['required'] && !$waitingForSignature['can_setup'] && !$waitingForSignature['can_confirm']
|
||||
&& !$waitingForSignature['can_approve'] && str_contains($waitingForSignature['message'], '有效电子签署'),
|
||||
'an uploaded prescription still needs the doctor signature to enter pharmacist review');
|
||||
$assert(!Db::name('prescription_esign')->where('prescription_id', 89)->find() && Fake::$reviewCalls === [],
|
||||
'order reviewer setup and status checks leave the pending prescription untouched');
|
||||
$original = Service::download(84, 22, $auditor);
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 84, 'prescription_id' => 84, 'creator_id' => 24,
|
||||
'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
$assert(!PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(84))['can_review_prescription'],
|
||||
'signed order prescription remains unavailable for review before upload');
|
||||
$assert(PrescriptionLogic::audit(84, 'reject', '测试驳回', 22, $auditor) === false
|
||||
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'direct rejection requires upload');
|
||||
$assert(PrescriptionOrderLogic::auditPrescription(84, 'reject', '测试驳回', 23, $otherAuditor) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方'), 'business rejection requires upload');
|
||||
foreach ([1, 2] as $status) {
|
||||
$assert(PrescriptionOrderLogic::addLog(['id' => 84, 'summary' => '测试审批', 'prescription_audit_status' => $status], 23, $otherAuditor) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方'), 'manual business audit changes require upload');
|
||||
}
|
||||
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'signed prescription still cannot receive a pharmacist signature before upload');
|
||||
$submitted = PrescriptionLogic::submitForReview(84, 1, $doctor);
|
||||
$assert($submitted['review_submitted_at'] > 0 && PrescriptionOrderLogic::withReviewAvailability(
|
||||
['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(84)
|
||||
)['can_review_prescription'] === true && Service::download(84, 22, $auditor) === $original,
|
||||
'a pre-existing signed archive becomes available for review after upload without changing its evidence');
|
||||
$throws(fn () => Service::assertSignedById(84, false, 22), 'doctor signature alone cannot approve');
|
||||
$assert(!Review::status(84, 84, 23, $otherAuditor)['can_approve']
|
||||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false,
|
||||
'business order remains blocked while there is only one signature');
|
||||
$throws(fn () => Review::confirm(84, 0, 1, $root, false), 'prescriber cannot review their own prescription');
|
||||
$assert(Review::status(84, 0, 22, $auditor)['can_confirm'] && Fake::$reviewCalls === [],
|
||||
'opening the audit verifies access without signing');
|
||||
@@ -1129,6 +1284,21 @@ namespace {
|
||||
$assert($attempt['state'] === 'uncertain' && $attempt['can_retry_verify']
|
||||
&& Fake::$reviewCalls === [['reviewer-account', 'stored-reviewer-authorization', $original['sha256']]],
|
||||
'review uses only reviewer authorization and the original PDF, and retains the signed result on a verification failure');
|
||||
$pendingLog = array_column(Service::status(84, 22, $auditor)['signing_log'], 'event');
|
||||
$assert(in_array('review_confirmed', $pendingLog, true) && in_array('review_uncertain', $pendingLog, true)
|
||||
&& !in_array('review_signed', $pendingLog, true), 'pending verification logs confirmation and the exception without certifying a signature');
|
||||
$reviewRow = Db::name('tcm_prescription')->where('id', 84)->find();
|
||||
$uncertainSummary = Service::describe($reviewRow, 22);
|
||||
$assert($uncertainSummary['review_state'] === 'uncertain' && !isset($uncertainSummary['review_signature_time']),
|
||||
'list reports uncertain pharmacist signing without treating the doctor signature as dual signing');
|
||||
$storedReview = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
|
||||
foreach ([['failed', time(), 'failed'], ['verifying', time(), 'verifying'], ['signing', time() - 3600, 'uncertain']] as [$state, $updated, $expected]) {
|
||||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update(['state' => $state, 'update_time' => $updated]);
|
||||
$assert(Service::describe($reviewRow, 22)['review_state'] === $expected, "list reports pharmacist $state as $expected");
|
||||
}
|
||||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update([
|
||||
'state' => $storedReview['state'], 'update_time' => $storedReview['update_time'],
|
||||
]);
|
||||
$assert(Service::download(84, 22, $auditor) === $original, 'a pending verification never replaces the original download');
|
||||
$throws(fn () => Review::confirm(84, 0, 23, $otherAuditor, true), 'another reviewer cannot recover or reuse the operation');
|
||||
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'a provider result that is already archived must not sign again');
|
||||
@@ -1136,20 +1306,85 @@ namespace {
|
||||
$result = Review::confirm(84, 0, 22, $auditor, true);
|
||||
$assert($result['state'] === 'signed' && $result['can_approve'] && count(Fake::$reviewCalls) === 1,
|
||||
'retry verifies the archived doctor and reviewer signatures without resubmitting the PDF to the signer');
|
||||
$listMetadata = Service::describe($reviewRow, 22);
|
||||
$assert($listMetadata['review_required'] && $listMetadata['review_state'] === 'signed'
|
||||
&& $listMetadata['review_signature_time'] === $result['signature_time'] && !isset($listMetadata['review_signature'])
|
||||
&& !isset($listMetadata['signing_log']), 'list metadata omits the image and signing log');
|
||||
$combined = Service::download(84, 22, $auditor);
|
||||
$expectedSeal = Fake::$reviewSignatures[$combined['sha256']][0]['sealData'];
|
||||
$reviewMetadata = Service::status(84, 22, $auditor);
|
||||
$assert($reviewMetadata['review_signature'] === 'data:image/png;base64,' . $expectedSeal
|
||||
&& $reviewMetadata['review_signature_time'] === $result['signature_time'],
|
||||
'status exposes the matched reviewer PNG and credible timestamp');
|
||||
$sealFiles = glob($dir . '/pdf/84-*/review-seal-*.png') ?: [];
|
||||
$assert(count($sealFiles) === 1, 'signature verification caches the matched image');
|
||||
unlink($sealFiles[0]);
|
||||
$restoredMetadata = Service::status(84, 22, $auditor);
|
||||
$assert($restoredMetadata['review_signature'] === $reviewMetadata['review_signature'] && count(Fake::$reviewCalls) === 1,
|
||||
'an older archive recovers its actual reviewer PNG without a new signature');
|
||||
$assert(str_ends_with($combined['filename'], '-dual-signed.pdf') && $combined['sha256'] !== $original['sha256']
|
||||
&& str_starts_with(base64_decode($combined['content_base64']), base64_decode($original['content_base64'])),
|
||||
'download returns the verified incremental dual-signed PDF');
|
||||
$throws(fn () => Service::assertSignedById(84, false, 23), 'one reviewer cannot approve with another reviewer signature');
|
||||
$throws(fn () => Service::assertSignedById(84, true), 'the dual-signed sandbox prescription remains blocked from dispensing');
|
||||
$assert(PrescriptionLogic::audit(84, 'approve', '', 22, $auditor)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 84)->value('audit_by') === 22,
|
||||
'the second signer can approve with the verified dual signature');
|
||||
$assert(!Review::status(84, 0, 23, $otherAuditor)['can_approve']
|
||||
&& !PrescriptionLogic::audit(84, 'approve', '', 23, $otherAuditor),
|
||||
'the independent prescription audit still requires the pharmacist who signed');
|
||||
$viewer = ['root' => 0, 'admin_id' => 24, 'name' => '仅查看订单'];
|
||||
$assert(!Review::status(84, 84, 24, $viewer)['can_approve']
|
||||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 24, $viewer) === false,
|
||||
'ownership alone does not authorize order approval');
|
||||
$orderReview = Review::status(84, 84, 23, $otherAuditor);
|
||||
$assert($orderReview['can_approve'] && !$orderReview['can_confirm'] && !$orderReview['can_setup']
|
||||
&& $orderReview['signer_name'] === $result['signer_name'],
|
||||
'an authorized order auditor can approve the verified signatures without another signing identity');
|
||||
Db::name('system_menu')->where('id', $orderAuditMenu)->update(['is_disable' => 1]);
|
||||
$assert(!Review::status(84, 84, 23, $otherAuditor)['can_approve']
|
||||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false,
|
||||
'a disabled order audit grant blocks a previously eligible submitter');
|
||||
Db::name('system_menu')->where('id', $orderAuditMenu)->update(['is_disable' => 0]);
|
||||
$archive = glob($dir . '/pdf/84-*/review-signed.pdf')[0];
|
||||
$archivedBytes = file_get_contents($archive);
|
||||
file_put_contents($archive, $archivedBytes . 'modified');
|
||||
$assert(PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false
|
||||
&& (int) Db::name('tcm_prescription_order')->where('id', 84)->value('prescription_audit_status') === 0,
|
||||
'a changed dual-sign PDF is refused under the order approval transaction');
|
||||
file_put_contents($archive, $archivedBytes);
|
||||
$order = PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor);
|
||||
$assert($order !== false && (int) $order['prescription_audit_status'] === 1
|
||||
&& (int) $order['payment_slip_audit_status'] === 0
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 84)->value('audit_by') === 23
|
||||
&& (int) Db::name('tcm_prescription_order_log')->where('prescription_order_id', 84)->value('admin_id') === 23,
|
||||
'order approval records the actual submitter and synchronizes the prescription without approving payment');
|
||||
$assert(Service::download(84, 22, $auditor) === $combined && count(Fake::$reviewCalls) === 1,
|
||||
'order approval preserves the pharmacist signature and archived original');
|
||||
$signedLog = Service::status(84, 22, $auditor)['signing_log'];
|
||||
$events = array_column($signedLog, null, 'event');
|
||||
$times = array_column($signedLog, 'time');
|
||||
$ordered = $times;
|
||||
sort($ordered);
|
||||
$assert($times === $ordered && isset($events['issued'], $events['doctor_verified'], $events['review_confirmed'],
|
||||
$events['review_verified'], $events['audit_approved']) && !isset($events['review_uncertain']),
|
||||
'signed history orders recorded milestones and replaces the resolved exception');
|
||||
$assert($events['doctor_signed']['time'] === $reviewMetadata['signature_time']
|
||||
&& $events['doctor_signed']['actor_name'] === $reviewMetadata['doctor_signer_name']
|
||||
&& $events['review_signed']['time'] === $result['signature_time']
|
||||
&& $events['review_signed']['actor_name'] === $result['signer_name']
|
||||
&& $events['doctor_signed']['source'] === 'tsa' && $events['review_signed']['source'] === 'tsa'
|
||||
&& $events['review_verified']['source'] === 'system',
|
||||
'signing log preserves the two verified provider times and distinguishes system milestones');
|
||||
$assert(Service::status(89, 22, $auditor)['signing_log'] === [], 'an unenrolled prescription has no fabricated events');
|
||||
$reopened = PrescriptionOrderLogic::revokeRxAudit(84, 23, $otherAuditor);
|
||||
$reopenedPrescription = Db::name('tcm_prescription')->find(84);
|
||||
$assert($reopened !== false && (int) $reopenedPrescription['review_submitted_at'] === 0
|
||||
&& !PrescriptionOrderLogic::withReviewAvailability($reopened, $reopenedPrescription)['can_review_prescription']
|
||||
&& !Review::status(84, 84, 23, $otherAuditor)['can_approve'], 'reopening requires a new doctor upload');
|
||||
file_put_contents(dirname(__DIR__, 2) . '/artifacts/esign-prescription-test.pdf', $pdf);
|
||||
echo "Prescription eSign flow: $checks checks passed (isolated SQLite, fake provider)\n";
|
||||
} finally {
|
||||
$manager->connect()->close();
|
||||
foreach (glob($dir . '/pdf/*/*.pdf') ?: [] as $file) { unlink($file); }
|
||||
foreach (glob($dir . '/pdf/*/review-seal-*.png') ?: [] as $file) { unlink($file); }
|
||||
foreach (glob($dir . '/pdf/*', GLOB_ONLYDIR) ?: [] as $folder) { rmdir($folder); }
|
||||
if (is_dir($dir . '/pdf')) { rmdir($dir . '/pdf'); }
|
||||
if (is_file($dir . '/fixture.sqlite')) { unlink($dir . '/fixture.sqlite'); }
|
||||
|
||||
@@ -7,6 +7,7 @@ require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\service\esign\PrescriptionCaSigningSettings;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
use app\common\service\pharmacy\PharmacySubmissionClaimService;
|
||||
@@ -39,6 +40,7 @@ $expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
$checks++;
|
||||
};
|
||||
try {
|
||||
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)');
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
|
||||
id INT UNSIGNED PRIMARY KEY,creator_id INT,doctor_name VARCHAR(100),patient_name VARCHAR(100),phone VARCHAR(30),gender INT,
|
||||
audit_status INT DEFAULT 0,void_status INT DEFAULT 0,delete_time INT NULL,update_time INT DEFAULT 0,
|
||||
@@ -49,8 +51,12 @@ try {
|
||||
$migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql');
|
||||
$pdo->exec($migration);
|
||||
$pdo->exec($migration);
|
||||
$submissionMigration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_21_prescription_review_submission.sql');
|
||||
$pdo->exec($submissionMigration);
|
||||
$pdo->exec($submissionMigration);
|
||||
$row = Db::name('tcm_prescription')->find(1);
|
||||
$expect((int) $row['esign_required'] === 0 && $row['esign_status'] === 'legacy', 'migration preserves historical rows and is repeatable');
|
||||
$expect((int) $row['review_submitted_at'] === 0, 'repeatable upload migration leaves legacy records without an upload time');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,esign_required,esign_status) VALUES (2,1,'测试医师',1,'pending')");
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY,prescription_order_id INT,source_revision INT,status VARCHAR(40))');
|
||||
@@ -64,8 +70,10 @@ try {
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,audit_status) VALUES (3,1,'测试医师',1)");
|
||||
PrescriptionEsignService::assertSignedById(3);
|
||||
$expect(PrescriptionEsignService::describe(Db::name('tcm_prescription')->find(3), 1)['status'] === 'legacy', 'previously approved historical prescription remains on record');
|
||||
$expect(PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(3))['can_review_prescription'],
|
||||
'an already approved historical prescription remains available to an existing order');
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual audit explains signature requirement');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual audit explains upload requirement');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false, 'order audit rejects unsigned before write');
|
||||
$expect((int) Db::name('tcm_prescription_order')->where('id', 1)->value('prescription_audit_status') === 0, 'order remains pending after rejection');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false, 'manual order log cannot bypass signature requirement');
|
||||
@@ -79,6 +87,40 @@ try {
|
||||
|
||||
// Real InnoDB contention: a second connection attempts to void the very
|
||||
// prescription being approved, at the exact model before-write boundary.
|
||||
Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'pending', 'herbs' => '[{"name":"Fixture herb"}]',
|
||||
'clinical_diagnosis' => 'Fixture diagnosis']);
|
||||
$pdo->exec('SET SESSION innodb_lock_wait_timeout=1');
|
||||
$events = new class($pdo, $expect) {
|
||||
public int $attempts = 0;
|
||||
public function __construct(private PDO $otherConnection, private Closure $expect) {}
|
||||
public function trigger(string $event, mixed $model): array {
|
||||
if (!str_ends_with($event, '.BeforeUpdate')) { return []; }
|
||||
$this->attempts++;
|
||||
try {
|
||||
$this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2');
|
||||
($this->expect)(false, 'concurrent void must wait for signature check + audit write');
|
||||
} catch (PDOException $e) {
|
||||
($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write');
|
||||
}
|
||||
throw new DomainException('TEST_LOCK_OBSERVED');
|
||||
}
|
||||
};
|
||||
\think\Model::setEvent($events);
|
||||
try {
|
||||
PrescriptionLogic::submitForReview(2, 1, $root);
|
||||
$expect(false, 'submission must retain its own prescription lock');
|
||||
} catch (DomainException $error) {
|
||||
$expect($error->getMessage() === 'TEST_LOCK_OBSERVED' && (int) Db::name('tcm_prescription')->where('id', 2)->value('review_submitted_at') === 0,
|
||||
'failed concurrent submission rolls back its audit timestamp');
|
||||
}
|
||||
\think\Model::setEvent(null);
|
||||
$submitted = PrescriptionLogic::submitForReview(2, 1, $root);
|
||||
$expect($submitted['review_submitted_at'] > 0 && PrescriptionLogic::submitForReview(2, 1, $root) === $submitted,
|
||||
'actual MySQL upload before signing is persisted once');
|
||||
$expect(!PrescriptionEsignService::status(2, 1, $root)['can_review_prescription']
|
||||
&& !PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root)
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署'),
|
||||
'persistent eSign requirement still gates review after upload when disabled');
|
||||
Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'signed']);
|
||||
$snapshot = PrescriptionEsignPolicy::hash(Db::name('tcm_prescription')->find(2));
|
||||
$storage = sys_get_temp_dir() . '/zyt-' . $database;
|
||||
@@ -101,27 +143,11 @@ try {
|
||||
} catch (DomainException $e) {
|
||||
$expect(str_contains($e->getMessage(), '沙箱'), 'claim boundary enforces production signatures');
|
||||
}
|
||||
$pdo->exec('SET SESSION innodb_lock_wait_timeout=1');
|
||||
$events = new class($pdo, $expect) {
|
||||
public int $attempts = 0;
|
||||
public function __construct(private PDO $otherConnection, private Closure $expect) {}
|
||||
public function trigger(string $event, mixed $model): array {
|
||||
if (!str_ends_with($event, '.BeforeUpdate')) { return []; }
|
||||
$this->attempts++;
|
||||
try {
|
||||
$this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2');
|
||||
($this->expect)(false, 'concurrent void must wait for signature check + audit write');
|
||||
} catch (PDOException $e) {
|
||||
($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write');
|
||||
}
|
||||
throw new DomainException('TEST_LOCK_OBSERVED');
|
||||
}
|
||||
};
|
||||
\think\Model::setEvent($events);
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false && PrescriptionLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual audit reaches locked write');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'order audit reaches locked write');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual status change reaches locked write');
|
||||
$expect($events->attempts === 3 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
$expect($events->attempts === 4 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
\think\Model::setEvent(null);
|
||||
Db::name('tcm_prescription_order')->where('id', 1)->update(['fulfillment_status' => 4]);
|
||||
$pdo->exec("INSERT INTO zyt_pharmacy_submission_claim VALUES (1, 1, 1, 'FAILED'), (2, 1, 2, 'PENDING')");
|
||||
@@ -129,7 +155,12 @@ try {
|
||||
'void locks and checks the latest pharmacy claim on a released order');
|
||||
Db::name('pharmacy_submission_claim')->where('id', 2)->update(['status' => 'FAILED']);
|
||||
$expect(PrescriptionLogic::void(2, 1, $root), 'void succeeds when the released order has no active claim');
|
||||
$expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf), 'void preserves downloadable signed evidence');
|
||||
$pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY,root INT,disable INT DEFAULT 0,delete_time INT)');
|
||||
$pdo->exec('INSERT INTO zyt_admin (id,root) VALUES (1,1)');
|
||||
PrescriptionCaSigningSettings::setEnabled(false, 1);
|
||||
$expect(!PrescriptionEsignService::enabled(), 'persistent admin flag disables CA in MySQL');
|
||||
$expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf),
|
||||
'turning CA off after void preserves downloadable signed evidence');
|
||||
echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n";
|
||||
} finally {
|
||||
\think\Model::setEvent(null);
|
||||
|
||||
@@ -31,6 +31,7 @@ $pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '',
|
||||
if (!$isWorker) $pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `{$database}`");
|
||||
$testApp = new think\App();
|
||||
$testApp->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new DbManager();
|
||||
$manager->setConfig([
|
||||
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
|
||||
@@ -63,6 +64,7 @@ if ($isWorker) {
|
||||
}
|
||||
|
||||
try {
|
||||
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order
|
||||
ADD agency_collect_amount DECIMAL(10,2) NULL, ADD paid DECIMAL(10,2) DEFAULT 0,
|
||||
@@ -76,6 +78,7 @@ try {
|
||||
audit_time INT NULL, audit_by INT NULL, audit_by_name VARCHAR(100) DEFAULT "", audit_remark VARCHAR(500) DEFAULT "",
|
||||
create_time INT DEFAULT 0, update_time INT DEFAULT 0, delete_time INT NULL
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_21_prescription_review_submission.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_order (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(50), patient_id INT DEFAULT 1,
|
||||
creator_id INT DEFAULT 1, order_type INT DEFAULT 3, amount DECIMAL(10,2), status INT,
|
||||
|
||||
@@ -26,6 +26,7 @@ $pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '',
|
||||
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `{$database}`");
|
||||
$testApp = new think\App();
|
||||
$testApp->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new DbManager();
|
||||
$manager->setConfig([
|
||||
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
|
||||
@@ -47,6 +48,7 @@ $expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
};
|
||||
|
||||
try {
|
||||
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order
|
||||
ADD agency_collect_amount DECIMAL(10,2) NULL, ADD paid DECIMAL(10,2) DEFAULT 0,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\assistantservice {
|
||||
// 只截取客户端给 cURL 的 URL 和请求头,全程不创建连接。
|
||||
function curl_init($url) { $GLOBALS['requests'][] = ['url' => $url]; return count($GLOBALS['requests']) - 1; }
|
||||
function curl_setopt_array($handle, $options) { $GLOBALS['requests'][$handle] += ['headers' => $options[CURLOPT_HTTPHEADER], 'options' => $options]; return true; }
|
||||
function curl_exec($handle) {
|
||||
$callback = $GLOBALS['requests'][$handle]['options'][CURLOPT_HEADERFUNCTION];
|
||||
foreach ($GLOBALS['response_headers'] as $header) { $callback($handle, $header . "\r\n"); }
|
||||
return '{}';
|
||||
}
|
||||
function curl_getinfo($handle, $option) { return $GLOBALS['upstream_status']; }
|
||||
function curl_close($handle) {}
|
||||
}
|
||||
|
||||
namespace {
|
||||
use app\common\service\assistantservice\WecomArchiveHttp as Feed;
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
$settings = ['wecom_archive_base_url' => 'https://archive.example.invalid', 'wecom_archive_token' => str_repeat('synthetic', 5)];
|
||||
function config($key, $default = '') { return $GLOBALS['settings'][substr($key, strlen('assistant_service.'))] ?? $default; }
|
||||
$requests = [];
|
||||
$upstream_status = 200;
|
||||
$response_headers = ['HTTP/1.1 100 Continue', 'X-Archive-Tenant: ignored', 'HTTP/1.1 200 OK', 'X-Archive-Tenant: tenant-a'];
|
||||
foreach (['', '*', "one\r\nX-Test: two"] as $tenant) {
|
||||
$settings['wecom_archive_tenant'] = $tenant;
|
||||
if (Feed::configured() || Feed::page('', 1)['configured']) { throw new \RuntimeException('Invalid tenant enabled HTTP'); }
|
||||
try { Feed::accounts(); throw new \LogicException('Expected invalid configuration'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
}
|
||||
if ($requests) { throw new \RuntimeException('Request sent without a tenant'); }
|
||||
$settings['wecom_archive_tenant'] = 'tenant-a';
|
||||
foreach (['http://archive.example.invalid', 'file:///tmp/example', 'http://localhost@archive.example.invalid',
|
||||
'http://archive.example.invalid\@localhost', 'https://example.invalid/?q=conflict'] as $url) {
|
||||
$settings['wecom_archive_base_url'] = $url;
|
||||
if (Feed::configured()) { throw new \RuntimeException('Unsafe transport accepted'); }
|
||||
try { Feed::accounts(); throw new \LogicException('Expected transport refusal'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
}
|
||||
foreach (['http://localhost:3210', 'http://[::1]:3210', 'http://127.0.0.1:3210'] as $url) {
|
||||
$settings['wecom_archive_base_url'] = $url;
|
||||
if (!Feed::configured()) { throw new \RuntimeException('Loopback HTTP rejected'); }
|
||||
}
|
||||
Feed::accounts();
|
||||
$settings['wecom_archive_base_url'] = 'https://archive.example.invalid';
|
||||
Feed::conversations('staff-a');
|
||||
Feed::messages('chat-a');
|
||||
$upstream_status = 403;
|
||||
try { Feed::page('', 1); throw new \LogicException('Expected upstream refusal'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
if (count($requests) !== 4) { throw new \RuntimeException('Unexpected requests'); }
|
||||
foreach ($requests as $request) {
|
||||
if (!in_array('X-Archive-Tenant: tenant-a', $request['headers'], true)
|
||||
|| !in_array('X-Archive-Feed-Token: ' . $settings['wecom_archive_token'], $request['headers'], true)) {
|
||||
throw new \RuntimeException('Missing archive service headers');
|
||||
}
|
||||
}
|
||||
if (!array_key_exists(CURLOPT_PROXY, $requests[0]['options']) || $requests[0]['options'][CURLOPT_PROXY] !== ''
|
||||
|| $requests[0]['options'][CURLOPT_FOLLOWLOCATION] !== false) { throw new \RuntimeException('Loopback transport options'); }
|
||||
$upstream_status = 200;
|
||||
foreach ([[], ['X-Archive-Tenant: tenant-b'], ['X-Archive-Tenant: tenant-a', 'X-Archive-Tenant: tenant-a'],
|
||||
['X-Archive-Tenant: tenant-a', 'HTTP/1.1 200 OK'], ['', 'X-Archive-Tenant: tenant-a']] as $headers) {
|
||||
$response_headers = array_merge(['HTTP/1.1 200 OK'], $headers);
|
||||
try { Feed::accounts(); throw new \LogicException('Expected missing or conflicting response tenant refusal'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
}
|
||||
echo "WECOM_ARCHIVE_HTTP PASS mocked_transport=1 network=0\n";
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// 默认仅使用内存 SQLite。可选的本机独立 MySQL 可重复验证生产迁移和旧会话唯一键。
|
||||
namespace {
|
||||
final class WorkstationClock { public static int $now; }
|
||||
}
|
||||
namespace app\adminapi\service { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\adminapi\logic { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\adminapi\http\middleware { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\common\cache {
|
||||
function time(): int { return \WorkstationClock::$now; }
|
||||
// 故意保留过期缓存,验证服务端始终以数据库为准。
|
||||
abstract class BaseCache {
|
||||
private static array $entries = [];
|
||||
public function get($key) { return self::$entries[$key] ?? null; }
|
||||
public function set($key, $value, $ttl = null) { self::$entries[$key] = $value; }
|
||||
public function delete($key): bool { return false; }
|
||||
}
|
||||
}
|
||||
namespace app\common\service {
|
||||
final class FileService {
|
||||
public static function getFileUrl($uri = ''): string { return (string) $uri; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
use app\adminapi\controller\LoginController;
|
||||
use app\adminapi\http\middleware\LoginMiddleware;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum as Terminal;
|
||||
use think\facade\Db;
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
function create_token(string $extra = ''): string { return bin2hex(random_bytes(16)); }
|
||||
function wsExpect(bool $ok, string $label): void {
|
||||
if (!$ok) { throw new RuntimeException($label); }
|
||||
$GLOBALS['wsChecks']++;
|
||||
}
|
||||
final class WorkstationLoginController extends LoginController {
|
||||
public function __construct(think\Request $request) {
|
||||
$this->request = $request;
|
||||
$this->initialize();
|
||||
}
|
||||
}
|
||||
$GLOBALS['wsChecks'] = 0;
|
||||
$port = (int) getenv('ZYT_WORKSTATION_TEST_MYSQL_PORT');
|
||||
$temporaryDb = 'workstation_test_' . bin2hex(random_bytes(8));
|
||||
$app = new think\App(sys_get_temp_dir() . '/' . $temporaryDb);
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'auto_timestamp' => false, 'datetime_format' => false,
|
||||
'connections' => ['test' => $port
|
||||
? ['type' => 'mysql', 'database' => $temporaryDb, 'prefix' => 'zyt_', 'hostname' => '127.0.0.1',
|
||||
'username' => 'root', 'password' => '', 'hostport' => $port, 'charset' => 'utf8mb4']
|
||||
: ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_']]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
$app->instance('log', new Psr\Log\NullLogger());
|
||||
$config = new think\Config();
|
||||
$config->set(['admin_token' => ['expire_duration' => 28800, 'be_expire_duration' => 3600],
|
||||
'default_image' => ['admin_avatar' => '']], 'project');
|
||||
$app->instance('config', $config);
|
||||
$app->env->set('work_wechat.force_bind_login', false);
|
||||
$app->env->set('WORK_WECHAT_FORCE_BIND_LOGIN', false);
|
||||
$request = static function (string $token = '', string $action = 'desktopHeartbeat', string $method = 'POST') use ($app) {
|
||||
$req = (new think\Request())->withServer(['REMOTE_ADDR' => '192.0.2.10', 'REQUEST_METHOD' => $method])
|
||||
->withHeader(['token' => $token]);
|
||||
$req->setController('Login');
|
||||
$req->setAction($action);
|
||||
$req->controllerObject = new WorkstationLoginController($req);
|
||||
$app->instance('request', $req);
|
||||
return $req;
|
||||
};
|
||||
$invoke = static function (string $token, string $action = 'desktopHeartbeat', string $method = 'POST') use ($request) {
|
||||
$req = $request($token, $action, $method);
|
||||
return (new LoginMiddleware())->handle($req, static function ($req) use ($action) {
|
||||
return (new WorkstationLoginController($req))->$action();
|
||||
})->getData();
|
||||
};
|
||||
$login = static function (int $terminal = Terminal::WORKSTATION) use ($request) {
|
||||
$request('', 'account');
|
||||
return (new LoginLogic())->login(['account' => 'doctor.ws', 'terminal' => $terminal]);
|
||||
};
|
||||
$ledger = static fn() => Db::name('desktop_login_session')->order('id', 'desc')->find();
|
||||
$root = null;
|
||||
try {
|
||||
if ($port) {
|
||||
$root = new PDO("mysql:host=127.0.0.1;port=$port;charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$root->exec("CREATE DATABASE `$temporaryDb` CHARACTER SET utf8mb4");
|
||||
$root->exec("USE `$temporaryDb`");
|
||||
$root->exec('CREATE TABLE zyt_admin_session (id INT PRIMARY KEY AUTO_INCREMENT, admin_id INT NOT NULL, terminal INT NOT NULL,
|
||||
token VARCHAR(32) UNIQUE, expire_time INT NOT NULL, update_time INT, UNIQUE KEY old_install_index(admin_id,terminal)) ENGINE=InnoDB');
|
||||
$root->exec('CREATE TABLE zyt_dev_crontab (name VARCHAR(64),type INT,`system` INT,remark TEXT,command VARCHAR(64),
|
||||
params VARCHAR(64),status INT,expression VARCHAR(64),last_time INT,create_time INT,update_time INT,delete_time INT)');
|
||||
$root->exec("INSERT INTO zyt_admin_session (admin_id,terminal,token,expire_time) VALUES (77,1,'legacy',123)");
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_24_desktop_login_session.sql');
|
||||
for ($run = 0; $run < 2; $run++) {
|
||||
$migration = $root->query($sql);
|
||||
while ($migration->nextRowset()) {
|
||||
// 消费可重复迁移中的所有 SELECT 与 DDL 结果。
|
||||
}
|
||||
$migration->closeCursor();
|
||||
}
|
||||
wsExpect((int) Db::name('dev_crontab')->where('command', 'desktop-session:settle')->count() === 1, 'one scheduled sweep');
|
||||
wsExpect((int) Db::name('admin_session')->where('token', 'legacy')->value('workstation_slot') === 0, 'old tokens retain ordinary slot');
|
||||
$duplicateRejected = false;
|
||||
try { $root->exec("INSERT INTO zyt_admin_session (admin_id,terminal,token,expire_time) VALUES (77,1,'other',123)"); }
|
||||
catch (PDOException $e) { $duplicateRejected = $e->getCode() === '23000'; }
|
||||
wsExpect($duplicateRejected, 'legacy terminals keep unique account-terminal constraint');
|
||||
} else {
|
||||
Db::execute('CREATE TABLE zyt_admin_session (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT, terminal INT, token TEXT UNIQUE,
|
||||
expire_time INT, update_time INT, workstation_slot INT NOT NULL DEFAULT 0, UNIQUE(admin_id, terminal, workstation_slot))');
|
||||
Db::execute("CREATE TABLE zyt_desktop_login_session (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT, account TEXT,
|
||||
name TEXT, login_ip TEXT, login_time INT, last_seen_time INT, expires_at INT, due_time INT, logout_time INT,
|
||||
duration_seconds INT DEFAULT 0, end_reason TEXT DEFAULT '')");
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INT PRIMARY KEY, account VARCHAR(60), name VARCHAR(60), root INT, disable INT,
|
||||
multipoint_login INT, delete_time INT, login_ip VARCHAR(45), login_time INT, update_time INT, avatar VARCHAR(100),
|
||||
is_paw INT, work_wechat_userid VARCHAR(100))');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
|
||||
Db::execute('CREATE TABLE zyt_system_role (id INT PRIMARY KEY, name VARCHAR(60), delete_time INT)');
|
||||
Db::name('admin')->insert(['id' => 7, 'account' => 'doctor.ws', 'name' => '甲医生', 'root' => 0,
|
||||
'disable' => 0, 'multipoint_login' => 1, 'is_paw' => 1, 'avatar' => '', 'work_wechat_userid' => '']);
|
||||
$start = (new DateTimeImmutable('2026-11-24 04:56:00+08:00'))->getTimestamp();
|
||||
$cutoff = $start + 240;
|
||||
WorkstationClock::$now = $start;
|
||||
wsExpect(DesktopSessionService::nextCutoff($cutoff - 1) === $cutoff
|
||||
&& DesktopSessionService::nextCutoff($cutoff) === $cutoff + 86400, 'exact Beijing cutoff independent of PHP timezone');
|
||||
$web = $login(Terminal::PC);
|
||||
wsExpect(!isset($web['desktop_expires_at']) && Db::name('desktop_login_session')->count() === 0, 'web login remains separate');
|
||||
wsExpect($invoke($web['token'])['code'] === -1, 'legacy desktop/web token cannot assert a workstation heartbeat');
|
||||
$first = $login();
|
||||
$firstId = $ledger()['id'];
|
||||
$second = $login();
|
||||
wsExpect($first['desktop_expires_at'] === $cutoff && $first['token'] !== $second['token'], 'parallel desktops get separate tokens');
|
||||
wsExpect($ledger()['account'] === 'doctor.ws' && $ledger()['name'] === '甲医生', 'identity snapshot persisted');
|
||||
wsExpect($invoke($second['token'], 'desktopHeartbeat', 'GET')['code'] === 0, 'heartbeat is POST only');
|
||||
WorkstationClock::$now += 62;
|
||||
wsExpect($invoke($first['token'])['data']['desktop_expires_at'] === $cutoff, 'heartbeat refreshes lease only');
|
||||
wsExpect($invoke($second['token'], 'logout')['code'] === 1 && $ledger()['end_reason'] === 'logout'
|
||||
&& (int) $ledger()['duration_seconds'] === 62, 'explicit logout settles only that instance to the second');
|
||||
wsExpect($invoke($second['token'])['code'] === -1 && !(new AdminTokenCache())->getAdminInfo($second['token']), 'stale cache cannot restore closed device');
|
||||
wsExpect((bool) (new AdminTokenCache())->getAdminInfo($web['token']), 'web token survives desktop logout');
|
||||
WorkstationClock::$now = $cutoff;
|
||||
wsExpect(!AdminTokenService::overtimeToken($first['token']) && $invoke($first['token'])['code'] === -1, 'no request or renewal at 05:00');
|
||||
WorkstationClock::$now += 3600;
|
||||
wsExpect(DesktopSessionService::settleDue() === 1 && DesktopSessionService::settleDue() === 0, 'delayed sweep settles once');
|
||||
$old = Db::name('desktop_login_session')->where('id', $firstId)->find();
|
||||
wsExpect((int) $old['logout_time'] === $cutoff && (int) $old['duration_seconds'] === 240 && $old['end_reason'] === 'daily_cutoff', 'durable daily cutoff even without requests');
|
||||
$idle = $login();
|
||||
WorkstationClock::$now += 52;
|
||||
$invoke($idle['token']);
|
||||
$lastSeen = WorkstationClock::$now;
|
||||
WorkstationClock::$now += 180;
|
||||
wsExpect($invoke($idle['token'])['code'] === -1 && DesktopSessionService::settleDue() === 1, 'expired heartbeat cannot revive a slot');
|
||||
wsExpect((int) $ledger()['logout_time'] === $lastSeen && (int) $ledger()['duration_seconds'] === 52
|
||||
&& $ledger()['end_reason'] === 'timeout', 'disconnected time excluded');
|
||||
Db::name('admin')->where('id', 7)->update(['multipoint_login' => 0]);
|
||||
$replaced = $login();
|
||||
$replacedId = $ledger()['id'];
|
||||
WorkstationClock::$now += 11;
|
||||
$replacement = $login();
|
||||
$old = Db::name('desktop_login_session')->where('id', $replacedId)->find();
|
||||
wsExpect($old['end_reason'] === 'replaced' && (int) $old['duration_seconds'] === 11, 'single-point relog closes old record');
|
||||
wsExpect($invoke($replaced['token'], 'logout')['code'] === -1 && $invoke($replacement['token'])['code'] === 1,
|
||||
'late logout cannot affect replacement');
|
||||
AdminTokenService::revokeNativeSessions(7);
|
||||
wsExpect($ledger()['end_reason'] === 'revoked' && $invoke($replacement['token'])['code'] === -1, 'account credential revocation settles the ledger');
|
||||
echo 'WorkstationSessionTest ' . ($port ? 'MySQL' : 'SQLite') . ': ' . $GLOBALS['wsChecks'] . " checks passed\n";
|
||||
} finally {
|
||||
if ($root) { $root->exec("DROP DATABASE IF EXISTS `$temporaryDb`"); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user