Files
zyt/server/app/common/service/esign/DoctorEsignIdentityService.php
T
Your NameandClaude Opus 5 (1M context) dfe5768cd2 「已开处方」新增作废、医生电子签署身份两个按钮权限,按角色勾选
- 作废(tcm.prescription/void):未勾选的角色看不到按钮、接口也拒绝;开方/删除/审核权限不再隐含作废。
  勾选后仍只能作废本人开具的处方,具备审核角色的可作废数据范围内他人的处方;审核驳回作废不受影响
- 医生电子签署身份(tcm.prescription/esignDoctor):医生角色未勾选时,顶部下拉入口与签署面板「签署身份与证书」隐藏,
  服务端认证、快捷签授权一并拒绝(即不能签署处方);药师审核签署身份不受影响。桌面端入口同步按此权限判断
- 迁移 2026_11_27_prescription_void_esign_doctor_menu.sql:挂在「已开处方」下,默认不授予任何角色
- 重新构建管理后台
- 记录诊单 IM 聊天补拉改为独立系统 cron 的部署说明(原串行调度会被其阻塞数小时)

Co-Authored-By: Claude Opus 5 (1M context) <[EMAIL]>
2026-11-27 15:45:58 +08:00

741 lines
36 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use app\adminapi\logic\auth\AuthLogic;
use DateTimeImmutable;
use DateTimeZone;
use DomainException;
use think\facade\Config;
use think\facade\Db;
final class DoctorEsignIdentityService
{
/** 「医生电子签署身份」按钮权限:医生角色须在角色权限中勾选后才能认证签署身份并签署处方。 */
public const DOCTOR_IDENTITY_PERMISSION = 'tcm.prescription/esignDoctor';
private const DOCTOR_ROLE_ID = 1;
private const FLOW_LIFETIME = 30 * 86400;
private const ACCOUNT_BINDING_PROOF_LIFETIME = 30 * 60;
private const QUICK_LIFETIME = 86400;
private const IDENTITY_FLOW_TABLE = 'doctor_esign_identity';
private const QUICK_FLOW_TABLE = 'doctor_esign_quicksign';
private const STATE_CHANGED = '医师认证状态已变化,请重新查询';
public static function enabled(): bool
{
return PrescriptionEsignService::enabled()
&& (filter_var(Config::get('esign.doctor_sms_enabled', false), FILTER_VALIDATE_BOOLEAN) || self::quickEnabled());
}
public static function quickEnabled(): bool
{
$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
{
if (!self::enabled()) {
return ['enabled' => false] + self::state('unbound', '医师电子签署认证尚未启用');
}
$scope = self::scope($actor);
$snapshot = self::snapshot($scope);
if (self::hasLease($snapshot['flow'])) {
return self::processing();
}
$client = new EsignClient();
if (self::hasCurrentFlow($snapshot)) {
[$status, $person] = self::identityResult($client, $snapshot);
if ($pending = self::pendingState($snapshot, $status, ($person['idNo'] ?? null) === null)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
}
}
$quick = self::quickEnabled() ? self::snapshot($scope, false, self::QUICK_FLOW_TABLE) : null;
if ($quick !== null && self::hasLease($quick['flow'])) {
return self::processing(true);
}
if ($quick !== null && self::hasPendingQuickFlow($quick)) {
[$quickStatus] = self::identityResult($client, $quick);
if ($pending = self::pendingState($quick, $quickStatus, false)) {
self::assertUnchanged($scope, $quick);
return $pending;
}
}
$state = self::readiness(
$client,
$snapshot,
allowCertificateRecovery: true,
requireMobile: $quick === null,
reportUnconfirmedCertificate: true
)['state'];
if (isset($status) && $state['status'] !== 'ready') {
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
}
if ($quick !== null && $state['status'] === 'ready') {
$state = self::withQuickValidity($state, self::quickValidity($client, $quick));
if (($quickStatus ?? '') === 'FAIL') {
$state['message'] = '快捷签认证未通过,请重新发起授权';
}
}
if ($quick !== null) {
self::assertUnchanged($scope, $quick);
}
self::assertUnchanged($scope, $snapshot);
return $state + self::reviewerNameEntry($snapshot);
}
public static function start(int $actor, string $mobile, ?string $signerName = null): array
{
$scope = self::scope($actor);
$mobile = trim($mobile);
if (self::quickEnabled() && $mobile === '' && $signerName === null) {
return self::startQuick($scope);
}
if (!self::validMobile($mobile)) {
throw new DomainException('请输入有效的大陆手机号');
}
$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();
$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);
// 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'];
if ($state['status'] === 'ready') {
self::assertUnchanged($scope, $snapshot);
return self::quickEnabled() ? self::status($actor) : $state;
}
$token = self::claim($scope, $snapshot);
try {
$accountId = $snapshot['account']['account_id'] ?? null;
$flow = $client->startDoctorIdentity($name, 'doctor-enrollment-' . $token, $mobile, $accountId);
self::finish($scope, $snapshot, $token, [
'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']]
+ self::reviewerNameEntry($snapshot);
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
}
public static function complete(int $actor, string $identityNumber = ''): array
{
$scope = self::scope($actor);
$snapshot = self::snapshot($scope);
if (self::hasLease($snapshot['flow'])) {
return self::processing();
}
if (!self::hasCurrentFlow($snapshot)) {
if (self::quickEnabled()) {
return self::completeQuick($scope);
}
return self::status($actor);
}
$token = self::claim($scope, $snapshot);
try {
$client = new EsignClient();
[$status, $person] = self::identityResult($client, $snapshot);
if ($status === 'FAIL' || $status === 'EXPIRED') {
self::finish($scope, $snapshot, $token, null);
$state = self::status($actor);
if ($state['status'] !== 'ready') {
$state['message'] = $status === 'FAIL' ? '认证未通过,请重新发起认证' : '认证已过期,请重新发起认证';
}
return $state;
}
if ($status !== 'SUCCESS') {
self::finish($scope, $snapshot, $token, []);
return self::pendingState($snapshot, $status, false);
}
if ($person && self::validMobile($person['mobile'])
&& !hash_equals($snapshot['flow']['mobile_hash'], self::mobileHash($scope, $person['mobile']))) {
self::finish($scope, $snapshot, $token, null);
throw new DomainException('认证手机号与本次发起的手机号不一致,请重新发起认证');
}
$newAccountId = null;
if ($snapshot['account']) {
$document = self::accountDocument($client, $snapshot);
if ($person && $person['idNo'] !== null && !hash_equals($document, $person['idNo'])) {
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
}
} else {
$document = $person['idNo'] ?? null;
if ($document === null) {
$document = strtoupper(trim($identityNumber));
if (!PrescriptionEsignService::validMainlandIdentityNumber($document)) {
self::finish($scope, $snapshot, $token, []);
$state = self::pendingState($snapshot, 'SUCCESS', true);
if ($document !== '') {
$state['message'] = '请输入本次认证使用的有效大陆身份证号码';
}
return $state;
}
}
// eSign matches the document and name against the authenticated identity before issuing the account.
$newAccountId = $client->createPerson($snapshot['name'], $document, $snapshot['flow']['flow_id']);
}
unset($identityNumber, $person, $document);
self::finish($scope, $snapshot, $token, null, $newAccountId);
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
return self::status($actor);
}
/** Returns the current doctor-scoped proof for the provider call only. */
public static function quickAuthorization(int $actor, string $signerName, string $accountId): string
{
if (!self::quickEnabled()) {
throw new DomainException('快捷签设置已变化,请重新查询处方');
}
$scope = self::scope($actor);
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
if (!$snapshot['account']) {
throw new DoctorEsignIdentityRequired('请先在医师电子签署设置中完成实名认证');
}
if ($snapshot['name'] !== $signerName || $snapshot['account']['doctor_name'] !== $signerName
|| $snapshot['account']['account_id'] !== $accountId) {
throw new DomainException('处方签署账号已变化,请重试');
}
$client = new EsignClient();
[$certStart, $certEnd] = self::certificatePeriod($client, $accountId);
if (!$certStart || $certStart > time() || $certEnd <= time()) {
throw new DoctorEsignIdentityRequired('医师签署证书需要续期,请在账号菜单中处理');
}
$validity = self::quickValidity($client, $snapshot);
self::assertUnchanged($scope, $snapshot);
if ($certEnd <= time()) {
throw new DoctorEsignIdentityRequired('医师签署证书需要续期,请在账号菜单中处理');
}
if ($validity['state'] !== 'valid') {
throw new DoctorEsignAuthorizationRequired($validity['state']);
}
if ($validity['expires_at'] <= time()) {
throw new DoctorEsignAuthorizationRequired('expired');
}
return $snapshot['flow']['flow_id'];
}
private static function startQuick(array $scope): array
{
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
if (self::hasLease($snapshot['flow'])) {
return self::processing(true);
}
$client = new EsignClient();
if (self::hasPendingQuickFlow($snapshot)) {
[$status] = self::identityResult($client, $snapshot);
if ($pending = self::pendingState($snapshot, $status, false)) {
self::assertUnchanged($scope, $snapshot);
return $pending;
}
}
$ready = self::readiness($client, $snapshot, true, false);
$state = $ready['state'];
if ($state['status'] !== 'ready') {
self::assertUnchanged($scope, $snapshot);
return $state;
}
$state = self::withQuickValidity($state, self::quickValidity($client, $snapshot));
if ($state['quicksign_expires_at'] > time()) {
self::assertUnchanged($scope, $snapshot);
return $state;
}
$token = self::claim($scope, $snapshot);
try {
$accountId = $snapshot['account']['account_id'];
$flow = $client->startDoctorQuickAuthorization($snapshot['name'], $ready['idNo'], 'doctor-quicksign-' . $token, $accountId);
self::finish($scope, $snapshot, $token, [
'doctor_name' => $snapshot['name'], 'account_id' => $accountId, 'flow_id' => $flow['flow_id'],
'auth_url' => $flow['auth_url'], 'flow_started_at' => time(), 'expires_at' => 0,
]);
return self::state('authenticating', '请完成快捷签人脸认证', 0, true) + ['auth_url' => $flow['auth_url']];
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
}
private static function completeQuick(array $scope): array
{
$snapshot = self::snapshot($scope, false, self::QUICK_FLOW_TABLE);
if (self::hasLease($snapshot['flow'])) {
return self::processing(true);
}
if (!self::hasPendingQuickFlow($snapshot)) {
return self::status($scope['doctor_id']);
}
$token = self::claim($scope, $snapshot);
try {
$client = new EsignClient();
[$status, $person] = self::identityResult($client, $snapshot);
if ($status === 'INIT' || $status === 'ING') {
self::finish($scope, $snapshot, $token, []);
return self::pendingState($snapshot, $status, false);
}
$expires = 0;
if ($status === 'SUCCESS') {
$document = self::accountDocument($client, $snapshot);
if ($person && $person['idNo'] !== null && !hash_equals($document, $person['idNo'])) {
self::finish($scope, $snapshot, $token, null);
throw new DomainException('认证证件与签署账号不一致,请联系管理员核实');
}
// 授权有效期以 e签宝返回为准(快捷签授权通常为 30 天)
$expires = intdiv($client->willingnessValidity($snapshot['flow']['flow_id'])['expires_at'], 1000);
}
if ($expires <= time()) {
self::finish($scope, $snapshot, $token, null);
$state = self::status($scope['doctor_id']);
$state['message'] = $status === 'FAIL' ? '快捷签认证未通过,请重新发起授权' : '快捷签授权已失效,请重新发起授权';
return $state;
}
self::finish($scope, $snapshot, $token, ['auth_url' => null, 'expires_at' => $expires]);
} catch (\Throwable $error) {
self::release($scope, $snapshot, $token);
throw $error;
}
return self::status($scope['doctor_id']);
}
/** @return array{state:string,expires_at:int,remaining_times:int} Expiration is in Unix seconds. */
private static function quickValidity(EsignClient $client, array $snapshot): array
{
$flow = $snapshot['flow'];
$localExpiry = (int) ($flow['expires_at'] ?? 0);
$missing = ['state' => 'missing', 'expires_at' => 0, 'remaining_times' => 0];
if (!$localExpiry || empty($flow['flow_id']) || self::hasLease($flow)) {
return $missing;
}
if (!$snapshot['account'] || $snapshot['account']['doctor_name'] !== $snapshot['name']
|| $flow['doctor_name'] !== $snapshot['name'] || $flow['account_id'] !== $snapshot['account']['account_id']) {
return ['state' => 'invalid'] + $missing;
}
if ($localExpiry <= time()) {
return ['state' => 'expired'] + $missing;
}
$validity = $client->willingnessValidity($flow['flow_id']);
if ($validity['state'] !== 'valid') {
return $validity;
}
$validity['expires_at'] = min($localExpiry, intdiv($validity['expires_at'], 1000));
return $validity['expires_at'] > time() ? $validity : ['state' => 'expired'] + $missing;
}
private static function withQuickValidity(array $state, array $validity): array
{
$state['quicksign_expires_at'] = $validity['expires_at'];
$state['quicksign_remaining_times'] = $validity['remaining_times'];
$state['quicksign_unavailable_reason'] = $validity['state'] === 'valid' ? '' : $validity['state'];
return $state;
}
/** @return array{name:string,idNo:string,mobile:string} For the provider call only. */
public static function willingnessRecipient(int $actor, string $signerName, string $accountId): array
{
$scope = self::scope($actor);
$snapshot = self::snapshot($scope);
if (!$snapshot['account']) {
throw new DoctorEsignIdentityRequired('请先在医师电子签署设置中完成实名认证');
}
if ($snapshot['name'] !== $signerName || $snapshot['account']['account_id'] !== $accountId) {
throw new DomainException('处方签署账号已变化,请重试');
}
$ready = self::readiness(new EsignClient(), $snapshot);
$current = self::snapshot($scope);
if ($current['name'] !== $snapshot['name'] || $current['account'] !== $snapshot['account']) {
throw new DomainException(self::STATE_CHANGED);
}
if ($ready['state']['status'] !== 'ready') {
throw new DoctorEsignIdentityRequired($ready['state']['message']);
}
if ($ready['state']['cert_expires_at'] <= time()) {
throw new DoctorEsignIdentityRequired('医师签署证书已过期,请重新认证');
}
return ['name' => $signerName, 'idNo' => $ready['idNo'], 'mobile' => $ready['mobile']];
}
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 | 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;
}
$message = $allowRenewal ? '暂时无法确认签署证书有效期,可重新查询或发起续期' : '暂时无法确认签署证书有效期,请重新查询';
return ['state' => self::state('renewal_required', $message) + ['certificate_state' => 'unconfirmed']];
}
$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']];
}
if ($requireMobile && !self::validMobile($mobile)) {
return ['state' => self::state('needs_mobile', '请完成实名手机号认证', $end) + ['certificate_state' => 'valid']];
}
return [
'state' => self::state('ready', '医师电子签署已就绪', $end) + ['certificate_state' => 'valid'],
'idNo' => $idNo,
'mobile' => $mobile,
];
}
private static function accountDocument(EsignClient $client, array $snapshot): string
{
$account = $snapshot['account'];
if ($account['doctor_name'] !== $snapshot['name']) {
throw new DomainException('签署账号实名信息已变化,请联系管理员核实');
}
$details = $client->signingAccount($account['account_id']);
$idNo = $details['idNo'] ?? '';
if (($details['accountId'] ?? '') !== $account['account_id'] || ($details['name'] ?? '') !== $snapshot['name']
|| ($details['accountType'] ?? '') !== 'PERSON' || ($details['idNoType'] ?? '') !== 'MAINLAND'
|| !is_string($idNo) || !preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9Xx])$/D', $idNo)) {
throw new DomainException('签署账号实名信息不一致,请联系管理员核实');
}
return strtoupper($idNo);
}
/** @return array{int,int} */
private static function certificatePeriod(EsignClient $client, string $accountId): array
{
$dates = $client->certificateValidity($accountId);
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(mixed $value): int
{
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);
if (!$time || $time->format('Y-m-d H:i:s') !== $value) {
throw new DomainException('暂时无法确认医师签署证书有效期,请稍后重试');
}
return $time->getTimestamp();
}
private static function identityResult(EsignClient $client, array $snapshot): array
{
$flow = $snapshot['flow'];
$detail = $client->identityDetail($flow['flow_id']);
$status = $detail['status'] ?? '';
if (($detail['flowId'] ?? '') !== $flow['flow_id']
|| (isset($detail['appId']) && (string) $detail['appId'] !== $flow['app_id'])
|| !in_array($status, ['INIT', 'ING', 'SUCCESS', 'FAIL'], true)) {
throw new DomainException('暂时无法确认本次医师认证,请稍后重试');
}
if ($status !== 'SUCCESS') {
return [$status, null, 0];
}
if (($detail['objectType'] ?? '') !== 'INDIVIDUAL') {
throw new DomainException('认证对象与医师个人签署不一致');
}
$completedAt = isset($detail['endTime']) && is_int($detail['endTime']) && $detail['endTime'] > 0
? intdiv($detail['endTime'], 1000) : (int) $flow['flow_started_at'];
if (!$snapshot['account'] && $completedAt + self::ACCOUNT_BINDING_PROOF_LIFETIME <= time()) {
return ['EXPIRED', null, $completedAt];
}
if (array_key_exists('indivInfo', $detail) && $detail['indivInfo'] === null) {
return [$status, null, $completedAt];
}
$person = $detail['indivInfo'] ?? null;
if (!is_array($person) || ($person['name'] ?? '') !== $snapshot['name']
|| ($person['certType'] ?? '') !== 'INDIVIDUAL_CH_IDCARD' || !is_string($person['certNo'] ?? null)) {
throw new DomainException('认证实名信息与医师账号不一致或证件类型不支持');
}
$idNo = strtoupper($person['certNo']);
if (str_contains($idNo, '*') && preg_match('/^(?:[0-9*]{15}|[0-9*]{17}[0-9X*])$/D', $idNo)) {
$idNo = null; // addPerson validates any supplemental number against the provider flow.
} elseif (!preg_match('/^(?:[0-9]{15}|[0-9]{17}[0-9X])$/D', $idNo)) {
throw new DomainException('认证证件号码格式无效,请重新认证');
}
$mobile = is_string($person['authMobileNo'] ?? null) ? $person['authMobileNo'] : null;
return [$status, ['idNo' => $idNo, 'mobile' => $mobile], $completedAt];
}
private static function pendingState(array $snapshot, string $status, bool $documentMissing): ?array
{
$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']]
+ self::reviewerNameEntry($snapshot);
}
if ($status === 'SUCCESS') {
$needed = !$snapshot['account'] && $documentMissing;
$message = match (true) {
$quick => '人脸认证已通过,请确认快捷签授权',
$needed => '认证已通过,请补充本次认证使用的身份证号码以绑定签署账号',
default => '认证已通过,请确认完成医师电子签署认证',
};
return self::state('binding_required', $message, 0, $quick) + ['identity_details_required' => $needed];
}
return null;
}
/** Returns doctor_id => signer name for accounts bound under the current eSign application. */
public static function signerNames(array $doctorIds): array
{
$doctorIds = array_values(array_filter(array_map('intval', $doctorIds)));
if ($doctorIds === []) {
return [];
}
return Db::name('doctor_esign_account')->where(self::configuredScope())
->whereIn('doctor_id', $doctorIds)->column('doctor_name', 'doctor_id');
}
/**
* 管理员解除某后台账号的签署身份(当前 e签宝 应用),同一实名才能改绑到另一个后台账号。
* 已签处方保留原签署证据,不受影响。
*/
public static function unbind(int $doctorId): void
{
if ($doctorId <= 0) {
throw new DomainException('管理员ID无效');
}
$scope = ['doctor_id' => $doctorId] + self::configuredScope();
Db::transaction(static function () use ($scope): void {
$account = Db::name('doctor_esign_account')->where($scope)->lock(true)->find();
foreach ([self::IDENTITY_FLOW_TABLE, self::QUICK_FLOW_TABLE] as $table) {
if (self::hasLease(Db::name($table)->where($scope)->lock(true)->find())) {
throw new DomainException('该账号的签署身份正在处理中,请稍后再试');
}
}
if (!$account) {
throw new DomainException('该账号未绑定签署身份');
}
Db::name('doctor_esign_account')->where($scope)->delete();
// 认证与快捷签授权都挂在旧签署账号上,一并清除,避免解绑后继续沿用。
Db::name(self::IDENTITY_FLOW_TABLE)->where($scope)->delete();
Db::name(self::QUICK_FLOW_TABLE)->where($scope)->delete();
});
}
private static function configuredScope(): array
{
return ['environment' => (string) Config::get('esign.environment', 'sandbox'),
'app_id' => (string) Config::get('esign.app_id', '')];
}
private static function scope(int $actor): array
{
if (!self::enabled()) {
throw new DomainException('医师电子签署认证尚未启用');
}
return ['doctor_id' => $actor] + self::configuredScope();
}
private static function snapshot(array $scope, bool $lock = false, string $flowTable = self::IDENTITY_FLOW_TABLE): array
{
$actor = $scope['doctor_id'];
$name = trim((string) Db::name('admin')->where('id', $actor)->where('disable', 0)
->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');
$reviewer = !$doctor && PrescriptionReviewEsignService::enabled()
&& PrescriptionReviewEsignService::canEnrollReviewer($actor);
if ($name === '' || (!$doctor && !$reviewer)) {
throw new DomainException('仅当前医师本人可使用医师电子签署认证');
}
if ($doctor && !self::hasDoctorIdentityGrant($actor)) {
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' => $name, 'account' => $account, 'flow' => $flow, 'flow_table' => $flowTable,
'reviewer' => $reviewer,
];
}
private static function hasDoctorIdentityGrant(int $actor): bool
{
if ((int) Db::name('admin')->where('id', $actor)->value('root') === 1) {
return true;
}
return in_array(strtolower(self::DOCTOR_IDENTITY_PERMISSION),
array_map('strtolower', AuthLogic::getAuthByAdminId($actor)), true);
}
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'];
return !empty($flow['flow_id']) && $flow['doctor_name'] === $snapshot['name']
&& $flow['account_id'] === ($snapshot['account']['account_id'] ?? '')
&& (int) $flow['flow_started_at'] + self::FLOW_LIFETIME > time();
}
private static function hasLease(?array $flow): bool
{
return !empty($flow['operation_token']) && (int) $flow['operation_expires_at'] > time();
}
private static function hasPendingQuickFlow(array $snapshot): bool
{
return $snapshot['account'] && self::hasCurrentFlow($snapshot)
&& (int) $snapshot['flow']['expires_at'] === 0
&& (int) $snapshot['flow']['flow_started_at'] + self::QUICK_LIFETIME > time();
}
private static function assertUnchanged(array $scope, array $snapshot, bool $lock = false): void
{
if (self::snapshot($scope, $lock, $snapshot['flow_table']) !== $snapshot) {
throw new DomainException(self::STATE_CHANGED);
}
}
private static function claim(array $scope, array $snapshot): string
{
$token = bin2hex(random_bytes(16));
// Quick-sign completion may make three sequential provider requests before committing.
$timeout = max(1, min(300, (int) Config::get('esign.timeout', 60)));
$claim = ['operation_token' => $token, 'operation_expires_at' => time() + 3 * $timeout + 30];
Db::transaction(static function () use ($scope, $snapshot, $claim): void {
self::assertUnchanged($scope, $snapshot, true);
$query = Db::name($snapshot['flow_table']);
if ($snapshot['flow']) {
$query->where($scope)->update($claim);
} else {
$query->insert($scope + $claim);
}
});
return $token;
}
private static function finish(array $scope, array $snapshot, string $token, ?array $nextFlow, ?string $newAccountId = null): void
{
Db::transaction(static function () use ($scope, $snapshot, $token, $nextFlow, $newAccountId): void {
$current = self::snapshot($scope, true, $snapshot['flow_table']);
if ($current['name'] !== $snapshot['name'] || $current['account'] !== $snapshot['account']
|| !self::hasLease($current['flow']) || $current['flow']['operation_token'] !== $token) {
throw new DomainException(self::STATE_CHANGED);
}
if ($newAccountId !== null) {
$owner = Db::name('doctor_esign_account')->where('environment', $scope['environment'])
->where('app_id', $scope['app_id'])->where('account_id', $newAccountId)->lock(true)->value('doctor_id');
if ($owner !== null) {
// e签宝 对同一实名只签发一个签署账号;指明占用方,便于管理员在管理员列表中解除后重试。
// 用名称+ID 而非登录账号:账号常为手机号,桌面端会屏蔽含长数字的提示。
$holder = (string) Db::name('admin')->where('id', $owner)->value('name');
$label = ($holder !== '' ? $holder : '已删除账号') . '(ID ' . (int) $owner . ')';
throw new DomainException(sprintf(
'该实名的签署账号已绑定后台账号「%s」,请管理员在「管理员」列表解除其签署身份后再确认绑定(刷脸结果 30 分钟内有效)',
$label
));
}
Db::name('doctor_esign_account')->insert($scope + [
'account_id' => $newAccountId, 'doctor_name' => $snapshot['name'], 'create_time' => time(),
]);
}
$query = Db::name($snapshot['flow_table'])->where($scope)->where('operation_token', $token);
if ($nextFlow === null) {
$query->delete();
} else {
$query->update($nextFlow + ['operation_token' => '', 'operation_expires_at' => 0]);
}
});
}
private static function release(array $scope, array $snapshot, string $token): void
{
Db::name($snapshot['flow_table'])->where($scope)->where('operation_token', $token)
->update(['operation_token' => '', 'operation_expires_at' => 0]);
}
private static function mobileHash(array $scope, string $mobile): string
{
$secret = (string) Config::get('esign.app_secret', '');
if ($secret === '') {
throw new DomainException('医师认证配置不完整,请联系管理员');
}
return hash_hmac('sha256', json_encode(['doctor-enrollment', $scope, $mobile], JSON_THROW_ON_ERROR), $secret);
}
private static function validMobile(?string $mobile): bool
{
return $mobile !== null && preg_match('/^1[3-9][0-9]{9}$/D', $mobile) === 1;
}
private static function processing(bool $quick = false): array
{
return self::state('authenticating', '医师认证请求处理中,请稍后查询', 0, $quick);
}
private static function state(string $status, string $message, int $certExpiresAt = 0, bool $quickAuthorizing = false): array
{
return [
'enabled' => true, 'status' => $status, 'cert_expires_at' => $certExpiresAt, 'message' => $message,
'quicksign_enabled' => self::quickEnabled(), 'quicksign_expires_at' => 0, 'quicksign_authorizing' => $quickAuthorizing,
];
}
}