From 82a91858f9b572737b2a1fa92e4368922f6a47ef Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 27 Nov 2026 17:25:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- artifacts/esign-prescription-test.pdf | 12 ++- .../adminapi/logic/tcm/PrescriptionLogic.php | 10 +- .../logic/tcm/PrescriptionOrderLogic.php | 96 ++++++++++++++++++- .../esign/PrescriptionEsignService.php | 18 ++-- .../common/service/esign/PrescriptionPdf.php | 9 +- server/tests/PrescriptionEsignFlowTest.php | 84 +++++++++++++++- .../PrescriptionOrderTrackingAuditTest.php | 17 +++- 7 files changed, 217 insertions(+), 29 deletions(-) diff --git a/artifacts/esign-prescription-test.pdf b/artifacts/esign-prescription-test.pdf index 4330f15aa..aded0a03e 100644 --- a/artifacts/esign-prescription-test.pdf +++ b/artifacts/esign-prescription-test.pdf @@ -19,7 +19,7 @@ endobj << /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents 7 0 R >> endobj 7 0 obj -<< /Length 1501>> +<< /Length 1789>> stream BT /F1 20 Tf 1 0 0 1 235 795 Tm <4e2d533b590465b97b3a> Tj ET BT /F1 12 Tf 1 0 0 1 170 770 Tm <6c997bb16d4b8bd565874ef6002000b700204e0d75284e8e6b635f0f53d1836f> Tj ET @@ -29,12 +29,16 @@ BT /F1 11 Tf 1 0 0 1 45 702 Tm <60a38005ff1a865a67846d4b8bd560a38005002000200020 BT /F1 11 Tf 1 0 0 1 45 684 Tm <80547cfb75358bddff1a00310033003800300030003000300030003000300030> Tj ET BT /F1 11 Tf 1 0 0 1 45 666 Tm <4e345e8a8bca65adff1a4ec575284e8e8f6f4ef66d4b8bd5> Tj ET BT /F1 11 Tf 1 0 0 1 45 648 Tm <836f54c100200031ff1a752891cf0020003100300020002f0020836f540d00206d4b8bd5836f67500020002f002053554f4d00200067> Tj ET -BT /F1 11 Tf 1 0 0 1 45 630 Tm <4ee3714eff1a5426> Tj ET +BT /F1 11 Tf 1 0 0 1 45 630 Tm <53556b21888b6570ff1a0033> Tj ET +BT /F1 11 Tf 1 0 0 1 45 612 Tm <4ee3714eff1a5426> Tj ET +BT /F1 11 Tf 1 0 0 1 45 594 Tm <8f8565b953556b21888b6570ff1a0034> Tj ET +BT /F1 11 Tf 1 0 0 1 45 576 Tm <8f8565b965b9540dff1a8f8552a965b96a21677f> Tj ET +BT /F1 11 Tf 1 0 0 1 45 558 Tm <8f8565b9670d752859296570ff1a0038> Tj ET 0.7 w 45 133 m 550 133 l S BT /F1 12 Tf 1 0 0 1 45 110 Tm <5f0065b9533b5e08ff1a6d4b8bd5533b5e08> Tj ET BT /F1 11 Tf 1 0 0 1 420 104 Tm <533b5e0875355b507b7e7ae0> Tj ET BT /F1 8 Tf 1 0 0 1 45 58 Tm <590465b95feb71670020005300480041002d003200350036> Tj ET -BT /F1 7 Tf 1 0 0 1 45 44 Tm <0039003300660065006100390065006300610063003400310064003700300031003400370032006200330036003800610036006400350030003000330035003400330033003400620034006300390032003600370035006600320066006100300062003800660033003300370036006100380063006100320036003000300032> Tj ET +BT /F1 7 Tf 1 0 0 1 45 44 Tm <0064003500380037003800330063003400360032006300650034006100610037003800610031006300620064006100620066006100300034003200650062003400340061006300310066003700650037006200360063006500360066006300630062003800390066006600650066003700380066003900620038003500330037> Tj ET BT /F1 9 Tf 1 0 0 1 515 30 Tm <00310020002f00200031> Tj ET endstream endobj @@ -50,5 +54,5 @@ xref 0000000735 00000 n trailer << /Size 8 /Root 1 0 R >> startxref -2286 +2574 %%EOF diff --git a/server/app/adminapi/logic/tcm/PrescriptionLogic.php b/server/app/adminapi/logic/tcm/PrescriptionLogic.php index 71e6404ce..27c5e2f82 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionLogic.php @@ -1053,12 +1053,12 @@ class PrescriptionLogic } try { - // Keep the signature check and audit write under the same row lock. - // Reject also shares pharmacy claim locks with void/edit operations. $mutate = static fn () => self::auditLocked($id, $action, $remark, $adminId, $adminInfo); - $row = $action === 'reject' - ? LockedPharmacySnapshotMutation::executeForPrescription($id, $mutate) - : Db::transaction($mutate); + $row = match ($action) { + 'approve' => PrescriptionOrderLogic::approvePrescriptionAndLinkedOrders($id, $mutate), + 'reject' => LockedPharmacySnapshotMutation::executeForPrescription($id, $mutate), + default => Db::transaction($mutate), + }; } catch (\Throwable $exception) { if (self::getError() === '') { self::setError($exception->getMessage()); diff --git a/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php b/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php index 19946620f..a8407fcff 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionOrderLogic.php @@ -40,6 +40,7 @@ use app\common\service\tcm\RevisitDueHook; use think\db\Query; use app\common\service\esign\PrescriptionEsignService; use app\common\service\esign\PrescriptionEsignPolicy; +use app\common\service\esign\PrescriptionReviewEsignService; use think\facade\Config; use think\facade\Db; use think\facade\Log; @@ -774,6 +775,87 @@ class PrescriptionOrderLogic } } + /** @param callable(): (Prescription|false) $approve */ + public static function approvePrescriptionAndLinkedOrders(int $prescriptionId, callable $approve): Prescription|false + { + return Db::transaction(static function () use ($prescriptionId, $approve): Prescription|false { + // Follow the order-before-prescription lock order used by order review and revocation. + $orders = PrescriptionOrder::where('prescription_id', $prescriptionId) + ->whereNull('delete_time') + ->where('prescription_audit_status', 0) + ->whereIn('fulfillment_status', [1, 2]) + ->order('id', 'asc') + ->lock(true) + ->select(); + $rx = $approve(); + if ($rx) { + foreach ($orders as $order) { + self::recordPrescriptionApproval($order, $rx->toArray()); + } + } + return $rx; + }); + } + + /** Reconcile a pending order using the existing approval and its archived signatures. */ + public static function syncRecordedPrescriptionApproval(int $orderId, bool $apply = false): bool + { + return Db::transaction(static function () use ($orderId, $apply): bool { + $order = PrescriptionOrder::where('id', $orderId)->whereNull('delete_time')->lock(true)->find(); + if (!$order || (int) $order->prescription_audit_status !== 0 + || !in_array((int) $order->fulfillment_status, [1, 2], true)) { + return false; + } + $rx = Prescription::where('id', (int) $order->prescription_id)->lock(true)->find(); + if (!$rx || !self::hasRecordedPrescriptionApproval($rx->toArray())) { + return false; + } + if ($apply) { + self::recordPrescriptionApproval($order, $rx->toArray()); + } + return true; + }); + } + + private static function hasRecordedPrescriptionApproval(array $rx): bool + { + if ((int) ($rx['audit_status'] ?? 0) !== 1 || !empty($rx['void_status']) || !empty($rx['delete_time']) + || (int) ($rx['audit_by'] ?? 0) <= 0 || (int) ($rx['audit_time'] ?? 0) <= 0 + || !PrescriptionEsignPolicy::hasPrescriptionContent($rx)) { + return false; + } + $id = (int) $rx['id']; + try { + PrescriptionEsignService::assertSignedById($id); + if (!empty($rx['esign_required'])) { + $doctor = Db::name('prescription_esign')->where('prescription_id', $id)->find(); + if (!$doctor) { + return false; + } + PrescriptionReviewEsignService::assertVerified($rx, $doctor, null); + } + } catch (\DomainException) { + return false; + } + return true; + } + + private static function recordPrescriptionApproval(PrescriptionOrder $order, array $rx): void + { + $remark = mb_substr(trim((string) $rx['audit_remark']), 0, 500); + $order->prescription_audit_status = 1; + $order->prescription_audit_remark = $remark; + self::syncFulfillmentStatus($order); + if (!$order->save()) { + throw new \RuntimeException('业务订单处方审核状态同步失败'); + } + self::writeLog( + (int) $order->id, (int) $rx['audit_by'], ['name' => (string) $rx['audit_by_name']], + 'audit_rx_approve', '同步已开处方审核通过' . ($remark !== '' ? ',意见:' . $remark : ''), + strict: true, occurredAt: (int) $rx['audit_time'] + ); + } + private static function syncFulfillmentStatus(PrescriptionOrder $order): void { $fs = (int) $order->fulfillment_status; @@ -1046,7 +1128,7 @@ class PrescriptionOrderLogic private static function createLocked(array $params, int $adminId, array $adminInfo) { self::$error = ''; - // 新建业务订单的两项审核均为待审核,不能在创建时预填单号。 + // 新建时支付单仍须审核,不能预填单号。 if (trim((string) ($params['tracking_number'] ?? '')) !== '') { self::$error = self::TRACKING_AUDIT_REQUIRED; @@ -1176,6 +1258,9 @@ class PrescriptionOrderLogic } self::writeLog((int) $order->id, $adminId, $adminInfo, 'create', '创建业务订单', true); + if (self::hasRecordedPrescriptionApproval($rx)) { + self::recordPrescriptionApproval($order, $rx); + } if ($payOrderIds !== []) { self::replacePayOrderLinks((int) $order->id, $payOrderIds); @@ -5807,7 +5892,8 @@ class PrescriptionOrderLogic array $adminInfo, string $action, string $summary, - bool $strict = false + bool $strict = false, + ?int $occurredAt = null ): void { $adminName = $adminInfo['name'] ?? ''; @@ -5821,10 +5907,12 @@ class PrescriptionOrderLogic $log->admin_name = mb_substr($adminName, 0, 64); $log->action = mb_substr($action, 0, 32); $log->summary = mb_substr($summary, 0, 500); - $log->create_time = time(); + $log->create_time = $occurredAt ?? time(); try { - $log->save(); + if (!$log->save() && $strict) { + throw new \RuntimeException('操作日志写入失败,变更未保存'); + } } catch (\Throwable $e) { if ($strict) { throw new \RuntimeException('操作日志写入失败,变更未保存', 0, $e); diff --git a/server/app/common/service/esign/PrescriptionEsignService.php b/server/app/common/service/esign/PrescriptionEsignService.php index 75b39886f..1da4c6d58 100644 --- a/server/app/common/service/esign/PrescriptionEsignService.php +++ b/server/app/common/service/esign/PrescriptionEsignService.php @@ -625,18 +625,18 @@ final class PrescriptionEsignService }; [$pdf, $issuedAt] = Db::transaction(static function () use ($id, $lockSigningWork): array { [$currentRow, $current] = $lockSigningWork(); - $pdf = self::readPdf($current['source_path'], $current['source_hash']); - $issuedAt = (int) ($current['issued_at'] ?? 0); - if ($issuedAt > 0) { + $archivedSource = self::readPdf($current['source_path'], $current['source_hash']); + // Reuse the issuance time on retries and apply the current disclosure rules before sending. + $issuedAt = (int) ($current['issued_at'] ?? 0) ?: time(); + $pdf = PrescriptionPdf::render($currentRow, $current['environment'], $issuedAt, !empty($current['review_required'])); + if ($pdf === $archivedSource) { return [$pdf, $issuedAt]; } - // This is reached only after the doctor confirms signing and their willingness is verified. - $issuedAt = time(); - $pdf = PrescriptionPdf::render($currentRow, $current['environment'], $issuedAt, !empty($current['review_required'])); - $path = $id . '-' . $current['snapshot_hash'] . '/source-issued.pdf'; + $sourceHash = hash('sha256', $pdf); + $path = $id . '-' . $current['snapshot_hash'] . '/source-issued-' . $sourceHash . '.pdf'; self::writePdf($path, $pdf); Db::name('prescription_esign')->where('prescription_id', $id)->update([ - 'issued_at' => $issuedAt, 'source_hash' => hash('sha256', $pdf), 'source_path' => $path, + 'issued_at' => $issuedAt, 'source_hash' => $sourceHash, 'source_path' => $path, ]); return [$pdf, $issuedAt]; }); @@ -1149,7 +1149,7 @@ final class PrescriptionEsignService private static function filePath(string $relative): string { - if (!preg_match('#^\d+-[a-f0-9]{64}/(?:(?:source(?:-issued)?|signed|review-signed)\.pdf|review-seal-[a-f0-9]{64}\.png)$#D', $relative)) { + if (!preg_match('#^\d+-[a-f0-9]{64}/(?:(?:source(?:-issued(?:-[a-f0-9]{64})?)?|signed|review-signed)\.pdf|review-seal-[a-f0-9]{64}\.png)$#D', $relative)) { throw new DomainException('签署文件引用无效'); } return rtrim((string) Config::get('esign.storage_path', root_path() . 'storage/esign'), '/\\') . DIRECTORY_SEPARATOR . $relative; diff --git a/server/app/common/service/esign/PrescriptionPdf.php b/server/app/common/service/esign/PrescriptionPdf.php index d84d02e57..adbe0472d 100644 --- a/server/app/common/service/esign/PrescriptionPdf.php +++ b/server/app/common/service/esign/PrescriptionPdf.php @@ -43,7 +43,6 @@ final class PrescriptionPdf $add('舌象', $row['tongue']); $add('脉象', $row['pulse']); $add('脉诊补充', $row['pulse_condition']); - $add('方名', $row['prescription_name']); $add('剂型', $row['prescription_type']); $herbLabels = ['name' => '药名', 'dosage' => '用量', 'unit' => '单位', 'remark' => '备注', 'usage' => '煎法', 'usage_method' => '煎法', 'method' => '煎法', 'group' => '组别', @@ -59,8 +58,7 @@ final class PrescriptionPdf $add('药品 ' . ($index + 1), implode(' / ', $parts)); } foreach ([ - 'dose_count' => '总剂数', 'dose_unit' => '剂数单位', 'dosage_amount' => '单次用量', - 'dosage_unit' => '用量单位', 'dosage_bag_count' => '单次袋数', 'bags_per_dose' => '每剂袋数', + 'dosage_amount' => '单次用量', 'dosage_unit' => '用量单位', 'dosage_bag_count' => '单次袋数', 'usage_days' => '服用天数', 'times_per_day' => '每日次数', 'usage_instruction' => '服用说明', 'usage_time' => '服药时间', 'usage_way' => '服用方式', 'dietary_taboo' => '忌口', 'usage_notes' => '医嘱', ] as $key => $label) { @@ -69,8 +67,11 @@ final class PrescriptionPdf $add('代煎', $row['need_decoction'] === '1' ? '是' : '否'); $add('金额(元)', $row['amount']); foreach ((array) $row['aux_usage'] as $key => $value) { + if ($key === 'bags_per_dose') { + continue; + } $label = ['dosage_amount' => '单次用量', 'dosage_bag_count' => '单次袋数', 'need_decoction' => '代煎', - 'bags_per_dose' => '每剂袋数', 'times_per_day' => '每日次数', 'usage_days' => '服用天数', + 'times_per_day' => '每日次数', 'usage_days' => '服用天数', 'prescription_name' => '方名'][$key] ?? $key; $add('辅方' . $label, $value); } diff --git a/server/tests/PrescriptionEsignFlowTest.php b/server/tests/PrescriptionEsignFlowTest.php index 6e1c49291..e253c196c 100644 --- a/server/tests/PrescriptionEsignFlowTest.php +++ b/server/tests/PrescriptionEsignFlowTest.php @@ -451,6 +451,35 @@ namespace { $assert($retry['issued_at'] === $frozen['issued_at'] && $retry['source_hash'] === $frozen['source_hash'], 'retry keeps the exact issuance time and PDF'); + $pdfText = static fn (string $text): string => bin2hex(mb_convert_encoding($text, 'UTF-16BE', 'UTF-8')); + $legacyRetryId = 8888; + $new($legacyRetryId); + Db::name('tcm_prescription')->where('id', $legacyRetryId)->update(['prescription_type' => '浓缩水丸', 'dose_count' => 543]); + Service::start($legacyRetryId, 1, $root); + Fake::$signRejection = 'PROVIDER_50001'; + $assert(Service::complete($legacyRetryId, 1, $root)['status'] === 'failed', 'fixture permits a fresh sign after a definite rejection'); + Fake::$signRejection = null; + $cached = Db::name('prescription_esign')->where('prescription_id', $legacyRetryId)->find(); + $row = Db::name('tcm_prescription')->where('id', $legacyRetryId)->find(); + $expectedSource = PrescriptionPdf::render($row, 'sandbox', (int) $cached['issued_at']); + // Equal-length text substitution creates a readable pre-change cached PDF with the excluded field. + $oldSource = str_replace($pdfText('剂型:浓缩水丸'), $pdfText('总剂数:543'), $expectedSource, $changed); + $assert($changed === 1 && strlen($oldSource) === strlen($expectedSource), 'legacy PDF fixture contains the excluded field'); + $oldPath = $legacyRetryId . '-' . $cached['snapshot_hash'] . '/source-issued.pdf'; + Service::writePdf($oldPath, $oldSource); + Db::name('prescription_esign')->where('prescription_id', $legacyRetryId)->update([ + 'source_path' => $oldPath, 'source_hash' => hash('sha256', $oldSource), + ]); + Service::start($legacyRetryId, 1, $root); + $assert(Service::complete($legacyRetryId, 1, $root)['status'] === 'signed', 'retry signs a current PDF from the frozen prescription'); + $reissued = Db::name('prescription_esign')->where('prescription_id', $legacyRetryId)->find(); + $assert($reissued['issued_at'] === $cached['issued_at'] && $reissued['source_path'] !== $oldPath + && hash_equals($reissued['source_hash'], hash('sha256', $expectedSource)) + && Service::readPdf($oldPath, hash('sha256', $oldSource)) === $oldSource, 'retry keeps the old archive and preserves original issuance time'); + $submitted = Service::readPdf($reissued['signed_path'], $reissued['signed_hash']); + $assert(str_starts_with($submitted, $expectedSource) && !str_contains($submitted, $pdfText('总剂数:')), + 'provider receives the updated PDF rather than the old cached disclosure'); + $new(8); Fake::$startFailure = true; $assert(Service::start(8, 1, $root)['status'] === 'failed', 'identity link outage records failed preparation'); Fake::$startFailure = false; @@ -741,7 +770,7 @@ namespace { ]); } Db::name('tcm_prescription_order')->insert([ - 'id' => 41, 'prescription_id' => 41, 'prescription_audit_status' => 0, 'fulfillment_status' => 0, + 'id' => 41, 'prescription_id' => 41, 'prescription_audit_status' => 0, 'fulfillment_status' => 1, ]); $disabled = Service::status(41, 1, $root); Service::assertSignedById(41, true); @@ -862,9 +891,33 @@ namespace { $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) + Db::name('tcm_prescription_order')->insertAll([ + ['id' => 4101, 'prescription_id' => 41, 'prescription_audit_status' => 2, 'fulfillment_status' => 1], + ['id' => 4102, 'prescription_id' => 41, 'prescription_audit_status' => 0, 'fulfillment_status' => 4], + ]); + Db::execute("CREATE TRIGGER reject_approval_log BEFORE INSERT ON zyt_tcm_prescription_order_log + BEGIN SELECT RAISE(ABORT, 'forced approval log failure'); END"); + $assert(!PrescriptionLogic::audit(41, 'approve', '测试意见', 1, $root) + && (int) Db::name('tcm_prescription')->where('id', 41)->value('audit_status') === 0 + && (int) Db::name('tcm_prescription_order')->where('id', 41)->value('prescription_audit_status') === 0, + 'approval and order sync both roll back when the order audit log cannot be written'); + Db::execute('DROP TRIGGER reject_approval_log'); + $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'); + $approvedRx = Db::name('tcm_prescription')->find(41); + $approvedOrder = Db::name('tcm_prescription_order')->find(41); + $approvalLog = Db::name('tcm_prescription_order_log')->where('prescription_order_id', 41)->find(); + $assert((int) $approvedOrder['prescription_audit_status'] === 1 + && $approvedOrder['prescription_audit_remark'] === '测试意见' + && (int) $approvedOrder['payment_slip_audit_status'] === 0 && (int) $approvedOrder['fulfillment_status'] === 1 + && (int) $approvalLog['admin_id'] === (int) $approvedRx['audit_by'] + && (int) $approvalLog['create_time'] === (int) $approvedRx['audit_time'] + && $approvalLog['action'] === 'audit_rx_approve', + 'the order records the original approval while payment stays pending'); + $assert((int) Db::name('tcm_prescription_order')->where('id', 4101)->value('prescription_audit_status') === 2 + && (int) Db::name('tcm_prescription_order')->where('id', 4102)->value('prescription_audit_status') === 0, + 'synchronization preserves rejected and cancelled orders'); $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'); @@ -1133,6 +1186,18 @@ namespace { $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'); + $pdf = PrescriptionPdf::render(array_replace($sample, [ + 'prescription_name' => '仅内部查看方名', 'dose_count' => 761, 'dose_unit' => '仅内部剂数单位', + 'bags_per_dose' => 762, 'dosage_bag_count' => 3, + 'aux_usage' => ['bags_per_dose' => 763, 'dosage_bag_count' => 4, 'usage_days' => 8, 'prescription_name' => '辅助方模板'], + ]), 'sandbox'); + foreach (['方名:仅内部查看方名', '总剂数:761', '剂数单位:仅内部剂数单位', '每剂袋数:762', '辅方每剂袋数:763', + '辅方bags_per_dose:763'] as $excluded) { + $assert(!str_contains($pdf, $pdfText($excluded)), 'signing PDF excludes: ' . $excluded); + } + foreach (['单次袋数:3', '辅方单次袋数:4', '辅方服用天数:8', '辅方方名:辅助方模板'] as $disclosed) { + $assert(str_contains($pdf, $pdfText($disclosed)), 'signing PDF retains distinct field: ' . $disclosed); + } $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'); @@ -1412,6 +1477,21 @@ namespace { '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'); + Db::name('tcm_prescription_order')->insert([ + 'id' => 8401, 'prescription_id' => 84, 'prescription_audit_status' => 0, 'fulfillment_status' => 1, + ]); + file_put_contents($archive, $archivedBytes . 'modified'); + $assert(!PrescriptionOrderLogic::syncRecordedPrescriptionApproval(8401, true), + 'historical approval cannot be synchronized with a changed dual-sign PDF'); + file_put_contents($archive, $archivedBytes); + $assert(PrescriptionOrderLogic::syncRecordedPrescriptionApproval(8401) + && (int) Db::name('tcm_prescription_order')->where('id', 8401)->value('prescription_audit_status') === 0 + && PrescriptionOrderLogic::syncRecordedPrescriptionApproval(8401, true) + && !PrescriptionOrderLogic::syncRecordedPrescriptionApproval(8401, true), + 'historical synchronization previews without changes and applies exactly once'); + $assert((int) Db::name('tcm_prescription_order')->where('id', 8401)->value('prescription_audit_status') === 1 + && (int) Db::name('tcm_prescription_order_log')->where('prescription_order_id', 8401)->value('admin_id') === 23, + 'historical synchronization preserves the original approver, who need not be the signing pharmacist'); $signedLog = Service::status(84, 22, $auditor)['signing_log']; $events = array_column($signedLog, null, 'event'); $times = array_column($signedLog, 'time'); diff --git a/server/tests/PrescriptionOrderTrackingAuditTest.php b/server/tests/PrescriptionOrderTrackingAuditTest.php index edb65fd1e..e3a405754 100755 --- a/server/tests/PrescriptionOrderTrackingAuditTest.php +++ b/server/tests/PrescriptionOrderTrackingAuditTest.php @@ -64,6 +64,7 @@ try { id INT PRIMARY KEY AUTO_INCREMENT, diagnosis_id INT DEFAULT 1, gender INT DEFAULT 0, creator_id INT DEFAULT 1, assistant_id INT DEFAULT 0, is_shared INT DEFAULT 0, herbs TEXT, audit_status INT DEFAULT 1, void_status INT DEFAULT 0, visible_role_ids VARCHAR(100) DEFAULT "", + audit_by INT NULL, audit_by_name VARCHAR(100), audit_time INT NULL, audit_remark VARCHAR(500), create_time INT DEFAULT 0, update_time INT DEFAULT 0, delete_time INT NULL ) ENGINE=InnoDB'); $pdo->exec('CREATE TABLE zyt_tcm_diagnosis (id INT PRIMARY KEY, assistant_id INT DEFAULT 0, delete_time INT NULL)'); @@ -171,7 +172,7 @@ try { 'Final pending audit must reject changed tracking and roll back all form changes'); } - // New orders always start pending, even if clients submit fake audit flags or the source prescription is approved. + // Creation trusts recorded approvals, never audit flags supplied by the client or set by a column default. $createParams = static fn (int $rxId): array => [ 'prescription_id' => $rxId, 'diagnosis_id' => 1, 'recipient_name' => '测试患者', 'recipient_phone' => '13000000000', 'shipping_address' => '测试地址', 'fee_type' => 3, 'amount' => 100, @@ -188,6 +189,20 @@ try { && (int) $out['prescription_audit_status'] === 0 && (int) $out['payment_slip_audit_status'] === 0, 'Normal creation must store empty tracking and pending audits'); } + $rxId = $newRx(); + $auditTime = time() - 90; + Db::name('tcm_prescription')->where('id', $rxId)->update([ + 'herbs' => '[{"name":"测试药材"}]', 'audit_by' => 2, 'audit_by_name' => '实际审核人', + 'audit_time' => $auditTime, 'audit_remark' => '已开处方审核意见', + ]); + $out = PrescriptionOrderLogic::create($createParams($rxId), 1, $admin); + $expect(is_array($out) && (int) $out['prescription_audit_status'] === 1 + && (int) $out['payment_slip_audit_status'] === 0 && (int) $out['fulfillment_status'] === 1, + 'An order created after prescription approval inherits the approval and still needs payment review'); + $approvalLog = $logs((int) $out['id'])[1]; + $expect($approvalLog['action'] === 'audit_rx_approve' && (int) $approvalLog['admin_id'] === 2 + && (int) $approvalLog['create_time'] === $auditTime, + 'Inherited approval records the original approver and approval time'); // Audit revocation must be observed on the next request; historical fulfillment/snapshot data grants no exemption. foreach ([1, 2, 3, 4, 5, 6, 9, 10] as $status) {