i更新
This commit is contained in:
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Isolated adapter tests: no ThinkPHP bootstrap, credentials, database or network.
|
||||
require_once dirname(__DIR__) . '/app/common/service/esign/EsignClient.php';
|
||||
|
||||
use app\common\service\esign\EsignClient;
|
||||
use app\common\service\esign\EsignOutcomeUnknownException;
|
||||
use app\common\service\esign\EsignProviderException;
|
||||
|
||||
$checks = 0;
|
||||
function esignExpect(bool $condition, string $label): void
|
||||
{
|
||||
global $checks;
|
||||
++$checks;
|
||||
if (!$condition) {
|
||||
throw new RuntimeException('FAIL: ' . $label);
|
||||
}
|
||||
}
|
||||
|
||||
function esignThrows(callable $call, string $class, string $code): EsignProviderException
|
||||
{
|
||||
try {
|
||||
$call();
|
||||
} catch (EsignProviderException $exception) {
|
||||
esignExpect(get_class($exception) === $class, 'exception type ' . $code);
|
||||
esignExpect($exception->providerCode === $code, 'exception code ' . $code);
|
||||
esignExpect($exception->getPrevious() === null, 'no sensitive previous exception');
|
||||
return $exception;
|
||||
}
|
||||
throw new RuntimeException('Expected exception: ' . $code);
|
||||
}
|
||||
|
||||
function esignConfig(array $overrides = []): array
|
||||
{
|
||||
return array_replace([
|
||||
'enabled' => true, 'environment' => 'sandbox', 'app_id' => 'test-app', 'app_secret' => 'test-secret',
|
||||
'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service', 'timeout' => 45,
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
function esignResponse(array $data, int $status = 200): array
|
||||
{
|
||||
return ['status' => $status, 'body' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
|
||||
}
|
||||
|
||||
/** @return array<string,array{headers:string,body:string}> */
|
||||
function esignMultipartParts(array $request): array
|
||||
{
|
||||
$contentType = $request['headers']['Content-Type'];
|
||||
esignExpect(str_starts_with($contentType, 'multipart/form-data; boundary='), 'multipart envelope');
|
||||
$boundary = substr($contentType, strlen('multipart/form-data; boundary='));
|
||||
$parts = [];
|
||||
foreach (explode('--' . $boundary, $request['body']) as $part) {
|
||||
if (!str_contains($part, "\r\n\r\n")) {
|
||||
continue;
|
||||
}
|
||||
[$headers, $body] = explode("\r\n\r\n", ltrim($part, "\r\n"), 2);
|
||||
preg_match('/name="([^"]+)"/', $headers, $matches);
|
||||
$parts[$matches[1]] = ['headers' => $headers, 'body' => substr($body, 0, -2)];
|
||||
}
|
||||
return $parts;
|
||||
}
|
||||
|
||||
$requests = [];
|
||||
$responses = [];
|
||||
$transport = static function (array $request) use (&$requests, &$responses): array {
|
||||
$requests[] = $request;
|
||||
if ($responses === []) {
|
||||
throw new RuntimeException('No fake response');
|
||||
}
|
||||
return array_shift($responses);
|
||||
};
|
||||
$clock = static fn (): int => 1800000000000;
|
||||
$client = new EsignClient(esignConfig(), $transport, $clock);
|
||||
esignExpect($client->isEnabled() && $client->environment() === 'sandbox', 'configured environment');
|
||||
$client->assertConfigured();
|
||||
|
||||
foreach ([
|
||||
[['enabled' => 'false'], 'DISABLED'],
|
||||
[['environment' => 'prod'], 'ENVIRONMENT_INVALID'],
|
||||
[['app_secret' => ''], 'CREDENTIALS_MISSING'],
|
||||
[['app_id' => "app\r\nInjected:yes"], 'CREDENTIALS_MISSING'],
|
||||
[['timeout' => 0], 'TIMEOUT_INVALID'],
|
||||
[['timeout' => 301], 'TIMEOUT_INVALID'],
|
||||
[['sdk_url' => 'http://example.com/paas-sdk-service'], 'SDK_HTTP_REQUIRES_PRIVATE_HOST'],
|
||||
[['sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service?x=1'], 'SDK_URL_INVALID'],
|
||||
[['sdk_url' => 'https://user:pass@example.com/paas-sdk-service'], 'SDK_URL_INVALID'],
|
||||
[['sdk_url' => 'file:///tmp/paas-sdk-service'], 'SDK_URL_INVALID'],
|
||||
] as [$config, $code]) {
|
||||
esignThrows(fn () => (new EsignClient(esignConfig($config), $transport, $clock))->assertConfigured(), EsignProviderException::class, $code);
|
||||
}
|
||||
esignExpect($requests === [], 'configuration failures issue no request');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0]);
|
||||
$client->initialize();
|
||||
$init = json_decode($requests[0]['body'], true);
|
||||
esignExpect($requests[0]['url'] === 'http://127.0.0.1:8091/paas-sdk-service/timevale/init', 'SDK init endpoint');
|
||||
esignExpect($init['projectConfig'] === [
|
||||
'projectId' => 'test-app', 'projectSecret' => 'test-secret',
|
||||
'itsmApiUrl' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
|
||||
], 'sandbox initialization parameters');
|
||||
esignExpect($init['httpConfig'] === ['httpType' => 'HTTPS', 'retry' => 0], 'SDK internal retry disabled');
|
||||
esignExpect($init['signConfig']['algorithm'] === 'HMACSHA256', 'SDK algorithm');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'shortLink' => 'https://smlt.esign.cn/identity7']]);
|
||||
$identity = $client->startIdentity('张医生', 'rx-7', 'sdk-account-1');
|
||||
$request = $requests[count($requests) - 1];
|
||||
$body = json_decode($request['body'], true);
|
||||
esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.esign.cn/identity7'], 'identity result');
|
||||
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');
|
||||
// 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']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'status' => 'SUCCESS']]);
|
||||
esignExpect($client->identityDetail('flow-7')['status'] === 'SUCCESS', 'identity official data returned');
|
||||
$request = $requests[count($requests) - 1];
|
||||
esignExpect($request['method'] === 'GET' && $request['body'] === '' && !isset($request['headers']['Content-MD5']), 'GET no body MD5');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'wPILAWFFD+SOKXrMxguRUqiG1Iwl+k/X9O9Fukf7hes=', 'GET HMACSHA256 vector');
|
||||
|
||||
$valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $clock() + 1000];
|
||||
$responses[] = esignResponse($valid);
|
||||
$client->checkWillingness('flow-7');
|
||||
esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint');
|
||||
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');
|
||||
}
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0, 'accountId' => 'person-7']);
|
||||
esignExpect($client->createPerson('张医生', 'TEST-IDENTITY', 'flow-7') === 'person-7', 'created SDK account');
|
||||
$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');
|
||||
|
||||
$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);
|
||||
esignExpect($sealBody === ['accountId' => 'person-7', 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE'], 'seal from account identity');
|
||||
|
||||
$pdf = "%PDF-1.7\n\x00\x01binary-pdf\r\n%%EOF";
|
||||
$signedPdf = "%PDF-1.7\nsigned\x00binary\n%%EOF";
|
||||
$responses[] = esignResponse(['errCode' => 0, 'signServiceId' => 'service-7', 'stream' => base64_encode($signedPdf)]);
|
||||
esignExpect($client->signPdf('person-7', 'flow-7', base64_encode('seal-image'), $pdf, 'rx-7.pdf') === ['sign_service_id' => 'service-7', 'pdf' => $signedPdf], 'decoded signed PDF bytes');
|
||||
$request = $requests[count($requests) - 1];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/user/sign/personSign'), 'SDK person sign endpoint');
|
||||
$parts = esignMultipartParts($request);
|
||||
esignExpect(array_keys($parts) === ['personSignParam', 'streamFile'], 'multipart field names');
|
||||
esignExpect(str_contains($parts['personSignParam']['headers'], 'Content-Type: application/json; charset=UTF-8'), 'JSON part media type');
|
||||
esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: application/octet-stream'), 'file part media type');
|
||||
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['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding');
|
||||
|
||||
$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]];
|
||||
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $signatures]);
|
||||
esignExpect($client->verifyPdf($signedPdf) === ['signatures' => $signatures], 'all signatures verified');
|
||||
$parts = esignMultipartParts($requests[count($requests) - 1]);
|
||||
esignExpect(isset($parts['verifyPdfParam']) && $parts['streamFile']['body'] === $signedPdf, 'verify multipart');
|
||||
foreach ([[], [['signature' => ['validate' => true]], ['signature' => ['validate' => false]]], [['signature' => ['validate' => 1]]], [['cert' => []]]] as $invalid) {
|
||||
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $invalid]);
|
||||
esignThrows(fn () => $client->verifyPdf($signedPdf), EsignProviderException::class, $invalid === [] ? 'NO_SIGNATURES' : 'SIGNATURE_INVALID');
|
||||
}
|
||||
|
||||
foreach ([
|
||||
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
|
||||
[['status' => 200, 'body' => '<html>secret identity data</html>'], 'INVALID_JSON'],
|
||||
[esignResponse(['msg' => 'private identity']), 'RESPONSE_INVALID'],
|
||||
[esignResponse(['errCode' => 42, 'msg' => 'private name/id/secret']), 'PROVIDER_42'],
|
||||
[['status' => 302, 'body' => 'Location: https://attacker.invalid'], 'HTTP_302'],
|
||||
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
|
||||
] as [$response, $code]) {
|
||||
$responses[] = $response;
|
||||
$before = count($requests);
|
||||
$exception = esignThrows(fn () => $client->createSeal('person-7'), EsignProviderException::class, $code);
|
||||
esignExpect(count($requests) === $before + 1, 'no retry ' . $code);
|
||||
esignExpect(!str_contains($exception->getMessage(), 'private') && !str_contains($exception->getMessage(), 'secret') && !str_contains($exception->getMessage(), 'attacker'), 'sanitized error ' . $code);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
|
||||
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
|
||||
[['status' => 502, 'body' => 'private server exception'], 'HTTP_502'],
|
||||
[esignResponse(['errCode' => 0, 'signServiceId' => 'already-signed']), 'SIGNED_FILE_UNAVAILABLE'],
|
||||
] as [$response, $code]) {
|
||||
$responses[] = $response;
|
||||
$before = count($requests);
|
||||
$exception = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, $code);
|
||||
esignExpect(count($requests) === $before + 1, 'unknown signing outcome is never retried');
|
||||
if ($code === 'SIGNED_FILE_UNAVAILABLE') {
|
||||
esignExpect($exception->signServiceId === 'already-signed', 'known sign reference retained');
|
||||
}
|
||||
}
|
||||
$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');
|
||||
$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');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://attacker.invalid/identity']]);
|
||||
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://t.esign.cn/identity']]);
|
||||
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => 'https://smlfront.esign.cn:8890/identity/login']]);
|
||||
esignExpect($client->startIdentity('医生', 'rx')['auth_url'] === 'https://smlfront.esign.cn:8890/identity/login', 'official sandbox long URL port');
|
||||
foreach (['https://smlfront.esign.cn:444/x', 'https://smlt.esign.cn:8890/x', 'https://smlt.esign.cn/a\\b'] as $invalidUrl) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => $invalidUrl]]);
|
||||
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
}
|
||||
|
||||
$production = new EsignClient(esignConfig(['environment' => 'production']), $transport, $clock);
|
||||
$responses[] = esignResponse(['errCode' => 0]);
|
||||
$production->initialize();
|
||||
$init = json_decode($requests[count($requests) - 1]['body'], true);
|
||||
esignExpect($init['projectConfig']['itsmApiUrl'] === 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2', 'production init endpoint');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => '', 'url' => 'https://idverify.esign.cn/identity']]);
|
||||
$production->startIdentity('医生', 'rx');
|
||||
esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint');
|
||||
|
||||
esignExpect($responses === [], 'all expected transport responses consumed');
|
||||
echo 'EsignClient: ' . $checks . " checks passed (offline)\n";
|
||||
@@ -0,0 +1,336 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
class EsignProviderException extends \RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode)
|
||||
{
|
||||
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
|
||||
}
|
||||
}
|
||||
class EsignOutcomeUnknownException extends EsignProviderException
|
||||
{
|
||||
public function __construct(string $code, public ?string $signServiceId = null) { parent::__construct('signPdf', $code); }
|
||||
}
|
||||
/** Only the external provider boundary is fake; service/ORM/files are real. */
|
||||
final class EsignClient
|
||||
{
|
||||
public static int $starts = 0;
|
||||
public static int $signs = 0;
|
||||
public static string $identityStatus = 'SUCCESS';
|
||||
public static string $identityName = '测试医师';
|
||||
public static bool $verifyFailure = false;
|
||||
public static ?string $verifyRejection = null;
|
||||
public static bool $signFailure = false;
|
||||
public static int $initializes = 0;
|
||||
public static ?string $signRejection = null;
|
||||
public static ?string $unknownServiceId = null;
|
||||
public static ?string $identityFlowId = null;
|
||||
public static bool $startFailure = false;
|
||||
public static bool $expiredWillingness = false;
|
||||
public static $duringSeal = null;
|
||||
public static $duringSign = null;
|
||||
public function assertConfigured(): void {}
|
||||
public function initialize(): void { self::$initializes++; }
|
||||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||||
{
|
||||
self::$starts++;
|
||||
if (self::$startFailure) { throw new EsignProviderException('startIdentity', 'HTTP_503'); }
|
||||
return ['flow_id' => 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/test'];
|
||||
}
|
||||
public function identityDetail(string $id): array
|
||||
{
|
||||
return ['flowId' => self::$identityFlowId ?? $id, 'appId' => 'fixture', 'status' => self::$identityStatus, 'objectType' => 'INDIVIDUAL',
|
||||
'indivInfo' => ['name' => self::$identityName, 'certNo' => '110101199001011234', 'certType' => 'INDIVIDUAL_CH_IDCARD']];
|
||||
}
|
||||
public function checkWillingness(string $id): void
|
||||
{
|
||||
if (self::$expiredWillingness) { throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID'); }
|
||||
}
|
||||
public function createPerson(string $name, string $idNo, string $flow): string { return 'account-test'; }
|
||||
public function createSeal(string $id): string
|
||||
{
|
||||
if (self::$duringSeal) { (self::$duringSeal)(); }
|
||||
return base64_encode('test-seal');
|
||||
}
|
||||
public function signPdf(string $account, string $flow, string $seal, string $pdf, string $name): array
|
||||
{
|
||||
self::$signs++;
|
||||
if (self::$duringSign) { (self::$duringSign)(); }
|
||||
if (self::$signRejection !== null) { throw new EsignProviderException('signPdf', self::$signRejection); }
|
||||
if (self::$signFailure) { throw new EsignOutcomeUnknownException('TIMEOUT', self::$unknownServiceId); }
|
||||
return ['pdf' => $pdf . "\n% provider signed fixture\n", 'sign_service_id' => 'sign-' . self::$signs];
|
||||
}
|
||||
public function verifyPdf(string $pdf): array
|
||||
{
|
||||
if (self::$verifyFailure) { throw new \RuntimeException('verify unavailable'); }
|
||||
if (self::$verifyRejection !== null) { throw new EsignProviderException('verifyPdf', self::$verifyRejection); }
|
||||
return ['signatures' => [['signature' => ['validate' => true], 'cert' => ['cn' => '测试医师'], 'sealData' => base64_encode('test-seal')]]];
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
use app\common\service\esign\PrescriptionEsignService as Service;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy as Policy;
|
||||
use app\common\service\esign\PrescriptionPdf;
|
||||
use app\common\service\esign\EsignClient as Fake;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
$app = new think\App(); // Never initialize or load .env / real DB credentials.
|
||||
$dir = sys_get_temp_dir() . '/zyt-esign-test-' . bin2hex(random_bytes(8));
|
||||
mkdir($dir, 0700);
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => $dir . '/fixture.sqlite', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'storage_path' => $dir . '/pdf'];
|
||||
$config->set($settings, 'esign');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
$root = ['root' => 1, 'admin_id' => 1, 'name' => '测试医师'];
|
||||
$checks = 0;
|
||||
$assert = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) { throw new \RuntimeException($message); }
|
||||
$checks++;
|
||||
};
|
||||
$throws = static function (callable $fn, string $message) use ($assert): void {
|
||||
try { $fn(); } catch (\DomainException $e) { $assert(true, $message); return; }
|
||||
$assert(false, $message);
|
||||
};
|
||||
try {
|
||||
$fields = array_unique(array_merge(Policy::CONTENT_FIELDS, ['esign_required', 'esign_status', 'is_system_auto', 'void_status', 'delete_time', 'doctor_signature', 'update_time']));
|
||||
$columns = array_map(static fn ($field) => $field === 'id' ? 'id INTEGER PRIMARY KEY' : $field . ' TEXT', $fields);
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription (' . implode(',', $columns) . ')');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER)');
|
||||
Db::name('admin')->insert(['id' => 1, 'name' => '测试医师']);
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql');
|
||||
preg_match_all('/CREATE TABLE IF NOT EXISTS `(zyt_\w+)` \((.*?)\) ENGINE/s', $sql, $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $match) {
|
||||
$defs = [];
|
||||
foreach (explode("\n", $match[2]) as $line) {
|
||||
if (preg_match('/^\s*`(\w+)`\s+(.+?)(?:,)?$/', $line, $m)) {
|
||||
$type = preg_match('/\bint\b/', $m[2]) ? 'INTEGER' : 'TEXT';
|
||||
$def = '`' . $m[1] . '` ' . $type;
|
||||
if ($m[1] === 'id' || ($match[1] === 'zyt_prescription_esign' && $m[1] === 'prescription_id')) { $def .= ' PRIMARY KEY'; }
|
||||
if (preg_match("/DEFAULT ('[^']*'|\d+)/", $m[2], $d)) { $def .= ' DEFAULT ' . $d[1]; }
|
||||
$defs[] = $def;
|
||||
}
|
||||
}
|
||||
Db::execute('CREATE TABLE ' . $match[1] . ' (' . implode(',', $defs) . ')');
|
||||
}
|
||||
Db::execute('CREATE UNIQUE INDEX uk_doctor ON zyt_doctor_esign_account(doctor_id,environment,app_id)');
|
||||
$new = static function (int $id): void {
|
||||
Db::name('tcm_prescription')->insert([
|
||||
'id' => $id, 'sn' => 'RX-TEST-' . $id, 'creator_id' => 1, 'doctor_name' => '测试医师',
|
||||
'patient_name' => '虚构测试患者', 'gender' => 1, 'age' => 30, 'phone' => '13800000000',
|
||||
'clinical_diagnosis' => '仅用于软件测试', 'herbs' => json_encode([['name' => '测试药材', 'dosage' => 10, 'unit' => 'g']], JSON_UNESCAPED_UNICODE),
|
||||
'prescription_date' => '2026-11-17', 'esign_required' => 1, 'esign_status' => 'pending', 'void_status' => 0,
|
||||
]);
|
||||
};
|
||||
$new(1);
|
||||
$throws(fn () => Service::start(1, 2, $root), 'non-creator cannot start even with root role');
|
||||
$throws(fn () => Service::assertSignedById(1), 'pending prescription cannot pass audit');
|
||||
$a = Service::start(1, 1, $root);
|
||||
$assert($a['status'] === 'authenticating' && isset($a['auth_url']), 'start returns authentication URL');
|
||||
Service::start(1, 1, $root);
|
||||
$assert(Fake::$starts === 1, 'repeat start must reuse flow');
|
||||
$throws(fn () => Policy::assertMutable(Db::name('tcm_prescription')->find(1)), 'auth freezes content');
|
||||
Fake::$identityStatus = 'ING';
|
||||
$assert(Service::complete(1, 1, $root)['status'] === 'authenticating' && Fake::$signs === 0, 'not authenticated cannot sign');
|
||||
Fake::$identityStatus = 'SUCCESS';
|
||||
Fake::$identityName = '其他医师';
|
||||
$assert(Service::complete(1, 1, $root)['status'] === 'failed' && Fake::$signs === 0, 'wrong identity cannot sign');
|
||||
Fake::$identityName = '测试医师';
|
||||
Service::start(1, 1, $root); // A rejected identity must be replaced, never silently reused.
|
||||
Fake::$duringSign = static function () use ($assert, $root): void {
|
||||
$assert(Service::complete(1, 1, $root)['status'] === 'signing', 'concurrent complete must not repeat sign');
|
||||
};
|
||||
$done = Service::complete(1, 1, $root);
|
||||
Fake::$duringSign = null;
|
||||
$assert($done['status'] === 'signed' && $done['can_download'], 'verified sign archived');
|
||||
Service::complete(1, 1, $root);
|
||||
$assert(Fake::$signs === 1, 'signed replay returns same result');
|
||||
$download = Service::download(1, 1, $root);
|
||||
$bytes = base64_decode($download['content_base64'], true);
|
||||
$assert(hash('sha256', $bytes) === $download['sha256'] && str_contains($bytes, 'provider signed fixture'), 'download original bytes and digest');
|
||||
Service::assertSignedById(1);
|
||||
$throws(fn () => Service::assertSignedById(1, true), 'sandbox cannot dispense');
|
||||
$throws(fn () => Policy::assertMutable(Db::name('tcm_prescription')->find(1)), 'signed content immutable');
|
||||
Db::name('tcm_prescription')->where('id', 1)->update(['clinical_diagnosis' => 'changed']);
|
||||
$throws(fn () => Service::assertSignedById(1), 'out-of-band content mutation invalidates approval');
|
||||
$assert(Service::status(1, 1, $root)['status'] === 'uncertain', 'changed content is not displayed as signed');
|
||||
|
||||
$new(2); Service::start(2, 1, $root);
|
||||
Fake::$verifyFailure = true;
|
||||
$assert(Service::complete(2, 1, $root)['status'] === 'uncertain', 'verification outage preserves unknown state');
|
||||
$before = Fake::$signs;
|
||||
Service::start(2, 1, $root); Service::complete(2, 1, $root);
|
||||
$assert(Fake::$signs === $before, 'unknown outcome never automatically resigns');
|
||||
Fake::$verifyFailure = false;
|
||||
Service::recover(2);
|
||||
$assert(Service::status(2, 1, $root)['status'] === 'signed' && Fake::$signs === $before, 'recover re-verifies original without signing');
|
||||
$assert(Db::name('tcm_prescription')->where('id', 2)->value('doctor_signature') === 'data:image/png;base64,' . base64_encode('test-seal'), 'recovery restores supplier-verified display seal');
|
||||
|
||||
$new(3); Service::start(3, 1, $root);
|
||||
Fake::$duringSign = static fn () => Db::name('tcm_prescription')->where('id', 3)->update(['void_status' => 1]);
|
||||
$assert(Service::complete(3, 1, $root)['status'] === 'voided', 'late signature never restores voided prescription');
|
||||
Fake::$duringSign = null;
|
||||
$throws(fn () => Service::assertSignedById(3), 'voided prescription cannot pass');
|
||||
|
||||
$new(4); Service::start(4, 1, $root);
|
||||
Fake::$signFailure = true;
|
||||
$assert(Service::complete(4, 1, $root)['status'] === 'uncertain', 'sign timeout remains uncertain');
|
||||
Fake::$signFailure = false;
|
||||
$throws(fn () => Service::recover(4), 'missing signed file cannot be invented');
|
||||
|
||||
$new(6); Service::start(6, 1, $root);
|
||||
Fake::$signFailure = true; Fake::$unknownServiceId = 'supplier-uncertain-6';
|
||||
$assert(Service::complete(6, 1, $root)['status'] === 'uncertain', 'typed timeout outcome remains uncertain');
|
||||
Fake::$signFailure = false; Fake::$unknownServiceId = null;
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 6)->find();
|
||||
$assert($evidence['sign_service_id'] === 'supplier-uncertain-6' && $evidence['account_id'] === 'account-test', 'unknown exception supplier reference is retained');
|
||||
$before = Fake::$signs;
|
||||
Service::start(6, 1, $root); Service::complete(6, 1, $root);
|
||||
$assert(Fake::$signs === $before, 'typed unknown cannot automatically resign');
|
||||
|
||||
$new(7); Service::start(7, 1, $root);
|
||||
Fake::$signRejection = 'PROVIDER_50001';
|
||||
$rejected = Service::complete(7, 1, $root);
|
||||
Fake::$signRejection = null;
|
||||
$assert($rejected['status'] === 'failed' && $rejected['can_sign'], 'explicit supplier rejection is retryable');
|
||||
$assert(str_contains($rejected['message'], 'PROVIDER_50001'), 'safe supplier code is retained');
|
||||
$assert(Db::name('prescription_esign')->where('prescription_id', 7)->value('flow_id') === '', 'explicit rejection requires fresh authentication');
|
||||
$before = Fake::$signs;
|
||||
$throws(fn () => Service::complete(7, 1, $root), 'cannot reuse rejected sign authentication');
|
||||
Service::start(7, 1, $root);
|
||||
$assert(Service::complete(7, 1, $root)['status'] === 'signed' && Fake::$signs === $before + 1, 'new auth can complete definite rejection retry');
|
||||
|
||||
$new(8); Fake::$startFailure = true;
|
||||
$assert(Service::start(8, 1, $root)['status'] === 'failed', 'identity link outage records failed preparation');
|
||||
Fake::$startFailure = false;
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 8)->find();
|
||||
$assert($evidence['flow_id'] === '' && $evidence['auth_url'] === '', 'failed preparation has no stale identity URL');
|
||||
$assert(Service::start(8, 1, $root)['status'] === 'authenticating', 'identity preparation can safely retry');
|
||||
|
||||
$new(9); Service::start(9, 1, $root); $before = Fake::$signs;
|
||||
Fake::$expiredWillingness = true;
|
||||
$assert(Service::complete(9, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'expired willingness never dispatches sign');
|
||||
Fake::$expiredWillingness = false;
|
||||
$assert(Db::name('prescription_esign')->where('prescription_id', 9)->value('flow_id') === '', 'expired willingness requires new auth flow');
|
||||
|
||||
$new(10); Service::start(10, 1, $root); $before = Fake::$signs;
|
||||
Fake::$identityFlowId = 'foreign-flow';
|
||||
$assert(Service::complete(10, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'identity response must echo bound flow');
|
||||
Fake::$identityFlowId = null;
|
||||
|
||||
$new(11); Service::start(11, 1, $root); $before = Fake::$signs;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replacement-account']);
|
||||
$assert(Service::complete(11, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'account replacement cannot reuse auth for old account');
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'account-test']);
|
||||
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->delete();
|
||||
$new(12); Service::start(12, 1, $root); $before = Fake::$signs;
|
||||
Db::name('doctor_esign_account')->insert(['doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||||
'account_id' => 'account-test', 'doctor_name' => '测试医师', 'create_time' => time()]);
|
||||
$assert(Service::complete(12, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'concurrent first binding cannot turn unbound auth into bound auth');
|
||||
Service::start(12, 1, $root);
|
||||
$assert(Service::complete(12, 1, $root)['status'] === 'signed', 'new auth binds the now existing account');
|
||||
|
||||
$new(13); Service::start(13, 1, $root);
|
||||
Db::name('tcm_prescription')->where('id', 13)->update(['esign_status' => 'signing']);
|
||||
Db::name('prescription_esign')->where('prescription_id', 13)->update(['started_at' => time() - 500]);
|
||||
$before = Fake::$signs;
|
||||
$stale = Service::status(13, 1, $root);
|
||||
Service::start(13, 1, $root); Service::complete(13, 1, $root);
|
||||
$assert($stale['status'] === 'uncertain' && !$stale['can_sign'] && Fake::$signs === $before, 'stale signing lease cannot trigger another sign');
|
||||
|
||||
$new(14); Service::start(14, 1, $root); $before = Fake::$signs;
|
||||
Fake::$duringSeal = static fn () => Db::name('tcm_prescription')->where('id', 14)->update(['usage_notes' => 'out-of-band mutation']);
|
||||
$assert(Service::complete(14, 1, $root)['status'] === 'uncertain' && Fake::$signs === $before, 'second fingerprint check prevents signing mutated prescription');
|
||||
Fake::$duringSeal = null;
|
||||
|
||||
$new(15); Service::start(15, 1, $root); $before = Fake::$signs;
|
||||
Fake::$duringSeal = static fn () => Db::name('tcm_prescription')->where('id', 15)->update(['void_status' => 1]);
|
||||
$assert(Service::complete(15, 1, $root)['status'] === 'voided' && Fake::$signs === $before, 'void during provider preparation prevents dispatch');
|
||||
Fake::$duringSeal = null;
|
||||
|
||||
$new(16); Service::start(16, 1, $root); Fake::$verifyFailure = true;
|
||||
Service::complete(16, 1, $root); Fake::$verifyFailure = false;
|
||||
Db::name('tcm_prescription')->where('id', 16)->update(['usage_notes' => 'modified after signing']);
|
||||
$before = Fake::$signs;
|
||||
$throws(fn () => Service::recover(16), 'recovery cannot approve a changed snapshot');
|
||||
$assert(Fake::$signs === $before && Service::status(16, 1, $root)['status'] === 'uncertain', 'changed recovery remains quarantined without signing');
|
||||
|
||||
$new(17); Service::start(17, 1, $root);
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 17)->find();
|
||||
$blockedPath = $dir . '/pdf/' . dirname($evidence['source_path']) . '/signed.pdf';
|
||||
mkdir($blockedPath);
|
||||
set_error_handler(static fn (): bool => true); // Expected rename failure, no sensitive error output.
|
||||
try { $archiveFailure = Service::complete(17, 1, $root); } finally { restore_error_handler(); rmdir($blockedPath); }
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 17)->find();
|
||||
$assert($archiveFailure['status'] === 'uncertain' && $evidence['sign_service_id'] !== '' && $evidence['signed_path'] === '', 'archive failure preserves successful supplier reference');
|
||||
$throws(fn () => Service::recover(17), 'archive failure requires manual retrieval, never resign');
|
||||
|
||||
$new(18); Service::start(18, 1, $root); $before = Fake::$signs;
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 18)->find();
|
||||
file_put_contents($dir . '/pdf/' . $evidence['source_path'], '%PDF-1.7 tampered');
|
||||
$assert(Service::complete(18, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'changed source file cannot be sent to provider');
|
||||
|
||||
$new(19); Service::start(19, 1, $root); $before = Fake::$signs;
|
||||
Db::name('admin')->where('id', 1)->update(['name' => '已改名医师']);
|
||||
$throws(fn () => Service::complete(19, 1, $root), 'doctor account rename invalidates pending identity binding');
|
||||
Db::name('admin')->where('id', 1)->update(['name' => '测试医师']);
|
||||
$assert(Fake::$signs === $before, 'renamed doctor does not send sign');
|
||||
|
||||
$new(20); Service::start(20, 1, $root);
|
||||
Fake::$verifyRejection = 'PROVIDER_70002';
|
||||
$invalidSigned = Service::complete(20, 1, $root);
|
||||
Fake::$verifyRejection = null;
|
||||
$assert($invalidSigned['status'] === 'uncertain' && !$invalidSigned['can_sign'], 'definite verification failure after signature is never a retryable sign failure');
|
||||
|
||||
$proof = Db::name('prescription_esign')->where('prescription_id', 2)->find();
|
||||
$proof['doctor_id'] = 99;
|
||||
$throws(fn () => Policy::assertSigned(Db::name('tcm_prescription')->find(2), $proof), 'proof author must match prescription creator');
|
||||
$assert(!str_contains(json_encode(Db::name('prescription_esign')->select()->toArray()), '110101199001011234')
|
||||
&& !str_contains(json_encode(Db::name('doctor_esign_account')->select()->toArray()), '110101199001011234'), 'identity document number never persisted');
|
||||
$assert(Fake::$initializes === 0, 'business operations and recovery never reinitialize shared SDK');
|
||||
|
||||
$new(5); Service::start(5, 1, $root);
|
||||
$config->set(array_merge($settings, ['environment' => 'production']), 'esign');
|
||||
$throws(fn () => Service::complete(5, 1, $root), 'environment switch cannot reuse sandbox identity');
|
||||
$config->set(array_merge($settings, ['enabled' => false]), 'esign');
|
||||
$throws(fn () => Service::start(5, 1, $root), 'disabled config blocks signing');
|
||||
$throws(fn () => Service::assertSignedById(5), 'feature off must not bypass existing signature requirement');
|
||||
$legacy = Db::name('tcm_prescription')->find(5); $legacy['esign_required'] = 0;
|
||||
Policy::assertSigned($legacy, null);
|
||||
$assert(true, 'historical handwritten record remains compatible');
|
||||
|
||||
$sample = Db::name('tcm_prescription')->find(2);
|
||||
$decimalRow = array_replace($sample, ['dosage_amount' => '10.0000', 'amount' => '20.00']);
|
||||
$floatRow = array_replace($sample, ['dosage_amount' => 10.0, 'amount' => 20]);
|
||||
$assert(Policy::hash($decimalRow) === Policy::hash($floatRow), 'raw DECIMAL and ORM float hashes agree');
|
||||
$assert(Policy::hash(Policy::snapshot($decimalRow)) === Policy::hash($decimalRow), 'snapshot hashing is idempotent');
|
||||
$pdf = PrescriptionPdf::render($sample, 'sandbox');
|
||||
$assert($pdf === PrescriptionPdf::render($sample, 'sandbox'), 'deterministic PDF');
|
||||
$manyHerbs = [];
|
||||
for ($i = 1; $i <= 65; ++$i) { $manyHerbs[] = ['name' => '虚构药品' . $i, 'dosage' => $i, 'unit' => 'g']; }
|
||||
$largePdf = PrescriptionPdf::render(array_replace($sample, ['herbs' => $manyHerbs, 'amount' => '18.50']), 'sandbox');
|
||||
$assert(preg_match('#/Type /Pages /Kids \[.*?\] /Count ([2-9]\d*)#', $largePdf) === 1, 'long prescription paginates');
|
||||
$assert(str_contains($largePdf, bin2hex(mb_convert_encoding('药品 65:', 'UTF-16BE', 'UTF-8'))), 'last drug is not truncated');
|
||||
$assert(str_contains($largePdf, bin2hex(mb_convert_encoding('金额(元):18.5', 'UTF-16BE', 'UTF-8'))), 'amount is present in signed document');
|
||||
file_put_contents(dirname(__DIR__, 2) . '/artifacts/esign-prescription-test.pdf', $pdf);
|
||||
echo "Prescription eSign flow: $checks checks passed (isolated SQLite, fake provider)\n";
|
||||
} finally {
|
||||
$manager->connect()->close();
|
||||
foreach (glob($dir . '/pdf/*/*.pdf') ?: [] as $file) { unlink($file); }
|
||||
foreach (glob($dir . '/pdf/*', GLOB_ONLYDIR) ?: [] as $folder) { rmdir($folder); }
|
||||
if (is_dir($dir . '/pdf')) { rmdir($dir . '/pdf'); }
|
||||
if (is_file($dir . '/fixture.sqlite')) { unlink($dir . '/fixture.sqlite'); }
|
||||
rmdir($dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Disposable localhost MySQL only; never bootstraps the application environment. */
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
use app\common\service\pharmacy\PharmacySubmissionClaimService;
|
||||
use think\Container;
|
||||
use think\facade\Db;
|
||||
|
||||
$port = (int) getenv('ZYT_ESIGN_TEST_MYSQL_PORT');
|
||||
if ($port <= 0) {
|
||||
throw new RuntimeException('Set ZYT_ESIGN_TEST_MYSQL_PORT to an isolated localhost test MySQL');
|
||||
}
|
||||
$database = 'esign_test_' . bin2hex(random_bytes(6));
|
||||
$pdo = new PDO("mysql:host=127.0.0.1;port=$port;charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$pdo->exec("CREATE DATABASE `$database` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `$database`");
|
||||
$app = new think\App();
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port, 'database' => $database,
|
||||
'username' => 'root', 'password' => '', 'prefix' => 'zyt_', 'charset' => 'utf8mb4', 'fields_strict' => true,
|
||||
]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$config->set(['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture'], 'esign');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
$root = ['root' => 1, 'admin_id' => 1, 'name' => '测试审核员'];
|
||||
$checks = 0;
|
||||
$pdfPath = null;
|
||||
$expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) { throw new RuntimeException($message); }
|
||||
$checks++;
|
||||
};
|
||||
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,
|
||||
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,'测试医师')");
|
||||
$migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql');
|
||||
$pdo->exec($migration);
|
||||
$pdo->exec($migration);
|
||||
$row = Db::name('tcm_prescription')->find(1);
|
||||
$expect((int) $row['esign_required'] === 0 && $row['esign_status'] === 'legacy', 'migration preserves historical rows and is repeatable');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,esign_required,esign_status) VALUES (2,1,'测试医师',1,'pending')");
|
||||
$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]);
|
||||
$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');
|
||||
$expect((int) Db::name('tcm_prescription_order')->where('id', 1)->value('prescription_audit_status') === 0, 'order remains pending after rejection');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false, 'manual order log cannot bypass signature requirement');
|
||||
Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'authenticating']);
|
||||
$expect(PrescriptionLogic::patchPatientContact(2, '变更患者', '13800000000', 1, 1, $root) === false, 'patient correction cannot alter frozen original');
|
||||
$expect(PrescriptionLogic::delete(2) === false, 'frozen evidence cannot be deleted through normal delete');
|
||||
$config->set(['enabled' => false], 'esign');
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'switching feature off cannot bypass persisted requirement');
|
||||
PrescriptionEsignService::assertSignedById(1);
|
||||
$expect(true, 'historical rows do not require new evidence');
|
||||
|
||||
// Real InnoDB contention: a second connection attempts to void the very
|
||||
// prescription being approved, at the exact model before-write boundary.
|
||||
Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'signed']);
|
||||
$snapshot = PrescriptionEsignPolicy::hash(Db::name('tcm_prescription')->find(2));
|
||||
$storage = sys_get_temp_dir() . '/zyt-' . $database;
|
||||
$relative = '2-' . $snapshot . '/signed.pdf';
|
||||
$pdfPath = $storage . '/' . $relative;
|
||||
mkdir(dirname($pdfPath), 0700, true);
|
||||
$pdf = "%PDF-1.7\nTEST ONLY\n%%EOF";
|
||||
file_put_contents($pdfPath, $pdf);
|
||||
$config->set(['storage_path' => $storage], 'esign');
|
||||
Db::name('prescription_esign')->insert([
|
||||
'prescription_id' => 2, 'doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||||
'snapshot_hash' => $snapshot, 'source_hash' => hash('sha256', $pdf), 'source_path' => '',
|
||||
'signed_hash' => hash('sha256', $pdf), 'signed_path' => $relative,
|
||||
'account_id' => 'fixture-account', 'sign_service_id' => 'fixture-sign',
|
||||
'signed_at' => time(), 'create_time' => time(), 'update_time' => time(),
|
||||
]);
|
||||
try {
|
||||
PharmacySubmissionClaimService::acquire(1, 1, 'gancao', 1, '测试');
|
||||
$expect(false, 'sandbox must not acquire a dispensing claim');
|
||||
} catch (DomainException $e) {
|
||||
$expect(str_contains($e->getMessage(), '沙箱'), 'claim boundary enforces production signatures');
|
||||
}
|
||||
$pdo->exec('SET SESSION innodb_lock_wait_timeout=1');
|
||||
$events = new class($pdo, $expect) {
|
||||
public int $attempts = 0;
|
||||
public function __construct(private PDO $otherConnection, private Closure $expect) {}
|
||||
public function trigger(string $event, mixed $model): array {
|
||||
if (!str_ends_with($event, '.BeforeUpdate')) { return []; }
|
||||
$this->attempts++;
|
||||
try {
|
||||
$this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2');
|
||||
($this->expect)(false, 'concurrent void must wait for signature check + audit write');
|
||||
} catch (PDOException $e) {
|
||||
($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write');
|
||||
}
|
||||
throw new DomainException('TEST_LOCK_OBSERVED');
|
||||
}
|
||||
};
|
||||
\think\Model::setEvent($events);
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false && PrescriptionLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual audit reaches locked write');
|
||||
$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');
|
||||
echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n";
|
||||
} finally {
|
||||
\think\Model::setEvent(null);
|
||||
if ($pdfPath !== null && is_file($pdfPath)) {
|
||||
unlink($pdfPath);
|
||||
rmdir(dirname($pdfPath));
|
||||
rmdir(dirname(dirname($pdfPath)));
|
||||
}
|
||||
$manager->connect()->close();
|
||||
if (!preg_match('/^esign_test_[a-f0-9]{12}$/D', $database)) { throw new RuntimeException('Unsafe test database'); }
|
||||
$pdo->exec("DROP DATABASE `$database`");
|
||||
}
|
||||
Reference in New Issue
Block a user