igengx
This commit is contained in:
@@ -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 : ''];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user