This commit is contained in:
Your Name
2026-12-02 09:27:53 +08:00
parent 1e165a7894
commit 91e35cb905
21 changed files with 1780 additions and 421 deletions
@@ -8,8 +8,10 @@ declare(strict_types=1);
* Never loads the application's database configuration or touches business data.
*/
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\lists\tcm\PrescriptionOrderLists;
use app\adminapi\logic\order\OrderLogic;
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\adminapi\validate\tcm\PrescriptionOrderValidate;
use think\Container;
@@ -89,7 +91,7 @@ try {
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_pay_order (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, pay_order_id INT,
create_time INT, UNIQUE KEY uk_po_pay (prescription_order_id,pay_order_id)
create_time INT, UNIQUE KEY uk_po_pay (prescription_order_id,pay_order_id), KEY idx_pay_order (pay_order_id)
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_log (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, admin_id INT,
@@ -135,9 +137,9 @@ try {
Db::name('tcm_prescription_order_log')->where('prescription_order_id', $id)->order('id')->select()->toArray(),
];
$amounts = static function (array $result, float $total, float $paid, float $collect, bool $checkStoredPaid = true) use ($expect): void {
$expect((float) $result['amount'] === $total, 'Unlink must leave the business total unchanged');
$expect((float) $result['amount'] === $total, 'Business total must use the expected settlement amount');
$expect((float) $result['linked_pay_paid_total'] === $paid, 'Paid total must use remaining active payments');
$expect((float) $result['agency_collect_amount'] === $collect, 'Collection snapshot must equal unchanged total minus remaining payments');
$expect((float) $result['agency_collect_amount'] === $collect, 'Collection snapshot must use the updated order and receipt amounts');
if ($checkStoredPaid) {
$expect((float) $result['paid'] === $paid, 'Response paid must match remaining effective receipts');
$expect((float) Db::name('tcm_prescription_order')->where('id', $result['id'])->value('paid') === $paid,
@@ -182,11 +184,9 @@ try {
$expect($remove($id, $otherPayIds[0]) === false && $snapshot($id) === $before, 'Foreign payment ID must not affect either order');
$expect(count($snapshot($otherId)[1]) === 1, 'Foreign order must retain its payment');
foreach ([3, 4] as $status) {
[$id, $payIds] = $fixture('100.00', [['amount' => '100.00']], ['fulfillment_status' => $status, 'paid' => '100.00']);
$before = $snapshot($id);
$expect($remove($id, $payIds[0]) === false && $snapshot($id) === $before, 'Completed/cancelled orders must retain amount and paid snapshot');
}
[$id, $payIds] = $fixture('100.00', [['amount' => '100.00']], ['fulfillment_status' => 4, 'paid' => '100.00']);
$before = $snapshot($id);
$expect($remove($id, $payIds[0]) === false && $snapshot($id) === $before, 'Cancelled orders must retain amount and paid snapshot');
foreach ([['amount' => '100.00', 'status' => 1],
['amount' => '100.00', 'delete_time' => time()], ['amount' => '-1.00']] as $payment) {
[$id, $payIds] = $fixture('100.00', [$payment]);
@@ -279,16 +279,115 @@ try {
$expect(is_array($out), 'Existing link payment flow must still succeed');
$amounts($out, 1000.0, 250.0, 750.0, false);
// Separate PHP/DB connections race against a held parent row lock. Both are ready
// before release, so this tests the database lock rather than sequential double-clicks.
$race = static function (int $id, array $operations) use ($database): array {
$attach = static fn (int $id, int $payId) => PrescriptionOrderLogic::attachReceipt([
'id' => $id, 'pay_order_id' => $payId,
], 1, $admin);
$newReceipt = static fn (array $fields = []): int => (int) Db::name('order')->insertGetId($fields + [
'order_no' => 'PAID-' . bin2hex(random_bytes(4)), 'patient_id' => 1, 'status' => 2,
'amount' => 80, 'create_time' => time(),
]);
[$id] = $fixture('1000.00', [], ['creator_id' => 2]);
$receipt = $newReceipt(['creator_id' => 2]);
$operator = ['root' => 0, 'admin_id' => 2, 'role_id' => [2], 'name' => '获授权测试员'];
$attachAsOperator = static fn () => PrescriptionOrderLogic::attachReceipt(['id' => $id, 'pay_order_id' => $receipt], 2, $operator);
$before = $snapshot($id);
$expect($attachAsOperator() === false
&& PrescriptionOrderLogic::linkPayOrder(['id' => $id, 'pay_order_id' => $receipt], 2, $operator) === false
&& $snapshot($id) === $before, 'Order access and unlink permission do not grant attachment through either workflow');
$migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_12_01_prescription_order_attach_receipt_menu.sql');
$pdo->exec($migration);
$pdo->exec($migration);
$menu = Db::name('system_menu')->where('perms', 'tcm.prescriptionOrder/attachReceipt');
$expect($menu->count() === 1 && $attachAsOperator() === false, 'Idempotent migration must not grant any role by default');
$attachMenuId = (int) $menu->value('id');
$expect($attachMenuId > 0, 'Attachment menu id must exist');
Db::name('system_role_menu')->insert(['role_id' => 2, 'menu_id' => $attachMenuId]);
$expect(is_array($attachAsOperator()), 'An authorized role can attach a receipt within its scope');
foreach (range(1, 12) as $status) {
$auditStatus = $status % 3;
[$id] = $fixture('1000.00', [], [
'fulfillment_status' => $status, 'prescription_audit_status' => $auditStatus,
'payment_slip_audit_status' => $auditStatus,
'payment_slip_audit_remark' => '保留原审核意见', 'completion_request' => 1,
'paid' => 35, 'refund_amount' => 100,
]);
$receipt = $newReceipt();
$out = $attach($id, $receipt);
$expect(is_array($out) && (int) $out['fulfillment_status'] === $status
&& (int) $out['prescription_audit_status'] === $auditStatus && (int) $out['payment_slip_audit_status'] === $auditStatus
&& $out['payment_slip_audit_remark'] === '保留原审核意见' && (int) $out['completion_request'] === 1
&& (float) $out['paid'] === ($status === 3 ? 80.0 : 35.0) && (float) $out['refund_amount'] === 100.0,
"Status {$status} must allow linking while preserving audit and refund history");
$amounts($out, 1000.0, 80.0, 920.0, false);
$expect((int) $out['linked_pay_order_id'] === $receipt
&& !in_array($receipt, array_map('intval', array_column(OrderLogic::listPaidOrdersForDiagnosis(1, 1, $admin), 'id')), true),
'A linked receipt must leave the candidates even for a cancelled order');
[$other] = $fixture('1000.00', []);
$expect($attach($id, $receipt) === false && $attach($other, $receipt) === false,
'A linked receipt cannot be counted twice');
}
[$id] = $fixture('100.00', [['amount' => 100]], ['fulfillment_status' => 3, 'paid' => 100]);
$before = $snapshot($id);
foreach ([['patient_id' => 2], ['status' => 1], ['status' => 4], ['amount' => -1], ['delete_time' => time()]] as $invalidReceipt) {
$expect($attach($id, $newReceipt($invalidReceipt)) === false && $snapshot($id) === $before,
'Out-of-scope or non-paid receipt must not change the order');
}
$receipt = $newReceipt();
$pdo->exec("CREATE TRIGGER reject_attach_log BEFORE INSERT ON zyt_tcm_prescription_order_log
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'forced attachment audit log failure'");
$expect($attach($id, $receipt) === false && $snapshot($id) === $before, 'Attaching must roll back when its audit log fails');
$pdo->exec('DROP TRIGGER reject_attach_log');
$out = $attach($id, $receipt);
$expect(is_array($out) && count($out['linked_pay_orders']) === 2 && (int) $out['linked_pay_order_id'] !== $receipt,
'Attaching another receipt must preserve the original link and primary receipt');
$amounts($out, 180.0, 180.0, 0.0);
[$id] = $fixture('9936.00', [['amount' => '9936.00']], [
'fulfillment_status' => 3, 'paid' => 9936, 'agency_collect_amount' => 0,
]);
$receipt = $newReceipt(['amount' => '100.01']);
$amounts($attach($id, $receipt), 10036.01, 10036.01, 0.0);
$out = $remove($id, $receipt);
$amounts($out, 10036.01, 9936.0, 100.01);
$expect((int) $out['fulfillment_status'] === 3
&& (int) Db::name('order')->where('id', $receipt)->value('status') === 2
&& in_array($receipt, array_map('intval', array_column($out['attachable_receipts'], 'id')), true),
'Completed unlink keeps the order complete and releases the original receipt back to the chooser');
$amounts($attach($id, $receipt), 10036.01, 10036.01, 0.0);
[$id, $payIds] = $fixture('1200.00', [['amount' => 800], ['amount' => 200, 'status' => 4]], [
'fulfillment_status' => 3, 'paid' => 700, 'refund_amount' => 300, 'agency_collect_amount' => 0,
]);
$out = $attach($id, $newReceipt(['amount' => '300.26']));
$amounts($out, 1200.0, 1100.26, 99.74, false);
$expect((float) $out['paid'] === 1000.26 && (float) $out['refund_amount'] === 300.0,
'New receipts first fill the current unpaid balance and preserve net paid after partial refund');
$tail = $newReceipt(['amount' => '100.00']);
$out = $attach($id, $tail);
$amounts($out, 1200.26, 1200.26, 0.0, false);
$expect((float) $out['paid'] === 1100.26 && str_contains($snapshot($id)[2][1]['summary'], '¥1200.00 → ¥1200.26'),
'Only the excess goes into the total and is recorded in the log');
$out = $remove($id, $payIds[1]);
$amounts($out, 1200.26, 1200.26, 0.0, false);
$expect((float) $out['paid'] === 1100.26, 'Removing an already refunded receipt leaves net payment and COD unchanged');
// Launch separate connections while the shared order or receipt row is locked.
$race = static function (int $id, array $operations, ?int $receiptId = null) use ($database): array {
putenv('ZYT_UNLINK_TEST_DATABASE=' . $database);
Db::startTrans();
Db::name('tcm_prescription_order')->where('id', $id)->lock(true)->find();
if ($receiptId !== null) {
Db::name('order')->where('id', $receiptId)->lock(true)->find();
} else {
Db::name('tcm_prescription_order')->where('id', $id)->lock(true)->find();
}
$workers = [];
try {
foreach ($operations as [$operation, $payId]) {
$process = proc_open([PHP_BINARY, __FILE__, '--worker', $operation, (string) $id, (string) $payId],
foreach ($operations as $operationParams) {
[$operation, $payId] = $operationParams;
$targetId = $operationParams[2] ?? $id;
$process = proc_open([PHP_BINARY, __FILE__, '--worker', $operation, (string) $targetId, (string) $payId],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
if (!is_resource($process)) throw new RuntimeException('Unable to start concurrency worker');
fclose($pipes[0]);
@@ -327,9 +426,24 @@ try {
$expect(count($remaining) === 1 && !in_array($payIds[0], array_map('intval', $remaining), true), 'Concurrent link replacement must not resurrect a removed payment');
}
[$cancelledId] = $fixture('1000.00', [], ['fulfillment_status' => 4]);
[$shippedId] = $fixture('1000.00', []);
$receipt = $newReceipt();
$results = $race($cancelledId, [['attachReceipt', $receipt], ['linkPayOrder', $receipt, $shippedId]], $receipt);
$expect(count(array_filter($results, static fn (array $r): bool => $r['success'])) === 1
&& Db::name('tcm_prescription_order_pay_order')->where('pay_order_id', $receipt)->count() === 1,
'Concurrent legacy and direct links to separate orders must reserve a receipt exactly once');
[$completedId] = $fixture('100.00', [['amount' => 100]], ['fulfillment_status' => 3, 'paid' => 100]);
$results = $race($completedId, [['attachReceipt', $newReceipt(['amount' => 20])], ['attachReceipt', $newReceipt(['amount' => 30])]]);
$completed = $snapshot($completedId)[0];
$expect($results[0]['success'] && $results[1]['success'] && (float) $completed['amount'] === 150.0
&& (float) $completed['paid'] === 150.0 && (float) $completed['agency_collect_amount'] === 0.0,
'Concurrent completed attachments must both be included in the settlement');
foreach ([[], ['id' => 1], ['id' => 0, 'pay_order_id' => 1], ['id' => 1, 'pay_order_id' => -1],
['id' => 1, 'pay_order_id' => 1.5], ['id' => 1, 'pay_order_id' => [1]]] as $params) {
$expect(!(new PrescriptionOrderValidate())->scene('unlinkPayOrder')->check($params), 'Request must require two positive integer IDs');
$expect(!(new PrescriptionOrderValidate())->scene('attachReceipt')->check($params), 'Attach requires two positive integer IDs');
}
$expect((new PrescriptionOrderValidate())->scene('unlinkPayOrder')->check(['id' => 1, 'pay_order_id' => 2]), 'Valid IDs must pass validation');
echo "PrescriptionOrderUnlinkPayOrderTest: {$checks} assertions passed\n";