This commit is contained in:
Your Name
2026-11-20 10:30:04 +08:00
parent 378bf32069
commit 0dc41a1507
96 changed files with 13497 additions and 791 deletions
+295
View File
@@ -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";
}
+178 -3
View File
@@ -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";
+127
View File
@@ -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";
}
+1 -1
View File
@@ -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);