PDO::ERRMODE_EXCEPTION]); $pdo->exec("CREATE DATABASE `$database` CHARACTER SET utf8mb4"); $pdo->exec("USE `$database`"); $app = new think\App(); $manager = new think\DbManager(); $manager->setConfig(['default' => 'test', 'connections' => ['test' => [ 'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port, 'database' => $database, 'username' => 'root', 'password' => '', 'prefix' => 'zyt_', 'charset' => 'utf8mb4', 'fields_strict' => true, ]]]); Container::getInstance()->instance('think\DbManager', $manager); $config = new think\Config(); $config->set(['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture'], 'esign'); Container::getInstance()->instance('config', $config); $root = ['root' => 1, 'admin_id' => 1, 'name' => '测试审核员']; $checks = 0; $pdfPath = null; $expect = static function (bool $ok, string $message) use (&$checks): void { if (!$ok) { throw new RuntimeException($message); } $checks++; }; try { $pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)'); $pdo->exec('CREATE TABLE zyt_tcm_prescription ( id INT UNSIGNED PRIMARY KEY,creator_id INT,doctor_name VARCHAR(100),patient_name VARCHAR(100),phone VARCHAR(30),gender INT, audit_status INT DEFAULT 0,void_status INT DEFAULT 0,delete_time INT NULL,update_time INT DEFAULT 0, void_time INT NULL,void_by INT NULL,void_by_name VARCHAR(100), is_system_auto INT DEFAULT 0,herbs TEXT,clinical_diagnosis TEXT ) ENGINE=InnoDB'); $pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name) VALUES (1,1,'测试医师')"); $migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql'); $pdo->exec($migration); $pdo->exec($migration); $submissionMigration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_21_prescription_review_submission.sql'); $pdo->exec($submissionMigration); $pdo->exec($submissionMigration); $row = Db::name('tcm_prescription')->find(1); $expect((int) $row['esign_required'] === 0 && $row['esign_status'] === 'legacy', 'migration preserves historical rows and is repeatable'); $expect((int) $row['review_submitted_at'] === 0, 'repeatable upload migration leaves legacy records without an upload time'); $pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,esign_required,esign_status) VALUES (2,1,'测试医师',1,'pending')"); $pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql')); $pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY,prescription_order_id INT,source_revision INT,status VARCHAR(40))'); Db::name('tcm_prescription_order')->insert(['id' => 1, 'order_no' => 'TEST-ESIGN', 'prescription_id' => 2, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]); Db::name('tcm_prescription_order')->insert(['id' => 2, 'order_no' => 'TEST-LEGACY-PENDING', 'prescription_id' => 1, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]); $expect(PrescriptionLogic::audit(1, 'approve', '', 1, $root) === false, 'unmarked pending prescription requires signature after enablement'); $expect(PrescriptionOrderLogic::auditPrescription(2, 'approve', '', 1, $root) === false, 'order audit also gates an unmarked pending prescription'); $expect(PrescriptionOrderLogic::addLog(['id' => 2, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false, 'manual order status cannot bypass a required signature on an unmarked draft'); $expect(Db::name('tcm_prescription')->find(1) === $row, 'approval attempts do not enroll or modify an unsigned prescription'); $pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,audit_status) VALUES (3,1,'测试医师',1)"); PrescriptionEsignService::assertSignedById(3); $expect(PrescriptionEsignService::describe(Db::name('tcm_prescription')->find(3), 1)['status'] === 'legacy', 'previously approved historical prescription remains on record'); $expect(PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(3))['can_review_prescription'], 'an already approved historical prescription remains available to an existing order'); $expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned'); $expect(str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual audit explains upload requirement'); $expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false, 'order audit rejects unsigned before write'); $expect((int) Db::name('tcm_prescription_order')->where('id', 1)->value('prescription_audit_status') === 0, 'order remains pending after rejection'); $expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false, 'manual order log cannot bypass signature requirement'); Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'authenticating']); $expect(PrescriptionLogic::patchPatientContact(2, '变更患者', '13800000000', 1, 1, $root) === false, 'patient correction cannot alter frozen original'); $expect(PrescriptionLogic::delete(2) === false, 'frozen evidence cannot be deleted through normal delete'); $config->set(['enabled' => false], 'esign'); $expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'switching feature off cannot bypass persisted requirement'); PrescriptionEsignService::assertSignedById(1); $expect(true, 'historical rows do not require new evidence'); // Real InnoDB contention: a second connection attempts to void the very // prescription being approved, at the exact model before-write boundary. Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'pending', 'herbs' => '[{"name":"Fixture herb"}]', 'clinical_diagnosis' => 'Fixture diagnosis']); $pdo->exec('SET SESSION innodb_lock_wait_timeout=1'); $events = new class($pdo, $expect) { public int $attempts = 0; public function __construct(private PDO $otherConnection, private Closure $expect) {} public function trigger(string $event, mixed $model): array { if (!str_ends_with($event, '.BeforeUpdate')) { return []; } $this->attempts++; try { $this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2'); ($this->expect)(false, 'concurrent void must wait for signature check + audit write'); } catch (PDOException $e) { ($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write'); } throw new DomainException('TEST_LOCK_OBSERVED'); } }; \think\Model::setEvent($events); try { PrescriptionLogic::submitForReview(2, 1, $root); $expect(false, 'submission must retain its own prescription lock'); } catch (DomainException $error) { $expect($error->getMessage() === 'TEST_LOCK_OBSERVED' && (int) Db::name('tcm_prescription')->where('id', 2)->value('review_submitted_at') === 0, 'failed concurrent submission rolls back its audit timestamp'); } \think\Model::setEvent(null); $submitted = PrescriptionLogic::submitForReview(2, 1, $root); $expect($submitted['review_submitted_at'] > 0 && PrescriptionLogic::submitForReview(2, 1, $root) === $submitted, 'actual MySQL upload before signing is persisted once'); $expect(!PrescriptionEsignService::status(2, 1, $root)['can_review_prescription'] && !PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) && str_contains(PrescriptionOrderLogic::getError(), '电子签署'), 'persistent eSign requirement still gates review after upload when disabled'); Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'signed']); $snapshot = PrescriptionEsignPolicy::hash(Db::name('tcm_prescription')->find(2)); $storage = sys_get_temp_dir() . '/zyt-' . $database; $relative = '2-' . $snapshot . '/signed.pdf'; $pdfPath = $storage . '/' . $relative; mkdir(dirname($pdfPath), 0700, true); $pdf = "%PDF-1.7\nTEST ONLY\n%%EOF"; file_put_contents($pdfPath, $pdf); $config->set(['storage_path' => $storage], 'esign'); Db::name('prescription_esign')->insert([ 'prescription_id' => 2, 'doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture', 'snapshot_hash' => $snapshot, 'source_hash' => hash('sha256', $pdf), 'source_path' => '', 'signed_hash' => hash('sha256', $pdf), 'signed_path' => $relative, 'account_id' => 'fixture-account', 'sign_service_id' => 'fixture-sign', 'signed_at' => time(), 'create_time' => time(), 'update_time' => time(), ]); try { PharmacySubmissionClaimService::acquire(1, 1, 'gancao', 1, '测试'); $expect(false, 'sandbox must not acquire a dispensing claim'); } catch (DomainException $e) { $expect(str_contains($e->getMessage(), '沙箱'), 'claim boundary enforces production signatures'); } \think\Model::setEvent($events); $expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false && PrescriptionLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual audit reaches locked write'); $expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'order audit reaches locked write'); $expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual status change reaches locked write'); $expect($events->attempts === 4 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked'); \think\Model::setEvent(null); Db::name('tcm_prescription_order')->where('id', 1)->update(['fulfillment_status' => 4]); $pdo->exec("INSERT INTO zyt_pharmacy_submission_claim VALUES (1, 1, 1, 'FAILED'), (2, 1, 2, 'PENDING')"); $expect(!PrescriptionLogic::void(2, 1, $root) && str_contains(PrescriptionLogic::getError(), '提交药房'), 'void locks and checks the latest pharmacy claim on a released order'); Db::name('pharmacy_submission_claim')->where('id', 2)->update(['status' => 'FAILED']); $expect(PrescriptionLogic::void(2, 1, $root), 'void succeeds when the released order has no active claim'); $pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY,root INT,disable INT DEFAULT 0,delete_time INT)'); $pdo->exec('INSERT INTO zyt_admin (id,root) VALUES (1,1)'); PrescriptionCaSigningSettings::setEnabled(false, 1); $expect(!PrescriptionEsignService::enabled(), 'persistent admin flag disables CA in MySQL'); $expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf), 'turning CA off after void preserves downloadable signed evidence'); echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n"; } finally { \think\Model::setEvent(null); if ($pdfPath !== null && is_file($pdfPath)) { unlink($pdfPath); rmdir(dirname($pdfPath)); rmdir(dirname(dirname($pdfPath))); } $manager->connect()->close(); if (!preg_match('/^esign_test_[a-f0-9]{12}$/D', $database)) { throw new RuntimeException('Unsafe test database'); } $pdo->exec("DROP DATABASE `$database`"); }