Files
zyt/server/tests/PrescriptionOrderPrescriptionLinksTest.php
T
2026-12-02 09:27:53 +08:00

276 lines
18 KiB
PHP

<?php
declare(strict_types=1);
/** Runs against a disposable local MySQL database. Never loads the site's database configuration. */
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\adminapi\validate\tcm\PrescriptionOrderValidate;
use think\Container;
use think\DbManager;
use think\facade\Db;
$port = (int) getenv('ZYT_RX_LINK_TEST_MYSQL_PORT');
if ($port <= 0) {
fwrite(STDERR, "Set ZYT_RX_LINK_TEST_MYSQL_PORT to an isolated local MySQL instance.\n");
exit(1);
}
$database = 'rx_links_test_' . bin2hex(random_bytes(6));
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec("CREATE DATABASE {$database} CHARACTER SET utf8mb4");
$pdo->exec("USE {$database}");
$app = new think\App();
$manager = new DbManager();
$manager->setConfig([
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
'connections' => ['mysql' => [
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port, 'database' => $database,
'username' => 'root', 'password' => '', 'charset' => 'utf8mb4', 'prefix' => 'zyt_', 'fields_strict' => true,
]],
]);
Container::getInstance()->instance('think\DbManager', $manager);
$config = new think\Config();
$config->set(['data_scope' => ['enabled' => false]], 'project');
Container::getInstance()->instance('config', $config);
think\Validate::maker(static fn (think\Validate $validator) => $validator->setLang(new think\Lang($app)));
$checks = 0;
$expect = static function (bool $condition, string $message) use (&$checks): void {
if (!$condition) {
throw new RuntimeException($message . ' | ' . PrescriptionOrderLogic::getError());
}
$checks++;
};
$denied = static function (callable $call, string $message) use ($expect): void {
try {
$call();
} catch (DomainException) {
$expect(true, $message);
return;
}
$expect(false, $message);
};
$migration = dirname(__DIR__) . '/database/migrations/';
try {
foreach (['2026_04_07_create_tcm_prescription_order.sql', '2026_04_09_prescription_order_pay_links.sql'] as $file) {
$pdo->exec(file_get_contents($migration . $file));
}
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
id INT PRIMARY KEY, sn VARCHAR(32), diagnosis_id INT, creator_id INT, assistant_id INT,
is_shared INT DEFAULT 0, visible_role_ids VARCHAR(80) DEFAULT "", void_status INT DEFAULT 0,
audit_status INT DEFAULT 1, gender INT DEFAULT 1, dose_count INT DEFAULT 1,
usage_days INT DEFAULT 7, esign_required INT DEFAULT 0, herbs TEXT,
delete_time INT NULL
)');
$pdo->exec('CREATE TABLE zyt_tcm_diagnosis (
id INT PRIMARY KEY, patient_id INT DEFAULT 0, assistant_id INT DEFAULT 0,
status INT DEFAULT 1, id_card VARCHAR(32), delete_time INT NULL
)');
$pdo->exec('CREATE TABLE zyt_system_menu (
id INT PRIMARY KEY AUTO_INCREMENT, pid INT, type VARCHAR(5), name VARCHAR(100), icon VARCHAR(50),
sort INT, perms VARCHAR(100), paths VARCHAR(100), component VARCHAR(100), selected VARCHAR(100),
params VARCHAR(100), is_cache INT, is_show INT, is_disable INT DEFAULT 0, create_time INT, update_time INT
)');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_log (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, admin_id INT, admin_name VARCHAR(64),
action VARCHAR(32), summary VARCHAR(500), create_time INT
)');
$pdo->exec('CREATE TABLE zyt_order (id INT PRIMARY KEY, patient_id INT, status INT, delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY, type VARCHAR(32), name VARCHAR(32), value TEXT)');
$pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY, name VARCHAR(64), account VARCHAR(64), delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_admin_dept (admin_id INT, dept_id INT)');
$pdo->exec('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
$pdo->exec('CREATE TABLE zyt_system_role (id INT PRIMARY KEY, name VARCHAR(64), data_scope INT, delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_system_role_menu (role_id INT, menu_id INT)');
$pdo->exec('CREATE TABLE zyt_doctor_appointment (id INT PRIMARY KEY, patient_id INT, doctor_id INT, status INT, delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY, prescription_order_id INT, source_revision INT)');
Db::name('system_menu')->insert(['type' => 'C', 'perms' => 'tcm.prescription/lists', 'component' => 'consumer/prescription/index']);
Db::name('tcm_diagnosis')->insertAll([
['id' => 1, 'patient_id' => 100, 'id_card' => 'TEST-PRIVATE'],
['id' => 2, 'patient_id' => 200, 'id_card' => 'OTHER'],
['id' => 3, 'patient_id' => 100, 'id_card' => 'TEST-PRIVATE'],
['id' => 4, 'patient_id' => 0, 'id_card' => 'LEGACY'],
['id' => 5, 'patient_id' => 0, 'id_card' => 'LEGACY'],
]);
foreach ([
[101, 1, 2, 1], [102, 1, 2, 0], [103, 2, 2, 1], [104, 1, 3, 1], [105, 1, 2, 0],
[106, 3, 2, 0], [107, 4, 2, 1], [108, 5, 2, 0], [109, 4, 2, 0], [110, 3, 2, 1],
[111, 1, 2, 0], [112, 1, 2, 0], [113, 1, 2, 1],
] as [$id, $diagnosisId, $owner, $void]) {
Db::name('tcm_prescription')->insert([
'id' => $id, 'sn' => 'RX-' . $id, 'diagnosis_id' => $diagnosisId, 'creator_id' => $owner,
'void_status' => $void, 'dose_count' => $id === 102 ? 2 : 1,
'herbs' => '[{"name":"fixture","formula_type":"辅方"}]',
]);
}
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order MODIFY prescription_id INT UNSIGNED NULL DEFAULT 0');
foreach ([
[201, 1, 101, 2, 1], [202, 1, 102, 2, 3], [203, 1, 104, 3, 6], [204, 2, 103, 2, 1],
[205, 4, 107, 2, 1], [206, 1, 101, 2, 3],
[207, 1, 105, 2, 1], [208, 1, 111, 2, 1], [209, 1, 112, 2, 1],
[210, 1, 0, 2, 1], [211, 1, 999, 2, 1], [212, 1, 113, 2, 1], [213, 1, 0, 2, 1],
[214, 1, null, 2, 1], [215, 1, 113, 2, 1],
] as [$id, $diagnosisId, $primary, $owner, $status]) {
Db::name('tcm_prescription_order')->insert([
'id' => $id, 'order_no' => 'PO-' . $id, 'diagnosis_id' => $diagnosisId, 'prescription_id' => $primary,
'creator_id' => $owner, 'fulfillment_status' => $status, 'prescription_audit_status' => 1,
'payment_slip_audit_status' => 1, 'recipient_name' => 'recipient-' . $id,
]);
}
Db::name('tcm_prescription')->where('id', 111)->update(['audit_status' => 2]);
Db::name('tcm_prescription')->where('id', 113)->update(['delete_time' => time()]);
Db::name('tcm_prescription_order')->whereIn('id', [207, 210, 211, 212, 214])->update(['prescription_audit_status' => 2]);
Db::name('tcm_prescription_order')->where('id', 209)->update(['payment_slip_audit_status' => 2]);
Db::name('system_role')->insert(['id' => 11, 'name' => '隔离测试角色', 'data_scope' => 4]);
Db::name('admin_role')->insert(['admin_id' => 2, 'role_id' => 11]);
$operator = ['root' => 0, 'admin_id' => 2, 'role_id' => [11], 'name' => '隔离测试员'];
$root = ['root' => 1, 'admin_id' => 1, 'name' => '隔离管理员'];
$list = static fn (int $id, string $sn = '') => PrescriptionOrderLogic::prescriptionOrdersForBinding($id, $sn, 2, $operator);
$bind = static fn (int $order, int $rx) => PrescriptionOrderLogic::bindPrescription($order, $rx, 2, $operator);
$denied(fn () => $list(102), 'Viewing or owning a prescription does not grant viewing its order links');
$sql = file_get_contents($migration . '2026_12_01_prescription_order_prescription_links.sql');
$pdo->exec($sql);
$pdo->exec($sql);
$path = 'tcm.prescriptionOrder/';
$menuIds = Db::name('system_menu')->whereIn('perms', [$path . 'prescriptionOrdersForBinding', $path . 'bindPrescription'])
->column('id', 'perms');
$expect(count($menuIds) === 2 && Db::name('system_role_menu')->count() === 0,
'Migration is repeatable and grants no roles');
Db::name('system_role_menu')->insert(['role_id' => 11, 'menu_id' => $menuIds[$path . 'prescriptionOrdersForBinding']]);
$result = $list(102);
$expect(!$result['can_bind'] && count($result['orders']) === 1 && $result['orders'][0]['is_primary'],
'View permission returns established links without exposing candidates');
$denied(fn () => $bind(201, 102), 'Viewing permission does not permit binding');
Db::name('system_role_menu')->insert(['role_id' => 11, 'menu_id' => $menuIds[$path . 'bindPrescription']]);
$expect(!PrescriptionOrderLogic::hasPrescriptionOrderMenuAccess($operator), 'Binding permission does not unlock unrelated order actions');
$result = $list(102, 'PO-201');
$expect($result['can_bind'] && array_map('intval', array_column($result['orders'], 'id')) === [202, 201],
'Search returns existing links and voided-primary candidates in scope');
$expect($list(106, 'PO-202')['orders'] === [], 'An order with an active original prescription is not offered');
$expect($list(106, 'PO-203')['orders'] === [], 'An inaccessible order with a voided original is not offered');
$expect($list(106, 'PO-204')['orders'] === [], 'An order for a different patient is not offered');
$expect(array_column($list(106, 'PO-206')['orders'], 'id') === [206],
'Order search finds a completed order from a different diagnosis of the same patient');
$expect(!$list(101)['can_bind'], 'A voided prescription can show its orders but cannot be bound again');
$expect(array_column($list(109, 'PO-205')['orders'], 'id') === [205] && $list(108, 'PO-205')['orders'] === [],
'Legacy patients without a patient ID can only bind within their own diagnosis');
$denied(fn () => $bind(203, 102), 'An order outside the data scope cannot be bound');
$denied(fn () => $bind(204, 102), 'Cross-patient binding cannot be done');
$denied(fn () => $bind(201, 104), 'An unreadable prescription cannot be bound');
$denied(fn () => $bind(202, 106), 'The API rejects an order with a live original');
$denied(fn () => $bind(201, 110), 'The API rejects a voided replacement');
$denied(fn () => $bind(205, 108), 'Legacy patient identities cannot match by card or placeholder ID');
Db::name('tcm_prescription')->where('id', 101)->update(['void_status' => 0]);
$denied(fn () => $bind(206, 106), 'The API rechecks the original current status after candidates are loaded');
Db::name('tcm_prescription')->where('id', 101)->update(['void_status' => 1]);
$before = Db::name('tcm_prescription_order')->where('id', 201)->find();
$bind(201, 102);
$bind(201, 102);
$bind(201, 101);
$expect(Db::name('tcm_prescription_order_prescription')->count() === 1
&& Db::name('tcm_prescription_order_log')->where('action', 'bind_prescription')->count() === 1
&& $before === Db::name('tcm_prescription_order')->where('id', 201)->find(),
'Duplicate and primary binds are idempotent and preserve operational order fields');
$result = $list(102);
$linkedOrders = array_values(array_filter($result['orders'], static fn (array $order) => $order['is_linked']));
$expect(array_column($linkedOrders, 'id') === [202, 201] && !$linkedOrders[1]['is_primary'],
'A supplemental prescription is visible from the reverse lookup');
$pdo->exec("CREATE TRIGGER reject_bind_log BEFORE INSERT ON zyt_tcm_prescription_order_log
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced bind log failure'");
try {
$bind(201, 105);
} catch (RuntimeException $exception) {
$expect(str_contains($exception->getMessage(), '日志写入失败'), 'Failed log invalidates the binding');
}
$expect(Db::name('tcm_prescription_order_prescription')->where('prescription_id', 105)->count() === 0,
'A log exception rolls back the binding');
$pdo->exec('DROP TRIGGER reject_bind_log');
$detail = PrescriptionOrderLogic::detail(201, 2, $operator, 0);
$expect(array_column($detail['linked_prescriptions'], 'id') === [101, 102]
&& (int) $detail['prescription']['id'] === 101, 'Order detail defaults to the primary prescription');
$ref = PrescriptionOrderLogic::detail(201, 2, $operator, 102);
$expect((int) $ref['prescription_id'] === 101 && (int) $ref['prescription']['id'] === 102
&& (int) $ref['prescription']['dose_count'] === 2 && !$ref['prescription']['can_review_prescription']
&& !isset($ref['prescription']['recipient_name'])
&& !isset($ref['prescription']['herbs']) && (int) $ref['prescription']['has_aux_formula'] === 1,
'Switching shows the selected original prescription, honoring herb masking and avoiding another order snapshot');
$expect(PrescriptionOrderLogic::detail(201, 1, $root, 105) === null, 'Even root cannot load a prescription unrelated to this order');
$bind(206, 106);
$linkedOrders = array_filter($list(106)['orders'], static fn (array $order) => $order['is_linked']);
$expect(array_column($linkedOrders, 'id') === [206],
'The reverse lookup shows the linked order across diagnoses');
$crossDiagnosis = PrescriptionOrderLogic::detail(206, 2, $operator, 106);
$expect(array_column($crossDiagnosis['linked_prescriptions'], 'id') === [101, 106]
&& (int) $crossDiagnosis['prescription']['id'] === 106 && (int) $crossDiagnosis['fulfillment_status'] === 3,
'The same order retains its archived original and can preview the new prescription without changing fulfillment');
$candidateIds = static fn (array $result): array => array_column(
array_filter($result['orders'], static fn (array $order) => !$order['is_linked']), 'id'
);
$expect($candidateIds($list(106, 'PO-207')) === [207],
'An order-side prescription rejection is eligible even though its primary prescription was not voided');
$expect($candidateIds($list(106, 'PO-208')) === [208],
'A historically rejected primary prescription without a void flag is eligible');
$expect($candidateIds($list(106, 'PO-209')) === [], 'A payment rejection alone does not make an order eligible');
$denied(fn () => $bind(209, 106), 'Submitting directly cannot bypass the prescription eligibility check');
$expect(!$list(111)['can_bind'], 'An already rejected prescription can show existing orders but is not an eligible replacement');
$denied(fn () => $bind(201, 111), 'Submitting directly cannot bind a rejected replacement');
Db::name('tcm_prescription_order')->where('id', 207)->update(['prescription_audit_status' => 0]);
$denied(fn () => $bind(207, 106), 'The API rechecks the order-side prescription review after search');
Db::name('tcm_prescription_order')->where('id', 207)->update(['prescription_audit_status' => 2]);
foreach ([207, 208] as $orderId) {
$archivedOrder = Db::name('tcm_prescription_order')->where('id', $orderId)->find();
$bind($orderId, 106);
$expect(Db::name('tcm_prescription_order_prescription')->where('prescription_order_id', $orderId)
->where('prescription_id', 106)->count() === 1
&& $archivedOrder === Db::name('tcm_prescription_order')->where('id', $orderId)->find()
&& str_contains((string) Db::name('tcm_prescription_order_log')->where('prescription_order_id', $orderId)
->where('action', 'bind_prescription')->value('summary'), '审核已驳回'),
'Binding adds a supplemental link and logs the rejection without changing the original order');
}
foreach ([210, 211, 212, 214] as $orderId) {
$expect($candidateIds($list(106, 'PO-' . $orderId)) === [$orderId],
'Rejected order remains selectable when its original is unset, dangling, deleted or null');
$archivedOrder = Db::name('tcm_prescription_order')->where('id', $orderId)->find();
$bind($orderId, 106);
$bind($orderId, 106);
$visibleOrder = PrescriptionOrderLogic::detail($orderId, 2, $operator, 106);
$expect((int) $visibleOrder['prescription']['id'] === 106
&& array_column($visibleOrder['linked_prescriptions'], 'id') === [106]
&& $archivedOrder === Db::name('tcm_prescription_order')->where('id', $orderId)->find()
&& Db::name('tcm_prescription_order_log')->where('prescription_order_id', $orderId)
->where('action', 'bind_prescription')->count() === 1,
'Binding and preview use the new association without changing the rejected original or recording a duplicate');
}
foreach ([213, 215] as $orderId) {
$expect($candidateIds($list(106, 'PO-' . $orderId)) === [],
'A non-rejected order is ineligible when the original is unset or only a deleted voided row remains');
$denied(fn () => $bind($orderId, 106), 'Direct binding also requires rejection if no current original exists');
}
Db::name('system_role_menu')->where('menu_id', $menuIds[$path . 'prescriptionOrdersForBinding'])->delete();
$expect(PrescriptionOrderLogic::detail(201, 2, $operator, 102) === null
&& !isset(PrescriptionOrderLogic::detail(201, 2, $operator, 0)['linked_prescriptions']),
'Orders without link-view permission keep their original details and omit supplemental relations');
$expect((new PrescriptionOrderValidate())->scene('detail')->check(['id' => 201])
&& (new PrescriptionOrderValidate())->scene('detail')->check(['id' => 201, 'prescription_id' => 102])
&& !(new PrescriptionOrderValidate())->scene('detail')->check(['id' => 201, 'prescription_id' => -1])
&& !(new PrescriptionOrderValidate())->scene('bindPrescription')->check(['id' => 201, 'prescription_id' => 0]),
'Detail preserves the existing request shape while mutations and explicit selections validate positive ids');
echo "PrescriptionOrderPrescriptionLinksTest: {$checks} assertions passed\n";
} finally {
$manager->connect()->close();
$pdo->exec("DROP DATABASE {$database}");
}