更新
This commit is contained in:
@@ -2,11 +2,23 @@
|
||||
# SDK 3.1.13+ is required for queryWillingnessValidity. Keep this service private.
|
||||
# Initialize the SDK once per JVM startup. Restart it before changing app or environment.
|
||||
[ESIGN]
|
||||
# Enable after deploying the SMS and doctor identity enrollment migrations.
|
||||
DOCTOR_SMS_ENABLED = false
|
||||
# Apply the doctor identity and quick-sign migrations. The eSign application must allow reusable authorization.
|
||||
DOCTOR_QUICKSIGN_ENABLED = false
|
||||
# Apply the prescription review signing migration before enabling.
|
||||
REVIEW_ENABLED = false
|
||||
ENABLED = false
|
||||
ENVIRONMENT = sandbox
|
||||
APP_ID =
|
||||
APP_SECRET =
|
||||
SDK_URL = http://127.0.0.1:8091/paas-sdk-service
|
||||
TIMEOUT = 60
|
||||
# Optional trusted CA bundle for eSign HTTPS calls when PHP has no CA bundle configured.
|
||||
# CA_FILE = /etc/ssl/certs/ca-certificates.crt
|
||||
# Sandbox only. A JSON object mapping an authorized doctor account ID to their verified legal name.
|
||||
# SANDBOX_SIGNER_NAMES = {"123":"测试实名"}
|
||||
# Match the SDK JVM timezone used for the unzoned signDate field.
|
||||
# SDK_TIMEZONE = Asia/Shanghai
|
||||
# Optional private persistent directory; default is server/storage/esign.
|
||||
# STORAGE_PATH = /srv/zyt-private/esign
|
||||
|
||||
@@ -7,7 +7,9 @@ namespace app\adminapi\controller\tcm;
|
||||
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\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionReviewEsignService;
|
||||
|
||||
/**
|
||||
* 中医处方单控制器
|
||||
@@ -171,12 +173,14 @@ class PrescriptionController extends BaseAdminController
|
||||
*/
|
||||
public function void()
|
||||
{
|
||||
if (!$this->request->isPost()) {
|
||||
return $this->fail('请使用 POST 作废处方');
|
||||
}
|
||||
$id = (int)($this->request->post('id') ?? 0);
|
||||
if (!$id) {
|
||||
if ($id <= 0) {
|
||||
return $this->fail('处方ID不能为空');
|
||||
}
|
||||
$admin = $this->adminInfo;
|
||||
$ok = PrescriptionLogic::void($id, (int)$this->adminId, $admin['name'] ?? '');
|
||||
$ok = PrescriptionLogic::void($id, $this->adminId, $this->adminInfo);
|
||||
if (!$ok) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
@@ -193,6 +197,11 @@ class PrescriptionController extends BaseAdminController
|
||||
return $this->esignOperation('status', false);
|
||||
}
|
||||
|
||||
public function esignIdentityStatus()
|
||||
{
|
||||
return $this->esignOperation('identityStatus', false);
|
||||
}
|
||||
|
||||
public function esignStart()
|
||||
{
|
||||
return $this->esignOperation('start', true);
|
||||
@@ -203,11 +212,102 @@ class PrescriptionController extends BaseAdminController
|
||||
return $this->esignOperation('complete', true);
|
||||
}
|
||||
|
||||
/** @notes 验证处方签署短信 */
|
||||
public function esignVerifyWillingness()
|
||||
{
|
||||
return $this->esignOperation('verifyWillingness', true);
|
||||
}
|
||||
|
||||
public function esignDownload()
|
||||
{
|
||||
return $this->esignOperation('download', false);
|
||||
}
|
||||
|
||||
public function esignReviewStatus()
|
||||
{
|
||||
return $this->esignReviewOperation(false);
|
||||
}
|
||||
|
||||
public function esignReviewConfirm()
|
||||
{
|
||||
return $this->esignReviewOperation(true);
|
||||
}
|
||||
|
||||
private function esignReviewOperation(bool $confirm)
|
||||
{
|
||||
if ($confirm ? !$this->request->isPost() : !$this->request->isGet()) {
|
||||
return $this->fail($confirm ? '请使用 POST 请求' : '请使用 GET 请求');
|
||||
}
|
||||
$params = $confirm ? $this->request->post() : $this->request->get();
|
||||
$id = (int) ($params['id'] ?? 0);
|
||||
$orderId = (int) ($params['order_id'] ?? 0);
|
||||
$actor = (int) $this->adminId;
|
||||
$verifyOnly = $params['verify_only'] ?? false;
|
||||
if ($id <= 0 || $orderId < 0 || !is_bool($verifyOnly)) {
|
||||
return $this->fail('审核签署参数无效');
|
||||
}
|
||||
if ($confirm && (int) ($params['actor_id'] ?? 0) !== $actor) {
|
||||
return $this->fail('登录账号已切换,请刷新并由当前审核人确认');
|
||||
}
|
||||
try {
|
||||
if ($confirm) {
|
||||
ignore_user_abort(true);
|
||||
set_time_limit(360);
|
||||
}
|
||||
$data = $confirm
|
||||
? PrescriptionReviewEsignService::confirm($id, $orderId, $actor, $this->adminInfo, $verifyOnly)
|
||||
: PrescriptionReviewEsignService::status($id, $orderId, $actor, $this->adminInfo);
|
||||
return $this->data($data)->header(['Cache-Control' => 'private, no-store']);
|
||||
} catch (\app\common\service\esign\DoctorEsignAuthorizationRequired) {
|
||||
return $this->fail('审核人快捷签授权需要开通或续期,请在「审核签署身份」中处理');
|
||||
} catch (\Throwable $error) {
|
||||
return $this->fail($error instanceof \DomainException || $error instanceof \app\common\service\esign\EsignProviderException
|
||||
? $error->getMessage() : '审核签署暂不可用,请刷新状态后重试');
|
||||
}
|
||||
}
|
||||
|
||||
/** @notes 查询医师电子签署认证 */
|
||||
public function esignDoctorStatus()
|
||||
{
|
||||
return $this->esignDoctorOperation('status', false);
|
||||
}
|
||||
|
||||
/** @notes 发起医师电子签署认证 */
|
||||
public function esignDoctorStart()
|
||||
{
|
||||
return $this->esignDoctorOperation('start', true, 'mobile');
|
||||
}
|
||||
|
||||
/** @notes 完成医师电子签署认证 */
|
||||
public function esignDoctorComplete()
|
||||
{
|
||||
return $this->esignDoctorOperation('complete', true, 'identity_number');
|
||||
}
|
||||
|
||||
private function esignDoctorOperation(string $operation, bool $post, string $field = '')
|
||||
{
|
||||
if ($post ? !$this->request->isPost() : !$this->request->isGet()) {
|
||||
return $this->fail($post ? '请使用 POST 请求' : '请使用 GET 请求');
|
||||
}
|
||||
try {
|
||||
if (!$post) {
|
||||
return $this->data(DoctorEsignIdentityService::status((int) $this->adminId))
|
||||
->header(['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
$input = $this->request->post($field, '');
|
||||
if (!is_string($input)) {
|
||||
return $this->fail($field === 'mobile' ? '手机号格式无效' : '身份证号码格式无效');
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
ignore_user_abort(true);
|
||||
}
|
||||
return $this->data(DoctorEsignIdentityService::{$operation}((int) $this->adminId, $input))
|
||||
->header(['Cache-Control' => 'private, no-store']);
|
||||
} catch (\Throwable $error) {
|
||||
return $this->fail($error instanceof \DomainException ? $error->getMessage() : '医师认证暂不可用,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
private function esignOperation(string $operation, bool $post)
|
||||
{
|
||||
if ($post && !$this->request->isPost()) {
|
||||
@@ -223,6 +323,35 @@ class PrescriptionController extends BaseAdminController
|
||||
set_time_limit(300);
|
||||
}
|
||||
try {
|
||||
$body = $post ? $this->request->post(false) : [];
|
||||
if ($operation === 'verifyWillingness') {
|
||||
$code = $this->request->post('auth_code', '');
|
||||
if (!is_string($code)) {
|
||||
return $this->fail('短信验证码格式无效');
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::verifyWillingness($id, (int) $this->adminId,
|
||||
$this->adminInfo, $code));
|
||||
}
|
||||
if ($operation === 'start') {
|
||||
$restartIdentity = array_key_exists('restart_identity', $body) ? $body['restart_identity'] : false;
|
||||
if (!is_bool($restartIdentity)) {
|
||||
return $this->fail('重新核身标记格式无效');
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::start($id, (int) $this->adminId,
|
||||
$this->adminInfo, $restartIdentity));
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
$verifyOnly = array_key_exists('verify_only', $body) ? $body['verify_only'] : false;
|
||||
if (!is_bool($verifyOnly)) {
|
||||
return $this->fail('验签标记格式无效');
|
||||
}
|
||||
$identityNumber = $this->request->post('identity_number', '');
|
||||
if (!is_string($identityNumber)) {
|
||||
return $this->fail('身份证号码格式无效');
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::complete($id, (int) $this->adminId,
|
||||
$this->adminInfo, $identityNumber, $verifyOnly));
|
||||
}
|
||||
return $this->data(PrescriptionEsignService::{$operation}($id, (int) $this->adminId, $this->adminInfo));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->fail($e instanceof \DomainException ? $e->getMessage() : '电子签署暂不可用,请联系管理员');
|
||||
|
||||
@@ -17,6 +17,7 @@ declare (strict_types=1);
|
||||
namespace app\adminapi\http\middleware;
|
||||
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\common\service\pharmacy\PharmacyUploadPermissionAlias;
|
||||
use app\common\service\qywx\QywxPromotionOperatorAccess;
|
||||
use app\common\{
|
||||
@@ -94,9 +95,18 @@ class AuthMiddleware
|
||||
$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']);
|
||||
$grants = in_array($action, ['esignstart', 'esigncomplete'], true) ? $writes : $reads;
|
||||
return in_array($action, ['esignstart', 'esigncomplete', 'esignstatus', 'esigndownload'], true)
|
||||
&& array_intersect($grants, $uris) !== []
|
||||
$audit = ['tcm.prescription/audit', 'cf.prescription/audit', 'tcm.prescriptionorder/auditprescription'];
|
||||
$writeActions = ['esignstart', 'esigncomplete', 'esignidentitystatus', 'esignverifywillingness'];
|
||||
$identityActions = ['esigndoctorstatus', 'esigndoctorstart', 'esigndoctorcomplete'];
|
||||
$grants = match (true) {
|
||||
in_array($action, $writeActions, true) => $writes,
|
||||
in_array($action, $identityActions, true) => array_merge($writes, $audit),
|
||||
$action === 'esignreviewconfirm' => $audit,
|
||||
default => $reads,
|
||||
};
|
||||
return in_array($action, array_merge($writeActions, $identityActions,
|
||||
['esignstatus', 'esigndownload', 'esignreviewstatus', 'esignreviewconfirm']), true)
|
||||
&& array_intersect($grants, $uris) !== []
|
||||
? $next($request) : JsonService::fail('权限不足,无法访问电子签署');
|
||||
}
|
||||
|
||||
@@ -264,17 +274,18 @@ class AuthMiddleware
|
||||
}
|
||||
|
||||
$prescriptionWriteAliases = [
|
||||
'tcm.prescription/add' => [
|
||||
'tcm.prescription/add', 'cf.prescription/add',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
],
|
||||
'tcm.prescription/add' => PrescriptionLogic::PRESCRIBE_PERMISSIONS,
|
||||
'tcm.prescription/edit' => [
|
||||
'tcm.prescription/edit', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
],
|
||||
'tcm.prescription/delete' => ['tcm.prescription/delete', 'cf.prescription/del'],
|
||||
'tcm.prescription/void' => ['tcm.prescription/void', 'cf.prescription/del', 'cf.prescription/audit'],
|
||||
'tcm.prescription/audit' => ['tcm.prescription/audit', 'cf.prescription/audit'],
|
||||
'tcm.prescription/void' => array_merge(
|
||||
PrescriptionLogic::PRESCRIBE_PERMISSIONS,
|
||||
PrescriptionLogic::VOID_MANAGE_PERMISSIONS,
|
||||
PrescriptionLogic::AUDIT_PERMISSIONS
|
||||
),
|
||||
'tcm.prescription/audit' => PrescriptionLogic::AUDIT_PERMISSIONS,
|
||||
];
|
||||
if (isset($prescriptionWriteAliases[$accessUri])
|
||||
&& count(array_intersect($prescriptionWriteAliases[$accessUri], $adminUris)) > 0) {
|
||||
|
||||
@@ -20,10 +20,11 @@ class OperationLog
|
||||
public function handle($response)
|
||||
{
|
||||
$request = request();
|
||||
$accessUri = strtolower($request->controller() . '/' . $request->action());
|
||||
|
||||
// Temporary visual observations and rejected upload parameters must never
|
||||
// enter the generic request/response audit log if this listener is enabled.
|
||||
if (strtolower($request->controller() . '/' . $request->action()) === 'tcm.diagnosis/aitonguescreenshot') {
|
||||
if ($accessUri === 'tcm.diagnosis/aitonguescreenshot') {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,6 +54,16 @@ class OperationLog
|
||||
|
||||
$params = $request->param();
|
||||
|
||||
// Signing requests can carry identity inputs, OTPs and private provider URLs.
|
||||
$esign = str_starts_with($accessUri, 'tcm.prescription/esign');
|
||||
if ($esign) {
|
||||
$recordId = in_array($accessUri, ['tcm.prescription/esignstart', 'tcm.prescription/esigncomplete',
|
||||
'tcm.prescription/esignverifywillingness', 'tcm.prescription/esignstatus',
|
||||
'tcm.prescription/esignidentitystatus', 'tcm.prescription/esigndownload'], true);
|
||||
$id = $request->isGet() ? $request->get('id', 0) : $request->post('id', 0);
|
||||
$params = $recordId ? ['id' => is_scalar($id) ? (int) $id : 0] : [];
|
||||
}
|
||||
|
||||
//过滤密码参数
|
||||
if (isset($params['password'])) {
|
||||
$params['password'] = "******";
|
||||
@@ -73,14 +84,29 @@ class OperationLog
|
||||
$systemLog->admin_name = $request->adminInfo['name'] ?? '';
|
||||
$systemLog->action = $notes;
|
||||
$systemLog->account = $request->adminInfo['account'] ?? '';
|
||||
$systemLog->url = $request->url(true);
|
||||
$systemLog->url = $esign ? strtok($request->url(true), '?') : $request->url(true);
|
||||
$systemLog->type = $request->isGet() ? 'GET' : 'POST';
|
||||
$systemLog->params = json_encode($params, true);
|
||||
$systemLog->ip = $request->ip();
|
||||
$systemLog->result = $this->shortenOperationLogResult((string) $response->getContent());
|
||||
$content = (string) $response->getContent();
|
||||
$systemLog->result = $esign ? $this->esignOperationLogResult($content) : $this->shortenOperationLogResult($content);
|
||||
return $systemLog->save();
|
||||
}
|
||||
|
||||
private function esignOperationLogResult(string $content): string
|
||||
{
|
||||
$decoded = json_decode($content, true);
|
||||
$result = [];
|
||||
if (is_int($decoded['code'] ?? null)) {
|
||||
$result['code'] = $decoded['code'];
|
||||
}
|
||||
$status = $decoded['data']['status'] ?? null;
|
||||
if (is_string($status) && preg_match('/^[a-z_]{1,32}$/D', $status)) {
|
||||
$result['status'] = $status;
|
||||
}
|
||||
return json_encode($result);
|
||||
}
|
||||
|
||||
/** MySQL TEXT 上限约 64KB,列表接口常含 base64 签名导致超长 */
|
||||
private function shortenOperationLogResult(string $content): string
|
||||
{
|
||||
@@ -100,6 +126,10 @@ class OperationLog
|
||||
private function stripLargeLogFields(array &$data): void
|
||||
{
|
||||
foreach ($data as $key => &$value) {
|
||||
if ($key === 'auth_url') {
|
||||
unset($data[$key]);
|
||||
continue;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
$this->stripLargeLogFields($value);
|
||||
continue;
|
||||
@@ -112,4 +142,4 @@ class OperationLog
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use app\adminapi\lists\BaseAdminDataLists;
|
||||
use app\common\lists\ListsSearchInterface;
|
||||
use app\common\lists\Traits\HasDataScopeFilter;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\model\tcm\Prescription;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
|
||||
@@ -256,6 +257,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
$rejectedRx = [];
|
||||
$bizRejectRemark = [];
|
||||
$hasBizOrderRx = [];
|
||||
$hasReleasedOrderRx = [];
|
||||
if ($rxIds !== []) {
|
||||
$bizRejectRows = PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->where('prescription_audit_status', 2)
|
||||
@@ -276,14 +278,18 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
}
|
||||
}
|
||||
|
||||
$orderRxIds = array_unique(array_map(
|
||||
'intval',
|
||||
PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->column('prescription_id')
|
||||
));
|
||||
$hasBizOrderRx = array_fill_keys($orderRxIds, true);
|
||||
$orders = PrescriptionOrder::whereIn('prescription_id', $rxIds)
|
||||
->whereNull('delete_time')
|
||||
->field(['prescription_id', 'fulfillment_status'])
|
||||
->select();
|
||||
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 {
|
||||
$hasBizOrderRx[$prescriptionId] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取医助姓名
|
||||
@@ -295,7 +301,13 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
}
|
||||
|
||||
// 处理字段格式
|
||||
$voidAccess = $lists === [] ? [] : PrescriptionLogic::getVoidAccess($this->adminId, $this->adminInfo);
|
||||
foreach ($lists as &$item) {
|
||||
$rid = (int) $item['id'];
|
||||
$item['can_void'] = empty($item['void_status']) && empty($hasBizOrderRx[$rid])
|
||||
&& PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess)
|
||||
&& (empty($hasReleasedOrderRx[$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['usage_time'] = $item['usage_time'] ?? '饭前';
|
||||
@@ -307,7 +319,6 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
$item['audit_status'] = (int) ($item['audit_status'] ?? 1);
|
||||
$item['void_status'] = (int) ($item['void_status'] ?? 0);
|
||||
$item['visible_role_ids'] = PrescriptionLogic::visibleRoleIdsToArray((string) ($item['visible_role_ids'] ?? ''));
|
||||
$rid = (int) ($item['id'] ?? 0);
|
||||
$item['business_prescription_audit_rejected'] = !empty($rejectedRx[$rid]) ? 1 : 0;
|
||||
$item['business_prescription_audit_remark'] = (string) ($bizRejectRemark[$rid] ?? '');
|
||||
$item['has_prescription_order'] = !empty($hasBizOrderRx[$rid]) ? 1 : 0;
|
||||
|
||||
@@ -10,6 +10,7 @@ use app\common\model\doctor\Medicine as DoctorMedicine;
|
||||
use app\common\model\tcm\Prescription;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
use app\common\model\tcm\Diagnosis;
|
||||
use app\common\service\DataScope\DataScopeService;
|
||||
use app\common\service\wechat\WechatWorkAppMessageService;
|
||||
use app\common\service\pharmacy\PharmacyHerbIdentityResolver;
|
||||
use app\common\service\pharmacy\LockedPharmacySnapshotMutation;
|
||||
@@ -24,6 +25,12 @@ use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
|
||||
class PrescriptionLogic
|
||||
{
|
||||
public const PRESCRIBE_PERMISSIONS = [
|
||||
'tcm.prescription/add', 'cf.prescription/add', 'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang',
|
||||
];
|
||||
public const VOID_MANAGE_PERMISSIONS = ['tcm.prescription/void', 'cf.prescription/del'];
|
||||
public const AUDIT_PERMISSIONS = ['tcm.prescription/audit', 'cf.prescription/audit'];
|
||||
|
||||
private static $error = '';
|
||||
|
||||
/** @var array{ok: bool, message?: string, errcode?: int}|null 最近一次审核成功后的企微通知结果 */
|
||||
@@ -140,6 +147,70 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @return array{own: bool, manage: bool, owner_ids: ?array} */
|
||||
public static function getVoidAccess(int $adminId, array $adminInfo): array
|
||||
{
|
||||
if ((int) ($adminInfo['root'] ?? 0) === 1) {
|
||||
return ['own' => true, 'manage' => true, 'owner_ids' => null];
|
||||
}
|
||||
|
||||
$uris = array_map('strtolower', AuthLogic::getAuthByAdminId($adminId));
|
||||
$hasVoidGrant = array_intersect(self::VOID_MANAGE_PERMISSIONS, $uris) !== [];
|
||||
$manage = ($hasVoidGrant || array_intersect(self::AUDIT_PERMISSIONS, $uris) !== [])
|
||||
&& self::canAuditPrescription($adminId, $adminInfo);
|
||||
$own = $hasVoidGrant || array_intersect(self::PRESCRIBE_PERMISSIONS, $uris) !== [];
|
||||
|
||||
return [
|
||||
'own' => $own,
|
||||
'manage' => $manage,
|
||||
'owner_ids' => ($own || $manage) ? DataScopeService::getVisibleAdminIds($adminId, $adminInfo) : [],
|
||||
];
|
||||
}
|
||||
|
||||
public static function hasVoidAccess(array $row, int $adminId, array $adminInfo, array $access): bool
|
||||
{
|
||||
$creator = (int) ($row['creator_id'] ?? 0);
|
||||
$assistant = (int) ($row['assistant_id'] ?? 0);
|
||||
$ownerIds = $access['owner_ids'];
|
||||
if ($adminId <= 0 || !empty($row['delete_time']) || ($ownerIds !== null
|
||||
&& !in_array($creator, $ownerIds, true) && !in_array($assistant, $ownerIds, true))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ($access['own'] && $creator === $adminId)
|
||||
|| ($access['manage'] && self::canViewPrescription($row, $adminId, $adminInfo));
|
||||
}
|
||||
|
||||
public static function canRestoreRejected(array $row): bool
|
||||
{
|
||||
return (int) ($row['audit_status'] ?? 0) === 2 && (int) ($row['void_status'] ?? 0) === 1
|
||||
&& (int) ($row['audit_time'] ?? 0) > 0 && (int) $row['audit_time'] === (int) ($row['void_time'] ?? 0)
|
||||
&& (int) ($row['audit_by'] ?? 0) > 0 && (int) $row['audit_by'] === (int) ($row['void_by'] ?? 0)
|
||||
&& (empty($row['esign_required']) || ($row['esign_status'] ?? 'pending') === 'pending');
|
||||
}
|
||||
|
||||
private static function withActionAvailability(array $row, int $viewerAdminId, array $viewerAdminInfo): array
|
||||
{
|
||||
$id = (int) $row['id'];
|
||||
// 与列表和创建校验一致:已取消 / 已退款的订单保留历史关联,但不再占用处方。
|
||||
$hasBizOrder = PrescriptionOrder::where('prescription_id', $id)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->count() > 0;
|
||||
$row['has_prescription_order'] = $hasBizOrder ? 1 : 0;
|
||||
$row['can_restore_rejected'] = self::canRestoreRejected($row);
|
||||
$row['can_void'] = !$hasBizOrder && empty($row['void_status'])
|
||||
&& self::hasVoidAccess(
|
||||
$row,
|
||||
$viewerAdminId,
|
||||
$viewerAdminInfo,
|
||||
self::getVoidAccess($viewerAdminId, $viewerAdminInfo)
|
||||
)
|
||||
&& PrescriptionOrderLogic::remoteSnapshotLockErrorForPrescription($id) === null;
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
private static function generateSn(): string
|
||||
{
|
||||
return 'RX' . date('Ymd') . str_pad((string)mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
|
||||
@@ -463,7 +534,12 @@ class PrescriptionLogic
|
||||
}
|
||||
|
||||
// 已通过且未作废:不可编辑
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
$current = $prescription->toArray();
|
||||
PrescriptionEsignPolicy::assertMutable($current);
|
||||
if (!empty($prescription->void_status) && !self::canRestoreRejected($current)) {
|
||||
self::setError('该处方已作废,请重新开方');
|
||||
return false;
|
||||
}
|
||||
if ((int) ($prescription->audit_status ?? 1) === 1 && (int) ($prescription->void_status ?? 0) === 0) {
|
||||
self::setError('该处方已通过审核,不可编辑');
|
||||
return false;
|
||||
@@ -807,7 +883,6 @@ class PrescriptionLogic
|
||||
$arr = $row->toArray();
|
||||
$arr['esign'] = PrescriptionEsignService::describe($arr, $viewerAdminId);
|
||||
$arr['gender_desc'] = $arr['gender'] == 1 ? '男' : '女';
|
||||
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
|
||||
|
||||
$bizPo = PrescriptionOrder::where('prescription_id', $id)
|
||||
->where('prescription_audit_status', 2)
|
||||
@@ -818,12 +893,8 @@ class PrescriptionLogic
|
||||
$arr['business_prescription_audit_rejected'] = $bizPo ? 1 : 0;
|
||||
$arr['business_prescription_audit_remark'] = $bizPo ? (string) ($bizPo->prescription_audit_remark ?? '') : '';
|
||||
|
||||
// 与列表和创建校验一致:已取消 / 已退款的订单保留历史关联,但不再占用处方。
|
||||
$hasBizOrder = PrescriptionOrder::where('prescription_id', $id)
|
||||
->whereNull('delete_time')
|
||||
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
|
||||
->count() > 0;
|
||||
$arr['has_prescription_order'] = $hasBizOrder ? 1 : 0;
|
||||
$arr = self::withActionAvailability($arr, $viewerAdminId, $viewerAdminInfo);
|
||||
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
|
||||
|
||||
/**
|
||||
* 处方笺展示所需的"收件信息/订单号/合计"等字段,
|
||||
@@ -871,7 +942,7 @@ class PrescriptionLogic
|
||||
if (!$row || (int) ($row->void_status ?? 0) === 1 || (int) ($row->audit_status ?? 1) !== 0) {
|
||||
return null;
|
||||
}
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId);
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId, false, $adminId);
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = time();
|
||||
$row->audit_by = $adminId;
|
||||
@@ -879,7 +950,7 @@ class PrescriptionLogic
|
||||
$row->audit_remark = $finalRemark;
|
||||
return $row->save() ? $row : null;
|
||||
});
|
||||
if ($row) {
|
||||
if ($row && (empty($row->esign_required) || !PrescriptionEsignService::isSandboxTest($prescriptionId))) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $finalRemark, $adminInfo);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
@@ -928,7 +999,9 @@ class PrescriptionLogic
|
||||
if (!$row) {
|
||||
return false;
|
||||
}
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, $action, $remark, $adminInfo);
|
||||
if (empty($row->esign_required) || !PrescriptionEsignService::isSandboxTest($id)) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, $action, $remark, $adminInfo);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -958,7 +1031,7 @@ class PrescriptionLogic
|
||||
|
||||
if ($action === 'approve') {
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById($id);
|
||||
PrescriptionEsignService::assertSignedById($id, false, $adminId);
|
||||
} catch (\DomainException $e) {
|
||||
self::setError($e->getMessage());
|
||||
return false;
|
||||
@@ -1135,7 +1208,7 @@ class PrescriptionLogic
|
||||
|
||||
$result = $row->toArray();
|
||||
$result['esign'] = PrescriptionEsignService::describe($result, $viewerAdminId);
|
||||
return $result;
|
||||
return self::withActionAvailability($result, $viewerAdminId, $viewerAdminInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1275,13 +1348,21 @@ class PrescriptionLogic
|
||||
/**
|
||||
* 作废处方
|
||||
*/
|
||||
public static function void(int $id, int $adminId, string $adminName): bool
|
||||
public static function void(int $id, int $adminId, array $adminInfo): bool
|
||||
{
|
||||
self::setError('');
|
||||
try {
|
||||
// Check visibility before taking pharmacy locks or reporting order state.
|
||||
$access = self::getVoidAccess($adminId, $adminInfo);
|
||||
$row = Prescription::where('id', $id)->whereNull('delete_time')->find();
|
||||
if (!$row || !self::hasVoidAccess($row->toArray(), $adminId, $adminInfo, $access)) {
|
||||
self::setError('处方不存在或无权作废');
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) LockedPharmacySnapshotMutation::executeForPrescription(
|
||||
$id,
|
||||
static fn (): bool => self::voidLocked($id, $adminId, $adminName)
|
||||
static fn (): bool => self::voidLocked($id, $adminId, $adminInfo, $access)
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
if (self::getError() === '') {
|
||||
@@ -1291,11 +1372,11 @@ class PrescriptionLogic
|
||||
}
|
||||
}
|
||||
|
||||
private static function voidLocked(int $id, int $adminId, string $adminName): bool
|
||||
private static function voidLocked(int $id, int $adminId, array $adminInfo, array $access): bool
|
||||
{
|
||||
$row = Prescription::where('id', $id)->lock(true)->find();
|
||||
if (!$row) {
|
||||
self::setError('处方不存在');
|
||||
$row = Prescription::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$row || !self::hasVoidAccess($row->toArray(), $adminId, $adminInfo, $access)) {
|
||||
self::setError('处方不存在或无权作废');
|
||||
return false;
|
||||
}
|
||||
if ((int)($row->void_status ?? 0) === 1) {
|
||||
@@ -1315,7 +1396,7 @@ class PrescriptionLogic
|
||||
$row->void_status = 1;
|
||||
$row->void_time = time();
|
||||
$row->void_by = $adminId;
|
||||
$row->void_by_name = $adminName;
|
||||
$row->void_by_name = (string) ($adminInfo['name'] ?? '');
|
||||
$saved = (bool) $row->save();
|
||||
if ($saved) {
|
||||
PrescriptionAiStore::invalidate($id, 'voided');
|
||||
|
||||
@@ -60,10 +60,10 @@ class PrescriptionOrderLogic
|
||||
return self::$error;
|
||||
}
|
||||
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false): bool
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false, ?int $reviewer = null): bool
|
||||
{
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing);
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing, $reviewer);
|
||||
return true;
|
||||
} catch (\DomainException $e) {
|
||||
self::$error = $e->getMessage();
|
||||
@@ -2397,7 +2397,7 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!self::canAuditPrescriptionOrder($adminInfo)) {
|
||||
if (!self::canAuditPrescriptionOrder($adminInfo) || !self::canAccessOrder($order, $adminId, $adminInfo)) {
|
||||
self::$error = '无处方审核权限';
|
||||
|
||||
return false;
|
||||
@@ -2424,7 +2424,7 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order)) {
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2870,10 +2870,10 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
if ($newRx === 1 && !self::assertEsignApproved($order)) {
|
||||
$oldRx = (int) $order->prescription_audit_status;
|
||||
if ($newRx === 1 && $newRx !== $oldRx && !self::assertEsignApproved($order, false, $adminId)) {
|
||||
return false;
|
||||
}
|
||||
$oldRx = (int) $order->prescription_audit_status;
|
||||
if ($newRx !== $oldRx) {
|
||||
$order->prescription_audit_status = $newRx;
|
||||
$changeParts[] = '处方审核:' . self::auditStatusLabelForLog($oldRx)
|
||||
|
||||
@@ -10,6 +10,7 @@ use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\console\input\Option;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
final class EsignSetup extends Command
|
||||
{
|
||||
@@ -17,7 +18,8 @@ final class EsignSetup extends Command
|
||||
{
|
||||
$this->setName('esign:setup')->setDescription('检查 e签宝配置、初始化内网 SDK 或恢复已归档签署结果')
|
||||
->addOption('initialize', null, Option::VALUE_NONE, '初始化已部署的 SDK;不创建医生、认证或处方签署')
|
||||
->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署');
|
||||
->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署')
|
||||
->addOption('backfill-signature-times', null, Option::VALUE_NONE, '从当前签署环境及应用的已验签原件补录签署时间');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output): int
|
||||
@@ -34,6 +36,9 @@ final class EsignSetup extends Command
|
||||
}
|
||||
PrescriptionEsignService::recover($id);
|
||||
$output->writeln('原件验签及状态恢复完成;未发送新的签署请求');
|
||||
} elseif ($input->getOption('backfill-signature-times')) {
|
||||
(new EsignClient())->assertConfigured();
|
||||
return $this->backfillSignatureTimes($config, $output);
|
||||
} elseif ($input->getOption('initialize')) {
|
||||
// Deployment may initialize before enabling the new clinical workflow.
|
||||
$client = new EsignClient(array_merge($config, ['enabled' => true]));
|
||||
@@ -49,4 +54,28 @@ final class EsignSetup extends Command
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private function backfillSignatureTimes(array $config, Output $output): int
|
||||
{
|
||||
$filled = 0;
|
||||
$failed = 0;
|
||||
Db::name('prescription_esign')
|
||||
->where('environment', $config['environment'])->where('app_id', $config['app_id'])
|
||||
->where('signed_at', '>', 0)->where('signature_time', 0)->field('prescription_id')
|
||||
->chunk(100, static function ($rows) use ($output, &$filled, &$failed): void {
|
||||
foreach ($rows as $row) {
|
||||
$id = (int) $row['prescription_id'];
|
||||
try {
|
||||
PrescriptionEsignService::recover($id);
|
||||
$filled++;
|
||||
} catch (\Throwable $error) {
|
||||
$failed++;
|
||||
$message = $error instanceof \DomainException ? $error->getMessage() : '暂时无法验签,请检查 SDK 服务';
|
||||
$output->writeln("处方 {$id} 的签署时间待核实({$message})");
|
||||
}
|
||||
}
|
||||
}, 'prescription_id');
|
||||
$output->writeln("签署时间补录完成 {$filled} 张,待核实 {$failed} 张");
|
||||
return $failed === 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
final class DoctorEsignAuthorizationRequired extends \DomainException
|
||||
{
|
||||
public function __construct(public readonly string $reason)
|
||||
{
|
||||
parent::__construct(match ($reason) {
|
||||
'exhausted' => '医生实名和证书已保存。e签宝签署授权次数已用完,请在账号菜单查看快捷签授权',
|
||||
'expired' => '医生实名和证书已保存。快捷签授权已到期,请在账号菜单续期',
|
||||
'invalid' => '医生实名和证书已保存。e签宝签署授权已失效,请在账号菜单检查授权',
|
||||
default => '医生实名和证书已保存。请在账号菜单的「医生电子签署身份」中授权快捷签',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
final class DoctorEsignIdentityRequired extends \DomainException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use DomainException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
final class DoctorEsignIdentityService
|
||||
{
|
||||
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
|
||||
{
|
||||
return 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, true, $quick === null)['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;
|
||||
}
|
||||
|
||||
public static function start(int $actor, string $mobile): array
|
||||
{
|
||||
$scope = self::scope($actor);
|
||||
$mobile = trim($mobile);
|
||||
if (self::quickEnabled() && $mobile === '') {
|
||||
return self::startQuick($scope);
|
||||
}
|
||||
if (!self::validMobile($mobile)) {
|
||||
throw new DomainException('请输入有效的大陆手机号');
|
||||
}
|
||||
$mobileHash = self::mobileHash($scope, $mobile);
|
||||
$snapshot = self::snapshot($scope);
|
||||
if (self::hasLease($snapshot['flow'])) {
|
||||
return self::processing();
|
||||
}
|
||||
$client = new EsignClient();
|
||||
if (self::hasCurrentFlow($snapshot) && hash_equals($snapshot['flow']['mobile_hash'], $mobileHash)) {
|
||||
[$status, $person] = self::identityResult($client, $snapshot);
|
||||
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($snapshot['name'], 'doctor-enrollment-' . $token, $mobile, $accountId);
|
||||
self::finish($scope, $snapshot, $token, [
|
||||
'doctor_name' => $snapshot['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']];
|
||||
} 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, $completedAt] = 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('认证证件与签署账号不一致,请联系管理员核实');
|
||||
}
|
||||
$providerExpiry = intdiv($client->willingnessValidity($snapshot['flow']['flow_id'])['expires_at'], 1000);
|
||||
$expires = min($providerExpiry, min(time(), $completedAt) + self::QUICK_LIFETIME);
|
||||
}
|
||||
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): 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_')) {
|
||||
throw $error;
|
||||
}
|
||||
return ['state' => self::state('renewal_required', '暂时无法确认签署证书有效期,可重新查询或发起续期')];
|
||||
}
|
||||
if ($start === 0 || $start > time() || $end <= time()) {
|
||||
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
|
||||
}
|
||||
$mobile = $requireMobile ? $client->authorizedMobile($snapshot['name'], $idNo) : null;
|
||||
if ($requireMobile && !self::validMobile($mobile)) {
|
||||
return ['state' => self::state('needs_mobile', '请完成实名手机号认证', $end)];
|
||||
}
|
||||
if ($end <= time()) {
|
||||
return ['state' => self::state('renewal_required', '医师签署证书需要续期,请重新认证', $end)];
|
||||
}
|
||||
return ['state' => self::state('ready', '医师电子签署已就绪', $end), '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'] ?? ''), self::certificateTime($dates['endDate'] ?? '')];
|
||||
}
|
||||
|
||||
/** SDK validity timestamps are local to the configured SDK timezone. */
|
||||
private static function certificateTime(string $value): int
|
||||
{
|
||||
if ($value === '') {
|
||||
return 0;
|
||||
}
|
||||
$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']];
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
private static function scope(int $actor): array
|
||||
{
|
||||
if (!self::enabled()) {
|
||||
throw new DomainException('医师电子签署认证尚未启用');
|
||||
}
|
||||
return ['doctor_id' => $actor, 'environment' => (string) Config::get('esign.environment', 'sandbox'),
|
||||
'app_id' => (string) Config::get('esign.app_id', '')];
|
||||
}
|
||||
|
||||
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');
|
||||
if ($name === '' || (!$doctor && !(PrescriptionReviewEsignService::enabled()
|
||||
&& PrescriptionReviewEsignService::canEnrollReviewer($actor)))) {
|
||||
throw new DomainException('仅当前医师本人可使用医师电子签署认证');
|
||||
}
|
||||
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,
|
||||
];
|
||||
}
|
||||
|
||||
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) {
|
||||
throw new DomainException('签署账号绑定冲突,请联系管理员核实');
|
||||
}
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,45 @@ use Throwable;
|
||||
/** Safe public errors deliberately omit provider messages, bodies and transport diagnostics. */
|
||||
class EsignProviderException extends RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode)
|
||||
public const APPLICATION_ACCESS_DENIED = 'APPLICATION_ACCESS_DENIED';
|
||||
public const IP_WHITELIST_MISMATCH = 'IP_WHITELIST_MISMATCH';
|
||||
public const SIGNATURE_MISMATCH = 'SIGNATURE_MISMATCH';
|
||||
public const IDENTITY_NAME_REJECTED = 'IDENTITY_NAME_REJECTED';
|
||||
public const IDENTITY_METHOD_REJECTED = 'IDENTITY_METHOD_REJECTED';
|
||||
public const IDENTITY_DOCUMENT_REJECTED = 'IDENTITY_DOCUMENT_REJECTED';
|
||||
public const IDENTITY_QUOTA_REJECTED = 'IDENTITY_QUOTA_REJECTED';
|
||||
|
||||
/** Nullable allowlisted enum; never contains a provider message or identifier. */
|
||||
public ?string $reason;
|
||||
|
||||
public function __construct(public string $operation, public string $providerCode, ?string $reason = null)
|
||||
{
|
||||
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
|
||||
$hints = [
|
||||
self::APPLICATION_ACCESS_DENIED => '该应用无权调用此接口,请管理员核查应用的接口授权',
|
||||
self::IP_WHITELIST_MISMATCH => '请求 IP 未通过白名单校验,请管理员核查出口 IP 与应用白名单',
|
||||
self::SIGNATURE_MISMATCH => '请求签名不匹配,请管理员核查签名配置',
|
||||
self::IDENTITY_NAME_REJECTED => '开方医生姓名未通过核身校验,请管理员核对账号登记的证件实名',
|
||||
self::IDENTITY_METHOD_REJECTED => '核身方式不可用,请管理员核对应用开通的认证方式',
|
||||
self::IDENTITY_DOCUMENT_REJECTED => '证件信息未通过核身校验,请核对认证设置',
|
||||
self::IDENTITY_QUOTA_REJECTED => '核身额度不足,请补充认证调试额度',
|
||||
];
|
||||
$validReason = match ($providerCode) {
|
||||
'PROVIDER_403' => in_array($reason, [self::APPLICATION_ACCESS_DENIED, self::IP_WHITELIST_MISMATCH, self::SIGNATURE_MISMATCH], true),
|
||||
'PROVIDER_30500121' => in_array($operation, ['startIdentity', 'startDoctorIdentity', 'startDoctorQuickAuthorization'], true) && in_array($reason, [self::IDENTITY_NAME_REJECTED,
|
||||
self::IDENTITY_METHOD_REJECTED, self::IDENTITY_DOCUMENT_REJECTED, self::IDENTITY_QUOTA_REJECTED], true),
|
||||
default => false,
|
||||
};
|
||||
$this->reason = $validReason ? $reason : null;
|
||||
$message = 'e签宝 ' . $operation . ' 失败(' . $providerCode . ')';
|
||||
if ($this->reason !== null) {
|
||||
$message .= ':' . $hints[$this->reason];
|
||||
} elseif ($operation === 'createPerson' && $providerCode === 'PROVIDER_403') {
|
||||
$message .= ':创建签署账号被拒绝,请管理员核查该应用的接口权限及 IP 白名单';
|
||||
} elseif ($operation === 'signPdf' && $providerCode === 'PROVIDER_10002') {
|
||||
// The signing service and local initialization reuse this numeric code for different errors.
|
||||
$message = 'e签宝签署次数不足(10002),请为当前应用补充电子签名 SDK 3.0 签署额度后重试';
|
||||
}
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,13 +66,16 @@ class EsignOutcomeUnknownException extends EsignProviderException
|
||||
* SDK 3.x PaaS HTTP adapter. Identity uses the independent v2 identity service.
|
||||
*
|
||||
* Transport receives {method,url,headers,body,timeout} and returns
|
||||
* {status:int,body:string,errno?:int}. It must not log request bodies or credentials.
|
||||
* {status:int,body:string,errno?:int}. HTTPS requests can include a local ca_file.
|
||||
* It must not log request bodies or credentials.
|
||||
* No method retries a request. initialize() is an explicit deployment operation:
|
||||
* an initialized JVM must be restarted before changing app/environment.
|
||||
*/
|
||||
final class EsignClient
|
||||
{
|
||||
private const JSON_TYPE = 'application/json; charset=UTF-8';
|
||||
private const MAINLAND_CERT_TYPE = 'INDIVIDUAL_CH_IDCARD';
|
||||
private const WILLINGNESS_PATH = '/v2/identity/willingness/api/individual';
|
||||
private const MAX_PDF_BYTES = 20971520;
|
||||
private const ENVIRONMENTS = [
|
||||
'sandbox' => [
|
||||
@@ -91,6 +130,10 @@ final class EsignClient
|
||||
if (filter_var($timeout, FILTER_VALIDATE_INT) === false || (int) $timeout < 1 || (int) $timeout > 300) {
|
||||
throw new EsignProviderException('configuration', 'TIMEOUT_INVALID');
|
||||
}
|
||||
$caFile = $this->configuration['ca_file'] ?? '';
|
||||
if (!is_string($caFile) || ($caFile !== '' && (!stream_is_local($caFile) || !is_file($caFile) || !is_readable($caFile)))) {
|
||||
throw new EsignProviderException('configuration', 'CA_FILE_INVALID');
|
||||
}
|
||||
$url = (string) ($this->configuration['sdk_url'] ?? '');
|
||||
$parts = parse_url($url);
|
||||
if (!is_array($parts) || !isset($parts['host'])
|
||||
@@ -124,27 +167,58 @@ final class EsignClient
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||||
{
|
||||
$this->requireText($name, 'startIdentity');
|
||||
$this->requireText($contextId, 'startIdentity');
|
||||
$person = ['name' => $name, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
|
||||
return $this->hostedIdentity('startIdentity', ['name' => $name, 'certType' => self::MAINLAND_CERT_TYPE],
|
||||
$contextId, 'PSN_TELECOM_AUTHCODE', $accountId);
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId = null): array
|
||||
{
|
||||
$this->requireMobile($mobile, 'startDoctorIdentity');
|
||||
// The provider binds the authorized number only after successful face authentication.
|
||||
return $this->hostedIdentity('startDoctorIdentity', [
|
||||
'name' => $name, 'certType' => self::MAINLAND_CERT_TYPE, 'authMobileNo' => $mobile,
|
||||
], $contextId, 'PSN_FACEAUTH_BYURL_ZHIMA', $accountId);
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startDoctorQuickAuthorization(string $name, string $idNo, string $contextId, string $accountId): array
|
||||
{
|
||||
$this->requireText($idNo, 'startDoctorQuickAuthorization');
|
||||
return $this->hostedIdentity('startDoctorQuickAuthorization', [
|
||||
'name' => $name, 'certType' => self::MAINLAND_CERT_TYPE, 'certNo' => $idNo,
|
||||
], $contextId, 'PSN_FACEAUTH_BYURL_ZHIMA', $accountId, 'PUREVERIFY');
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
private function hostedIdentity(
|
||||
string $operation, array $person, string $contextId, string $authType, ?string $accountId, string $usageType = 'CERTAPPLY'
|
||||
): array {
|
||||
$this->requireText($person['name'], $operation);
|
||||
$this->requireText($contextId, $operation);
|
||||
if ($accountId !== null) {
|
||||
$this->requireText($accountId, 'startIdentity');
|
||||
$this->requireText($accountId, $operation);
|
||||
$person['sdkAccountId'] = $accountId;
|
||||
}
|
||||
$response = $this->identityJson('startIdentity', 'POST', '/v2/identity/auth/web/indivAuthUrl', [
|
||||
$uneditable = ['name', 'certType'];
|
||||
if (isset($person['certNo'])) {
|
||||
$uneditable[] = 'certNo';
|
||||
}
|
||||
$response = $this->identityJson($operation, 'POST', '/v2/identity/auth/web/indivAuthUrl', [
|
||||
'indivInfo' => $person,
|
||||
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
|
||||
'usageType' => $usageType,
|
||||
'authType' => $authType,
|
||||
'availableAuthTypes' => [$authType],
|
||||
'configParams' => ['indivUneditableInfo' => $uneditable],
|
||||
'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true],
|
||||
]);
|
||||
$data = $response['data'] ?? null;
|
||||
if (!is_array($data) || !is_string($data['flowId'] ?? null) || trim($data['flowId']) === '') {
|
||||
throw new EsignProviderException('startIdentity', 'RESPONSE_INVALID');
|
||||
}
|
||||
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
$flowId = $this->requiredResponseText($data, 'flowId', $operation);
|
||||
$url = !empty($data['shortLink']) ? $data['shortLink'] : ($data['url'] ?? '');
|
||||
if (!is_string($url) || !$this->isTrustedAuthUrl($url)) {
|
||||
throw new EsignProviderException('startIdentity', 'AUTH_URL_INVALID');
|
||||
throw new EsignProviderException($operation, 'AUTH_URL_INVALID');
|
||||
}
|
||||
return ['flow_id' => $data['flowId'], 'auth_url' => $url];
|
||||
return ['flow_id' => $flowId, 'auth_url' => $url];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
@@ -159,13 +233,125 @@ final class EsignClient
|
||||
|
||||
public function checkWillingness(string $flowId): void
|
||||
{
|
||||
$this->requireText($flowId, 'checkWillingness');
|
||||
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
|
||||
if (($data['status'] ?? null) !== 1
|
||||
|| !is_int($data['remainingTimes'] ?? null) || $data['remainingTimes'] < 1
|
||||
|| !is_int($data['expireAt'] ?? null) || $data['expireAt'] <= ($this->clock)()) {
|
||||
$this->willingnessExpiresAt($flowId);
|
||||
}
|
||||
|
||||
/** Returns the provider's current expiration in Unix milliseconds. */
|
||||
public function willingnessExpiresAt(string $flowId): int
|
||||
{
|
||||
$validity = $this->willingnessValidity($flowId);
|
||||
if ($validity['state'] !== 'valid') {
|
||||
throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID');
|
||||
}
|
||||
return $validity['expires_at'];
|
||||
}
|
||||
|
||||
/** @return array{state:string,expires_at:int,remaining_times:int} Expiration is in Unix milliseconds. */
|
||||
public function willingnessValidity(string $flowId): array
|
||||
{
|
||||
$this->requireText($flowId, 'checkWillingness');
|
||||
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
|
||||
$status = $data['status'] ?? null;
|
||||
$expiresAt = $data['expireAt'] ?? null;
|
||||
$remaining = $data['remainingTimes'] ?? null;
|
||||
$state = match (true) {
|
||||
!in_array($status, [0, 1], true), !is_int($expiresAt), $expiresAt <= 0 => 'invalid',
|
||||
$expiresAt <= ($this->clock)() => 'expired',
|
||||
$remaining === 0 => 'exhausted',
|
||||
$status === 1 && is_int($remaining) && $remaining > 0 => 'valid',
|
||||
default => 'invalid',
|
||||
};
|
||||
return [
|
||||
'state' => $state,
|
||||
'expires_at' => $state === 'valid' ? $expiresAt : 0,
|
||||
'remaining_times' => $state === 'valid' ? $remaining : 0,
|
||||
];
|
||||
}
|
||||
|
||||
public function authorizedMobile(string $name, string $idNo): ?string
|
||||
{
|
||||
$this->requireText($name, 'authorizedMobile');
|
||||
$this->requireText($idNo, 'authorizedMobile');
|
||||
$response = $this->identityJson('authorizedMobile', 'POST', self::WILLINGNESS_PATH . '/get-individual-info', [
|
||||
'name' => $name, 'idNo' => $idNo, 'certType' => self::MAINLAND_CERT_TYPE,
|
||||
]);
|
||||
$data = $response['data'] ?? null;
|
||||
if ($data !== null && !is_array($data)) {
|
||||
throw new EsignProviderException('authorizedMobile', 'RESPONSE_INVALID');
|
||||
}
|
||||
$mobile = $data['mobileNo'] ?? null;
|
||||
if ($mobile === null || $mobile === '') {
|
||||
return null;
|
||||
}
|
||||
if (!is_string($mobile) || !preg_match('/^1[3-9][0-9]{9}$/D', $mobile)) {
|
||||
throw new EsignProviderException('authorizedMobile', 'RESPONSE_INVALID');
|
||||
}
|
||||
return $mobile;
|
||||
}
|
||||
|
||||
public function sendWillingnessCode(string $name, string $idNo, string $mobile): string
|
||||
{
|
||||
$this->requireText($name, 'sendWillingnessCode');
|
||||
$this->requireText($idNo, 'sendWillingnessCode');
|
||||
$this->requireMobile($mobile, 'sendWillingnessCode');
|
||||
$response = $this->identityJson('sendWillingnessCode', 'POST', self::WILLINGNESS_PATH . '/send-code', [
|
||||
'mobileNo' => $mobile, 'name' => $name, 'idNo' => $idNo, 'certType' => self::MAINLAND_CERT_TYPE,
|
||||
]);
|
||||
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
return $this->requiredResponseText($data, 'flowId', 'sendWillingnessCode');
|
||||
}
|
||||
|
||||
public function verifyWillingnessCode(string $flowId, string $code): void
|
||||
{
|
||||
$this->requireText($flowId, 'verifyWillingnessCode');
|
||||
if (!preg_match('/^[0-9]{6}$/D', $code)) {
|
||||
throw new EsignProviderException('verifyWillingnessCode', 'INPUT_INVALID');
|
||||
}
|
||||
$this->identityJson('verifyWillingnessCode', 'POST',
|
||||
self::WILLINGNESS_PATH . '/' . rawurlencode($flowId) . '/verify-send-code', ['authCode' => $code]);
|
||||
}
|
||||
|
||||
/** @return array{accountId:string,name:string,idNo:string,idNoType:string,accountType:string} */
|
||||
public function signingAccount(string $accountId): array
|
||||
{
|
||||
$this->requireText($accountId, 'signingAccount');
|
||||
$data = $this->sdkJson('signingAccount', '/timevale/account/queryByAccountId', ['accountId' => $accountId]);
|
||||
$returnedId = $this->requiredResponseText($data, 'accountId', 'signingAccount');
|
||||
if ($returnedId !== $accountId) {
|
||||
throw new EsignProviderException('signingAccount', 'RESPONSE_INVALID');
|
||||
}
|
||||
return [
|
||||
'accountId' => $returnedId,
|
||||
'name' => $this->requiredResponseText($data, 'name', 'signingAccount'),
|
||||
'idNo' => $this->requiredResponseText($data, 'idNo', 'signingAccount'),
|
||||
'idNoType' => $this->requiredResponseText($data, 'idNoType', 'signingAccount'),
|
||||
'accountType' => $this->requiredResponseText($data, 'accountType', 'signingAccount'),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{startDate:string,endDate:string} */
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
$data = $this->latestCertificate($accountId);
|
||||
return [
|
||||
'startDate' => $this->requiredResponseText($data, 'startDate', 'certificateValidity'),
|
||||
'endDate' => $this->requiredResponseText($data, 'endDate', 'certificateValidity'),
|
||||
];
|
||||
}
|
||||
|
||||
private function latestCertificate(string $accountId): array
|
||||
{
|
||||
$this->requireText($accountId, 'certificateValidity');
|
||||
return $this->sdkJson('certificateValidity', '/timevale/user/cert/queryLatestAvailableCert', ['accountId' => $accountId]);
|
||||
}
|
||||
|
||||
public function certificateIdentity(string $accountId): array
|
||||
{
|
||||
$data = $this->latestCertificate($accountId);
|
||||
return [
|
||||
'issuerCN' => $this->requiredResponseText($data, 'issuerCN', 'certificateValidity'),
|
||||
'sn' => $this->requiredResponseText($data, 'sn', 'certificateValidity'),
|
||||
];
|
||||
}
|
||||
|
||||
public function createPerson(string $name, string $idNo, string $flowId): string
|
||||
@@ -194,6 +380,16 @@ final class EsignClient
|
||||
|
||||
/** @return array{sign_service_id:string,pdf:string} */
|
||||
public function signPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
|
||||
{
|
||||
return $this->signAt($accountId, $flowId, $sealData, $pdfBytes, $fileName, 520, 108);
|
||||
}
|
||||
|
||||
public function signReviewPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
|
||||
{
|
||||
return $this->signAt($accountId, $flowId, $sealData, $pdfBytes, $fileName, 520, 63);
|
||||
}
|
||||
|
||||
private function signAt(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName, int $x, int $y): array
|
||||
{
|
||||
foreach ([$accountId, $flowId, $sealData, $fileName] as $value) {
|
||||
$this->requireText($value, 'signPdf');
|
||||
@@ -205,7 +401,7 @@ final class EsignClient
|
||||
$data = $this->sdkMultipart('signPdf', '/timevale/user/sign/personSign', 'personSignParam', [
|
||||
'accountId' => $accountId, 'willingnessId' => $flowId, 'sealData' => $sealData,
|
||||
'signType' => 'Single', 'fileBean' => ['fileName' => $fileName],
|
||||
'posBeans' => [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]],
|
||||
'posBeans' => [['posPage' => '1', 'posX' => $x, 'posY' => $y, 'width' => 48]],
|
||||
], $pdfBytes, true);
|
||||
$serviceId = is_string($data['signServiceId'] ?? null) && trim($data['signServiceId']) !== '' ? $data['signServiceId'] : null;
|
||||
$pdf = is_string($data['stream'] ?? null) ? base64_decode($data['stream'], true) : false;
|
||||
@@ -274,10 +470,15 @@ final class EsignClient
|
||||
private function request(string $operation, string $method, string $url, array $headers, string $body, string $codeKey, bool $signing = false): array
|
||||
{
|
||||
try {
|
||||
$response = ($this->transport)([
|
||||
$request = [
|
||||
'method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body,
|
||||
'timeout' => (int) ($this->configuration['timeout'] ?? 60),
|
||||
]);
|
||||
];
|
||||
$caFile = $this->configuration['ca_file'] ?? '';
|
||||
if ($caFile !== '' && str_starts_with($url, 'https://')) {
|
||||
$request['ca_file'] = $caFile;
|
||||
}
|
||||
$response = ($this->transport)($request);
|
||||
} catch (Throwable $exception) {
|
||||
// Never attach the original exception: its URL/body may contain identity or secret data.
|
||||
$this->fail($operation, 'TRANSPORT_ERROR', $signing);
|
||||
@@ -302,11 +503,56 @@ final class EsignClient
|
||||
$this->fail($operation, 'RESPONSE_INVALID', $signing);
|
||||
}
|
||||
if ($data[$codeKey] !== 0) {
|
||||
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey]);
|
||||
$reason = match (true) {
|
||||
$data[$codeKey] === 403 => $this->forbiddenReason($data),
|
||||
in_array($operation, ['startIdentity', 'startDoctorIdentity', 'startDoctorQuickAuthorization'], true) && $data[$codeKey] === 30500121
|
||||
=> $this->identityStartReason($data['message'] ?? $data['msg'] ?? null),
|
||||
default => null,
|
||||
};
|
||||
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey],
|
||||
$reason);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function forbiddenReason(array $data): ?string
|
||||
{
|
||||
$message = $data['msg'] ?? null;
|
||||
if (!is_string($message)) {
|
||||
return null;
|
||||
}
|
||||
// Translate recognized phrases to fixed codes; do not retain or echo vendor text.
|
||||
if (str_contains($message, '该应用无权调用此接口')) {
|
||||
return EsignProviderException::APPLICATION_ACCESS_DENIED;
|
||||
}
|
||||
foreach (['IP不在白名单', 'IP地址不在白名单', 'IP 不在白名单', 'IP 地址不在白名单',
|
||||
'IP白名单不匹配', 'IP 白名单不匹配', 'IP白名单校验失败', 'IP 白名单校验失败'] as $phrase) {
|
||||
if (str_contains($message, $phrase)) {
|
||||
return EsignProviderException::IP_WHITELIST_MISMATCH;
|
||||
}
|
||||
}
|
||||
if (preg_match('/(?<![A-Za-z0-9_])SignatureDoesNotMatch(?![A-Za-z0-9_])/', $message) === 1) {
|
||||
return EsignProviderException::SIGNATURE_MISMATCH;
|
||||
}
|
||||
// FORBIDDEN alone does not distinguish application permissions from an IP rejection.
|
||||
return null;
|
||||
}
|
||||
|
||||
private function identityStartReason(mixed $message): ?string
|
||||
{
|
||||
if (!is_string($message)) {
|
||||
return null;
|
||||
}
|
||||
// Translate provider detail into fixed hints. Do not return identity data from the supplier.
|
||||
return match (true) {
|
||||
str_contains($message, '姓名') => EsignProviderException::IDENTITY_NAME_REJECTED,
|
||||
str_contains($message, '余额不足') || str_contains($message, '次数不足') => EsignProviderException::IDENTITY_QUOTA_REJECTED,
|
||||
str_contains($message, '认证方式') => EsignProviderException::IDENTITY_METHOD_REJECTED,
|
||||
str_contains($message, '证件') || str_contains($message, '身份证') => EsignProviderException::IDENTITY_DOCUMENT_REJECTED,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
private function fail(string $operation, string $code, bool $signing): void
|
||||
{
|
||||
if ($signing) {
|
||||
@@ -331,6 +577,13 @@ final class EsignClient
|
||||
}
|
||||
}
|
||||
|
||||
private function requireMobile(string $mobile, string $operation): void
|
||||
{
|
||||
if (!preg_match('/^1[3-9][0-9]{9}$/D', $mobile)) {
|
||||
throw new EsignProviderException($operation, 'INPUT_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requirePdf(string $bytes, string $operation): void
|
||||
{
|
||||
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > self::MAX_PDF_BYTES) {
|
||||
@@ -398,6 +651,9 @@ final class EsignClient
|
||||
return strlen($chunk);
|
||||
},
|
||||
]);
|
||||
if (isset($request['ca_file'])) {
|
||||
curl_setopt($handle, CURLOPT_CAINFO, $request['ca_file']);
|
||||
}
|
||||
if ($request['method'] !== 'GET') {
|
||||
curl_setopt($handle, CURLOPT_POSTFIELDS, $request['body']);
|
||||
}
|
||||
|
||||
@@ -99,5 +99,10 @@ final class PrescriptionEsignPolicy
|
||||
if ($forDispensing && ($evidence['environment'] ?? '') !== 'production') {
|
||||
throw new DomainException('沙箱签署处方仅供测试,不能用于正式发药');
|
||||
}
|
||||
$issuedAt = (int) ($evidence['issued_at'] ?? 0);
|
||||
if ($issuedAt > 0 && (($evidence['signature_time_source'] ?? '') !== 'tsa'
|
||||
|| (int) ($evidence['signature_time'] ?? 0) < $issuedAt)) {
|
||||
throw new DomainException('处方开具和签署时间的验签证据不完整');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,7 @@ namespace app\common\service\esign;
|
||||
/** Deterministic, text based A4 prescription; fixed first-page signature area. */
|
||||
final class PrescriptionPdf
|
||||
{
|
||||
public static function render(array $row, string $environment): string
|
||||
public static function render(array $row, string $environment, int $issuedAt = 0, bool $review = false): string
|
||||
{
|
||||
$row = PrescriptionEsignPolicy::snapshot($row);
|
||||
$lines = [];
|
||||
@@ -32,6 +32,10 @@ final class PrescriptionPdf
|
||||
};
|
||||
$add('处方编号', $row['sn']);
|
||||
$add('日期', $row['prescription_date']);
|
||||
if ($issuedAt > 0) {
|
||||
$time = (new \DateTimeImmutable('@' . $issuedAt))->setTimezone(new \DateTimeZone('Asia/Shanghai'));
|
||||
$add('开具确认时间(北京时间)', $time->format('Y-m-d H:i:s'));
|
||||
}
|
||||
$add('患者', $row['patient_name'] . ' 性别:' . ($row['gender'] === '1' ? '男' : '女') . ' 年龄:' . $row['age']);
|
||||
$add('联系电话', $row['phone']);
|
||||
$add('门诊号', $row['visit_no']);
|
||||
@@ -93,7 +97,10 @@ final class PrescriptionPdf
|
||||
$stream .= "0.7 w 45 133 m 550 133 l S\n";
|
||||
$stream .= self::text('开方医师:' . $row['doctor_name'], 45, 110, 12);
|
||||
if ($index === 0) {
|
||||
$stream .= self::text('医师电子签章', 420, 117, 11);
|
||||
$stream .= self::text('医师电子签章', 420, 104, 11);
|
||||
if ($review) {
|
||||
$stream .= self::text('审核电子签章', 420, 59, 11);
|
||||
}
|
||||
}
|
||||
$stream .= self::text('处方快照 SHA-256', 45, 58, 8);
|
||||
$stream .= self::text(PrescriptionEsignPolicy::hash($row), 45, 44, 7);
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\model\tcm\PrescriptionOrder;
|
||||
use DomainException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
final class PrescriptionReviewEsignService
|
||||
{
|
||||
public const ORDER_PERMISSION = 'tcm.prescriptionOrder/auditPrescription';
|
||||
private const TABLE = 'prescription_review_esign';
|
||||
private const VERIFY_LEASE_SECONDS = 360;
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return filter_var(Config::get('esign.review_enabled', false), FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
/** Recheck the live personnel record and grants, including for an existing binding. */
|
||||
public static function reviewerAccess(int $actor): array
|
||||
{
|
||||
$admin = Db::name('admin')->where('id', $actor)->where('disable', 0)->whereNull('delete_time')
|
||||
->field('id,name,root')->find();
|
||||
if (!$admin) {
|
||||
return [];
|
||||
}
|
||||
$admin['admin_id'] = $actor;
|
||||
$admin['role_id'] = Db::name('admin_role')->where('admin_id', $actor)->column('role_id');
|
||||
$admin['permissions'] = (int) $admin['root'] === 1 ? ['*'] : AuthLogic::getAuthByAdminId($actor);
|
||||
if (!PrescriptionLogic::canAuditPrescription($actor, $admin)) {
|
||||
return [];
|
||||
}
|
||||
return $admin;
|
||||
}
|
||||
|
||||
public static function canEnrollReviewer(int $actor): bool
|
||||
{
|
||||
$admin = self::reviewerAccess($actor);
|
||||
return $admin && self::hasGrant($admin, array_merge(PrescriptionLogic::AUDIT_PERMISSIONS, [self::ORDER_PERMISSION]));
|
||||
}
|
||||
|
||||
private static function hasGrant(array $admin, array $grants): bool
|
||||
{
|
||||
return (int) ($admin['root'] ?? 0) === 1 || array_intersect($admin['permissions'] ?? [], $grants) !== [];
|
||||
}
|
||||
|
||||
private static function review(int $id): ?array
|
||||
{
|
||||
return Db::name(self::TABLE)->where('prescription_id', $id)->find() ?: null;
|
||||
}
|
||||
|
||||
private static function path(array $doctor): string
|
||||
{
|
||||
return $doctor['prescription_id'] . '-' . $doctor['snapshot_hash'] . '/review-signed.pdf';
|
||||
}
|
||||
|
||||
/** Called under the same prescription lock as approval or dispatch. */
|
||||
public static function assertVerified(array $row, array $doctor, ?int $actor): void
|
||||
{
|
||||
// Previously approved single-signature records retain their archived evidence.
|
||||
if (empty($doctor['review_required']) && !($actor !== null && self::enabled())) {
|
||||
return;
|
||||
}
|
||||
$review = self::review((int) $row['id']);
|
||||
if (!self::hasVerifiedReview($doctor, $review)) {
|
||||
throw new DomainException('请由另一位有审核权限的人员完成处方审核电子签署');
|
||||
}
|
||||
if ($actor !== null && ($actor !== (int) $review['reviewer_id'] || !self::canEnrollReviewer($actor))) {
|
||||
throw new DomainException('请由已签署此处方且仍有审核权限的审核人本人提交审核');
|
||||
}
|
||||
PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
|
||||
}
|
||||
|
||||
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'])
|
||||
&& $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
|
||||
{
|
||||
if (empty($doctor['review_required']) || !($review = self::review((int) $doctor['prescription_id']))
|
||||
|| !self::hasVerifiedReview($doctor, $review)) {
|
||||
return [];
|
||||
}
|
||||
return ['review_signer_name' => $review['signer_name'], 'review_signature_time' => (int) $review['signature_time']];
|
||||
}
|
||||
|
||||
public static function download(array $doctor): ?array
|
||||
{
|
||||
if (empty($doctor['review_required'])) {
|
||||
return null;
|
||||
}
|
||||
$review = self::review((int) $doctor['prescription_id']);
|
||||
if (!self::hasVerifiedReview($doctor, $review)) {
|
||||
return null;
|
||||
}
|
||||
$pdf = PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
|
||||
return ['filename' => 'prescription-' . $doctor['prescription_id'] . '-dual-signed.pdf',
|
||||
'sha256' => $review['signed_hash'], 'content_base64' => base64_encode($pdf)];
|
||||
}
|
||||
|
||||
public static function status(int $id, int $orderId, int $actor, array $adminInfo): array
|
||||
{
|
||||
$context = self::context($id, $orderId, $actor, $adminInfo);
|
||||
return self::describeContext($context, $actor);
|
||||
}
|
||||
|
||||
private static function context(int $id, int $orderId, int $actor, array $adminInfo, bool $lock = false): array
|
||||
{
|
||||
$order = $orderId > 0 ? PrescriptionOrder::where('id', $orderId)->whereNull('delete_time')->lock($lock)->find() : null;
|
||||
if ($orderId > 0 && (!$order || (int) $order->prescription_id !== $id
|
||||
|| !PrescriptionOrderLogic::canAccessOrder($order, $actor, $adminInfo))) {
|
||||
throw new DomainException('业务订单不存在或无权查看');
|
||||
}
|
||||
$row = Db::name('tcm_prescription')->where('id', $id)->whereNull('delete_time')->lock($lock)->find();
|
||||
if (!$row || (!$order && !PrescriptionLogic::canViewPrescription($row, $actor, $adminInfo))) {
|
||||
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']));
|
||||
$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;
|
||||
return ['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required,
|
||||
'can_audit' => $pending && $reviewer && self::hasGrant($reviewer, $grants),
|
||||
'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;
|
||||
$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;
|
||||
$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) {
|
||||
!$required => '',
|
||||
$signed => $own ? '审核签章已验签,可以提交通过。' : '请由已签署此处方的审核人本人提交审核。',
|
||||
!$differentPerson => '请切换到另一位有权限的审核人账号。',
|
||||
!$canAudit => '当前账号或处方状态不允许审核签署。',
|
||||
($row['esign_status'] ?? '') !== 'signed' => '请开方医生先完成电子签署。',
|
||||
$state === 'uncertain' => (string) $review['error_message'],
|
||||
in_array($state, ['signing', 'verifying'], true) && !$stale => '正在处理审核签署,请稍后刷新。',
|
||||
in_array($state, ['signing', 'verifying'], true) => '审核签署结果待核实,请查询状态或重试验签。',
|
||||
!$canWork => '当前签署环境或快捷签配置不可用。',
|
||||
!$account => '请先完成审核人本人的实名和快捷签授权。',
|
||||
default => (string) (($review['error_message'] ?? '') ?: '核对处方后,请审核人本人确认追加签章。'),
|
||||
};
|
||||
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,
|
||||
'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,
|
||||
'message' => $message,
|
||||
];
|
||||
}
|
||||
|
||||
public static function confirm(int $id, int $orderId, int $actor, array $adminInfo, bool $verifyOnly): array
|
||||
{
|
||||
$client = new EsignClient();
|
||||
$context = self::context($id, $orderId, $actor, $adminInfo);
|
||||
$status = self::describeContext($context, $actor);
|
||||
$doctor = $context['doctor'];
|
||||
if ($status['required'] && $status['can_approve']) {
|
||||
return $status;
|
||||
}
|
||||
if (!($verifyOnly ? $status['can_retry_verify'] : $status['can_confirm'])) {
|
||||
throw new DomainException($status['message'] ?: '当前处方无需审核签署');
|
||||
}
|
||||
PrescriptionEsignPolicy::assertSigned($context['row'], $doctor);
|
||||
$source = PrescriptionEsignService::readPdf($doctor['signed_path'], $doctor['signed_hash']);
|
||||
$token = bin2hex(random_bytes(16));
|
||||
if ($verifyOnly) {
|
||||
$newProof = [];
|
||||
} else {
|
||||
$account = PrescriptionEsignService::account($actor);
|
||||
if (!$account || $account['account_id'] === $doctor['account_id']) {
|
||||
throw new DomainException('审核人必须使用自己的签署账号,并与开方医生不同');
|
||||
}
|
||||
$name = (string) $account['doctor_name'];
|
||||
$accountId = (string) $account['account_id'];
|
||||
$doctorName = ($doctor['signer_name'] ?? '') ?: (string) $context['row']['doctor_name'];
|
||||
$before = self::doctorSignature($client->verifyPdf($source), $doctorName, (int) $doctor['signature_time']);
|
||||
$certificate = self::certificateKey($client->certificateIdentity($accountId));
|
||||
if ($certificate === $before['certificate']) {
|
||||
throw new DomainException('审核证书必须与开方医生的证书不同');
|
||||
}
|
||||
$seal = $client->createSeal($accountId);
|
||||
// Verify consent and certificate validity immediately before taking the signing lease.
|
||||
$flow = DoctorEsignIdentityService::quickAuthorization($actor, $name, $accountId);
|
||||
$newProof = [
|
||||
'reviewer_id' => $actor, 'signer_name' => $name, 'account_id' => $accountId,
|
||||
'environment' => $doctor['environment'], 'app_id' => $doctor['app_id'],
|
||||
'reviewer_certificate' => $certificate, 'doctor_signature' => $before['key'],
|
||||
'doctor_pdf_hash' => $doctor['signed_hash'], 'confirmed_at' => time(),
|
||||
'signed_hash' => '', 'signature_time' => 0, 'sign_service_id' => '',
|
||||
];
|
||||
}
|
||||
$work = Db::transaction(static function () use ($id, $orderId, $actor, $adminInfo, $verifyOnly, $doctor, $newProof, $token): array {
|
||||
$current = self::context($id, $orderId, $actor, $adminInfo, true);
|
||||
$checked = self::describeContext($current, $actor);
|
||||
if (!($verifyOnly ? $checked['can_retry_verify'] : $checked['can_confirm'])
|
||||
|| $current['doctor']['signed_hash'] !== $doctor['signed_hash']) {
|
||||
throw new DomainException('处方或审核签署状态已变化,请刷新');
|
||||
}
|
||||
PrescriptionEsignPolicy::assertSigned($current['row'], $current['doctor']);
|
||||
if (!$verifyOnly && (PrescriptionEsignService::account($actor)['account_id'] ?? '') !== $newProof['account_id']) {
|
||||
throw new DomainException('审核签署账号已变化,请重新确认');
|
||||
}
|
||||
$data = $newProof + ['state' => $verifyOnly ? 'verifying' : 'signing', 'operation_token' => $token,
|
||||
'update_time' => time(), 'error_message' => ''];
|
||||
if ($current['review']) {
|
||||
Db::name(self::TABLE)->where('prescription_id', $id)->update($data);
|
||||
} else {
|
||||
Db::name(self::TABLE)->insert($data + ['prescription_id' => $id]);
|
||||
}
|
||||
if (empty($current['doctor']['review_required'])) {
|
||||
Db::name('prescription_esign')->where('prescription_id', $id)->update(['review_required' => 1]);
|
||||
}
|
||||
return $data + ($current['review'] ?? []);
|
||||
});
|
||||
|
||||
$received = $verifyOnly;
|
||||
try {
|
||||
if ($verifyOnly) {
|
||||
$dual = PrescriptionEsignService::readPdf(self::path($doctor), $work['signed_hash']);
|
||||
} else {
|
||||
$signed = $client->signReviewPdf($accountId, $flow, $seal, $source, 'prescription-' . $id . '.pdf');
|
||||
$received = true;
|
||||
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']);
|
||||
}
|
||||
$time = self::verifyReview($source, $dual, $client->verifyPdf($dual), $doctor, $work);
|
||||
self::save($id, $token, ['state' => 'signed', 'signature_time' => $time, 'error_message' => '']);
|
||||
} catch (\Throwable $error) {
|
||||
$definiteRejection = !$received && $error instanceof EsignProviderException && !($error instanceof EsignOutcomeUnknownException);
|
||||
$details = $definiteRejection || $error instanceof DomainException ? $error->getMessage()
|
||||
: '审核签署结果待核实,请刷新状态或重试验签';
|
||||
$fields = ['state' => $definiteRejection ? 'failed' : 'uncertain', 'error_message' => mb_substr($details, 0, 240)];
|
||||
if ($error instanceof EsignOutcomeUnknownException && $error->signServiceId !== null) {
|
||||
$fields['sign_service_id'] = $error->signServiceId;
|
||||
}
|
||||
self::save($id, $token, $fields);
|
||||
}
|
||||
return self::status($id, $orderId, $actor, $adminInfo);
|
||||
}
|
||||
|
||||
private static function save(int $id, string $token, array $fields): void
|
||||
{
|
||||
// One lease protects any provider request. Only verification can resume an archived result.
|
||||
Db::name(self::TABLE)->where('prescription_id', $id)->where('operation_token', $token)
|
||||
->update($fields + ['update_time' => time()]);
|
||||
}
|
||||
|
||||
private static function certificateKey(array $cert): string
|
||||
{
|
||||
$issuer = trim((string) ($cert['issuerCN'] ?? ''));
|
||||
$serial = ltrim(strtolower(trim((string) ($cert['sn'] ?? ''))), '0');
|
||||
if ($issuer === '' || !preg_match('/^[a-f0-9]+$/D', $serial)) {
|
||||
throw new DomainException('e签宝未返回可核对的签署证书信息');
|
||||
}
|
||||
return hash('sha256', $issuer . "\0" . $serial);
|
||||
}
|
||||
|
||||
private static function signature(array $entry): array
|
||||
{
|
||||
$signature = $entry['signature'] ?? [];
|
||||
$cert = $entry['cert'] ?? [];
|
||||
$field = (string) ($signature['signatureName'] ?? '');
|
||||
$timing = PrescriptionEsignService::verifiedSigningTime($signature);
|
||||
if (($signature['validate'] ?? null) !== true || $field === '' || ($timing['signature_time_source'] ?? '') !== 'tsa') {
|
||||
throw new DomainException('原件签章或可信时间戳未通过核验');
|
||||
}
|
||||
$name = (string) ($cert['cn'] ?? '');
|
||||
$time = $timing['signature_time'];
|
||||
$certificate = self::certificateKey($cert);
|
||||
$key = hash('sha256', json_encode([$field, $certificate, $name, $time], JSON_THROW_ON_ERROR));
|
||||
return compact('field', 'name', 'time', 'certificate', 'key');
|
||||
}
|
||||
|
||||
private static function doctorSignature(array $verified, string $doctorName, int $recordedTime): array
|
||||
{
|
||||
$entries = $verified['signatures'] ?? [];
|
||||
if (count($entries) !== 1 || $doctorName === '') {
|
||||
throw new DomainException('开方原件须有且仅有一枚医生签章');
|
||||
}
|
||||
$signature = self::signature($entries[0]);
|
||||
if ($signature['name'] !== $doctorName || ($recordedTime > 0 && $signature['time'] !== $recordedTime)) {
|
||||
throw new DomainException('医生签章与归档签署记录不一致');
|
||||
}
|
||||
return $signature;
|
||||
}
|
||||
|
||||
public static function verifyReview(string $source, string $dual, array $verified, array $doctor, array $proof): int
|
||||
{
|
||||
if (strlen($dual) <= strlen($source) || !str_starts_with($dual, $source)) {
|
||||
throw new DomainException('双签原件未保留医生已签的原始文档,请联系管理员');
|
||||
}
|
||||
$entries = $verified['signatures'] ?? [];
|
||||
if (count($entries) !== 2) {
|
||||
throw new DomainException('双签原件须包含两枚有效签章');
|
||||
}
|
||||
[$first, $second] = array_map([self::class, 'signature'], $entries);
|
||||
[$original, $review] = $first['key'] === $proof['doctor_signature'] ? [$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'];
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ final class LockedPharmacySnapshotMutation
|
||||
foreach ($orders as $order) {
|
||||
$claim = Db::name('pharmacy_submission_claim')
|
||||
->where('prescription_order_id', (int) $order['id'])
|
||||
->where('source_revision', 1)
|
||||
->order('source_revision', 'desc')
|
||||
->lock(true)
|
||||
->find();
|
||||
PharmacyRemoteSnapshotPolicy::assertMutable($order, $claim ?: null);
|
||||
|
||||
@@ -5,10 +5,16 @@ declare(strict_types=1);
|
||||
// Secrets remain server-side. Identity/API initialization hosts are fixed by environment in EsignClient.
|
||||
return [
|
||||
'enabled' => env('esign.enabled', false),
|
||||
'doctor_sms_enabled' => env('esign.doctor_sms_enabled', false),
|
||||
'doctor_quicksign_enabled' => env('esign.doctor_quicksign_enabled', false),
|
||||
'review_enabled' => env('esign.review_enabled', false),
|
||||
'environment' => env('esign.environment', 'sandbox'),
|
||||
'app_id' => env('esign.app_id', ''),
|
||||
'app_secret' => env('esign.app_secret', ''),
|
||||
'sdk_url' => env('esign.sdk_url', 'http://127.0.0.1:8091/paas-sdk-service'),
|
||||
'ca_file' => env('esign.ca_file', ''),
|
||||
'sandbox_signer_names' => env('esign.sandbox_signer_names', ''),
|
||||
'sdk_timezone' => env('esign.sdk_timezone', 'Asia/Shanghai'),
|
||||
'timeout' => env('esign.timeout', 60),
|
||||
'storage_path' => env('esign.storage_path', dirname(__DIR__) . '/storage/esign'),
|
||||
];
|
||||
|
||||
@@ -8,6 +8,7 @@ DEALLOCATE PREPARE stmt;
|
||||
CREATE TABLE IF NOT EXISTS `zyt_prescription_esign` (
|
||||
`prescription_id` int unsigned NOT NULL,
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`signer_name` varchar(100) NOT NULL DEFAULT '',
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`snapshot_hash` char(64) NOT NULL,
|
||||
@@ -17,18 +18,57 @@ CREATE TABLE IF NOT EXISTS `zyt_prescription_esign` (
|
||||
`signed_hash` char(64) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`auth_method` varchar(8) NOT NULL DEFAULT '',
|
||||
`sms_sent_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`sms_verified_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`sms_attempts` tinyint unsigned NOT NULL DEFAULT 0,
|
||||
`doctor_setup_required` tinyint unsigned NOT NULL DEFAULT 0,
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`sign_service_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`error_message` varchar(255) NOT NULL DEFAULT '',
|
||||
`started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`issued_at` bigint unsigned NOT NULL DEFAULT 0,
|
||||
`signed_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`signature_time` bigint unsigned NOT NULL DEFAULT 0,
|
||||
`signature_time_source` varchar(16) NOT NULL DEFAULT '',
|
||||
`create_time` int unsigned NOT NULL,
|
||||
`update_time` int unsigned NOT NULL,
|
||||
PRIMARY KEY (`prescription_id`),
|
||||
UNIQUE KEY `uk_flow` (`environment`,`app_id`,`flow_id`,`prescription_id`)
|
||||
UNIQUE KEY `uk_flow` (`environment`,`app_id`,`flow_id`,`prescription_id`),
|
||||
KEY `idx_esign_doctor_sms` (`doctor_id`,`environment`,`app_id`,`sms_sent_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='冻结处方原文及签署证据,文件保存于私有存储';
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='signer_name');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD signer_name varchar(100) NOT NULL DEFAULT ''''', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='signature_time');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD signature_time bigint unsigned NOT NULL DEFAULT 0', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='signature_time_source');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD signature_time_source varchar(16) NOT NULL DEFAULT ''''', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='issued_at');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD issued_at bigint unsigned NOT NULL DEFAULT 0', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='auth_method');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_prescription_esign ADD auth_method varchar(8) NOT NULL DEFAULT '''', ADD sms_sent_at int unsigned NOT NULL DEFAULT 0, ADD sms_verified_at int unsigned NOT NULL DEFAULT 0, ADD sms_attempts tinyint unsigned NOT NULL DEFAULT 0, ADD doctor_setup_required tinyint unsigned NOT NULL DEFAULT 0, ADD INDEX idx_esign_doctor_sms (doctor_id,environment,app_id,sms_sent_at)', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_account` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Apply before enabling ESIGN_DOCTOR_SMS_ENABLED. Existing doctor accounts are reused.
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_identity` (
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`doctor_name` varchar(100) NOT NULL DEFAULT '',
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`mobile_hash` char(64) NOT NULL DEFAULT '',
|
||||
`flow_started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`operation_expires_at` int unsigned NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`doctor_id`,`environment`,`app_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='医师实名在途流程,不保存原始证件号、手机号或验证码';
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Apply before enabling ESIGN_DOCTOR_QUICKSIGN_ENABLED.
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_quicksign` (
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`doctor_name` varchar(100) NOT NULL DEFAULT '',
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`flow_started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`expires_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`operation_expires_at` int unsigned NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`doctor_id`,`environment`,`app_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='医师快捷签意愿授权';
|
||||
@@ -0,0 +1,29 @@
|
||||
SET @has_review_required = (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_prescription_esign' AND COLUMN_NAME='review_required'
|
||||
);
|
||||
SET @ddl = IF(@has_review_required=0, 'ALTER TABLE zyt_prescription_esign ADD review_required tinyint NOT NULL DEFAULT 0', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `zyt_prescription_review_esign` (
|
||||
`prescription_id` int unsigned NOT NULL,
|
||||
`reviewer_id` int unsigned NOT NULL,
|
||||
`signer_name` varchar(100) NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`account_id` varchar(128) NOT NULL,
|
||||
`reviewer_certificate` char(64) NOT NULL,
|
||||
`doctor_signature` char(64) NOT NULL,
|
||||
`doctor_pdf_hash` char(64) NOT NULL,
|
||||
`state` varchar(16) NOT NULL,
|
||||
`operation_token` char(32) NOT NULL,
|
||||
`confirmed_at` bigint unsigned NOT NULL,
|
||||
`update_time` bigint unsigned NOT NULL,
|
||||
`sign_service_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`signed_hash` char(64) NOT NULL DEFAULT '',
|
||||
`signature_time` bigint unsigned NOT NULL DEFAULT 0,
|
||||
`error_message` varchar(255) NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (`prescription_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='处方复核电子签署证据';
|
||||
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
class EsignProviderException extends \RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode) {}
|
||||
}
|
||||
|
||||
final class EsignClient
|
||||
{
|
||||
public const NAME = '测试医师';
|
||||
public const DOCUMENT = '110101199001011237';
|
||||
public static array $identity = ['status' => 'INIT'];
|
||||
public static int $starts = 0;
|
||||
public static int $creates = 0;
|
||||
public static ?string $mobile = null;
|
||||
public static bool $expired = false;
|
||||
public static ?\Closure $duringStart = null;
|
||||
public static ?\Closure $duringRecipientLookup = null;
|
||||
public static ?string $account = null;
|
||||
public static int $quickStarts = 0;
|
||||
public static int $willingnessChecks = 0;
|
||||
public static int $willingnessExpiry = 0;
|
||||
public static bool $willingnessValid = true;
|
||||
public static ?\Closure $duringWillingnessCheck = null;
|
||||
|
||||
public function startDoctorIdentity(string $name, string $contextId, string $mobile, ?string $accountId): array
|
||||
{
|
||||
++self::$starts;
|
||||
self::$account = $accountId;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
return ['flow_id' => 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/example/' . self::$starts];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
{
|
||||
return self::$identity + ['flowId' => $flowId, 'appId' => 'fixture', 'objectType' => 'INDIVIDUAL'];
|
||||
}
|
||||
|
||||
public function startDoctorQuickAuthorization(string $name, string $document, string $contextId, string $accountId): array
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT || $accountId !== 'bound-account'
|
||||
|| !str_starts_with($contextId, 'doctor-quicksign-')) {
|
||||
throw new \RuntimeException('Wrong quick-sign authorization subject or context');
|
||||
}
|
||||
++self::$quickStarts;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
return ['flow_id' => 'quick-proof-' . self::$quickStarts, 'auth_url' => 'https://smlt.esign.cn/quick/' . self::$quickStarts];
|
||||
}
|
||||
|
||||
public function willingnessValidity(string $flowId): array
|
||||
{
|
||||
++self::$willingnessChecks;
|
||||
if (self::$duringWillingnessCheck) {
|
||||
(self::$duringWillingnessCheck)();
|
||||
}
|
||||
if ($flowId !== 'quick-proof-' . self::$quickStarts || !self::$willingnessValid) {
|
||||
return ['state' => 'exhausted', 'expires_at' => 0, 'remaining_times' => 0];
|
||||
}
|
||||
return ['state' => 'valid', 'expires_at' => self::$willingnessExpiry, 'remaining_times' => 2];
|
||||
}
|
||||
|
||||
public function createPerson(string $name, string $document, string $flowId): string
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT || $flowId !== 'flow-' . self::$starts) {
|
||||
throw new \RuntimeException('Identity proof mismatch');
|
||||
}
|
||||
++self::$creates;
|
||||
return 'bound-account';
|
||||
}
|
||||
|
||||
public function signingAccount(string $accountId): array
|
||||
{
|
||||
return ['accountId' => $accountId, 'name' => self::NAME, 'idNo' => self::DOCUMENT,
|
||||
'accountType' => 'PERSON', 'idNoType' => 'MAINLAND'];
|
||||
}
|
||||
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
return ['startDate' => '2024-01-01 08:00:00',
|
||||
'endDate' => self::$expired ? '2024-02-01 08:00:00' : '2099-01-01 08:00:00'];
|
||||
}
|
||||
|
||||
public function authorizedMobile(string $name, string $document): ?string
|
||||
{
|
||||
if ($name !== self::NAME || $document !== self::DOCUMENT) {
|
||||
throw new \RuntimeException('Wrong provider subject');
|
||||
}
|
||||
if (self::$duringRecipientLookup) {
|
||||
(self::$duringRecipientLookup)();
|
||||
}
|
||||
return self::$mobile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\common\service\esign\DoctorEsignIdentityRequired;
|
||||
use app\common\service\esign\DoctorEsignAuthorizationRequired;
|
||||
use app\common\service\esign\DoctorEsignIdentityService as Enrollment;
|
||||
use app\common\service\esign\EsignClient as Provider;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
$app = new think\App();
|
||||
$app->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'app_secret' => 'fixture-secret'];
|
||||
$config->set($settings, 'esign');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
|
||||
foreach (['identity', 'quicksign'] as $migration) {
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_' . $migration . '.sql');
|
||||
$sql = preg_replace('/\) ENGINE=.*;/u', ');', $sql);
|
||||
Db::execute($sql);
|
||||
Db::execute($sql);
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER,role_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_esign_account (doctor_id INTEGER,environment TEXT,app_id TEXT,account_id TEXT,
|
||||
doctor_name TEXT,create_time INTEGER,UNIQUE(doctor_id,environment,app_id))');
|
||||
Db::name('admin')->insertAll([['id' => 1, 'name' => Provider::NAME], ['id' => 2, 'name' => '另一位医师'], ['id' => 3, 'name' => '客服']]);
|
||||
Db::name('admin_role')->insertAll([['admin_id' => 1, 'role_id' => 1], ['admin_id' => 2, 'role_id' => 1], ['admin_id' => 3, 'role_id' => 2]]);
|
||||
|
||||
$checks = 0;
|
||||
$assert = static function (bool $condition, string $message) use (&$checks): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
++$checks;
|
||||
};
|
||||
$throws = static function (callable $operation, string $expected, string $message) use ($assert): void {
|
||||
try {
|
||||
$operation();
|
||||
} catch (DomainException $error) {
|
||||
$assert(is_a($error, $expected), $message);
|
||||
return;
|
||||
}
|
||||
$assert(false, $message);
|
||||
};
|
||||
|
||||
$phone = '13800000000';
|
||||
$assert(Enrollment::status(1)['enabled'] === false, 'SMS enrollment defaults off');
|
||||
$config->set(['doctor_sms_enabled' => true], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'doctor starts unbound');
|
||||
$throws(static fn () => Enrollment::status(3), DomainException::class, 'non-physician denied');
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, ''), DoctorEsignIdentityRequired::class, 'setup-required reason distinguishes an unbound doctor');
|
||||
|
||||
Provider::$duringStart = static function () use ($assert, $phone): void {
|
||||
$duplicate = Enrollment::start(1, $phone);
|
||||
$assert($duplicate['status'] === 'authenticating' && !isset($duplicate['auth_url']), 'concurrent start is held by the operation lease');
|
||||
};
|
||||
$first = Enrollment::start(1, $phone);
|
||||
Provider::$duringStart = null;
|
||||
$assert($first['status'] === 'authenticating' && Enrollment::start(1, $phone) === $first && Provider::$starts === 1,
|
||||
'explicit repeat resumes the hosted flow');
|
||||
$assert(Enrollment::status(2)['status'] === 'unbound', 'another physician cannot see this URL');
|
||||
$config->set(['app_id' => 'other-app'], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'another eSign application cannot see this URL');
|
||||
$config->set(['app_id' => 'fixture'], 'esign');
|
||||
$assert(!str_contains(json_encode(Db::name('doctor_esign_identity')->find()), $phone), 'mobile stored only as a keyed digest');
|
||||
$assert(Enrollment::complete(1)['status'] === 'authenticating' && Provider::$creates === 0, 'unfinished H5 does not bind');
|
||||
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
|
||||
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => '1101**********123X']];
|
||||
$pending = Enrollment::status(1);
|
||||
$assert($pending['status'] === 'binding_required' && $pending['identity_details_required'] && !isset($pending['auth_url'])
|
||||
&& Provider::$creates === 0, 'successful polling exposes only safe metadata and accepts masked identity as supplemental');
|
||||
$assert(Enrollment::complete(1, 'bad-input')['identity_details_required'] && Provider::$creates === 0, 'invalid supplemental number never reaches SDK');
|
||||
$assert(Enrollment::complete(1, Provider::DOCUMENT)['status'] === 'needs_mobile' && Provider::$creates === 1,
|
||||
'successful provider proof binds without signing, but an absent provider authorization is not ready');
|
||||
$assert(Db::name('doctor_esign_identity')->count() === 0 && !str_contains(json_encode(Db::name('doctor_esign_account')->find()), Provider::DOCUMENT),
|
||||
'completed enrollment clears hosted URL and does not persist identity number');
|
||||
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class, 'willingness requires a current authorized mobile');
|
||||
Provider::$expired = true;
|
||||
$assert(Enrollment::status(1)['status'] === 'renewal_required', 'expired provider certificate requires renewal');
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account', 'renewal reuses canonical account');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
Provider::$mobile = $phone;
|
||||
Provider::$expired = false;
|
||||
$assert(Enrollment::status(1)['identity_details_required'] === false, 'a bound account needs no supplemental input');
|
||||
$ready = Enrollment::complete(1);
|
||||
$assert($ready['status'] === 'ready' && $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
'same account becomes ready with certificate date in configured SDK timezone');
|
||||
$assert(!str_contains(json_encode($ready), $phone) && !str_contains(json_encode($ready), Provider::DOCUMENT), 'status never returns provider identity');
|
||||
$recipient = Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account');
|
||||
$assert($recipient === ['name' => Provider::NAME, 'idNo' => Provider::DOCUMENT, 'mobile' => $phone], 'recipient includes only verified transient provider fields');
|
||||
|
||||
Provider::$duringRecipientLookup = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DomainException::class, 'mid-flight account change cannot authorize willingness');
|
||||
Provider::$duringRecipientLookup = null;
|
||||
Provider::$mobile = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
|
||||
$assert(!Enrollment::quickEnabled(), 'quick-sign is disabled by default');
|
||||
$config->set(['doctor_sms_enabled' => false, 'doctor_quicksign_enabled' => true], 'esign');
|
||||
$quickReady = Enrollment::status(1);
|
||||
$assert($quickReady['status'] === 'ready' && $quickReady['quicksign_enabled'] && $quickReady['quicksign_expires_at'] === 0,
|
||||
'a bound current certificate can enter quick-sign without SMS or previous authorization');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'an established signing account and historical identity are insufficient to sign');
|
||||
$assert(Enrollment::start(2, '')['status'] === 'unbound' && Provider::$quickStarts === 0, 'an unbound physician cannot start a quick-sign grant');
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$duringStart = static function () use ($assert): void {
|
||||
$processing = Enrollment::status(1);
|
||||
$assert($processing['status'] === 'authenticating' && $processing['quicksign_authorizing'] && !isset($processing['auth_url']),
|
||||
'quick-sign grant initiation is serialized');
|
||||
};
|
||||
$quick = Enrollment::start(1, '');
|
||||
Provider::$duringStart = null;
|
||||
$assert($quick['quicksign_authorizing'] && $quick['status'] === 'authenticating' && $quick['quicksign_expires_at'] === 0
|
||||
&& isset($quick['auth_url']) && Enrollment::start(1, '') === $quick && Provider::$quickStarts === 1,
|
||||
'empty mobile starts or resumes a distinct provider grant');
|
||||
$assert(Enrollment::complete(1) === $quick && Provider::$willingnessChecks === 0, 'incomplete face authentication cannot grant signing');
|
||||
|
||||
$now = time();
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null, 'endTime' => $now * 1000];
|
||||
Provider::$willingnessExpiry = ($now + 3 * 86400) * 1000;
|
||||
$quickPending = Enrollment::status(1);
|
||||
$assert($quickPending['status'] === 'binding_required' && $quickPending['quicksign_authorizing']
|
||||
&& !$quickPending['identity_details_required'] && $quickPending['quicksign_expires_at'] === 0 && !isset($quickPending['auth_url']),
|
||||
'provider success waits for explicit physician confirmation without another identity prompt');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider face verification alone does not activate grant');
|
||||
$quickGranted = Enrollment::complete(1);
|
||||
$assert($quickGranted['status'] === 'ready' && !$quickGranted['quicksign_authorizing']
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& !str_contains(json_encode($quickGranted), 'quick-proof') && !str_contains(json_encode($quickGranted), Provider::DOCUMENT),
|
||||
'confirmed provider proof is capped to 24 hours and remains server-only');
|
||||
$quickRow = Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->find();
|
||||
$assert($quickRow['flow_id'] === 'quick-proof-1' && $quickRow['auth_url'] === null
|
||||
&& Db::name('doctor_esign_identity')->count() === 0 && Provider::$creates === 1, 'grant clears its hosted link and keeps enrollment untouched');
|
||||
|
||||
$checksBeforeReuse = Provider::$willingnessChecks;
|
||||
Provider::$willingnessExpiry = ($now + 120) * 1000 + 123;
|
||||
$assert(Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
|
||||
&& Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account') === 'quick-proof-1'
|
||||
&& Provider::$willingnessChecks === $checksBeforeReuse + 2,
|
||||
'the same independent proof can be reused with a fresh provider check each time');
|
||||
$assert(Enrollment::status(1)['quicksign_expires_at'] === $now + 120, 'reported validity honors a shorter provider expiry');
|
||||
$assert(Enrollment::start(1, '')['quicksign_expires_at'] === $now + 120 && Provider::$quickStarts === 1, 'a current grant is never replaced by a casual repeat');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(2, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'another physician cannot use this proof');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'other-account'), DomainException::class,
|
||||
'signatures must match the authorized SDK account');
|
||||
$config->set(['app_id' => 'other-app'], 'esign');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'another eSign application cannot use this proof');
|
||||
$config->set(['app_id' => 'fixture'], 'esign');
|
||||
Provider::$duringWillingnessCheck = static fn () => Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'changed']);
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DomainException::class,
|
||||
'a mid-flight account change invalidates the checked result');
|
||||
Provider::$duringWillingnessCheck = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
Provider::$willingnessValid = false;
|
||||
$spent = Enrollment::status(1);
|
||||
$assert($spent['quicksign_expires_at'] === 0 && $spent['quicksign_remaining_times'] === 0
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready',
|
||||
'provider exhaustion leaves certificate enrollment valid and reports the spent grant');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider cancellation/exhaustion blocks dispatch');
|
||||
Provider::$willingnessValid = true;
|
||||
Provider::$expired = true;
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class,
|
||||
'expired identity certificate is distinct from an unavailable signing grant');
|
||||
Provider::$expired = false;
|
||||
$checksBeforeExpiry = Provider::$willingnessChecks;
|
||||
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update(['expires_at' => time() - 1]);
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'locally expired grant remains invalid even if the provider still accepts the flow');
|
||||
$assert(Provider::$willingnessChecks === $checksBeforeExpiry && Enrollment::status(1)['status'] === 'ready'
|
||||
&& Enrollment::status(1)['quicksign_expires_at'] === 0, 'expired grant leaves the current signing account enrolled');
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, '')['quicksign_authorizing'] && Provider::$quickStarts === 2, 'expired grant permits a new standalone grant');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['quicksign_expires_at'] === $now + 120, 'provider validity is preserved when shorter than the local bound');
|
||||
echo "Doctor eSign enrollment: $checks checks passed (SQLite and provider doubles)\n";
|
||||
}
|
||||
@@ -112,9 +112,12 @@ esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.es
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl', 'independent v2 identity API');
|
||||
esignExpect($body['indivInfo']['sdkAccountId'] === 'sdk-account-1' && !isset($body['sdkAccountId']), 'SDK account nested in indivInfo');
|
||||
esignExpect($body['configParams']['indivUneditableInfo'] === ['name', 'certType'], 'doctor name locked');
|
||||
esignExpect($body['usageType'] === 'CERTAPPLY', 'identity requests certificate agreement and issuance for signing');
|
||||
esignExpect($body['authType'] === 'PSN_TELECOM_AUTHCODE'
|
||||
&& $body['availableAuthTypes'] === ['PSN_TELECOM_AUTHCODE'], 'embedded identity uses mobile authentication without external face apps');
|
||||
// Fixed vectors independently calculated with Python hashlib/hmac; UTF-8 bytes must match exactly.
|
||||
esignExpect($request['headers']['Content-MD5'] === 'M2hjK+7n9RSpPC8C09vWVQ==', 'POST content MD5 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'i2dGU5UsRuMb6has/RBZN5BAsECYV4ziEDF17YHaL0g=', 'POST HMACSHA256 vector');
|
||||
esignExpect($request['headers']['Content-MD5'] === 'j/xD3VTZtMlQ9HftwFK6Cg==', 'POST content MD5 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'oMBDY2WjbOSJrIhQbxtsf9EgX/iYzf6NoP60AtqGEI4=', 'POST HMACSHA256 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode');
|
||||
|
||||
@@ -128,6 +131,15 @@ $valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $c
|
||||
$responses[] = esignResponse($valid);
|
||||
$client->checkWillingness('flow-7');
|
||||
esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint');
|
||||
$responses[] = esignResponse($valid);
|
||||
esignExpect($client->willingnessExpiresAt('flow-7') === $valid['expireAt'], 'valid authorization returns its Unix millisecond expiry');
|
||||
$responses[] = esignResponse(array_replace($valid, ['remainingTimes' => 2]));
|
||||
esignExpect($client->willingnessValidity('flow-7') === [
|
||||
'state' => 'valid', 'expires_at' => $valid['expireAt'], 'remaining_times' => 2,
|
||||
], 'valid authorization exposes the provider count');
|
||||
$responses[] = esignResponse(array_replace($valid, ['status' => 0, 'remainingTimes' => 0]));
|
||||
esignExpect($client->willingnessValidity('flow-7')['state'] === 'exhausted',
|
||||
'provider returns exhausted even when the expiration is still in the future');
|
||||
foreach ([['status' => 0], ['remainingTimes' => 0], ['expireAt' => $clock()], ['status' => '1'], ['expireAt' => 'not-a-date']] as $invalid) {
|
||||
$responses[] = esignResponse(array_replace($valid, $invalid));
|
||||
esignThrows(fn () => $client->checkWillingness('flow-7'), EsignProviderException::class, 'WILLINGNESS_INVALID');
|
||||
@@ -139,6 +151,13 @@ $request = $requests[count($requests) - 1];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/account/addPerson'), 'account SDK endpoint');
|
||||
esignExpect(json_decode($request['body'], true) === ['name' => '张医生', 'idNo' => 'TEST-IDENTITY', 'idNoType' => 'MAINLAND', 'identityAuthId' => 'flow-7'], 'identity bound to SDK account');
|
||||
|
||||
$privateIdentity = '110101199001011237'; // Synthetic fixture, never sent over a network.
|
||||
$responses[] = esignResponse(['errCode' => 9001, 'msg' => 'mismatch ' . $privateIdentity, 'idNo' => $privateIdentity]);
|
||||
$before = count($requests);
|
||||
$bindingError = esignThrows(fn () => $client->createPerson('张医生', $privateIdentity, 'flow-7'), EsignProviderException::class, 'PROVIDER_9001');
|
||||
esignExpect(!str_contains($bindingError->getMessage(), $privateIdentity), 'SDK binding error cannot echo supplemental number');
|
||||
esignExpect(count($requests) === $before + 1, 'SDK binding is never automatically retried');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0, 'sealData' => base64_encode('seal-image')]);
|
||||
esignExpect($client->createSeal('person-7') === base64_encode('seal-image'), 'seal result');
|
||||
$sealBody = json_decode($requests[count($requests) - 1]['body'], true);
|
||||
@@ -157,7 +176,7 @@ esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: applica
|
||||
esignExpect($parts['streamFile']['body'] === $pdf, 'multipart preserves arbitrary binary bytes');
|
||||
$parameters = json_decode($parts['personSignParam']['body'], true);
|
||||
esignExpect($parameters['fileBean'] === ['fileName' => 'rx-7.pdf'] && !isset($parameters['fileBean']['dstPdfFile']), 'stream response requested');
|
||||
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]], 'fixed prescription signature location');
|
||||
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 520, 'posY' => 108, 'width' => 48]], 'compact first-page prescription signature');
|
||||
esignExpect($parameters['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding');
|
||||
|
||||
$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]];
|
||||
@@ -201,6 +220,14 @@ foreach ([
|
||||
}
|
||||
$responses[] = esignResponse(['errCode' => 55, 'msg' => 'secret rejected identity']);
|
||||
esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_55');
|
||||
$responses[] = esignResponse(['errCode' => 10002, 'msg' => '签署次数不足 private supplier text']);
|
||||
$beforeQuotaRejection = count($requests);
|
||||
$quotaRejection = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_10002');
|
||||
esignExpect(str_contains($quotaRejection->getMessage(), '签署次数不足') && !str_contains($quotaRejection->getMessage(), 'private'), 'signing quota provides fixed guidance without raw supplier text');
|
||||
esignExpect(count($requests) === $beforeQuotaRejection + 1, 'signing quota error sends only one request');
|
||||
$responses[] = esignResponse(['errCode' => 10002, 'msg' => 'duplicate local initialization']);
|
||||
$initializationRejection = esignThrows(fn () => $client->initialize(), EsignProviderException::class, 'PROVIDER_10002');
|
||||
esignExpect(!str_contains($initializationRejection->getMessage(), '签署次数不足'), 'initialization 10002 is not interpreted as a signing error');
|
||||
$throwing = new EsignClient(esignConfig(), static function (): array { throw new RuntimeException('https://secret:password/private'); }, $clock);
|
||||
esignThrows(fn () => $throwing->createSeal('person-7'), EsignProviderException::class, 'TRANSPORT_ERROR');
|
||||
esignThrows(fn () => $throwing->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, 'TRANSPORT_ERROR');
|
||||
@@ -225,5 +252,153 @@ $responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLin
|
||||
$production->startIdentity('医生', 'rx');
|
||||
esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 403, 'msg' => 'private supplied identity 11010519491231002X']);
|
||||
$before403 = count($requests);
|
||||
$forbidden = esignThrows(fn () => $client->createPerson('测试医生', '11010519491231002X', 'flow-403'), EsignProviderException::class, 'PROVIDER_403');
|
||||
esignExpect(str_contains($forbidden->getMessage(), '接口权限及 IP 白名单'), 'account 403 supplies fixed actionable configuration guidance');
|
||||
esignExpect(!str_contains($forbidden->getMessage(), '11010519491231002X') && !str_contains($forbidden->getMessage(), 'private'), '403 guidance never echoes provider identity data');
|
||||
esignExpect(count($requests) === $before403 + 1, 'account 403 is not automatically retried');
|
||||
esignExpect($forbidden->operation === 'createPerson' && $forbidden->reason === null, 'unknown 403 retains operation without guessing a cause');
|
||||
|
||||
$privateSuffix = ' idNo=11010519491231002X appSecret=private-secret-token name=私密测试医生';
|
||||
foreach ([
|
||||
['该应用无权调用此接口' . $privateSuffix, EsignProviderException::APPLICATION_ACCESS_DENIED, '应用的接口授权'],
|
||||
['FORBIDDEN: IP地址不在白名单' . $privateSuffix, EsignProviderException::IP_WHITELIST_MISMATCH, '出口 IP'],
|
||||
['IP 白名单校验失败' . $privateSuffix, EsignProviderException::IP_WHITELIST_MISMATCH, '出口 IP'],
|
||||
['SignatureDoesNotMatch' . $privateSuffix, EsignProviderException::SIGNATURE_MISMATCH, '签名配置'],
|
||||
['FORBIDDEN' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
['未知供应商错误' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
['IP 白名单信息' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
['NotSignatureDoesNotMatch' . $privateSuffix, null, '接口权限及 IP 白名单'],
|
||||
[['msg' => '该应用无权调用此接口' . $privateSuffix], null, '接口权限及 IP 白名单'],
|
||||
[null, null, '接口权限及 IP 白名单'],
|
||||
] as [$vendorMessage, $reason, $hint]) {
|
||||
$responses[] = esignResponse(['errCode' => 403, 'msg' => $vendorMessage, 'idNo' => $privateIdentity]);
|
||||
$before = count($requests);
|
||||
$exception = esignThrows(fn () => $client->createPerson('测试医生', 'TEST-IDENTITY', 'flow-403'), EsignProviderException::class, 'PROVIDER_403');
|
||||
esignExpect($exception->operation === 'createPerson' && $exception->reason === $reason, '403 reason is a recognized enum or null');
|
||||
esignExpect(str_contains($exception->getMessage(), $hint), '403 reason supplies only fixed guidance');
|
||||
foreach (['11010519491231002X', $privateIdentity, 'private-secret-token', '私密测试医生', '未知供应商错误'] as $privateValue) {
|
||||
esignExpect(!str_contains($exception->getMessage(), $privateValue), '403 diagnostic omits provider payload');
|
||||
}
|
||||
esignExpect(count($requests) === $before + 1, 'classified 403 never retries');
|
||||
}
|
||||
$responses[] = esignResponse(['errCode' => 9001, 'msg' => '该应用无权调用此接口' . $privateSuffix]);
|
||||
$exception = esignThrows(fn () => $client->createPerson('测试医生', 'TEST-IDENTITY', 'flow-other'), EsignProviderException::class, 'PROVIDER_9001');
|
||||
esignExpect($exception->reason === null, '403 classification does not alter other provider errors');
|
||||
$invalidReason = new EsignProviderException('createPerson', 'PROVIDER_403', $privateSuffix);
|
||||
esignExpect($invalidReason->reason === null && !str_contains($invalidReason->getMessage(), 'private-secret-token'), 'exception rejects unrecognized reason values');
|
||||
|
||||
$account = [
|
||||
'accountId' => 'person-7', 'name' => '测试医生', 'idNo' => $privateIdentity,
|
||||
'idNoType' => 'MAINLAND', 'accountType' => 'PERSON',
|
||||
];
|
||||
$responses[] = esignResponse(['errCode' => 0, 'cert' => 'cert-contents'] + $account);
|
||||
esignExpect($client->signingAccount('person-7') === $account, 'signing account returns only requested fields');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/account/queryByAccountId')
|
||||
&& json_decode($request['body'], true) === ['accountId' => 'person-7'], 'signing account SDK request');
|
||||
foreach ([['idNo' => null], ['accountId' => 'other-person']] as $invalidAccount) {
|
||||
$responses[] = esignResponse(['errCode' => 0] + $invalidAccount + $account);
|
||||
esignThrows(fn () => $client->signingAccount('person-7'), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
}
|
||||
|
||||
$certDates = ['startDate' => '2026-09-11 10:20:30', 'endDate' => '2027-09-11 10:20:30'];
|
||||
$responses[] = esignResponse(['errCode' => 0, 'sn' => 'cert-serial', 'owner' => '测试医生'] + $certDates);
|
||||
esignExpect($client->certificateValidity('person-7') === $certDates, 'certificate validity retains provider dates only');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/user/cert/queryLatestAvailableCert')
|
||||
&& json_decode($request['body'], true) === ['accountId' => 'person-7'], 'certificate validity SDK request');
|
||||
$responses[] = esignResponse(['errCode' => 0, 'startDate' => $certDates['startDate']]);
|
||||
esignThrows(fn () => $client->certificateValidity('person-7'), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
|
||||
$doctorIdentity = ['flowId' => 'doctor-enrollment-1', 'shortLink' => 'https://smlt.esign.cn/enrollment'];
|
||||
foreach ([null, 'person-7'] as $accountId) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => $doctorIdentity]);
|
||||
esignExpect($client->startDoctorIdentity('测试医生', 'doctor-context', '13800138000', $accountId)
|
||||
=== ['flow_id' => 'doctor-enrollment-1', 'auth_url' => $doctorIdentity['shortLink']], 'doctor enrollment returns hosted URL');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
$body = json_decode($request['body'], true);
|
||||
$person = ['name' => '测试医生', 'certType' => 'INDIVIDUAL_CH_IDCARD', 'authMobileNo' => '13800138000'];
|
||||
if ($accountId !== null) {
|
||||
$person['sdkAccountId'] = $accountId;
|
||||
}
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl'
|
||||
&& $body === [
|
||||
'indivInfo' => $person,
|
||||
'usageType' => 'CERTAPPLY',
|
||||
'authType' => 'PSN_FACEAUTH_BYURL_ZHIMA',
|
||||
'availableAuthTypes' => ['PSN_FACEAUTH_BYURL_ZHIMA'],
|
||||
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
|
||||
'contextInfo' => ['contextId' => 'doctor-context', 'showResultPage' => true],
|
||||
], 'enrollment requests certificate and authorizes mobile through Alipay face authentication');
|
||||
}
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'enrollment', 'shortLink' => 'https://attacker.invalid/enrollment']]);
|
||||
esignThrows(fn () => $client->startDoctorIdentity('测试医生', 'ctx', '13800138000'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'quick-auth', 'shortLink' => 'https://smlt.esign.cn/quick']]);
|
||||
esignExpect($client->startDoctorQuickAuthorization('测试医生', $privateIdentity, 'doctor-quicksign-ctx', 'person-7')
|
||||
=== ['flow_id' => 'quick-auth', 'auth_url' => 'https://smlt.esign.cn/quick'], 'quickface authorization result stays limited to a flow and hosted URL');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
$body = json_decode($request['body'], true);
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl'
|
||||
&& $body['indivInfo'] === ['name' => '测试医生', 'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => $privateIdentity, 'sdkAccountId' => 'person-7']
|
||||
&& $body['usageType'] === 'PUREVERIFY'
|
||||
&& $body['availableAuthTypes'] === ['PSN_FACEAUTH_BYURL_ZHIMA']
|
||||
&& $body['configParams']['indivUneditableInfo'] === ['name', 'certType', 'certNo']
|
||||
&& $body['contextInfo']['contextId'] === 'doctor-quicksign-ctx', 'quick-sign face flow locks the bound identity and asks for no SMS credentials');
|
||||
|
||||
$willingnessEndpoint = 'https://smlopenapi.esign.cn/v2/identity/willingness/api/individual';
|
||||
$doctorInfo = ['name' => '测试医生', 'idNo' => $privateIdentity, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['mobileNo' => '13800138000']]);
|
||||
esignExpect($client->authorizedMobile('测试医生', $privateIdentity) === '13800138000', 'authorized phone returned as text');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/get-individual-info'
|
||||
&& json_decode($request['body'], true) === $doctorInfo, 'authorized phone read-only request');
|
||||
foreach ([null, ['mobileNo' => null], ['mobileNo' => '']] as $unbound) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => $unbound]);
|
||||
esignExpect($client->authorizedMobile('测试医生', $privateIdentity) === null, 'provider returned no phone binding');
|
||||
}
|
||||
foreach (['unexpected', ['mobileNo' => '138****8000'], ['mobileNo' => 13800138000]] as $malformed) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => $malformed]);
|
||||
esignThrows(fn () => $client->authorizedMobile('测试医生', $privateIdentity), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
}
|
||||
|
||||
foreach (['sms-flow-1', 'sms-flow-2'] as $smsFlow) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => $smsFlow]]);
|
||||
esignExpect($client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000') === $smsFlow, 'new willingness flow from provider');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/send-code'
|
||||
&& json_decode($request['body'], true) === ['mobileNo' => '13800138000'] + $doctorInfo,
|
||||
'SMS request for the authorized user');
|
||||
}
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => null]);
|
||||
esignThrows(fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000'), EsignProviderException::class, 'RESPONSE_INVALID');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => null]);
|
||||
$client->verifyWillingnessCode('sms/flow', '000123');
|
||||
$request = $requests[array_key_last($requests)];
|
||||
esignExpect($request['method'] === 'POST' && $request['url'] === $willingnessEndpoint . '/sms%2Fflow/verify-send-code'
|
||||
&& json_decode($request['body'], true) === ['authCode' => '000123'], 'verification preserves leading zeroes and encodes the flow path');
|
||||
|
||||
$before = count($requests);
|
||||
esignThrows(fn () => $client->startDoctorIdentity('测试医生', 'ctx', '138****8000'), EsignProviderException::class, 'INPUT_INVALID');
|
||||
esignThrows(fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '+8613800138000'), EsignProviderException::class, 'INPUT_INVALID');
|
||||
esignThrows(fn () => $client->verifyWillingnessCode('sms-flow-1', '12345'), EsignProviderException::class, 'INPUT_INVALID');
|
||||
esignExpect(count($requests) === $before, 'invalid phone and code are rejected before provider requests');
|
||||
|
||||
foreach ([
|
||||
['authorizedMobile', fn () => $client->authorizedMobile('测试医生', $privateIdentity), 30500101],
|
||||
['sendWillingnessCode', fn () => $client->sendWillingnessCode('测试医生', $privateIdentity, '13800138000'), 30500101],
|
||||
['verifyWillingnessCode', fn () => $client->verifyWillingnessCode('sms-flow-1', '000123'), 30503002],
|
||||
] as [$operation, $call, $code]) {
|
||||
$responses[] = esignResponse(['code' => $code, 'message' => 'private ' . $privateIdentity . ' 13800138000 000123', 'data' => ['idNo' => $privateIdentity]]);
|
||||
$before = count($requests);
|
||||
$exception = esignThrows($call, EsignProviderException::class, 'PROVIDER_' . $code);
|
||||
esignExpect($exception->operation === $operation && count($requests) === $before + 1, 'provider errors preserve operation without retries');
|
||||
foreach ([$privateIdentity, '13800138000', '000123', 'private'] as $secret) {
|
||||
esignExpect(!str_contains($exception->getMessage(), $secret), 'provider errors omit sensitive payloads');
|
||||
}
|
||||
}
|
||||
|
||||
esignExpect($responses === [], 'all expected transport responses consumed');
|
||||
echo 'EsignClient: ' . $checks . " checks passed (offline)\n";
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
final class PrescriptionEsignService
|
||||
{
|
||||
public static array $calls = [];
|
||||
public static array $starts = [];
|
||||
public static array $verifications = [];
|
||||
public static function start(int $id, int $actor, array $info, bool $restartIdentity = false): array
|
||||
{
|
||||
self::$starts[] = [$id, $actor, $info, $restartIdentity];
|
||||
return ['status' => 'authenticating'];
|
||||
}
|
||||
public static function complete(int $id, int $actor, array $info, string $identityNumber = '', bool $verifyOnly = false): array
|
||||
{
|
||||
self::$calls[] = [$id, $actor, $info, $identityNumber, $verifyOnly];
|
||||
return ['status' => 'signed'];
|
||||
}
|
||||
public static function verifyWillingness(int $id, int $actor, array $info, string $code): array
|
||||
{
|
||||
self::$verifications[] = [$id, $actor, $info, $code];
|
||||
return ['status' => 'authenticating'];
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace app\common\model {
|
||||
class OperationLog
|
||||
{
|
||||
public array $fields = [];
|
||||
public static array $saved = [];
|
||||
public function __set(string $key, $value): void { $this->fields[$key] = $value; }
|
||||
public function save(): bool { self::$saved[] = $this->fields; return true; }
|
||||
}
|
||||
}
|
||||
namespace app\adminapi\controller {
|
||||
class BaseAdminController
|
||||
{
|
||||
public $request;
|
||||
public int $adminId = 7;
|
||||
public array $adminInfo = ['admin_id' => 7, 'name' => '测试医师'];
|
||||
public function isNotNeedLogin(): bool { return false; }
|
||||
protected function data(array $data): array { return ['code' => 1, 'data' => $data]; }
|
||||
protected function fail(string $message): array { return ['code' => 0, 'msg' => $message]; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
$app = new think\App(); // No initialize, environment, real DB, credentials or network.
|
||||
$checks = 0;
|
||||
$expect = static function (bool $condition, string $label) use (&$checks): void {
|
||||
if (!$condition) { throw new RuntimeException($label); }
|
||||
++$checks;
|
||||
};
|
||||
$number = '110101199001011237';
|
||||
$controller = new app\adminapi\controller\tcm\PrescriptionController();
|
||||
$request = (new app\Request())->withServer(['REQUEST_METHOD' => 'POST'])->setMethod('POST')->setController('tcm.Prescription')->setAction('esignComplete')
|
||||
->setUrl('/adminapi/tcm.prescription/esignComplete?identity_number=' . $number)
|
||||
->withPost(['id' => 41, 'identity_number' => $number, 'extra' => ['identity_number' => $number]]);
|
||||
$request->controllerObject = $controller;
|
||||
$request->adminInfo = $controller->adminInfo;
|
||||
$controller->request = $request;
|
||||
$result = $controller->esignComplete();
|
||||
$calls = app\common\service\esign\PrescriptionEsignService::$calls;
|
||||
$expect($result['code'] === 1 && $calls[0] === [41, 7, $controller->adminInfo, $number, false], 'POST input forwarded only to current authenticated doctor service');
|
||||
$expect(!str_contains(json_encode($result), $number), 'controller response has no supplemental input');
|
||||
|
||||
think\Container::getInstance()->instance('request', $request);
|
||||
$response = new class($result) {
|
||||
public function __construct(private array $result) {}
|
||||
public function getContent(): string { return json_encode($this->result); }
|
||||
};
|
||||
(new app\adminapi\listener\OperationLog())->handle($response);
|
||||
$audit = app\common\model\OperationLog::$saved[0];
|
||||
$expect(json_decode($audit['params'], true) === ['id' => 41], 'operation audit allowlists prescription id only, including nested malicious inputs');
|
||||
$expect(!str_contains(json_encode($audit), $number) && !str_contains($audit['url'], '?'), 'operation audit removes submitted identity and URL query');
|
||||
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 41, 'identity_number' => [$number]]);
|
||||
$expect($controller->esignComplete()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$calls) === 1, 'array identity input rejected without invoking completion');
|
||||
$controller->request = (new app\Request())->setMethod('GET')->withGet(['id' => 41, 'identity_number' => $number]);
|
||||
$expect($controller->esignComplete()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$calls) === 1, 'GET never performs completion');
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42]);
|
||||
$expect($controller->esignComplete()['code'] === 1 && app\common\service\esign\PrescriptionEsignService::$calls[1][3] === '', 'existing complete callers keep optional input compatibility');
|
||||
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'verify_only' => true]);
|
||||
$expect($controller->esignComplete()['code'] === 1 && app\common\service\esign\PrescriptionEsignService::$calls[2][4] === true, 'explicit archive verification flag forwarded');
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'restart_identity' => true]);
|
||||
$expect($controller->esignStart()['code'] === 1 && app\common\service\esign\PrescriptionEsignService::$starts[0][3] === true, 'explicit replacement flag forwarded');
|
||||
foreach ([null, 'true', 'false', 1, [], ['true']] as $invalid) {
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'verify_only' => $invalid, 'restart_identity' => $invalid]);
|
||||
$expect($controller->esignComplete()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$calls) === 3, 'invalid archive verification flag cannot fall through to signing');
|
||||
$expect($controller->esignStart()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$starts) === 1, 'invalid replacement flag cannot change identity flow');
|
||||
}
|
||||
|
||||
$code = '023941';
|
||||
$mobile = '13800000000';
|
||||
$authUrl = 'https://smlt.esign.cn/example/private-auth-url';
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'auth_code' => $code, 'doctor_id' => 41]);
|
||||
$expect($controller->esignVerifyWillingness()['code'] === 1
|
||||
&& app\common\service\esign\PrescriptionEsignService::$verifications === [[42, 7, $controller->adminInfo, $code]], 'OTP verifies only for current authenticated actor; leading zero preserved');
|
||||
$controller->request = (new app\Request())->setMethod('GET')->withGet(['id' => 42, 'auth_code' => $code]);
|
||||
$expect($controller->esignVerifyWillingness()['code'] === 0, 'GET cannot submit an OTP');
|
||||
foreach (['esignVerifyWillingness', 'esignDoctorStart', 'esignDoctorComplete', 'esignDoctorStatus', 'detail'] as $action) {
|
||||
$privacyRequest = (new app\Request())->setMethod('POST')->setController('tcm.Prescription')->setAction($action)
|
||||
->setUrl('/adminapi/tcm.prescription/' . $action . '?mobile=' . $mobile);
|
||||
if ($action !== 'detail') {
|
||||
$privacyRequest->withPost(['id' => 42, 'mobile' => $mobile, 'identity_number' => $number, 'auth_code' => $code]);
|
||||
}
|
||||
$privacyRequest->controllerObject = $controller;
|
||||
$privacyRequest->adminInfo = $controller->adminInfo;
|
||||
think\Container::getInstance()->instance('request', $privacyRequest);
|
||||
$privacyResponse = new class($authUrl) {
|
||||
public function __construct(private string $url) {}
|
||||
public function getContent(): string { return json_encode(['code' => 1, 'data' => ['status' => 'authenticating', 'auth_url' => $this->url]]); }
|
||||
};
|
||||
if ($action === 'detail') {
|
||||
$privacyRequest->setUrl('/adminapi/tcm.prescription/detail');
|
||||
}
|
||||
(new app\adminapi\listener\OperationLog())->handle($privacyResponse);
|
||||
$audit = end(app\common\model\OperationLog::$saved);
|
||||
$entry = json_encode($audit);
|
||||
$expect(!str_contains($entry, $mobile) && !str_contains($entry, $number) && !str_contains($entry, $code)
|
||||
&& !str_contains($audit['result'], 'private-auth-url'), "$action audit omits signing secrets and authorization URL");
|
||||
}
|
||||
echo "eSign identity controller/privacy: $checks checks passed (isolated doubles, no DB/network)\n";
|
||||
}
|
||||
@@ -426,7 +426,7 @@ try {
|
||||
$expect($blankBatch['trigger_type'] === 'blank_to_manual' && (int) $blankBatch['patient_id'] === 100, 'blank hook carries authoritative binding');
|
||||
$expect(\app\adminapi\logic\tcm\PrescriptionLogic::edit($editParams, 1), 'same edit can replay');
|
||||
$expect((int) Db::name('prescription_ai_batch')->where('prescription_id', $blank['id'])->count() === 1, 'same edit does not generate twice');
|
||||
$expect(\app\adminapi\logic\tcm\PrescriptionLogic::void((int) $blank['id'], 1, 'Test'), 'real void hook succeeds');
|
||||
$expect(\app\adminapi\logic\tcm\PrescriptionLogic::void((int) $blank['id'], 1, $root), 'real void hook succeeds');
|
||||
$expect(Db::name('prescription_ai_batch')->where('id', $blankBatch['id'])->value('validity') === 'voided', 'real void hook invalidates');
|
||||
$addParams = ['request_key' => 'add-request-1234567890123456', 'diagnosis_id' => 0, 'patient_id' => 100,
|
||||
'patient_name' => 'fixture', 'gender' => 1, 'age' => 50, 'clinical_diagnosis' => 'fixture',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -42,6 +42,7 @@ try {
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
|
||||
id INT UNSIGNED PRIMARY KEY,creator_id INT,doctor_name VARCHAR(100),patient_name VARCHAR(100),phone VARCHAR(30),gender INT,
|
||||
audit_status INT DEFAULT 0,void_status INT DEFAULT 0,delete_time INT NULL,update_time INT DEFAULT 0,
|
||||
void_time INT NULL,void_by INT NULL,void_by_name VARCHAR(100),
|
||||
is_system_auto INT DEFAULT 0,herbs TEXT,clinical_diagnosis TEXT
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name) VALUES (1,1,'测试医师')");
|
||||
@@ -54,6 +55,15 @@ try {
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY,prescription_order_id INT,source_revision INT,status VARCHAR(40))');
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 1, 'order_no' => 'TEST-ESIGN', 'prescription_id' => 2, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 2, 'order_no' => 'TEST-LEGACY-PENDING', 'prescription_id' => 1, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
$expect(PrescriptionLogic::audit(1, 'approve', '', 1, $root) === false, 'unmarked pending prescription requires signature after enablement');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(2, 'approve', '', 1, $root) === false, 'order audit also gates an unmarked pending prescription');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 2, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false,
|
||||
'manual order status cannot bypass a required signature on an unmarked draft');
|
||||
$expect(Db::name('tcm_prescription')->find(1) === $row, 'approval attempts do not enroll or modify an unsigned prescription');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,audit_status) VALUES (3,1,'测试医师',1)");
|
||||
PrescriptionEsignService::assertSignedById(3);
|
||||
$expect(PrescriptionEsignService::describe(Db::name('tcm_prescription')->find(3), 1)['status'] === 'legacy', 'previously approved historical prescription remains on record');
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual audit explains signature requirement');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false, 'order audit rejects unsigned before write');
|
||||
@@ -112,6 +122,14 @@ try {
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'order audit reaches locked write');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual status change reaches locked write');
|
||||
$expect($events->attempts === 3 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
\think\Model::setEvent(null);
|
||||
Db::name('tcm_prescription_order')->where('id', 1)->update(['fulfillment_status' => 4]);
|
||||
$pdo->exec("INSERT INTO zyt_pharmacy_submission_claim VALUES (1, 1, 1, 'FAILED'), (2, 1, 2, 'PENDING')");
|
||||
$expect(!PrescriptionLogic::void(2, 1, $root) && str_contains(PrescriptionLogic::getError(), '提交药房'),
|
||||
'void locks and checks the latest pharmacy claim on a released order');
|
||||
Db::name('pharmacy_submission_claim')->where('id', 2)->update(['status' => 'FAILED']);
|
||||
$expect(PrescriptionLogic::void(2, 1, $root), 'void succeeds when the released order has no active claim');
|
||||
$expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf), 'void preserves downloadable signed evidence');
|
||||
echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n";
|
||||
} finally {
|
||||
\think\Model::setEvent(null);
|
||||
|
||||
Reference in New Issue
Block a user