Files
zyt/server/tests/PrescriptionEsignFlowTest.php
T
2026-11-17 17:06:05 +08:00

337 lines
23 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\service\esign {
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);
}
}