- 药师签署验签通过后,立即把最终双签 PDF 以私有对象上传到后台配置的腾讯云 COS, 对象键 private/esign/prescription/<环境>/<处方ID>-<sha256>.pdf,带 Content-MD5 校验,不返回任何 URL - 上传失败不影响签署:记录原因并指数退避,由 esign:archive-work 每分钟补传(最长 1 小时一次) - 签署日志新增「签署件已归档至云存储」/「归档未完成,系统将自动重试」 - 迁移 2026_11_27_prescription_review_archive.sql:归档字段 + 定时任务登记 Co-Authored-By: Claude Opus 5 (1M context) <[EMAIL]>
1438 lines
111 KiB
PHP
1438 lines
111 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
namespace app\common\service\esign {
|
||
function time_nanosleep(int $seconds, int $nanoseconds): bool|array
|
||
{
|
||
return EsignClient::$duringIssueWait === null
|
||
? \time_nanosleep($seconds, $nanoseconds)
|
||
: (EsignClient::$duringIssueWait)($seconds, $nanoseconds);
|
||
}
|
||
|
||
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 string $startedName = '';
|
||
public static int $signs = 0;
|
||
public static int $identityQueries = 0;
|
||
public static string $identityStatus = 'SUCCESS';
|
||
public static string $identityName = '测试医师';
|
||
public static string $identityDetails = 'full';
|
||
public static string $identityApp = 'fixture';
|
||
public static string $identityObject = 'INDIVIDUAL';
|
||
public static int $creates = 0;
|
||
public static int $willingnessChecks = 0;
|
||
public static ?string $createRejection = null;
|
||
public static array $createdPerson = [];
|
||
public static bool $verifyFailure = false;
|
||
public static ?string $verifyRejection = null;
|
||
public static string $verifiedDoctor = '测试医师';
|
||
public static int $verifies = 0;
|
||
public static array $reviewCalls = [];
|
||
public static bool $failReviewVerification = false;
|
||
public static array $reviewSignatures = [];
|
||
public static ?string $signDate = null;
|
||
public static int $tsaClockOffset = 0;
|
||
public static string $timeFrom = 'tsa';
|
||
public static array $signedTimes = [];
|
||
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 int $quickRemainingTimes = 2;
|
||
public static array $smsFlows = [];
|
||
public static ?string $smsMobile = '13900000000';
|
||
public static $duringSeal = null;
|
||
public static $duringIssueWait = null;
|
||
public static $duringSign = null;
|
||
public static $duringIdentity = null;
|
||
public static $duringWillingness = null;
|
||
public static $duringVerify = null;
|
||
public function assertConfigured(): void {}
|
||
public function initialize(): void { self::$initializes++; }
|
||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||
{
|
||
self::$starts++;
|
||
self::$startedName = $name;
|
||
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
|
||
{
|
||
self::$identityQueries++;
|
||
if (self::$duringIdentity) { (self::$duringIdentity)(); }
|
||
$detail = ['flowId' => self::$identityFlowId ?? $id, 'appId' => self::$identityApp, 'status' => self::$identityStatus, 'objectType' => self::$identityObject,
|
||
'indivInfo' => ['name' => self::$identityName, 'certNo' => '110101199001011234', 'certType' => 'INDIVIDUAL_CH_IDCARD']];
|
||
if (self::$identityDetails === 'null') { $detail['indivInfo'] = null; }
|
||
if (self::$identityDetails === 'missing') { unset($detail['indivInfo']); }
|
||
if (self::$identityDetails === 'empty') { $detail['indivInfo'] = []; }
|
||
if (self::$identityDetails === 'malformed') { $detail['indivInfo'] = 'invalid'; }
|
||
if (self::$identityDetails === 'masked') { $detail['indivInfo']['certNo'] = '110***********1234'; }
|
||
return $detail;
|
||
}
|
||
public function checkWillingness(string $id): void
|
||
{
|
||
self::$willingnessChecks++;
|
||
if (self::$duringWillingness) { (self::$duringWillingness)(); }
|
||
if (self::$expiredWillingness || (array_key_exists($id, self::$smsFlows) && self::$smsFlows[$id] !== 'verified')) {
|
||
throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID');
|
||
}
|
||
}
|
||
public function willingnessValidity(string $id): array
|
||
{
|
||
try {
|
||
$this->checkWillingness($id);
|
||
} catch (EsignProviderException $error) {
|
||
return ['state' => 'expired', 'expires_at' => 0, 'remaining_times' => 0];
|
||
}
|
||
return self::$quickRemainingTimes > 0
|
||
? ['state' => 'valid', 'expires_at' => (time() + 3600) * 1000, 'remaining_times' => self::$quickRemainingTimes]
|
||
: ['state' => 'exhausted', 'expires_at' => 0, 'remaining_times' => 0];
|
||
}
|
||
public function signingAccount(string $accountId): array
|
||
{
|
||
return ['accountId' => $accountId, 'accountType' => 'PERSON', 'idNoType' => 'MAINLAND',
|
||
'name' => '测试医师', 'idNo' => '110101199001011237'];
|
||
}
|
||
public function certificateValidity(string $accountId): array
|
||
{
|
||
return ['startDate' => '2026-01-01 00:00:00', 'endDate' => '2099-01-01 00:00:00'];
|
||
}
|
||
public function certificateIdentity(string $accountId): array
|
||
{
|
||
return ['issuerCN' => 'Test CA', 'sn' => '00B2'];
|
||
}
|
||
public function authorizedMobile(string $name, string $idNo): ?string
|
||
{
|
||
return self::$smsMobile;
|
||
}
|
||
public function sendWillingnessCode(string $name, string $idNo, string $mobile): string
|
||
{
|
||
$flow = 'sms-' . (count(self::$smsFlows) + 1);
|
||
self::$smsFlows[$flow] = 'sent';
|
||
return $flow;
|
||
}
|
||
public function verifyWillingnessCode(string $flowId, string $code): void
|
||
{
|
||
if (self::$smsFlows[$flowId] !== 'sent' || $code !== '123456') {
|
||
throw new EsignProviderException('verifyWillingnessCode', 'PROVIDER_30503002');
|
||
}
|
||
self::$smsFlows[$flowId] = 'verified';
|
||
}
|
||
public function createPerson(string $name, string $idNo, string $flow): string
|
||
{
|
||
self::$creates++;
|
||
self::$createdPerson = [$name, $idNo, $flow];
|
||
if (self::$createRejection !== null) { throw new EsignProviderException('createPerson', self::$createRejection); }
|
||
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); }
|
||
$signed = $pdf . "\n% provider signed fixture\n";
|
||
if (array_key_exists($flow, self::$smsFlows)) {
|
||
self::$smsFlows[$flow] = 'used';
|
||
}
|
||
self::$signedTimes[hash('sha256', $signed)] = gmdate('Y-m-d H:i:s', time() + self::$tsaClockOffset + 28800);
|
||
return ['pdf' => $signed, 'sign_service_id' => 'sign-' . self::$signs];
|
||
}
|
||
public function verifyPdf(string $pdf): array
|
||
{
|
||
self::$verifies++;
|
||
if (self::$duringVerify) { (self::$duringVerify)(); }
|
||
if (self::$verifyFailure) { throw new \RuntimeException('verify unavailable'); }
|
||
if (self::$verifyRejection !== null) { throw new EsignProviderException('verifyPdf', self::$verifyRejection); }
|
||
$hash = hash('sha256', $pdf);
|
||
if (isset(self::$reviewSignatures[$hash])) {
|
||
if (self::$failReviewVerification) {
|
||
throw new \RuntimeException('review verify unavailable');
|
||
}
|
||
return ['signatures' => self::$reviewSignatures[$hash]];
|
||
}
|
||
return ['signatures' => [[
|
||
'signature' => ['signatureName' => 'Signature1', 'validate' => true,
|
||
'signDate' => self::$signDate ?? self::$signedTimes[$hash], 'timeFrom' => self::$timeFrom],
|
||
'cert' => ['cn' => self::$verifiedDoctor, 'issuerCN' => 'Test CA', 'sn' => 'a1'], 'sealData' => base64_encode('test-seal'),
|
||
]]];
|
||
}
|
||
public function signReviewPdf(string $account, string $flow, string $seal, string $pdf, string $name): array
|
||
{
|
||
self::$reviewCalls[] = [$account, $flow, hash('sha256', $pdf)];
|
||
$dual = $pdf . "\n% provider appended reviewer signature\n";
|
||
$original = $this->verifyPdf($pdf)['signatures'][0];
|
||
self::$reviewSignatures[hash('sha256', $dual)] = [[
|
||
'signature' => ['signatureName' => 'Signature2', 'validate' => true,
|
||
'signDate' => gmdate('Y-m-d H:i:s', max(time() + 28800, strtotime($original['signature']['signDate'] . ' UTC'))), 'timeFrom' => 'tsa'],
|
||
'cert' => ['cn' => '测试审核人', 'issuerCN' => 'Test CA', 'sn' => 'b2'],
|
||
'sealData' => 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/J5cAAAAASUVORK5CYII=',
|
||
], $original];
|
||
return ['pdf' => $dual, 'sign_service_id' => 'review-sign-1'];
|
||
}
|
||
}
|
||
}
|
||
namespace {
|
||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||
use app\adminapi\http\middleware\AuthMiddleware;
|
||
use app\adminapi\lists\tcm\PrescriptionLists;
|
||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||
use app\common\service\esign\PrescriptionEsignService as Service;
|
||
use app\common\service\esign\PrescriptionEsignPolicy as Policy;
|
||
use app\common\service\esign\PrescriptionReviewEsignService as Review;
|
||
use app\common\service\esign\PrescriptionEsignArchive as Archive;
|
||
use app\common\service\esign\PrescriptionEsignCos;
|
||
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.
|
||
$app->instance('log', new Psr\Log\NullLogger());
|
||
// Only the COS boundary is fake; archive bookkeeping and the signed-PDF read path are real.
|
||
$cos = new class extends PrescriptionEsignCos {
|
||
public array $puts = [];
|
||
public int $failures = 0;
|
||
public function location(): array { return ['bucket' => 'fixture-1250000000', 'region' => 'ap-guangzhou']; }
|
||
public function put(array $object, string $pdf): void
|
||
{
|
||
if ($this->failures > 0) {
|
||
$this->failures--;
|
||
throw new \DomainException('云存储暂不可用(HTTP 503)');
|
||
}
|
||
$this->puts[] = $object + ['sha256' => hash('sha256', $pdf), 'pdf' => $pdf];
|
||
}
|
||
};
|
||
Container::getInstance()->instance(PrescriptionEsignCos::class, $cos);
|
||
$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', 'delete_time', 'doctor_signature', 'update_time',
|
||
'create_time', 'template_id', 'is_shared', 'visible_role_ids', 'assistant_id',
|
||
'audit_status', 'audit_time', 'audit_by', 'audit_by_name', 'audit_remark',
|
||
'void_status', 'void_time', 'void_by', 'void_by_name', 'review_submitted_at',
|
||
]));
|
||
$columns = array_map(static fn ($field) => match ($field) {
|
||
'id' => 'id INTEGER PRIMARY KEY',
|
||
'void_status' => 'void_status INTEGER NOT NULL DEFAULT 0',
|
||
'review_submitted_at' => 'review_submitted_at INTEGER NOT NULL DEFAULT 0',
|
||
default => $field . ' TEXT',
|
||
}, $fields);
|
||
Db::execute('CREATE TABLE zyt_tcm_prescription (' . implode(',', $columns) . ')');
|
||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER,disable INTEGER DEFAULT 0,root INTEGER DEFAULT 0)');
|
||
Db::execute('CREATE TABLE zyt_tcm_prescription_order (
|
||
id INTEGER PRIMARY KEY, prescription_id INTEGER, prescription_audit_status INTEGER,
|
||
prescription_audit_remark TEXT, payment_slip_audit_status INTEGER DEFAULT 0,
|
||
fulfillment_status INTEGER, delete_time INTEGER, diagnosis_id INTEGER, creator_id INTEGER,
|
||
create_time INTEGER, update_time INTEGER
|
||
)');
|
||
Db::execute('CREATE TABLE zyt_tcm_prescription_order_pay_order (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, pay_order_id INTEGER)');
|
||
Db::execute('CREATE TABLE zyt_pharmacy_submission_claim (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, source_revision INTEGER, status TEXT)');
|
||
Db::execute('CREATE TABLE zyt_tcm_prescription_order_log (id INTEGER PRIMARY KEY, prescription_order_id INTEGER,
|
||
admin_id INTEGER, admin_name TEXT, action TEXT, summary TEXT, create_time INTEGER)');
|
||
Db::name('admin')->insert(['id' => 1, 'name' => '测试医师']);
|
||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql')
|
||
. file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_identity.sql')
|
||
. file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_quicksign.sql')
|
||
. file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_prescription_review_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' || (in_array($match[1], ['zyt_prescription_esign', 'zyt_prescription_review_esign'], true)
|
||
&& $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)');
|
||
Db::execute('ALTER TABLE zyt_prescription_esign ADD review_required INTEGER NOT NULL DEFAULT 0');
|
||
preg_match_all('/ADD COLUMN `(\w+)` (\w+)/', file_get_contents(dirname(__DIR__)
|
||
. '/database/migrations/2026_11_27_prescription_review_archive.sql'), $archiveColumns, PREG_SET_ORDER);
|
||
foreach ($archiveColumns as [, $column, $type]) {
|
||
Db::execute("ALTER TABLE zyt_prescription_review_esign ADD $column "
|
||
. ($type === 'int' ? 'INTEGER NOT NULL DEFAULT 0' : "TEXT NOT NULL DEFAULT ''"));
|
||
}
|
||
$new = static function (int $id, bool $uploaded = true): 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,
|
||
'review_submitted_at' => $uploaded ? time() : 0,
|
||
]);
|
||
};
|
||
$new(1);
|
||
$throws(fn () => Service::start(1, 2, $root), 'non-creator cannot start even with root role');
|
||
$throws(fn () => Service::identityStatus(1, 2, $root), 'non-creator cannot query personal authentication even with root role');
|
||
$throws(fn () => Service::complete(1, 1, $root, '', true), 'verify-only on a pending record cannot start signing');
|
||
$assert(Service::identityStatus(1, 1, $root)['identity_status'] === 'UNAVAILABLE'
|
||
&& Fake::$identityQueries === 0 && Fake::$signs === 0 && Fake::$verifies === 0, 'pending has no authentication or original to verify');
|
||
$throws(fn () => Service::assertSignedById(1), 'pending prescription cannot pass audit');
|
||
$a = Service::start(1, 1, $root);
|
||
$assert($a['status'] === 'authenticating' && $a['can_resume_identity'] && isset($a['auth_url']), 'start returns resumable authentication URL');
|
||
$other = Service::status(1, 2, $root);
|
||
$assert(!$other['can_resume_identity'] && !isset($other['auth_url']), 'other viewers cannot resume the doctors flow or see the 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');
|
||
$pollEvidence = Db::name('prescription_esign')->where('prescription_id', 1)->find();
|
||
foreach (['INIT', 'ING', 'FAIL', 'SUCCESS'] as $identityState) {
|
||
Fake::$identityStatus = $identityState;
|
||
$poll = Service::identityStatus(1, 1, $root);
|
||
$assert($poll['identity_status'] === $identityState && $poll['can_complete'] === ($identityState === 'SUCCESS'), 'trusted identity polling readiness ' . $identityState);
|
||
$assert(!str_contains(json_encode($poll), '110101199001011234') && !isset($poll['indivInfo']), 'identity poll omits personal data');
|
||
if ($identityState === 'FAIL') {
|
||
$assert(!$poll['identity_details_required'] && !isset($poll['auth_url']), 'rejected provider flow offers no sign readiness or obsolete auth URL');
|
||
}
|
||
}
|
||
$assert($pollEvidence === Db::name('prescription_esign')->where('prescription_id', 1)->find()
|
||
&& Fake::$signs === 0 && Db::name('doctor_esign_account')->count() === 0, 'polling is read only and never creates account or signs');
|
||
Fake::$identityName = '其他医师';
|
||
$throws(fn () => Service::identityStatus(1, 1, $root), 'wrong identity cannot become ready');
|
||
Fake::$identityName = '测试医师';
|
||
Fake::$identityFlowId = 'different-flow';
|
||
$throws(fn () => Service::identityStatus(1, 1, $root), 'unrelated authentication cannot become ready');
|
||
Fake::$identityFlowId = null;
|
||
Fake::$identityStatus = 'UNKNOWN';
|
||
$throws(fn () => Service::identityStatus(1, 1, $root), 'unknown provider status fails closed');
|
||
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');
|
||
$before = Fake::$starts;
|
||
Service::start(1, 1, $root, true);
|
||
$assert(Fake::$starts === $before, 'restarting the identity cannot interrupt an in-flight signature');
|
||
};
|
||
$done = Service::complete(1, 1, $root);
|
||
Fake::$duringSign = null;
|
||
$assert($done['status'] === 'signed' && $done['can_download'], 'verified sign archived');
|
||
$pollQueries = Fake::$identityQueries;
|
||
$assert(!Service::identityStatus(1, 1, $root)['can_complete'] && Fake::$identityQueries === $pollQueries, 'signed status polls never contact identity provider');
|
||
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);
|
||
Db::name('tcm_prescription')->where('id', 2)->update(['diagnosis_id' => 10, 'appointment_id' => 40]);
|
||
Service::start(2, 1, $root);
|
||
Fake::$verifyFailure = true;
|
||
$uncertain = Service::complete(2, 1, $root);
|
||
$assert($uncertain['status'] === 'uncertain' && $uncertain['can_retry_verify']
|
||
&& !$uncertain['can_sign'] && !$uncertain['can_resume_identity'], 'verification outage offers original-only verification');
|
||
$before = Fake::$signs; $startsBefore = Fake::$starts; $verifiesBefore = Fake::$verifies;
|
||
Service::start(2, 1, $root, true); Service::complete(2, 1, $root);
|
||
$assert(Fake::$signs === $before && Fake::$starts === $startsBefore, 'unknown outcome never replaces authentication or automatically resigns');
|
||
$assert(!Service::status(2, 2, $root)['can_retry_verify'], 'original verification capability belongs to the signing doctor');
|
||
$throws(fn () => Service::retryVerification(2, 2, $root), 'other viewers cannot retry original verification');
|
||
$stillUncertain = Service::complete(2, 1, $root, '', true);
|
||
$assert($stillUncertain['status'] === 'uncertain' && $stillUncertain['can_retry_verify']
|
||
&& Fake::$signs === $before && Fake::$verifies === $verifiesBefore + 1, 'temporary retry failure leaves original verification available');
|
||
Fake::$verifyFailure = false;
|
||
Fake::$duringVerify = static function () use ($assert, $root): void {
|
||
$state = Service::complete(2, 1, $root, '', true);
|
||
$assert($state['status'] === 'uncertain' && !$state['can_retry_verify'] && !$state['can_sign'], 'concurrent verify request returns current progress without calling provider');
|
||
Service::start(2, 1, $root, true);
|
||
Service::complete(2, 1, $root);
|
||
};
|
||
$verifiedAgain = Service::complete(2, 1, $root, '', true);
|
||
Fake::$duringVerify = null;
|
||
$assert($verifiedAgain['status'] === 'signed' && $verifiedAgain['can_download'] && !$verifiedAgain['can_retry_verify']
|
||
&& Fake::$signs === $before && Fake::$starts === $startsBefore && Fake::$verifies === $verifiesBefore + 2, 'only repeated verification confirms the original and never dispatches signing');
|
||
$assert(Service::complete(2, 1, $root, '', true)['status'] === 'signed' && Fake::$verifies === $verifiesBefore + 2, 'verification-only replay is idempotent');
|
||
$signedAt = $verifiedAgain['signed_at'];
|
||
Service::recover(2);
|
||
$assert(Service::status(2, 1, $root)['signed_at'] === $signedAt && Fake::$signs === $before
|
||
&& Fake::$verifies === $verifiesBefore + 3, 'CLI still re-verifies confirmed original without signing or changing the signature time');
|
||
$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;
|
||
$unknownState = Service::complete(4, 1, $root);
|
||
$assert($unknownState['status'] === 'uncertain' && !$unknownState['can_retry_verify'], 'sign timeout remains uncertain without archived evidence');
|
||
Fake::$signFailure = false;
|
||
$throws(fn () => Service::recover(4), 'missing signed file cannot be invented');
|
||
$throws(fn () => Service::complete(4, 1, $root, '', true), 'verification-only does not replace missing signed file');
|
||
|
||
$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'] && !$rejected['can_resume_identity'], 'explicit supplier rejection allows a fresh identity only');
|
||
$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);
|
||
$frozen = Db::name('prescription_esign')->where('prescription_id', 7)->find();
|
||
Fake::$duringIssueWait = static fn () => throw new \RuntimeException('eligible issuance should not wait again');
|
||
$assert(Service::complete(7, 1, $root)['status'] === 'signed' && Fake::$signs === $before + 1,
|
||
'new auth can retry a definite rejection without waiting again');
|
||
Fake::$duringIssueWait = null;
|
||
$retry = Db::name('prescription_esign')->where('prescription_id', 7)->find();
|
||
$assert($retry['issued_at'] === $frozen['issued_at'] && $retry['source_hash'] === $frozen['source_hash'],
|
||
'retry keeps the exact issuance time and PDF');
|
||
|
||
$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;
|
||
$expired = Service::identityStatus(9, 1, $root);
|
||
$assert($expired['identity_status'] === 'EXPIRED' && !$expired['can_complete']
|
||
&& !$expired['identity_details_required'] && !isset($expired['auth_url']), 'live expiry blocks signing even after successful provider identity');
|
||
$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');
|
||
$throws(fn () => Service::retryVerification(16, 1, $root), 'API cannot query the original against a changed snapshot');
|
||
$assert(Fake::$signs === $before && Service::status(16, 1, $root)['status'] === 'uncertain'
|
||
&& !Service::status(16, 1, $root)['can_retry_verify'], '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' && !$archiveFailure['can_retry_verify']
|
||
&& $evidence['sign_service_id'] !== '' && $evidence['signed_path'] === '', 'archive failure preserves successful supplier reference for manual retrieval');
|
||
$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');
|
||
|
||
$new(21); Service::start(21, 1, $root);
|
||
Fake::$duringIdentity = static fn () => Db::name('prescription_esign')->where('prescription_id', 21)->update(['flow_id' => 'replacement-flow']);
|
||
$assert(!Service::identityStatus(21, 1, $root)['can_complete'], 'stale authentication result after flow replacement cannot become ready');
|
||
Fake::$duringIdentity = null;
|
||
$new(22); Service::start(22, 1, $root);
|
||
Fake::$duringIdentity = static fn () => Db::name('tcm_prescription')->where('id', 22)->update(['void_status' => 1]);
|
||
$throws(fn () => Service::identityStatus(22, 1, $root), 'void during poll invalidates readiness');
|
||
Fake::$duringIdentity = null;
|
||
$new(23); Service::start(23, 1, $root);
|
||
Fake::$duringIdentity = static fn () => Db::name('tcm_prescription')->where('id', 23)->update(['clinical_diagnosis' => 'changed while polling']);
|
||
$changedPoll = Service::identityStatus(23, 1, $root);
|
||
$assert($changedPoll['status'] === 'uncertain' && !$changedPoll['can_complete'], 'snapshot change during poll blocks readiness');
|
||
Fake::$duringIdentity = null;
|
||
|
||
// Some valid auth flows deliberately return no personal details. Only the SDK may validate supplied identity.
|
||
Db::name('doctor_esign_account')->where('doctor_id', 1)->delete();
|
||
$new(24); Service::start(24, 1, $root);
|
||
Fake::$identityDetails = 'null';
|
||
$nullEvidence = Db::name('prescription_esign')->where('prescription_id', 24)->find();
|
||
$before = Fake::$signs; $createsBefore = Fake::$creates; $willBefore = Fake::$willingnessChecks;
|
||
$poll = Service::identityStatus(24, 1, $root);
|
||
$assert($poll['identity_status'] === 'SUCCESS' && !$poll['can_complete'] && $poll['identity_details_required'], 'null identity requires supplemental details before first account binding');
|
||
$assert($nullEvidence === Db::name('prescription_esign')->where('prescription_id', 24)->find()
|
||
&& Fake::$creates === $createsBefore && Fake::$willingnessChecks === $willBefore + 1,
|
||
'supplemental identity poll reads live willingness without mutating database state');
|
||
$willBefore = Fake::$willingnessChecks;
|
||
// Generated fixture: checksum-valid shape, never a real user or provider request.
|
||
$supplementalNumber = '110101199001011237';
|
||
foreach (['', 'invalid', '110101199013011234', '110101199001011234', str_repeat('1', 300), "110101199001011237\n9"] as $invalidNumber) {
|
||
$invalid = Service::complete(24, 1, $root, $invalidNumber);
|
||
$assert($invalid['status'] === 'authenticating' && $invalid['identity_details_required'] && !$invalid['can_complete'], 'invalid/missing supplemental input preserves authentication and requests correction');
|
||
$assert(Fake::$creates === $createsBefore && Fake::$signs === $before && Fake::$willingnessChecks === ++$willBefore,
|
||
'invalid input only checks willingness without calling binding or signing');
|
||
$assert(Db::name('prescription_esign')->where('prescription_id', 24)->value('flow_id') === $nullEvidence['flow_id'], 'invalid input does not discard successful auth flow');
|
||
}
|
||
Fake::$createRejection = 'PROVIDER_IDENTITY_MISMATCH';
|
||
$rejected = Service::complete(24, 1, $root, $supplementalNumber);
|
||
Fake::$createRejection = null;
|
||
$assert($rejected['status'] === 'failed' && $rejected['can_resume_identity'] && Fake::$creates === $createsBefore + 1
|
||
&& Fake::$signs === $before && Db::name('doctor_esign_account')->count() === 0, 'SDK identity mismatch cannot bind an account or sign');
|
||
$assert(!str_contains(json_encode($rejected), $supplementalNumber), 'SDK rejection DTO never includes supplemental number');
|
||
$failedEvidence = Db::name('prescription_esign')->where('prescription_id', 24)->find();
|
||
$failedPoll = Service::identityStatus(24, 1, $root);
|
||
$assert($failedPoll['identity_details_required'] && $failedPoll['can_resume_identity'] && !$failedPoll['can_complete']
|
||
&& $failedEvidence === Db::name('prescription_esign')->where('prescription_id', 24)->find(), 'retained pre-sign error can poll the same original flow without mutation');
|
||
$startsBefore = Fake::$starts;
|
||
$reused = Service::start(24, 1, $root);
|
||
$assert($reused['status'] === 'failed' && $reused['can_resume_identity'] && Fake::$starts === $startsBefore,
|
||
'ordinary start reuses a retained failed flow');
|
||
$validatedFlow = Db::name('prescription_esign')->where('prescription_id', 24)->value('flow_id');
|
||
$signedSupplement = Service::complete(24, 1, $root, $supplementalNumber);
|
||
$assert($signedSupplement['status'] === 'signed' && Fake::$signs === $before + 1, 'SDK validated supplemental identity may sign');
|
||
$assert(Fake::$createdPerson === ['测试医师', $supplementalNumber, $validatedFlow], 'SDK binding uses server doctor name, supplemental number and exact validated flow');
|
||
$assert(!str_contains(json_encode($signedSupplement), $supplementalNumber), 'successful DTO never includes supplemental number');
|
||
$assert(!str_contains(json_encode(Db::name('prescription_esign')->select()->toArray()), $supplementalNumber)
|
||
&& !str_contains(json_encode(Db::name('doctor_esign_account')->select()->toArray()), $supplementalNumber), 'supplemental number is never stored in evidence or account tables');
|
||
|
||
$new(25); Service::start(25, 1, $root);
|
||
$createsBefore = Fake::$creates;
|
||
$poll = Service::identityStatus(25, 1, $root);
|
||
$assert($poll['can_complete'] && !$poll['identity_details_required'], 'null identity on original SDK-bound flow needs no repeated identity input');
|
||
$assert(Service::complete(25, 1, $root)['status'] === 'signed' && Fake::$creates === $createsBefore, 'bound-null flow reuses matching account without creating another');
|
||
|
||
$new(26); Service::start(26, 1, $root); $before = Fake::$signs;
|
||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replaced-account']);
|
||
$throws(fn () => Service::identityStatus(26, 1, $root), 'null identity with replaced bound account is not ready');
|
||
$assert(Service::complete(26, 1, $root, $supplementalNumber)['status'] === 'failed' && Fake::$signs === $before, 'supplement cannot override replaced SDK account binding');
|
||
Db::name('doctor_esign_account')->where('doctor_id', 1)->delete();
|
||
$new(27); Service::start(27, 1, $root);
|
||
Db::name('doctor_esign_account')->insert(['doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||
'account_id' => 'account-test', 'doctor_name' => '测试医师', 'create_time' => time()]);
|
||
$throws(fn () => Service::identityStatus(27, 1, $root), 'concurrent first binding cannot make null unbound poll ready');
|
||
$assert(Service::complete(27, 1, $root, $supplementalNumber)['status'] === 'failed' && Fake::$signs === $before, 'concurrent first binding cannot convert null unbound auth into bound auth');
|
||
Db::name('doctor_esign_account')->where('doctor_id', 1)->delete();
|
||
|
||
$caseId = 28;
|
||
foreach (['missing', 'empty', 'malformed', 'masked'] as $badDetails) {
|
||
$new($caseId); Service::start($caseId, 1, $root); Fake::$identityDetails = $badDetails;
|
||
$throws(fn () => Service::identityStatus($caseId, 1, $root), 'malformed or missing identity never asks for supplemental override');
|
||
$assert(Service::complete($caseId, 1, $root, $supplementalNumber)['status'] === 'failed'
|
||
&& Fake::$creates === $createsBefore && Fake::$signs === $before, 'supplement cannot override malformed provider identity');
|
||
$caseId++;
|
||
}
|
||
Fake::$identityDetails = 'full'; Fake::$identityName = '其他医师';
|
||
$new(32); Service::start(32, 1, $root);
|
||
$assert(Service::complete(32, 1, $root, $supplementalNumber)['status'] === 'failed'
|
||
&& Fake::$creates === $createsBefore && Fake::$signs === $before, 'supplement cannot override explicit identity name mismatch');
|
||
Fake::$identityName = '测试医师'; Fake::$identityDetails = 'null';
|
||
$new(33); Service::start(33, 1, $root); Fake::$identityObject = 'ORGANIZATION';
|
||
$throws(fn () => Service::identityStatus(33, 1, $root), 'null individual details on organization flow are rejected');
|
||
$assert(Service::complete(33, 1, $root, $supplementalNumber)['status'] === 'failed' && Fake::$creates === $createsBefore, 'wrong object type cannot bind supplemental identity');
|
||
Fake::$identityObject = 'INDIVIDUAL';
|
||
$new(34); Service::start(34, 1, $root); Fake::$identityApp = 'foreign-app';
|
||
$throws(fn () => Service::identityStatus(34, 1, $root), 'null details from another app cannot become ready');
|
||
$assert(Service::complete(34, 1, $root, $supplementalNumber)['status'] === 'failed' && Fake::$creates === $createsBefore, 'wrong app cannot bind supplemental identity');
|
||
Fake::$identityApp = 'fixture';
|
||
$new(35); Service::start(35, 1, $root); Fake::$expiredWillingness = true;
|
||
$expired = Service::identityStatus(35, 1, $root);
|
||
$assert($expired['identity_status'] === 'EXPIRED' && !$expired['identity_details_required']
|
||
&& !$expired['can_complete'], 'expired null identity never solicits supplemental input');
|
||
$expiredCompletion = Service::complete(35, 1, $root);
|
||
$assert($expiredCompletion['status'] === 'failed' && !$expiredCompletion['can_resume_identity']
|
||
&& empty($expiredCompletion['identity_details_required']) && Fake::$creates === $createsBefore && Fake::$signs === $before,
|
||
'expired auth cannot ask for, bind supplemental identity, or sign');
|
||
Fake::$expiredWillingness = false;
|
||
$new(36); Service::start(36, 1, $root);
|
||
Fake::$duringIdentity = static fn () => Db::name('prescription_esign')->where('prescription_id', 36)->update(['flow_id' => 'replacement-flow']);
|
||
$poll = Service::identityStatus(36, 1, $root);
|
||
$assert(!$poll['can_complete'] && !$poll['identity_details_required'], 'stale null identity poll requests neither sign nor supplemental identity');
|
||
Fake::$duringIdentity = null; Fake::$identityDetails = 'full';
|
||
|
||
$new(37); Service::start(37, 1, $root); $startsBefore = Fake::$starts;
|
||
$flow = Db::name('prescription_esign')->where('prescription_id', 37)->value('flow_id');
|
||
Fake::$duringWillingness = static fn () => Service::start(37, 1, $root, true);
|
||
$poll = Service::identityStatus(37, 1, $root);
|
||
Fake::$duringWillingness = null;
|
||
$assert($poll['identity_status'] === 'UNAVAILABLE' && !$poll['can_complete'] && !$poll['identity_details_required']
|
||
&& Fake::$starts === $startsBefore + 1
|
||
&& Db::name('prescription_esign')->where('prescription_id', 37)->value('flow_id') !== $flow,
|
||
'explicit restart replaces the flow and makes the in-progress poll result stale');
|
||
|
||
$new(38); Service::start(38, 1, $root);
|
||
Fake::$verifiedDoctor = '其他医师';
|
||
$wrongCertificate = Service::complete(38, 1, $root);
|
||
$before = Fake::$signs;
|
||
$assert($wrongCertificate['status'] === 'uncertain' && $wrongCertificate['can_retry_verify'] && !$wrongCertificate['can_download'],
|
||
'valid PDF certificate for a different doctor never confirms a new prescription');
|
||
$wrongCertificate = Service::retryVerification(38, 1, $root);
|
||
$assert($wrongCertificate['status'] === 'uncertain' && !$wrongCertificate['can_download'] && Fake::$signs === $before,
|
||
'valid PDF certificate for a different doctor never confirms a recovered prescription');
|
||
Fake::$verifiedDoctor = '测试医师';
|
||
Fake::$duringVerify = static fn () => Db::name('prescription_esign')->where('prescription_id', 38)->update(['operation_token' => 'replacement-token']);
|
||
$changed = Service::retryVerification(38, 1, $root);
|
||
Fake::$duringVerify = null;
|
||
$assert($changed['status'] === 'uncertain' && !$changed['can_download'] && Fake::$signs === $before,
|
||
'in-flight verification cannot commit with a stale archive token');
|
||
Db::name('prescription_esign')->where('prescription_id', 38)->update(['started_at' => time() - 361, 'update_time' => time() - 361]);
|
||
$assert(Service::status(38, 1, $root)['can_retry_verify'], 'abandoned verification lease can safely be retried');
|
||
$assert(Service::retryVerification(38, 1, $root)['status'] === 'signed' && Fake::$signs === $before,
|
||
'expired verification lease only rechecks the same signed original');
|
||
|
||
$new(39); Service::start(39, 1, $root); Fake::$verifyFailure = true;
|
||
Service::complete(39, 1, $root); Fake::$verifyFailure = false;
|
||
$evidence = Db::name('prescription_esign')->where('prescription_id', 39)->find();
|
||
$archivePath = $dir . '/pdf/' . $evidence['signed_path'];
|
||
Fake::$duringVerify = static fn () => file_put_contents($archivePath, '%PDF-1.7 tampered original');
|
||
$tampered = Service::retryVerification(39, 1, $root);
|
||
Fake::$duringVerify = null;
|
||
$assert($tampered['status'] === 'uncertain' && !$tampered['can_download'], 'artifact modified during verification cannot become signed');
|
||
$verifiesBefore = Fake::$verifies;
|
||
$assert(Service::retryVerification(39, 1, $root)['status'] === 'uncertain' && Fake::$verifies === $verifiesBefore,
|
||
'tampered original never reaches the verification provider');
|
||
unlink($archivePath);
|
||
$assert(!Service::status(39, 1, $root)['can_retry_verify'], 'missing archived file disables the retry action even with a reference and digest');
|
||
|
||
$new(40); Service::start(40, 1, $root); Fake::$verifyFailure = true;
|
||
Service::complete(40, 1, $root); Fake::$verifyFailure = false;
|
||
Db::name('tcm_prescription')->where('id', 40)->update(['esign_status' => 'signing']);
|
||
$throws(fn () => Service::recover(40), 'CLI cannot interrupt an in-flight signature with archive data');
|
||
$throws(fn () => Service::retryVerification(40, 1, $root), 'API cannot interrupt an in-flight signature with archive data');
|
||
Db::name('prescription_esign')->where('prescription_id', 40)->update(['update_time' => time() - 361, 'started_at' => time() - 361]);
|
||
$assert(Service::status(40, 1, $root)['can_retry_verify'], 'abandoned signing lease permits verification of its archived original');
|
||
$before = Fake::$signs;
|
||
Service::recover(40);
|
||
$assert(Service::status(40, 1, $root)['status'] === 'signed' && Fake::$signs === $before, 'CLI can reverify an older archived signing lease');
|
||
|
||
$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');
|
||
|
||
$legacyCases = [
|
||
41 => [],
|
||
42 => ['audit_status' => 1],
|
||
43 => ['audit_status' => 2],
|
||
44 => ['is_system_auto' => 1],
|
||
45 => ['void_status' => 1],
|
||
46 => ['delete_time' => time()],
|
||
47 => [],
|
||
48 => ['clinical_diagnosis' => ''],
|
||
];
|
||
foreach ($legacyCases as $id => $values) {
|
||
$new($id, false);
|
||
Db::name('tcm_prescription')->where('id', $id)->update($values + [
|
||
'esign_required' => 0, 'esign_status' => 'legacy', 'audit_status' => 0,
|
||
'doctor_signature' => 'original-handwritten-signature',
|
||
]);
|
||
}
|
||
Db::name('tcm_prescription_order')->insert([
|
||
'id' => 41, 'prescription_id' => 41, 'prescription_audit_status' => 0, 'fulfillment_status' => 0,
|
||
]);
|
||
$disabled = Service::status(41, 1, $root);
|
||
Service::assertSignedById(41, true);
|
||
$assert(!$disabled['enabled'] && !$disabled['required'] && $disabled['status'] === 'legacy' && !$disabled['can_sign'],
|
||
'disabled rollout keeps an unenrolled pending prescription compatible');
|
||
$assert($disabled['can_submit_for_review'] === true && $disabled['review_submitted_at'] === 0,
|
||
'prescriptions created without required e-sign can still be submitted');
|
||
$legacySubmission = PrescriptionLogic::submitForReview(47, 1, $root);
|
||
$assert($legacySubmission['review_submitted_at'] > 0 && $legacySubmission['can_submit_for_review'] === false,
|
||
'legacy submission records the first upload under existing signature configuration');
|
||
$assert(Service::status(47, 2, $root)['can_review_prescription']
|
||
&& PrescriptionLogic::audit(47, 'reject', '测试驳回', 1, $root)
|
||
&& (int) Db::name('tcm_prescription')->where('id', 47)->value('void_status') === 1,
|
||
'an uploaded handwritten prescription is reviewable while eSign is disabled');
|
||
$alreadyEnrolled = Service::status(5, 1, $root);
|
||
$assert($alreadyEnrolled['required'] && !$alreadyEnrolled['can_sign']
|
||
&& str_contains($alreadyEnrolled['message'], '尚未启用'), 'disabled rollout explains blocked enrolled signing');
|
||
|
||
$config->set($settings, 'esign');
|
||
$draft = Db::name('tcm_prescription')->find(41);
|
||
$pending = Service::status(41, 1, $root);
|
||
$assert($pending['required'] && $pending['status'] === 'pending' && !$pending['can_sign']
|
||
&& $pending['awaiting_upload'] && $pending['can_submit_for_review'] && !$pending['can_review_prescription']
|
||
&& !$pending['can_resume_identity'], 'unenrolled pending prescription offers upload before eSign');
|
||
$other = Service::status(41, 2, $root);
|
||
$assert($other['required'] && !$other['can_sign'] && $other['awaiting_upload'] && !$other['can_submit_for_review']
|
||
&& !$other['can_review_prescription'] && str_contains($other['message'], '上传处方'),
|
||
'auditor can see that the doctor needs to upload');
|
||
$throws(fn () => Service::start(41, 2, $root), 'auditor cannot enroll a different doctor’s pending prescription');
|
||
$startsBeforeUpload = Fake::$starts;
|
||
$throws(fn () => Service::start(41, 1, $root), 'doctor cannot start prescription signing before upload');
|
||
$throws(fn () => Service::identityStatus(41, 1, $root), 'identity status cannot resume before upload');
|
||
$throws(fn () => Service::complete(41, 1, $root), 'doctor cannot complete signing before upload');
|
||
$assert(PrescriptionLogic::audit(41, 'approve', '', 1, $root) === false
|
||
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual approval blocks an unsubmitted prescription');
|
||
$assert(PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root) === false
|
||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方')
|
||
&& (int) Db::name('tcm_prescription_order')->where('id', 41)->value('prescription_audit_status') === 0,
|
||
'business order approval blocks an unsubmitted prescription');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(41, 2, $root), 'another doctor cannot upload on behalf of the owner');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(42, 1, $root), 'closed historical prescription cannot get a new upload timestamp');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(44, 1, $root), 'system-generated blank prescription cannot upload');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(45, 1, $root), 'voided prescription cannot upload');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(46, 1, $root), 'deleted prescription cannot upload');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(48, 1, $root), 'a prescription awaiting eSign must have a clinical diagnosis before upload');
|
||
$assert($draft === Db::name('tcm_prescription')->find(41)
|
||
&& Fake::$starts === $startsBeforeUpload && !Db::name('prescription_esign')->where('prescription_id', 41)->find(),
|
||
'blocked checks neither contact the signing provider nor change the draft');
|
||
|
||
foreach ([42, 43, 45, 46] as $id) {
|
||
$historical = Service::describe(Db::name('tcm_prescription')->find($id), 1);
|
||
$assert(!$historical['required'] && $historical['status'] === 'legacy' && !$historical['can_sign']
|
||
&& !$historical['awaiting_upload'] && !$historical['can_review_prescription'],
|
||
'approved, rejected, voided and deleted legacy cases are never auto-enrolled');
|
||
$throws(fn () => Service::start($id, 1, $root), 'closed historical prescription cannot be enrolled by signing');
|
||
}
|
||
Service::assertSignedById(42, true);
|
||
$blank = Service::status(44, 1, $root);
|
||
$assert($blank['required'] && $blank['status'] === 'pending' && !$blank['can_sign']
|
||
&& str_contains($blank['message'], '补全处方'), 'auto blank explains the need to fill its contents');
|
||
$throws(fn () => Service::start(44, 1, $root), 'auto blank cannot be frozen or signed');
|
||
$throws(fn () => Service::start(48, 1, $root), 'invalid legacy contents fail before enrollment');
|
||
$assert((int) Db::name('tcm_prescription')->where('id', 48)->value('esign_required') === 0
|
||
&& !Db::name('prescription_esign')->where('prescription_id', 48)->find(), 'failed preparation keeps the draft unmodified');
|
||
$submission = PrescriptionLogic::submitForReview(41, 1, $root);
|
||
$assert($submission['review_submitted_at'] > 0 && $submission['can_submit_for_review'] === false
|
||
&& PrescriptionLogic::submitForReview(41, 1, $root) === $submission,
|
||
'doctor upload persists once before signing and is idempotent');
|
||
$uploaded = Service::status(41, 1, $root);
|
||
$assert($uploaded['can_sign'] && !$uploaded['awaiting_upload'] && !$uploaded['can_review_prescription']
|
||
&& !$uploaded['can_submit_for_review'] && $uploaded['review_submitted_at'] === $submission['review_submitted_at'],
|
||
'upload enables doctor signing while the prescription remains unavailable for review');
|
||
$pendingList = static fn () => new class($root) extends PrescriptionLists {
|
||
public function __construct(array $adminInfo)
|
||
{
|
||
$this->adminId = 1;
|
||
$this->adminInfo = $adminInfo;
|
||
$this->params = ['audit_filter' => 'pending'];
|
||
$this->searchWhere = [['id', 'in', [41, 42, 44, 48]]];
|
||
$this->limitOffset = 0;
|
||
$this->limitLength = 20;
|
||
}
|
||
};
|
||
$list = $pendingList();
|
||
$assert($list->count() === 0 && $list->lists() === [],
|
||
'pending review filter excludes uploaded but unsigned prescriptions from both results and count');
|
||
$assert(PrescriptionLogic::audit(41, 'reject', '测试驳回', 1, $root) === false
|
||
&& str_contains(PrescriptionLogic::getError(), '电子签署')
|
||
&& PrescriptionOrderLogic::auditPrescription(41, 'reject', '测试驳回', 1, $root) === false
|
||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署'), 'existing review entry points require doctor signature after upload');
|
||
|
||
$started = Service::start(41, 1, $root);
|
||
$frozen = Db::name('tcm_prescription')->find(41);
|
||
$evidence = Db::name('prescription_esign')->where('prescription_id', 41)->find();
|
||
$assert($started['status'] === 'authenticating' && $started['can_resume_identity']
|
||
&& (int) $frozen['esign_required'] === 1 && $frozen['doctor_signature'] === $draft['doctor_signature']
|
||
&& $evidence['snapshot_hash'] === Policy::hash($draft) && is_file($dir . '/pdf/' . $evidence['source_path']),
|
||
'starting eSign freezes the same prescription and preserves its handwritten data');
|
||
$throws(fn () => Policy::assertMutable($frozen), 'newly enrolled draft is frozen before approval');
|
||
$signedStatus = Service::complete(41, 1, $root);
|
||
$signedRx = PrescriptionLogic::withSigningStatus(Db::name('tcm_prescription')->find(41), 2, false);
|
||
$assert($signedStatus['status'] === 'signed' && $signedStatus['can_review_prescription']
|
||
&& $signedRx['can_review_prescription'] && $signedRx['esign']['can_review_prescription']
|
||
&& !$signedStatus['can_submit_for_review'] && $signedStatus['review_submitted_at'] === $submission['review_submitted_at']
|
||
&& (int) $signedRx['audit_status'] === 0, 'verified signing makes the existing upload available for review without approving it');
|
||
$list = $pendingList();
|
||
$assert($list->count() === 1 && array_map('intval', array_column($list->lists(), 'id')) === [41],
|
||
'pending review filter includes the signed prescription in the actual page and count');
|
||
$archivePath = $dir . '/pdf/' . Db::name('prescription_esign')->where('prescription_id', 41)->value('signed_path');
|
||
$archived = file_get_contents($archivePath);
|
||
file_put_contents($archivePath, $archived . 'changed');
|
||
$assert(!Service::status(41, 1, $root)['can_review_prescription']
|
||
&& !PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0],
|
||
Db::name('tcm_prescription')->find(41))['can_review_prescription']
|
||
&& !PrescriptionLogic::audit(41, 'reject', '测试驳回', 1, $root)
|
||
&& !PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root),
|
||
'a missing or modified original blocks review status and mutations');
|
||
$assert(!$pendingList()->lists()[0]['can_review_prescription'],
|
||
'a row with a stored signed state still needs an intact archive to allow review');
|
||
file_put_contents($archivePath, $archived);
|
||
$assert(PrescriptionLogic::audit(41, 'approve', '', 1, $root)
|
||
&& (int) Db::name('tcm_prescription')->where('id', 41)->value('audit_status') === 1,
|
||
'the same prescription can be approved after verified eSign');
|
||
$assert(PrescriptionLogic::submitForReview(41, 1, $root) === $submission,
|
||
'a retry after approval still returns the existing upload receipt');
|
||
$throws(fn () => Service::assertSignedById(41, true), 'sandbox enrollment permits approval but still blocks formal dispensing');
|
||
|
||
$new(49);
|
||
Db::name('admin')->insert(['id' => 2, 'name' => '医生显示名']);
|
||
Db::name('tcm_prescription')->where('id', 49)->update(['creator_id' => 2, 'doctor_name' => '医生显示名', 'audit_status' => 0]);
|
||
Fake::$startFailure = true;
|
||
$assert(Service::start(49, 2, $root)['status'] === 'failed' && Fake::$startedName === '医生显示名',
|
||
'unconfigured signer uses the original prescription name');
|
||
Fake::$startFailure = false;
|
||
$before = Db::name('prescription_esign')->where('prescription_id', 49)->find();
|
||
$aliasSettings = $settings + ['sandbox_signer_names' => '{"2":"测试实名"}'];
|
||
$config->set($aliasSettings, 'esign');
|
||
$assert(Service::start(49, 2, $root)['can_resume_identity'] && Fake::$startedName === '测试实名',
|
||
'a fresh attempt after provider rejection uses the authorized legal name');
|
||
$after = Db::name('prescription_esign')->where('prescription_id', 49)->find();
|
||
$assert($after['signer_name'] === '测试实名' && array_intersect_key($before, array_flip(['snapshot_hash', 'source_hash', 'source_path']))
|
||
=== array_intersect_key($after, array_flip(['snapshot_hash', 'source_hash', 'source_path'])), 'the retry keeps the original PDF and freezes the new signer');
|
||
$config->set($settings + ['sandbox_signer_names' => '{"2":"变更实名"}'], 'esign');
|
||
Fake::$identityName = '医生显示名';
|
||
$throws(fn () => Service::identityStatus(49, 2, $root), 'provider must confirm the frozen signer, not the display name');
|
||
Fake::$identityName = '测试实名';
|
||
$assert(Service::identityStatus(49, 2, $root)['can_complete'], 'config changes do not change the pending identity flow');
|
||
Fake::$verifiedDoctor = '医生显示名';
|
||
$assert(Service::complete(49, 2, $root)['can_retry_verify'] && Fake::$createdPerson[0] === '测试实名',
|
||
'account binds under the frozen name and a certificate with the display name fails verification');
|
||
Fake::$verifiedDoctor = '测试实名';
|
||
$before = Fake::$signs;
|
||
$assert(Service::retryVerification(49, 2, $root)['status'] === 'signed' && Fake::$signs === $before,
|
||
'archive verification uses the frozen signer after configuration changes without signing again');
|
||
PrescriptionLogic::submitForReview(49, 2, $root);
|
||
$assert(PrescriptionLogic::audit(49, 'approve', '', 1, $root)
|
||
&& !empty(Service::download(49, 2, $root)['sha256']), 'verified alias prescription can be audited and downloaded');
|
||
$assert(PrescriptionLogic::consumeLastAuditWecomNotify() === null, 'a sandbox audit does not send a live WeCom notification');
|
||
$throws(fn () => Service::assertSignedById(49, true), 'alias mapping does not make a sandbox prescription dispensable');
|
||
$new(50);
|
||
Db::name('tcm_prescription')->where('id', 50)->update(['creator_id' => 2, 'doctor_name' => '医生显示名']);
|
||
$config->set(array_replace($aliasSettings, ['environment' => 'production']), 'esign');
|
||
$assert(Service::start(50, 2, $root)['can_resume_identity'] && Fake::$startedName === '医生显示名', 'production does not read sandbox signer mappings');
|
||
$config->set($settings, 'esign');
|
||
Fake::$identityName = Fake::$verifiedDoctor = '测试医师';
|
||
|
||
$new(51);
|
||
Service::start(51, 1, $root);
|
||
Fake::$signDate = '2026-02-30 13:45:36';
|
||
$unverifiedTime = Service::complete(51, 1, $root);
|
||
$assert($unverifiedTime['status'] === 'uncertain' && $unverifiedTime['signature_time'] === 0
|
||
&& $unverifiedTime['can_retry_verify'] && !$unverifiedTime['can_download'],
|
||
'a missing or invalid signing date cannot pass completion or cause a second signing attempt');
|
||
$before = Fake::$signs;
|
||
$issuedEvidence = Db::name('prescription_esign')->where('prescription_id', 51)->find();
|
||
$issuedAt = (int) $issuedEvidence['issued_at'];
|
||
$expected = $issuedAt + 1;
|
||
Fake::$signDate = gmdate('Y-m-d H:i:s', $expected + 28800);
|
||
Fake::$timeFrom = 'local';
|
||
$assert(Service::retryVerification(51, 1, $root)['status'] === 'uncertain', 'new issuance requires a TSA timestamp');
|
||
Fake::$timeFrom = 'tsa';
|
||
Fake::$signDate = gmdate('Y-m-d H:i:s', $issuedAt - 1 + 28800);
|
||
$assert(Service::retryVerification(51, 1, $root)['status'] === 'uncertain', 'TSA cannot predate issuance confirmation');
|
||
Fake::$signDate = gmdate('Y-m-d H:i:s', $expected + 28800);
|
||
$withTime = Service::retryVerification(51, 1, $root);
|
||
$assert($withTime['status'] === 'signed' && $withTime['issued_at'] === $issuedAt && $withTime['signature_time'] === $expected
|
||
&& $withTime['signature_time_source'] === 'tsa' && Fake::$signs === $before,
|
||
'reverification recovers the original signing time in the SDK timezone without signing again');
|
||
$issuedText = '开具确认时间(北京时间):' . gmdate('Y-m-d H:i:s', $issuedAt + 28800);
|
||
$assert($issuedAt > 0 && str_contains(file_get_contents($dir . '/pdf/' . $issuedEvidence['source_path']),
|
||
bin2hex(mb_convert_encoding($issuedText, 'UTF-16BE', 'UTF-8'))), 'the PDF given to the signer contains the exact frozen issuance time');
|
||
Fake::$timeFrom = 'tsa';
|
||
Db::name('tcm_prescription')->where('id', 51)->update(['void_status' => 1, 'esign_status' => 'voided']);
|
||
$unchanged = Db::name('tcm_prescription')->find(51);
|
||
Db::name('prescription_esign')->where('prescription_id', 51)->update(['signature_time' => 0, 'signature_time_source' => '']);
|
||
Service::recover(51);
|
||
$backfilled = Service::status(51, 1, $root);
|
||
$assert($backfilled['status'] === 'voided' && $backfilled['signature_time'] === $expected
|
||
&& $backfilled['signature_time_source'] === 'tsa' && $backfilled['signed_at'] === $withTime['signed_at']
|
||
&& $unchanged === Db::name('tcm_prescription')->find(51), 'backfill records the audit evidence of a voided prescription without changing its lifecycle');
|
||
Fake::$signDate = gmdate('Y-m-d H:i:s', $expected + 1 + 28800);
|
||
$throws(fn () => Service::recover(51), 'an inconsistent repeat result is not allowed to overwrite the recorded signing time');
|
||
$assert(Service::status(51, 1, $root) === $backfilled, 'recorded signing time remains intact after inconsistent verification');
|
||
Fake::$signDate = null;
|
||
|
||
$new(52); Service::start(52, 1, $root);
|
||
$waited = false;
|
||
Fake::$duringIssueWait = static function (int $seconds, int $nanoseconds) use (&$waited): bool|array {
|
||
$waited = true;
|
||
return \time_nanosleep($seconds, $nanoseconds);
|
||
};
|
||
Fake::$tsaClockOffset = -1;
|
||
$skewed = Service::complete(52, 1, $root);
|
||
Fake::$tsaClockOffset = 0;
|
||
Fake::$duringIssueWait = null;
|
||
$assert($waited && $skewed['status'] === 'signed' && $skewed['signature_time_source'] === 'tsa'
|
||
&& $skewed['signature_time'] >= $skewed['issued_at'], 'new dispatch accounts for a TSA clock one second behind');
|
||
|
||
foreach ([53 => 'voided', 54 => 'signing'] as $id => $expectedStatus) {
|
||
$new($id); Service::start($id, 1, $root); $before = Fake::$signs;
|
||
Fake::$duringIssueWait = static function () use ($assert, $manager, $root, $id, $before): bool {
|
||
$assert(!$manager->connect()->getPdo()->inTransaction()
|
||
&& (int) Db::name('prescription_esign')->where('prescription_id', $id)->value('issued_at') > 0,
|
||
'the issuance is committed before the dispatch wait');
|
||
$assert(Service::complete($id, 1, $root)['status'] === 'signing' && Fake::$signs === $before,
|
||
'a second completion cannot dispatch while the first is waiting');
|
||
if ($id === 53) {
|
||
Db::name('tcm_prescription')->where('id', $id)->update(['void_status' => 1]);
|
||
} else {
|
||
Db::name('prescription_esign')->where('prescription_id', $id)->update(['operation_token' => 'replacement-token']);
|
||
}
|
||
return true;
|
||
};
|
||
$state = Service::complete($id, 1, $root);
|
||
Fake::$duringIssueWait = null;
|
||
$assert($state['status'] === $expectedStatus && Fake::$signs === $before,
|
||
'a void or operation replacement during the wait prevents dispatch');
|
||
}
|
||
|
||
$sample = Db::name('tcm_prescription')->find(2);
|
||
Db::execute('CREATE TABLE zyt_system_menu (id INTEGER PRIMARY KEY, perms TEXT, is_disable INTEGER DEFAULT 0)');
|
||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER, role_id INTEGER)');
|
||
Db::execute('CREATE TABLE zyt_system_role_menu (role_id INTEGER, menu_id INTEGER)');
|
||
Db::execute('CREATE TABLE zyt_system_role (id INTEGER PRIMARY KEY, name TEXT, data_scope INTEGER, delete_time INTEGER)');
|
||
Db::execute("INSERT INTO zyt_system_menu (id, perms) VALUES (1, 'tcm.diagnosis/kaifang'), (2, 'cf.prescription/lists'), (3, 'cf.prescription/audit')");
|
||
Db::execute('INSERT INTO zyt_admin_role VALUES (1, 1), (2, 1), (3, 2), (4, 3)');
|
||
Db::execute('INSERT INTO zyt_system_role_menu VALUES (1, 1), (2, 2), (3, 3)');
|
||
Db::execute("INSERT INTO zyt_system_role VALUES (1, 'Doctor', 4, NULL), (2, 'Read only', 4, NULL), (3, 'Audit', 1, NULL)");
|
||
Db::execute('CREATE TABLE zyt_tcm_diagnosis (id INTEGER PRIMARY KEY, status INTEGER, patient_id INTEGER,
|
||
assistant_id INTEGER, patient_name TEXT, gender INTEGER, age INTEGER, phone TEXT, delete_time INTEGER)');
|
||
Db::execute("INSERT INTO zyt_tcm_diagnosis VALUES (10, 1, 99, 3, 'Test patient', 1, 30, '13800000000', NULL)");
|
||
Db::execute('CREATE TABLE zyt_doctor_appointment (id INTEGER PRIMARY KEY, patient_id INTEGER, doctor_id INTEGER, status INTEGER)');
|
||
Db::execute('INSERT INTO zyt_doctor_appointment VALUES (40, 10, 1, 3)');
|
||
Db::execute('CREATE TABLE zyt_doctor_note (id INTEGER PRIMARY KEY, diagnosis_id INTEGER, delete_time INTEGER)');
|
||
Db::execute('CREATE TABLE zyt_diagnosis_view_records (id INTEGER PRIMARY KEY, diagnosis_id INTEGER, user_id INTEGER, delete_time INTEGER)');
|
||
Db::execute('CREATE TABLE zyt_doctor_medicine (id INTEGER PRIMARY KEY, name TEXT, status INTEGER, delete_time INTEGER)');
|
||
Db::execute("INSERT INTO zyt_doctor_medicine VALUES (1, '测试药材', 1, NULL)");
|
||
|
||
$doctor = ['root' => 0, 'admin_id' => 1, 'name' => '测试医师', 'role_id' => [1]];
|
||
$otherDoctor = array_replace($doctor, ['admin_id' => 2, 'permissions' => ['tcm.diagnosis/kaifang']]);
|
||
$readOnly = ['root' => 0, 'admin_id' => 3, 'role_id' => [2]];
|
||
$auditor = ['root' => 0, 'admin_id' => 4, 'role_id' => [3]];
|
||
$permissionAlias = new \ReflectionMethod(AuthMiddleware::class, 'matchPermissionAlias');
|
||
foreach (PrescriptionLogic::PRESCRIBE_PERMISSIONS as $grant) {
|
||
$assert($permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/void', [$grant]), 'prescribing grants permit the void route');
|
||
$assert($permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/submitforreview', [$grant]), 'prescribing grants permit the upload route');
|
||
}
|
||
$assert(!$permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/void', ['cf.prescription/lists']), 'read permission grants no void route');
|
||
$assert(!$permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/submitforreview', ['cf.prescription/lists']), 'read permission grants no upload route');
|
||
$throws(fn () => PrescriptionLogic::submitForReview(41, 3, $readOnly), 'read-only accounts cannot upload prescriptions');
|
||
$assert(PrescriptionLogic::detail(2, 1, $doctor)['can_void'], 'creator can void signed prescription through detail');
|
||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||
$assert((int) $appointmentPrescription['id'] === 2 && $appointmentPrescription['can_void'] === true
|
||
&& $appointmentPrescription['can_restore_rejected'] === false && $appointmentPrescription['esign']['status'] === 'signed',
|
||
'appointment lookup exposes creator actions and the original signature state');
|
||
$assert(!PrescriptionLogic::detail(2, 2, $otherDoctor)['can_void']
|
||
&& PrescriptionLogic::getByAppointment(40, 2, $otherDoctor)['can_void'] === false
|
||
&& !PrescriptionLogic::void(2, 2, $otherDoctor), 'readable prescription cannot be voided by another doctor');
|
||
$assert(PrescriptionLogic::getByAppointment(40, 3, $readOnly) === null && PrescriptionLogic::getError() !== '',
|
||
'appointment lookup keeps action state behind prescription view permission');
|
||
Db::name('system_menu')->insert(['id' => 4, 'perms' => 'cf.prescription/del']);
|
||
Db::name('system_role_menu')->insert(['role_id' => 1, 'menu_id' => 4]);
|
||
Db::name('system_role')->where('id', 1)->update(['data_scope' => 1]);
|
||
$assert(!PrescriptionLogic::void(2, 2, $otherDoctor), 'a doctor with a delete grant still cannot void another doctor\'s prescription');
|
||
Db::name('system_role_menu')->where('menu_id', 4)->delete();
|
||
Db::name('system_role')->where('id', 1)->update(['data_scope' => 4]);
|
||
$assert(!PrescriptionLogic::void(2, 3, $readOnly), 'read-only account cannot void a prescription');
|
||
$assert(PrescriptionLogic::detail(2, 4, $auditor)['can_void'], 'configured audit role retains void privilege');
|
||
Db::name('system_role')->where('id', 3)->update(['data_scope' => 4]);
|
||
$assert(!PrescriptionLogic::void(2, 4, $auditor), 'audit permissions respect the configured owner data scope');
|
||
|
||
Db::name('tcm_prescription_order')->insert(['id' => 1, 'prescription_id' => 2, 'fulfillment_status' => 1]);
|
||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||
$assert(!PrescriptionLogic::detail(2, 1, $doctor)['can_void']
|
||
&& $appointmentPrescription['has_prescription_order'] === 1 && $appointmentPrescription['can_void'] === false
|
||
&& !PrescriptionLogic::void(2, 1, $doctor), 'an active business order blocks void from detail and appointment');
|
||
Db::name('tcm_prescription_order')->where('id', 1)->update(['fulfillment_status' => 4]);
|
||
Db::execute("INSERT INTO zyt_pharmacy_submission_claim VALUES (1, 1, 1, 'FAILED'), (2, 1, 2, 'PENDING')");
|
||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||
$assert(!PrescriptionLogic::detail(2, 1, $doctor)['can_void']
|
||
&& $appointmentPrescription['has_prescription_order'] === 0 && $appointmentPrescription['can_void'] === false
|
||
&& !PrescriptionLogic::void(2, 1, $doctor), 'latest pharmacy claim blocks void on a released order');
|
||
Db::name('pharmacy_submission_claim')->where('id', 2)->update(['status' => 'FAILED']);
|
||
$assert(PrescriptionLogic::getByAppointment(40, 1, $doctor)['can_void'] === true,
|
||
'released order without a pharmacy lock allows void from appointment');
|
||
|
||
$params = ['diagnosis_id' => 10, 'appointment_id' => 40, 'prescription_date' => $sample['prescription_date'],
|
||
'herbs' => [['medicine_id' => 1, 'name' => '测试药材', 'dosage' => 10, 'unit' => 'g']]];
|
||
$originalFile = Service::download(2, 1, $doctor);
|
||
$originalEvidence = Db::name('prescription_esign')->where('prescription_id', 2)->find();
|
||
$assert(PrescriptionLogic::add($params, 1, $doctor) === null && str_contains(PrescriptionLogic::getError(), '未作废处方'),
|
||
'same-day reissue is refused while an active prescription exists');
|
||
$assert(PrescriptionLogic::void(2, 1, $doctor), 'the prescribing doctor can void the signed prescription after release');
|
||
$assert(Service::status(2, 1, $doctor)['status'] === 'voided' && Service::download(2, 1, $doctor) === $originalFile
|
||
&& Db::name('prescription_esign')->where('prescription_id', 2)->find() === $originalEvidence,
|
||
'void preserves the original signed PDF and evidence');
|
||
$assert(!PrescriptionLogic::void(2, 1, $doctor), 'repeat void does not change the archived record');
|
||
$oldId = 2;
|
||
foreach (['signed', 'pending', 'legacy'] as $previousState) {
|
||
$newId = PrescriptionLogic::add($params, 1, $doctor);
|
||
$assert($newId !== null && $newId !== $oldId, 'same-day ' . $previousState . ' reissue creates a new record: ' . PrescriptionLogic::getError());
|
||
$reissued = Db::name('tcm_prescription')->find($newId);
|
||
$assert($reissued['sn'] !== Db::name('tcm_prescription')->find($oldId)['sn'] && $reissued['esign_status'] === 'pending'
|
||
&& (int) $reissued['audit_status'] === 0 && Db::name('prescription_esign')->where('prescription_id', $newId)->count() === 0,
|
||
'reissue gets a new serial number and its own pending signature and audit');
|
||
if ($previousState === 'pending') {
|
||
Db::name('tcm_prescription')->where('id', $newId)->update([
|
||
'esign_required' => 0, 'esign_status' => 'legacy', 'is_system_auto' => 1, 'herbs' => '[]',
|
||
]);
|
||
Db::name('tcm_prescription_order')->insert([
|
||
'id' => 2041, 'prescription_id' => $newId, 'fulfillment_status' => 1,
|
||
'prescription_audit_status' => 0, 'payment_slip_audit_status' => 1,
|
||
]);
|
||
$assert(!PrescriptionLogic::detail($newId, 1, $doctor)['can_void']
|
||
&& !PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true),
|
||
'an approved payment audit still blocks void from the issued list');
|
||
Db::name('tcm_prescription_order')->where('id', 2041)->update(['payment_slip_audit_status' => 0]);
|
||
$linkedBefore = Db::name('tcm_prescription_order')->find(2041);
|
||
$assert(PrescriptionLogic::detail($newId, 1, $doctor)['can_void'],
|
||
'blank pending prescription can be voided before either linked order audit');
|
||
}
|
||
if ($previousState === 'signed') {
|
||
Db::name('tcm_prescription')->where('id', $newId)->update(['audit_status' => 1]);
|
||
$assert(!PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true)
|
||
&& str_contains(PrescriptionLogic::getError(), '审核状态已变化')
|
||
&& (int) Db::name('tcm_prescription')->where('id', $newId)->value('void_status') === 0,
|
||
'a stale issued-list action cannot void a prescription that has since been approved');
|
||
Db::name('tcm_prescription')->where('id', $newId)->update(['audit_status' => 0]);
|
||
}
|
||
$assert(PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true) && !PrescriptionLogic::edit(['id' => $newId], 1),
|
||
'a manually voided record cannot be edited back into use');
|
||
if ($previousState === 'pending') {
|
||
$assert(Db::name('tcm_prescription_order')->find(2041) === $linkedBefore
|
||
&& PrescriptionOrderLogic::auditPrescription(2041, 'approve', '', 1, $root) === false,
|
||
'void preserves the linked order and blocks order approval on the voided prescription');
|
||
$throws(fn () => Service::assertSignedById($newId, true),
|
||
'voided handwritten prescription cannot be dispatched through a linked order');
|
||
}
|
||
$oldId = $newId;
|
||
}
|
||
$auditRejected = ['audit_status' => 2, 'void_status' => 1, 'audit_time' => 100, 'void_time' => 100,
|
||
'audit_by' => 4, 'void_by' => 4, 'esign_required' => 1, 'esign_status' => 'pending'];
|
||
$assert(PrescriptionLogic::canRestoreRejected($auditRejected)
|
||
&& !PrescriptionLogic::canRestoreRejected(array_replace($auditRejected, ['void_time' => 101])),
|
||
'audit rejection retains its correction path and differs from manual void');
|
||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||
$assert((int) $appointmentPrescription['id'] === $oldId && $appointmentPrescription['can_void'] === false
|
||
&& $appointmentPrescription['can_restore_rejected'] === false,
|
||
'latest manually voided prescription is returned with both actions unavailable');
|
||
Db::name('tcm_prescription')->where('id', $oldId)->update($auditRejected);
|
||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||
$assert($appointmentPrescription['can_void'] === false && $appointmentPrescription['can_restore_rejected'] === true
|
||
&& PrescriptionLogic::detail($oldId, 1, $doctor)['can_restore_rejected'] === true,
|
||
'audit rejection is restorable from detail and appointment');
|
||
$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');
|
||
$config->set($settings + ['doctor_sms_enabled' => true], 'esign');
|
||
$new(81);
|
||
$new(82);
|
||
$new(83);
|
||
$signsBefore = Fake::$signs;
|
||
$identityBefore = Fake::$identityQueries;
|
||
$recipientMissing = Fake::$smsMobile;
|
||
Fake::$smsMobile = null;
|
||
$needEnrollment = Service::start(83, 1, $doctor);
|
||
$assert($needEnrollment['doctor_identity_required'] && count(Fake::$smsFlows) === 0,
|
||
'missing authorized phone requires independent enrollment without sending a code');
|
||
Fake::$smsMobile = $recipientMissing;
|
||
$startedSms = Service::start(81, 1, $doctor);
|
||
$assert($startedSms['verification_method'] === 'sms' && $startedSms['sms_sent'] && !isset($startedSms['auth_url']),
|
||
'valid doctor certificate and mobile start SMS without an identity page');
|
||
Service::start(81, 1, $doctor);
|
||
$assert(count(Fake::$smsFlows) === 1, 'ordinary reopen uses the sent code without sending another');
|
||
$throws(fn () => Service::start(82, 1, $doctor), 'additional prescriptions share SMS send cooldown');
|
||
$throws(fn () => Service::verifyWillingness(82, 1, $doctor, '123456'), 'code requires a flow for the current prescription');
|
||
$throws(fn () => Service::verifyWillingness(81, 2, $otherDoctor, '123456'), 'only the prescribing doctor verifies');
|
||
$throws(fn () => Service::complete(81, 1, $doctor), 'SMS proof is required even on a direct signing request');
|
||
$wrong = Service::verifyWillingness(81, 1, $doctor, '000000');
|
||
$assert($wrong['identity_status'] === 'ING' && !$wrong['can_complete'], 'incorrect SMS code keeps the same flow available for retry');
|
||
$verifiedSms = Service::verifyWillingness(81, 1, $doctor, '123456');
|
||
$assert($verifiedSms['can_complete'] && !$verifiedSms['identity_details_required'] && Fake::$signs === $signsBefore,
|
||
'provider code verification unlocks explicit confirmation without signing');
|
||
$assert(Service::identityStatus(81, 1, $doctor)['can_complete'], 'reopening a verified SMS flow keeps the confirmation available');
|
||
$assert(Service::complete(81, 1, $doctor)['status'] === 'signed', 'explicit confirmation signs and verifies the initial SMS prescription');
|
||
Db::name('prescription_esign')->where('prescription_id', 81)->update(['sms_sent_at' => time() - 61]);
|
||
$startedSecond = Service::start(82, 1, $doctor);
|
||
$assert($startedSecond['sms_sent'] && !isset($startedSecond['auth_url']) && count(Fake::$smsFlows) === 2,
|
||
'a second prescription receives independent willingness without new identity proof');
|
||
$first = Db::name('prescription_esign')->where('prescription_id', 81)->find();
|
||
$second = Db::name('prescription_esign')->where('prescription_id', 82)->find();
|
||
$assert($first['flow_id'] !== $second['flow_id'] && $first['account_id'] === $second['account_id'],
|
||
'one verified identity and a separate willingness flow per prescription');
|
||
Db::name('prescription_esign')->where('prescription_id', 82)->update(['sms_sent_at' => time() - 901]);
|
||
$assert(Service::identityStatus(82, 1, $doctor)['identity_status'] === 'EXPIRED', 'expired SMS code is never usable');
|
||
$throws(fn () => Service::verifyWillingness(82, 1, $doctor, '123456'), 'expired code is rejected before contacting the supplier');
|
||
Service::start(82, 1, $doctor, true);
|
||
$assert(Service::verifyWillingness(82, 1, $doctor, '123456')['can_complete'], 'explicit restart obtains a usable SMS code');
|
||
$assert(Service::complete(82, 1, $doctor)['status'] === 'signed'
|
||
&& Fake::$signs === $signsBefore + 2 && Fake::$identityQueries === $identityBefore,
|
||
'two successful signatures reuse the doctor account with no per-prescription identity lookup');
|
||
|
||
$new(84); $new(85); $new(86); $new(87);
|
||
Db::name('prescription_esign')->where('doctor_id', 1)->update(['sms_sent_at' => time() - 61]);
|
||
Service::start(85, 1, $doctor);
|
||
$beforeQuick = [Fake::$signs, Fake::$identityQueries, count(Fake::$smsFlows)];
|
||
$config->set($settings + ['doctor_sms_enabled' => true, 'doctor_quicksign_enabled' => true], 'esign');
|
||
$assert(Service::capability()['verification_method'] === 'quick', 'editor can identify account-level quick signing');
|
||
$needGrant = Service::start(84, 1, $doctor);
|
||
$assert($needGrant['verification_method'] === 'quick' && !$needGrant['doctor_identity_required']
|
||
&& $needGrant['signing_authorization_required'] && $needGrant['signing_authorization_reason'] === 'missing'
|
||
&& !isset($needGrant['auth_url']), 'certificate alone requires independent quick-sign consent, not new identity');
|
||
$throws(fn () => Service::verifyWillingness(85, 1, $doctor, '123456'), 'quick mode disables the old SMS step');
|
||
$throws(fn () => Service::complete(85, 1, $doctor), 'old SMS flow cannot bypass quick authorization');
|
||
|
||
$account = Db::name('doctor_esign_account')->where('doctor_id', 1)->where('app_id', 'fixture')->find();
|
||
$grant = ['doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture', 'doctor_name' => '测试医师',
|
||
'account_id' => $account['account_id'], 'flow_id' => 'joined-doctor-authorization', 'expires_at' => time() + 3600,
|
||
'flow_started_at' => time()];
|
||
Db::name('doctor_esign_quicksign')->insert($grant);
|
||
Db::name('prescription_esign')->where('prescription_id', 84)->update(['doctor_setup_required' => 1]);
|
||
$assert(!Service::status(84, 1, $doctor)['doctor_identity_required'],
|
||
'a previous quick-sign failure cannot block a usable account-level grant after reopening');
|
||
foreach ([84, 85] as $prescriptionId) {
|
||
$ready = Service::start($prescriptionId, 1, $doctor);
|
||
$assert($ready['verification_method'] === 'quick' && !$ready['doctor_identity_required']
|
||
&& !array_intersect(['auth_url', 'flow_id', 'sms_sent'], array_keys($ready)),
|
||
'provider proof prepares a quick prescription without a new challenge');
|
||
$status = Service::identityStatus($prescriptionId, 1, $doctor);
|
||
$assert($status['can_complete'] && !$status['identity_details_required'], 'quick proof allows explicit confirmation without an ID input');
|
||
$assert(Fake::$signs === $beforeQuick[0] + $prescriptionId - 84, 'preparing and checking a quick prescription never signs it');
|
||
$result = Service::complete($prescriptionId, 1, $doctor);
|
||
$assert($result['status'] === 'signed' && $result['signature_time_source'] === 'tsa'
|
||
&& $result['signature_time'] >= $result['issued_at'], 'each explicit confirmation creates independently verified evidence');
|
||
}
|
||
$assert(Fake::$signs === $beforeQuick[0] + 2 && Fake::$identityQueries === $beforeQuick[1]
|
||
&& count(Fake::$smsFlows) === $beforeQuick[2], 'two consecutive quick signatures use the same stored authorization with no SMS');
|
||
Service::start(86, 1, $doctor);
|
||
Fake::$quickRemainingTimes = 0;
|
||
$unavailable = Service::identityStatus(86, 1, $doctor);
|
||
$assert(!$unavailable['can_complete'] && !$unavailable['doctor_identity_required']
|
||
&& $unavailable['signing_authorization_required'] && $unavailable['signing_authorization_reason'] === 'exhausted',
|
||
'supplier exhaustion never invalidates the doctor identity');
|
||
$blocked = Service::complete(86, 1, $doctor);
|
||
$assert($blocked['signing_authorization_required'] && !$blocked['doctor_identity_required']
|
||
&& Fake::$signs === $beforeQuick[0] + 2, 'an exhausted grant before confirmation blocks signing without requesting enrollment');
|
||
Fake::$quickRemainingTimes = 2;
|
||
Service::start(87, 1, $doctor);
|
||
Fake::$duringSeal = static function (): void { Fake::$expiredWillingness = true; };
|
||
$assert(Service::complete(87, 1, $doctor)['signing_authorization_reason'] === 'expired' && Fake::$signs === $beforeQuick[0] + 2,
|
||
'expiry during signing preparation is rechecked before PDF dispatch');
|
||
Fake::$duringSeal = null;
|
||
Fake::$expiredWillingness = false;
|
||
$new(88);
|
||
Service::start(88, 1, $doctor);
|
||
Db::name('tcm_prescription')->where('id', 88)->update(['audit_status' => 0, 'review_submitted_at' => 0]);
|
||
$inFlight = Service::status(88, 1, $doctor);
|
||
$assert($inFlight['can_submit_for_review'] && !$inFlight['can_resume_identity'] && !isset($inFlight['auth_url']),
|
||
'a signing session prepared before upload is gated until the doctor uploads');
|
||
$throws(fn () => Service::complete(88, 1, $doctor), 'a pre-existing signing session cannot confirm without upload');
|
||
PrescriptionLogic::submitForReview(88, 1, $doctor);
|
||
$assert(Service::status(88, 1, $doctor)['can_resume_identity'], 'upload unlocks a retained doctor signing session');
|
||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replacement-account']);
|
||
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update([
|
||
'account_id' => 'replacement-account', 'flow_id' => 'replacement-grant',
|
||
]);
|
||
$stale = Service::identityStatus(88, 1, $doctor);
|
||
$assert($stale['identity_status'] === 'EXPIRED' && !$stale['can_complete'] && !$stale['signing_authorization_required'],
|
||
'a prepared prescription safely discovers an already renewed independent grant');
|
||
$assert(Service::start(88, 1, $doctor, true)['can_resume_identity']
|
||
&& Service::identityStatus(88, 1, $doctor)['can_complete'] && Fake::$signs === $beforeQuick[0] + 2,
|
||
'renewed authorization can prepare an existing prescription without automatic signing');
|
||
|
||
$config->set(['review_enabled' => true] + $config->get('esign'), 'esign');
|
||
Db::name('tcm_prescription')->where('id', 84)->update(['audit_status' => 0, 'review_submitted_at' => 0]);
|
||
Db::name('admin')->insert(['id' => 22, 'name' => '测试审核人', 'root' => 1]);
|
||
Db::name('admin')->insert(['id' => 23, 'name' => '另一位测试审核人']);
|
||
Db::name('admin')->insert(['id' => 24, 'name' => '仅查看订单']);
|
||
$orderAuditMenu = Db::name('system_menu')->insertGetId(['perms' => Review::ORDER_PERMISSION]);
|
||
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => $orderAuditMenu]);
|
||
Db::name('admin_role')->insert(['admin_id' => 23, 'role_id' => 3]);
|
||
$auditor = ['root' => 1, 'admin_id' => 22, 'name' => '测试审核人'];
|
||
$otherAuditor = ['root' => 0, 'admin_id' => 23, 'name' => '另一位测试审核人', 'role_id' => [3]];
|
||
$reviewerAccount = ['doctor_id' => 22, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||
'doctor_name' => '测试审核人', 'account_id' => 'reviewer-account'];
|
||
Db::name('doctor_esign_account')->insert($reviewerAccount + ['create_time' => time()]);
|
||
Db::name('doctor_esign_quicksign')->insert($reviewerAccount + [
|
||
'flow_id' => 'stored-reviewer-authorization', 'expires_at' => time() + 3600, 'flow_started_at' => time(),
|
||
]);
|
||
$new(89, false);
|
||
Db::name('tcm_prescription')->where('id', 89)->update(['esign_required' => 0, 'esign_status' => 'legacy', 'audit_status' => 0]);
|
||
Db::name('tcm_prescription_order')->insert(['id' => 89, 'prescription_id' => 89, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||
$waitingForDoctor = Review::status(89, 89, 22, $auditor);
|
||
$assert($waitingForDoctor['required'] && !$waitingForDoctor['can_setup']
|
||
&& !$waitingForDoctor['can_confirm'] && !$waitingForDoctor['can_approve']
|
||
&& str_contains($waitingForDoctor['message'], '上传处方'),
|
||
'order audit and reviewer signing wait for the doctor to upload');
|
||
$throws(fn () => Review::confirm(89, 89, 22, $auditor, false), 'reviewer cannot sign an unenrolled pending prescription');
|
||
PrescriptionLogic::submitForReview(89, 1, $doctor);
|
||
$waitingForSignature = Review::status(89, 89, 22, $auditor);
|
||
$assert($waitingForSignature['required'] && !$waitingForSignature['can_setup'] && !$waitingForSignature['can_confirm']
|
||
&& !$waitingForSignature['can_approve'] && str_contains($waitingForSignature['message'], '有效电子签署'),
|
||
'an uploaded prescription still needs the doctor signature to enter pharmacist review');
|
||
$assert(!Db::name('prescription_esign')->where('prescription_id', 89)->find() && Fake::$reviewCalls === [],
|
||
'order reviewer setup and status checks leave the pending prescription untouched');
|
||
$original = Service::download(84, 22, $auditor);
|
||
Db::name('tcm_prescription_order')->insert(['id' => 84, 'prescription_id' => 84, 'creator_id' => 24,
|
||
'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||
$assert(!PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(84))['can_review_prescription'],
|
||
'signed order prescription remains unavailable for review before upload');
|
||
$assert(PrescriptionLogic::audit(84, 'reject', '测试驳回', 22, $auditor) === false
|
||
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'direct rejection requires upload');
|
||
$assert(PrescriptionOrderLogic::auditPrescription(84, 'reject', '测试驳回', 23, $otherAuditor) === false
|
||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方'), 'business rejection requires upload');
|
||
foreach ([1, 2] as $status) {
|
||
$assert(PrescriptionOrderLogic::addLog(['id' => 84, 'summary' => '测试审批', 'prescription_audit_status' => $status], 23, $otherAuditor) === false
|
||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方'), 'manual business audit changes require upload');
|
||
}
|
||
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'signed prescription still cannot receive a pharmacist signature before upload');
|
||
$submitted = PrescriptionLogic::submitForReview(84, 1, $doctor);
|
||
$assert($submitted['review_submitted_at'] > 0 && PrescriptionOrderLogic::withReviewAvailability(
|
||
['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(84)
|
||
)['can_review_prescription'] === true && Service::download(84, 22, $auditor) === $original,
|
||
'a pre-existing signed archive becomes available for review after upload without changing its evidence');
|
||
$throws(fn () => Service::assertSignedById(84, false, 22), 'doctor signature alone cannot approve');
|
||
$assert(!Review::status(84, 84, 23, $otherAuditor)['can_approve']
|
||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false,
|
||
'business order remains blocked while there is only one signature');
|
||
$throws(fn () => Review::confirm(84, 0, 1, $root, false), 'prescriber cannot review their own prescription');
|
||
$assert(Review::status(84, 0, 22, $auditor)['can_confirm'] && Fake::$reviewCalls === [],
|
||
'opening the audit verifies access without signing');
|
||
Fake::$failReviewVerification = true;
|
||
$attempt = Review::confirm(84, 0, 22, $auditor, false);
|
||
$assert($attempt['state'] === 'uncertain' && $attempt['can_retry_verify']
|
||
&& Fake::$reviewCalls === [['reviewer-account', 'stored-reviewer-authorization', $original['sha256']]],
|
||
'review uses only reviewer authorization and the original PDF, and retains the signed result on a verification failure');
|
||
$pendingLog = array_column(Service::status(84, 22, $auditor)['signing_log'], 'event');
|
||
$assert(in_array('review_confirmed', $pendingLog, true) && in_array('review_uncertain', $pendingLog, true)
|
||
&& !in_array('review_signed', $pendingLog, true), 'pending verification logs confirmation and the exception without certifying a signature');
|
||
$reviewRow = Db::name('tcm_prescription')->where('id', 84)->find();
|
||
$uncertainSummary = Service::describe($reviewRow, 22);
|
||
$assert($uncertainSummary['review_state'] === 'uncertain' && !isset($uncertainSummary['review_signature_time']),
|
||
'list reports uncertain pharmacist signing without treating the doctor signature as dual signing');
|
||
$storedReview = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
|
||
foreach ([['failed', time(), 'failed'], ['verifying', time(), 'verifying'], ['signing', time() - 3600, 'uncertain']] as [$state, $updated, $expected]) {
|
||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update(['state' => $state, 'update_time' => $updated]);
|
||
$assert(Service::describe($reviewRow, 22)['review_state'] === $expected, "list reports pharmacist $state as $expected");
|
||
}
|
||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update([
|
||
'state' => $storedReview['state'], 'update_time' => $storedReview['update_time'],
|
||
]);
|
||
$assert(Service::download(84, 22, $auditor) === $original, 'a pending verification never replaces the original download');
|
||
$throws(fn () => Review::confirm(84, 0, 23, $otherAuditor, true), 'another reviewer cannot recover or reuse the operation');
|
||
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'a provider result that is already archived must not sign again');
|
||
Fake::$failReviewVerification = false;
|
||
$cos->failures = 1;
|
||
$result = Review::confirm(84, 0, 22, $auditor, true);
|
||
$assert($result['state'] === 'signed' && $result['can_approve'] && count(Fake::$reviewCalls) === 1,
|
||
'retry verifies the archived doctor and reviewer signatures without resubmitting the PDF to the signer');
|
||
$archiveRow = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
|
||
$assert($cos->puts === [] && $archiveRow['archive_hash'] === '' && (int) $archiveRow['archive_attempts'] === 1
|
||
&& $archiveRow['archive_error'] === '云存储暂不可用(HTTP 503)'
|
||
&& (int) $archiveRow['archive_next_retry_at'] > time() && Archive::pending(10) === [],
|
||
'a COS failure keeps the signature, records the reason and backs off before the next retry');
|
||
$pendingEvents = array_column(Service::status(84, 22, $auditor)['signing_log'], null, 'event');
|
||
$assert(isset($pendingEvents['review_verified'], $pendingEvents['review_archive_pending'])
|
||
&& !isset($pendingEvents['review_archived']), 'the signing log shows the archive retry is outstanding');
|
||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update(['archive_next_retry_at' => 0]);
|
||
$assert(array_map('intval', Archive::pending(10)) === [84] && Archive::upload(84), 'the archive worker retries once due');
|
||
$archiveRow = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
|
||
$assert(count($cos->puts) === 1 && $cos->puts[0]['bucket'] === 'fixture-1250000000'
|
||
&& preg_match('#^private/esign/prescription/sandbox/84-[a-f0-9]{64}\.pdf$#D', $cos->puts[0]['key']) === 1
|
||
&& $cos->puts[0]['sha256'] === $archiveRow['signed_hash']
|
||
&& $cos->puts[0]['pdf'] === file_get_contents(glob($dir . '/pdf/84-*/review-signed.pdf')[0])
|
||
&& $archiveRow['archive_hash'] === $archiveRow['signed_hash'] && $archiveRow['archive_key'] === $cos->puts[0]['key']
|
||
&& (int) $archiveRow['archive_attempts'] === 0 && $archiveRow['archive_error'] === '' && Archive::pending(10) === [],
|
||
'the exact verified dual-signed PDF is archived as a private object keyed by its hash');
|
||
$assert(Archive::upload(84) && count($cos->puts) === 1, 'an archived prescription is not uploaded again');
|
||
$listMetadata = Service::describe($reviewRow, 22);
|
||
$assert($listMetadata['review_required'] && $listMetadata['review_state'] === 'signed'
|
||
&& $listMetadata['review_signature_time'] === $result['signature_time'] && !isset($listMetadata['review_signature'])
|
||
&& !isset($listMetadata['signing_log']), 'list metadata omits the image and signing log');
|
||
$combined = Service::download(84, 22, $auditor);
|
||
$expectedSeal = Fake::$reviewSignatures[$combined['sha256']][0]['sealData'];
|
||
$reviewMetadata = Service::status(84, 22, $auditor);
|
||
$assert($reviewMetadata['review_signature'] === 'data:image/png;base64,' . $expectedSeal
|
||
&& $reviewMetadata['review_signature_time'] === $result['signature_time'],
|
||
'status exposes the matched reviewer PNG and credible timestamp');
|
||
$sealFiles = glob($dir . '/pdf/84-*/review-seal-*.png') ?: [];
|
||
$assert(count($sealFiles) === 1, 'signature verification caches the matched image');
|
||
unlink($sealFiles[0]);
|
||
$restoredMetadata = Service::status(84, 22, $auditor);
|
||
$assert($restoredMetadata['review_signature'] === $reviewMetadata['review_signature'] && count(Fake::$reviewCalls) === 1,
|
||
'an older archive recovers its actual reviewer PNG without a new signature');
|
||
$assert(str_ends_with($combined['filename'], '-dual-signed.pdf') && $combined['sha256'] !== $original['sha256']
|
||
&& str_starts_with(base64_decode($combined['content_base64']), base64_decode($original['content_base64'])),
|
||
'download returns the verified incremental dual-signed PDF');
|
||
$throws(fn () => Service::assertSignedById(84, false, 23), 'one reviewer cannot approve with another reviewer signature');
|
||
$throws(fn () => Service::assertSignedById(84, true), 'the dual-signed sandbox prescription remains blocked from dispensing');
|
||
$assert(!Review::status(84, 0, 23, $otherAuditor)['can_approve']
|
||
&& !PrescriptionLogic::audit(84, 'approve', '', 23, $otherAuditor),
|
||
'the independent prescription audit still requires the pharmacist who signed');
|
||
$viewer = ['root' => 0, 'admin_id' => 24, 'name' => '仅查看订单'];
|
||
$assert(!Review::status(84, 84, 24, $viewer)['can_approve']
|
||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 24, $viewer) === false,
|
||
'ownership alone does not authorize order approval');
|
||
$orderReview = Review::status(84, 84, 23, $otherAuditor);
|
||
$assert($orderReview['can_approve'] && !$orderReview['can_confirm'] && !$orderReview['can_setup']
|
||
&& $orderReview['signer_name'] === $result['signer_name'],
|
||
'an authorized order auditor can approve the verified signatures without another signing identity');
|
||
Db::name('system_menu')->where('id', $orderAuditMenu)->update(['is_disable' => 1]);
|
||
$assert(!Review::status(84, 84, 23, $otherAuditor)['can_approve']
|
||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false,
|
||
'a disabled order audit grant blocks a previously eligible submitter');
|
||
Db::name('system_menu')->where('id', $orderAuditMenu)->update(['is_disable' => 0]);
|
||
$archive = glob($dir . '/pdf/84-*/review-signed.pdf')[0];
|
||
$archivedBytes = file_get_contents($archive);
|
||
file_put_contents($archive, $archivedBytes . 'modified');
|
||
$assert(PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false
|
||
&& (int) Db::name('tcm_prescription_order')->where('id', 84)->value('prescription_audit_status') === 0,
|
||
'a changed dual-sign PDF is refused under the order approval transaction');
|
||
file_put_contents($archive, $archivedBytes);
|
||
$order = PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor);
|
||
$assert($order !== false && (int) $order['prescription_audit_status'] === 1
|
||
&& (int) $order['payment_slip_audit_status'] === 0
|
||
&& (int) Db::name('tcm_prescription')->where('id', 84)->value('audit_by') === 23
|
||
&& (int) Db::name('tcm_prescription_order_log')->where('prescription_order_id', 84)->value('admin_id') === 23,
|
||
'order approval records the actual submitter and synchronizes the prescription without approving payment');
|
||
$assert(Service::download(84, 22, $auditor) === $combined && count(Fake::$reviewCalls) === 1,
|
||
'order approval preserves the pharmacist signature and archived original');
|
||
$signedLog = Service::status(84, 22, $auditor)['signing_log'];
|
||
$events = array_column($signedLog, null, 'event');
|
||
$times = array_column($signedLog, 'time');
|
||
$ordered = $times;
|
||
sort($ordered);
|
||
$assert($times === $ordered && isset($events['issued'], $events['doctor_verified'], $events['review_confirmed'],
|
||
$events['review_verified'], $events['audit_approved']) && !isset($events['review_uncertain']),
|
||
'signed history orders recorded milestones and replaces the resolved exception');
|
||
$assert($events['doctor_signed']['time'] === $reviewMetadata['signature_time']
|
||
&& $events['doctor_signed']['actor_name'] === $reviewMetadata['doctor_signer_name']
|
||
&& $events['review_signed']['time'] === $result['signature_time']
|
||
&& $events['review_signed']['actor_name'] === $result['signer_name']
|
||
&& $events['doctor_signed']['source'] === 'tsa' && $events['review_signed']['source'] === 'tsa'
|
||
&& $events['review_verified']['source'] === 'system'
|
||
&& $events['review_archived']['source'] === 'system' && !isset($events['review_archive_pending']),
|
||
'signing log preserves the two verified provider times and distinguishes system milestones');
|
||
$assert(Service::status(89, 22, $auditor)['signing_log'] === [], 'an unenrolled prescription has no fabricated events');
|
||
$reopened = PrescriptionOrderLogic::revokeRxAudit(84, 23, $otherAuditor);
|
||
$reopenedPrescription = Db::name('tcm_prescription')->find(84);
|
||
$assert($reopened !== false && (int) $reopenedPrescription['review_submitted_at'] === 0
|
||
&& !PrescriptionOrderLogic::withReviewAvailability($reopened, $reopenedPrescription)['can_review_prescription']
|
||
&& !Review::status(84, 84, 23, $otherAuditor)['can_approve'], 'reopening requires a new doctor upload');
|
||
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/*/review-seal-*.png') ?: [] 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);
|
||
}
|
||
}
|