Files
zyt/server/app/common/service/esign/PrescriptionReviewEsignService.php
T
2026-11-26 15:46:20 +08:00

494 lines
27 KiB
PHP

<?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
{
$managed = PrescriptionCaSigningSettings::override();
return $managed ?? (PrescriptionEsignService::enabled()
&& filter_var(Config::get('esign.review_enabled', false), FILTER_VALIDATE_BOOLEAN));
}
/** Recheck the live personnel record and grants, including for an existing binding. */
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, bool $orderApproval = false): 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) {
if ($orderApproval) {
if (!self::canSubmitOrderAudit(self::reviewerAccess($actor))) {
throw new DomainException('当前账号没有业务订单处方审核权限');
}
} elseif ($actor !== (int) $review['reviewer_id'] || !self::canEnrollReviewer($actor)) {
throw new DomainException('请由已签署此处方且仍有审核权限的审核人本人提交审核');
}
}
PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
}
private static function canSubmitOrderAudit(array $admin): bool
{
return $admin && PrescriptionOrderLogic::canAuditPrescriptionOrder($admin)
&& self::hasGrant($admin, [self::ORDER_PERMISSION]);
}
private static function hasVerifiedReview(array $doctor, ?array $review): bool
{
return self::matchesDoctor($doctor, $review) && $review['state'] === 'signed'
&& $review['sign_service_id'] !== '' && $review['signed_hash'] !== ''
&& (int) $review['signature_time'] > 0
&& (int) $review['signature_time'] >= (int) $doctor['signature_time'];
}
private static function matchesDoctor(array $doctor, ?array $review): bool
{
return $review && $doctor['signed_hash'] !== '' && (int) $review['reviewer_id'] > 0
&& (int) $review['reviewer_id'] !== (int) $doctor['doctor_id']
&& $review['account_id'] !== '' && $review['account_id'] !== $doctor['account_id']
&& $review['environment'] === $doctor['environment'] && $review['app_id'] === $doctor['app_id']
&& hash_equals($doctor['signed_hash'], $review['doctor_pdf_hash']);
}
public static function describe(?array $doctor, ?array $prescription = null): array
{
$required = !empty($doctor['review_required']);
$review = $required ? self::review((int) $doctor['prescription_id']) : null;
$verified = $doctor && self::hasVerifiedReview($doctor, $review);
$result = $prescription === null ? [] : ['signing_log' => self::signingLog($prescription, $doctor, $review, $verified)];
if ($required) {
$state = $review['state'] ?? 'pending';
$result['review_state'] = match (true) {
$verified => 'signed',
$review === null => 'pending',
!self::matchesDoctor($doctor, $review) => 'uncertain',
in_array($state, ['pending', 'failed', 'uncertain'], true) => $state,
in_array($state, ['signing', 'verifying'], true)
&& time() - (int) $review['update_time'] < self::VERIFY_LEASE_SECONDS => $state,
default => 'uncertain',
};
}
if (!$verified) {
return $result;
}
$result += ['review_signer_name' => $review['signer_name'], 'review_signature_time' => (int) $review['signature_time']];
if ($prescription !== null && ($seal = self::reviewSeal($doctor, $review)) !== null) {
$result['review_signature'] = 'data:image/png;base64,' . base64_encode($seal);
}
return $result;
}
/** Project the archived milestones and the latest persisted exception. */
private static function signingLog(array $prescription, ?array $doctor, ?array $review, bool $verifiedReview): array
{
if (!$doctor) {
return [];
}
$events = [];
$add = static function (string $event, string $label, int $time, string $actor = '', string $source = 'system') use (&$events): void {
if ($time > 0) {
$events[] = ['event' => $event, 'label' => $label, 'time' => $time, 'source' => $source]
+ ($actor === '' ? [] : ['actor_name' => $actor]);
}
};
$doctorName = (string) (($doctor['signer_name'] ?? '') ?: ($prescription['doctor_name'] ?? ''));
$add('doctor_flow_created', '医师签署流程建立', (int) ($doctor['create_time'] ?? 0), $doctorName);
$add('issued', '开具确认', (int) ($doctor['issued_at'] ?? 0), $doctorName);
$verifiedAt = (int) ($doctor['signed_at'] ?? 0);
if ($verifiedAt > 0 && !empty($doctor['signed_path'])) {
$source = (string) ($doctor['signature_time_source'] ?? '');
if (in_array($source, ['tsa', 'local'], true)) {
$add('doctor_signed', '医师签署', (int) ($doctor['signature_time'] ?? 0), $doctorName, $source);
}
$add('doctor_verified', '医师签章验签通过', $verifiedAt);
}
$state = (string) ($prescription['esign_status'] ?? '');
if (in_array($state, ['failed', 'uncertain'], true)) {
$add('doctor_' . $state, $state === 'failed' ? '医师签署未完成' : '医师签署结果待核实',
(int) ($doctor['update_time'] ?? 0), $doctorName);
}
if (self::matchesDoctor($doctor, $review)) {
$reviewer = (string) ($review['signer_name'] ?? '');
$add('review_confirmed', '药师确认签署', (int) $review['confirmed_at'], $reviewer);
if ($verifiedReview) {
$add('review_signed', '药师签署', (int) $review['signature_time'], $reviewer, 'tsa');
$add('review_verified', '药师签章验签通过', (int) $review['update_time']);
} elseif (in_array($review['state'], ['failed', 'uncertain'], true)) {
$add('review_' . $review['state'], $review['state'] === 'failed' ? '药师签署未完成' : '药师签署结果待核实',
(int) $review['update_time'], $reviewer);
}
}
$auditState = (int) ($prescription['audit_status'] ?? 0);
if ($auditState === 1 || $auditState === 2) {
$add($auditState === 1 ? 'audit_approved' : 'audit_rejected', $auditState === 1 ? '处方审核通过' : '处方审核驳回',
(int) ($prescription['audit_time'] ?? 0), (string) ($prescription['audit_by_name'] ?? ''));
}
if (!empty($prescription['void_status'])) {
$add('voided', '处方作废', (int) ($prescription['void_time'] ?? 0), (string) ($prescription['void_by_name'] ?? ''));
}
usort($events, static fn (array $left, array $right): int => $left['time'] <=> $right['time']);
return $events;
}
private static function sealPath(array $doctor, array $review): string
{
return $doctor['prescription_id'] . '-' . $doctor['snapshot_hash'] . '/review-seal-' . $review['signed_hash'] . '.png';
}
/** Preview the exact seal from a verified signature. Existing archives need no re-signing. */
private static function reviewSeal(array $doctor, array $review): ?string
{
try {
$path = self::sealPath($doctor, $review);
$cached = PrescriptionEsignService::readReviewSeal($path);
if ($cached !== null || !PrescriptionEsignService::matchesEnvironment($doctor)) {
return $cached;
}
$source = PrescriptionEsignService::readPdf($doctor['signed_path'], $doctor['signed_hash']);
$pdf = PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash']);
$signature = self::verifiedReviewSignature($source, $pdf, (new EsignClient())->verifyPdf($pdf), $doctor, $review);
if ($signature['time'] === (int) $review['signature_time']) {
return self::cacheSeal($path, $signature['seal']);
}
} catch (\Throwable) {
// The archived PDF and verified time are still available if the preview cannot be loaded.
}
return null;
}
private static function cacheSeal(string $path, string $seal): ?string
{
$png = base64_decode($seal, true);
if ($png === false || $png === '') {
return null;
}
try {
PrescriptionEsignService::writeReviewSeal($path, $png);
} catch (\Throwable) {
return null;
}
return $png;
}
public static function download(array $doctor): ?array
{
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($doctor['review_required']) || (self::enabled()
&& PrescriptionEsignService::requiresSignature($row, PrescriptionEsignService::enabled()));
$review = $required && !empty($doctor['review_required']) ? self::review($id) : null;
$pending = empty($row['void_status']) && ($order
? (int) $order->prescription_audit_status === 0 && !in_array((int) $order->fulfillment_status, [3, 4], true)
: (int) $row['audit_status'] === 0);
$reviewReady = PrescriptionEsignService::canReview($row, $doctor);
$reviewer = $required && $pending && $reviewReady ? self::reviewerAccess($actor) : [];
return ['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required,
'review_ready' => $reviewReady,
'can_audit' => $order ? self::canSubmitOrderAudit($reviewer)
: ($reviewer && self::hasGrant($reviewer, PrescriptionLogic::AUDIT_PERMISSIONS)),
'order_audit' => $order !== null,
'reviewer' => $reviewer];
}
private static function describeContext(array $context, int $actor): array
{
['row' => $row, 'doctor' => $doctor, 'review' => $review, 'required' => $required, 'can_audit' => $canAudit,
'review_ready' => $reviewReady,
'order_audit' => $orderAudit, 'reviewer' => $reviewer] = $context;
$differentPerson = $actor !== (int) $row['creator_id'];
$signed = $doctor && self::hasVerifiedReview($doctor, $review);
$own = (int) ($review['reviewer_id'] ?? 0) === $actor;
$active = $doctor && PrescriptionEsignService::matchesEnvironment($doctor);
$state = (string) ($review['state'] ?? 'pending');
$canApprove = $signed && $canAudit && ($orderAudit || $own) && ($row['esign_status'] ?? '') === 'signed';
$canSetup = !$signed && $canAudit && $differentPerson && (!$doctor || $active) && self::enabled()
&& DoctorEsignIdentityService::quickEnabled();
$canWork = $canSetup && $active && ($row['esign_status'] ?? '') === 'signed';
$account = $canSetup ? PrescriptionEsignService::account($actor) : null;
$stale = time() - (int) ($review['update_time'] ?? 0) >= self::VERIFY_LEASE_SECONDS;
$canRetry = $canAudit && $own && $active && PrescriptionEsignService::enabled() && !empty($review['signed_hash'])
&& ($state === 'uncertain' || (in_array($state, ['signing', 'verifying'], true) && $stale));
$message = match (true) {
PrescriptionEsignPolicy::isAwaitingUpload($row) => '请开方医生先上传处方,再进行审核。',
PrescriptionEsignPolicy::isPendingReview($row) && !$reviewReady => '请开方医生完成有效电子签署后再进行审核。',
!$required => '',
$canApprove => '医师和药师签章均已验签,可以提交审核通过。',
$signed && ($orderAudit || $own) => '当前账号或处方状态不允许提交审核。',
$signed => '请由已签署此处方的审核人本人提交审核。',
!$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' => $reviewReady && (!$required || $canApprove),
'can_setup' => $canSetup,
'actor_id' => $actor, 'actor_name' => (string) ($account['doctor_name'] ?? $reviewer['name'] ?? ''),
'signer_name' => $signed ? $review['signer_name'] : '',
'signature_time' => $signed ? (int) $review['signature_time'] : 0,
'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);
$work['signed_hash'] = hash('sha256', $dual);
self::save($id, $token, ['signed_hash' => $work['signed_hash'], 'state' => 'verifying']);
}
$signature = self::verifiedReviewSignature($source, $dual, $client->verifyPdf($dual), $doctor, $work);
self::cacheSeal(self::sealPath($doctor, $work), $signature['seal']);
self::save($id, $token, ['state' => 'signed', 'signature_time' => $signature['time'], 'error_message' => '']);
} catch (\Throwable $error) {
$definiteRejection = !$received && $error instanceof EsignProviderException && !($error instanceof EsignOutcomeUnknownException);
$details = $definiteRejection || $error instanceof DomainException ? $error->getMessage()
: '审核签署结果待核实,请刷新状态或重试验签';
$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
{
return self::verifiedReviewSignature($source, $dual, $verified, $doctor, $proof)['time'];
}
/** @return array{time:int,seal:string} */
private static function verifiedReviewSignature(string $source, string $dual, array $verified, array $doctor, array $proof): array
{
if (strlen($dual) <= strlen($source) || !str_starts_with($dual, $source)) {
throw new DomainException('双签原件未保留医生已签的原始文档,请联系管理员');
}
$entries = $verified['signatures'] ?? [];
if (count($entries) !== 2) {
throw new DomainException('双签原件须包含两枚有效签章');
}
[$first, $second] = array_map([self::class, 'signature'], $entries);
$originalIndex = $first['key'] === $proof['doctor_signature'] ? 0 : 1;
[$original, $review] = $originalIndex === 0 ? [$first, $second] : [$second, $first];
if ($original['key'] !== $proof['doctor_signature'] || $original['field'] === $review['field']
|| $original['certificate'] === $review['certificate']
|| $review['certificate'] !== $proof['reviewer_certificate'] || $review['name'] !== $proof['signer_name']
|| $review['time'] < max((int) $doctor['issued_at'], $original['time'])) {
throw new DomainException('医生与审核人签章、证书或时间顺序未通过核验');
}
$seal = $entries[1 - $originalIndex]['sealData'] ?? null;
return ['time' => $review['time'], 'seal' => is_string($seal) ? $seal : ''];
}
}