This commit is contained in:
Your Name
2026-11-26 15:46:20 +08:00
parent db6d327e91
commit be79e09c83
170 changed files with 21159 additions and 13217 deletions
+264 -29
View File
@@ -187,6 +187,7 @@ namespace app\common\service\esign {
'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'];
}
@@ -196,6 +197,7 @@ 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;
@@ -234,19 +236,27 @@ namespace {
'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',
'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,
fulfillment_status INTEGER, delete_time INTEGER, diagnosis_id INTEGER, creator_id INTEGER, create_time 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')
@@ -269,12 +279,13 @@ namespace {
}
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');
$new = static function (int $id): void {
$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);
@@ -700,7 +711,7 @@ namespace {
48 => ['clinical_diagnosis' => ''],
];
foreach ($legacyCases as $id => $values) {
$new($id);
$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',
@@ -713,6 +724,15 @@ namespace {
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');
@@ -720,27 +740,38 @@ namespace {
$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['can_resume_identity'], 'unenrolled pending prescription enters eSign for its doctor');
$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'] && str_contains($other['message'], '开方医生'),
'auditor can see that the doctor needs to sign');
$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');
$assert(Service::identityStatus(41, 1, $root)['identity_status'] === 'UNAVAILABLE',
'pending legacy identity status waits for enrollment');
$throws(fn () => Service::complete(41, 1, $root), 'unenrolled draft cannot complete signing before starting');
$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 unenrolled pending prescription');
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual approval blocks an unsubmitted prescription');
$assert(PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root) === false
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署')
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方')
&& (int) Db::name('tcm_prescription_order')->where('id', 41)->value('prescription_audit_status') === 0,
'business order approval blocks an unenrolled pending prescription');
'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)
&& !Db::name('prescription_esign')->where('prescription_id', 41)->find(), 'status and audit checks never enroll or change the draft');
&& 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'],
$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');
}
@@ -752,9 +783,32 @@ namespace {
$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');
$assert(PrescriptionLogic::audit(47, 'reject', '测试驳回', 1, $root)
&& (int) Db::name('tcm_prescription')->where('id', 47)->value('void_status') === 1,
'unsigned pending prescription remains correctable through rejection');
$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);
@@ -764,10 +818,32 @@ namespace {
&& $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');
$assert(Service::complete(41, 1, $root)['status'] === 'signed', 'the enrolled doctor can sign the existing prescription');
$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);
@@ -797,6 +873,7 @@ namespace {
$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');
@@ -897,7 +974,6 @@ namespace {
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_pharmacy_submission_claim (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, source_revision INTEGER, status TEXT)');
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)");
@@ -908,8 +984,11 @@ namespace {
$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
@@ -966,10 +1045,38 @@ namespace {
&& (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']);
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');
}
$assert(PrescriptionLogic::void($newId, 1, $doctor) && !PrescriptionLogic::edit(['id' => $newId], 1),
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,
@@ -1096,6 +1203,13 @@ namespace {
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',
@@ -1108,19 +1222,60 @@ namespace {
'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]);
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' => '另一位测试审核人', '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' => 1, 'admin_id' => 23, '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');
@@ -1129,6 +1284,21 @@ namespace {
$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');
@@ -1136,20 +1306,85 @@ namespace {
$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');
$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(PrescriptionLogic::audit(84, 'approve', '', 22, $auditor)
&& (int) Db::name('tcm_prescription')->where('id', 84)->value('audit_by') === 22,
'the second signer can approve with the verified dual signature');
$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',
'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'); }