diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index 05b4112fb..59e791868 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -98,7 +98,7 @@ from PySide6.QtWidgets import ( ) from shiboken6 import isValid -from ...core.esign import esign_config, esign_status +from ...core.esign import certificate_identity_number, esign_config, esign_status from .. import icons from ..design_system import clinical_stylesheet from ..diagnosis_terms import shared_terms @@ -993,6 +993,7 @@ _REISSUE_FIELDS = ( "herbs", "dose_count", "dose_unit", "dosage_amount", "dosage_unit", "dosage_bag_count", "need_decoction", "bags_per_dose", "usage_days", "times_per_day", "usage_instruction", "usage_time", "usage_way", "dietary_taboo", "usage_notes", "aux_usage", "ai_assisted", + "patient_id_card", ) @@ -3451,12 +3452,21 @@ class PrescriptionEditorDialog(QDialog): self.age.setRange(0, 150) self.visit_no = QLineEdit() self.visit_no.setPlaceholderText("自动生成或手动输入") + # 手机号写入处方笺;身份证号写回关联诊单(服务端校验格式与重复,并按出生日期更新年龄)。 + self.phone = QLineEdit() + self.phone.setPlaceholderText("处方笺显示的手机号") + self.phone.setMaxLength(20) + self.id_card = QLineEdit() + self.id_card.setPlaceholderText("15 或 18 位身份证号,保存后同步到诊单") + self.id_card.setMaxLength(18) self.date_edit = PrescriptionDateEdit(QDate.currentDate()) name_grid = QGridLayout() self._prepare_grid(name_grid, 2) self._place_field(name_grid, 0, 0, "患者姓名", self.patient_name, required=True) self._place_field(name_grid, 0, 1, "门诊号", self.visit_no) + self._place_field(name_grid, 1, 0, "手机号", self.phone) + self._place_field(name_grid, 1, 1, "身份证号", self.id_card) layout.addLayout(name_grid) self._register_responsive_grid(name_grid, 2) @@ -3855,6 +3865,8 @@ class PrescriptionEditorDialog(QDialog): appointment_id=_int(source.get("appointment_id"), 0), ) self.visit_no.setText(visit_no) + self.phone.setText(str(source.get("phone") or "").strip()) + self.id_card.setText(str(source.get("patient_id_card") or source.get("id_card") or "").strip()) self._set_gender(source.get("gender", 1)) self.age.setValue(_int(source.get("age"), 0)) date_value = QDate.fromString( @@ -4301,6 +4313,8 @@ class PrescriptionEditorDialog(QDialog): "need_decoction": int(self.need_decoction.isChecked()), "bags_per_dose": self.bags_per_dose.value(), "patient_name": self.patient_name.text().strip(), + "phone": self.phone.text().strip(), + "id_card": self.id_card.text().strip().upper(), "gender": self._gender_value(), "age": self.age.value(), "visit_no": self.visit_no.text().strip(), @@ -4398,6 +4412,14 @@ class PrescriptionEditorDialog(QDialog): self.validation.show_message(message, "warning") widget.setFocus() return + if payload.get("id_card"): + try: + payload["id_card"] = certificate_identity_number(payload["id_card"]) + except ValueError as error: + self.tabs.setCurrentIndex(0) + self.validation.show_message(str(error), "warning") + self.id_card.setFocus() + return length_checks = ( ( payload["clinical_diagnosis"], diff --git a/app/tests/test_dialog_detail_layout.py b/app/tests/test_dialog_detail_layout.py index a49ee6a6d..aafa7bf48 100755 --- a/app/tests/test_dialog_detail_layout.py +++ b/app/tests/test_dialog_detail_layout.py @@ -143,3 +143,24 @@ def test_ai_report_columns_keep_headings_at_the_same_text_baseline( assert abs(centers[0] - centers[1]) <= 1 finally: dialog.close() + + +def test_prescription_form_edits_phone_and_id_card(application: QApplication) -> None: + editor = PrescriptionEditorDialog( + SimpleNamespace(list_medicines=lambda **kwargs: {"lists": [], "count": 0}), + {"id": 77, "diagnosis_id": 501, "patient_name": "林晓岚", "phone": "13800000000", + "patient_id_card": "11010119800101123X", "prescription_type": "浓缩水丸"}, + ) + try: + # 已开处方编辑时手机号、身份证号可见可改(姓名仍只读),保存时随处方提交。 + assert editor.phone.text() == "13800000000" and editor.id_card.text() == "11010119800101123X" + assert not editor.phone.isReadOnly() and not editor.id_card.isReadOnly() + editor.phone.setText(" 13900000001 ") + editor.id_card.setText("110101200001011234") + payload = editor.payload() + assert payload["phone"] == "13900000001" and payload["id_card"] == "110101200001011234" + editor.id_card.setText("12345") + assert editor.payload()["id_card"] == "12345" + finally: + editor.close() + editor.deleteLater() diff --git a/server/app/adminapi/controller/tcm/PrescriptionController.php b/server/app/adminapi/controller/tcm/PrescriptionController.php index 5a4d2fb36..4605648d1 100755 --- a/server/app/adminapi/controller/tcm/PrescriptionController.php +++ b/server/app/adminapi/controller/tcm/PrescriptionController.php @@ -45,7 +45,7 @@ class PrescriptionController extends BaseAdminController public function edit() { $params = (new PrescriptionValidate())->post()->goCheck('edit'); - $result = PrescriptionLogic::edit($params, $this->adminId); + $result = PrescriptionLogic::edit($params, $this->adminId, $this->adminInfo); if (!$result) { return $this->fail(PrescriptionLogic::getError()); } diff --git a/server/app/adminapi/logic/tcm/PrescriptionLogic.php b/server/app/adminapi/logic/tcm/PrescriptionLogic.php index e574df80a..7bc4b4f03 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionLogic.php @@ -534,7 +534,13 @@ class PrescriptionLogic if (!self::assertUniquePrescriptionPerDiagnosisDay($diagnosisIdRule, $adminId, $dateYmd, null)) { throw new \DomainException(self::getError()); } + // 开方入口已校验诊单管理权限;身份证号写回诊单并按出生日期更新年龄。 + $age = self::applyPatientIdCard($diagnosisIdRule, (string) ($params['id_card'] ?? '')); + if ($age !== null) { + $data['age'] = $age; + } } + $data['phone'] = self::phoneParam($params, (string) $data['phone']); $prescription = new Prescription(); $prescription->save($data); $id = (int) $prescription->id; @@ -560,14 +566,14 @@ class PrescriptionLogic /** * 编辑处方 */ - public static function edit(array $params, int $adminId): bool + public static function edit(array $params, int $adminId, array $adminInfo = []): bool { $prescriptionId = (int) ($params['id'] ?? 0); self::setError(''); try { return (bool) LockedPharmacySnapshotMutation::executeForPrescription( $prescriptionId, - static fn (): bool => self::editLocked($params, $adminId) + static fn (): bool => self::editLocked($params, $adminId, $adminInfo) ); } catch (\Throwable $exception) { if (self::getError() === '') { @@ -577,7 +583,7 @@ class PrescriptionLogic } } - private static function editLocked(array $params, int $adminId): bool + private static function editLocked(array $params, int $adminId, array $adminInfo = []): bool { try { $prescription = Prescription::where('id', $params['id'])->lock(true)->find(); @@ -723,6 +729,17 @@ class PrescriptionLogic $data['void_by'] = null; $data['void_by_name'] = ''; } + $data['phone'] = self::phoneParam($params, (string) ($prescription->phone ?? '')); + if (trim((string) ($params['id_card'] ?? '')) !== '') { + if ($newDiagnosisId <= 0 || $adminInfo === [] + || !DiagnosisLogic::canManageDiagnosis($newDiagnosisId, $adminId, $adminInfo)) { + throw new \DomainException('无权修改该患者身份证号'); + } + $age = self::applyPatientIdCard($newDiagnosisId, (string) $params['id_card']); + if ($age !== null) { + $data['age'] = $age; + } + } $prescription->save($data); PrescriptionOrderLogic::onConsumerPrescriptionSaved((int) $params['id']); @@ -739,6 +756,41 @@ class PrescriptionLogic } } + /** 处方笺手机号:传入非空值时采用(最长 20 位),否则保留原值。 */ + private static function phoneParam(array $params, string $fallback): string + { + $phone = trim((string) ($params['phone'] ?? '')); + if ($phone === '') { + return $fallback; + } + if (strlen($phone) > 20) { + throw new \DomainException('手机号过长'); + } + return $phone; + } + + /** + * 补全/修改患者身份证号:写入诊单并按出生日期更新年龄,返回新年龄;为空或未变更返回 null。 + * 调用方须已确认当前账号可管理该诊单,并在同一事务内调用。 + */ + private static function applyPatientIdCard(int $diagnosisId, string $idCard): ?int + { + $idCard = strtoupper(trim($idCard)); + if ($diagnosisId <= 0 || $idCard === '') { + return null; + } + if (strtoupper(trim((string) Diagnosis::where('id', $diagnosisId)->value('id_card'))) === $idCard) { + return null; + } + if (!empty(DiagnosisLogic::checkIdCard(['id' => $diagnosisId, 'id_card' => $idCard])['exists'])) { + throw new \DomainException('该身份证号已登记在其他诊单'); + } + if (!DiagnosisLogic::fillIdCard(['id' => $diagnosisId, 'id_card' => $idCard])) { + throw new \DomainException(DiagnosisLogic::getError() ?: '身份证号保存失败'); + } + return (int) Diagnosis::where('id', $diagnosisId)->value('age'); + } + private static function scheduleAiSaved(array $saved, int $actor, ?array $info, array $options): void { try { @@ -955,6 +1007,11 @@ class PrescriptionLogic $arr = self::withActionAvailability($arr, $viewerAdminId, $viewerAdminInfo); $arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? ''); + // 患者身份证号存于诊单,仅对可管理该诊单的账号返回,供编辑处方时修改。 + $diagnosisId = (int) ($arr['diagnosis_id'] ?? 0); + if ($diagnosisId > 0 && DiagnosisLogic::canManageDiagnosis($diagnosisId, $viewerAdminId, $viewerAdminInfo)) { + $arr['patient_id_card'] = (string) Diagnosis::where('id', $diagnosisId)->value('id_card'); + } /** * 处方笺展示所需的"收件信息/订单号/合计"等字段, diff --git a/server/tests/PrescriptionEsignFlowTest.php b/server/tests/PrescriptionEsignFlowTest.php index 6fb1161d5..d6b132b64 100644 --- a/server/tests/PrescriptionEsignFlowTest.php +++ b/server/tests/PrescriptionEsignFlowTest.php @@ -1050,8 +1050,9 @@ namespace { Db::name('system_role_menu')->insert(['role_id' => 1, 'menu_id' => 6]); Db::execute("INSERT INTO zyt_system_role VALUES (1, 'Doctor', 4, NULL), (2, 'Read only', 4, NULL), (3, 'Audit', 1, NULL)"); Db::execute('CREATE TABLE zyt_tcm_diagnosis (id INTEGER PRIMARY KEY, status INTEGER, patient_id INTEGER, - assistant_id INTEGER, patient_name TEXT, gender INTEGER, age INTEGER, phone TEXT, delete_time INTEGER)'); - Db::execute("INSERT INTO zyt_tcm_diagnosis VALUES (10, 1, 99, 3, 'Test patient', 1, 30, '13800000000', NULL)"); + assistant_id INTEGER, patient_name TEXT, gender INTEGER, age INTEGER, phone TEXT, delete_time INTEGER, id_card TEXT DEFAULT "")'); + Db::execute("INSERT INTO zyt_tcm_diagnosis VALUES (10, 1, 99, 3, 'Test patient', 1, 30, '13800000000', NULL, '')"); + Db::execute("INSERT INTO zyt_tcm_diagnosis VALUES (11, 1, 98, 3, 'Other patient', 1, 40, '', NULL, '110101199001011237')"); Db::execute('CREATE TABLE zyt_doctor_appointment (id INTEGER PRIMARY KEY, patient_id INTEGER, doctor_id INTEGER, status INTEGER)'); 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)'); @@ -1244,6 +1245,34 @@ namespace { Db::name('tcm_prescription_order')->where('id', 3002)->update(['gancao_order_state' => 91, 'fulfillment_status' => 4]); $assert(PrescriptionLogic::detail($gancaoRx, 1, $doctor)['can_void'] === true && PrescriptionLogic::void($gancaoRx, 1, $doctor), 'a Gancao withdrawal callback (91) makes the prescription voidable'); + + // 开方/编辑处方可修改处方笺手机号;身份证号写回诊单(校验格式与重复、按出生日期更新年龄),仅可管理诊单者可见。 + $contactRx = PrescriptionLogic::add($params + ['phone' => '13900000001', 'id_card' => '11010119800101123x'], 1, $doctor); + $contact = Db::name('tcm_prescription')->find($contactRx); + $assert($contactRx !== null && $contact['phone'] === '13900000001' + && Db::name('tcm_diagnosis')->where('id', 10)->value('id_card') === '11010119800101123X' + && (int) $contact['age'] === (int) Db::name('tcm_diagnosis')->where('id', 10)->value('age') + && (int) $contact['age'] >= 45, 'new prescriptions store the phone and fill the diagnosis ID card with derived age'); + $assert(PrescriptionLogic::detail($contactRx, 1, $doctor)['patient_id_card'] === '11010119800101123X' + && !array_key_exists('patient_id_card', PrescriptionLogic::detail($contactRx, 4, ['root' => 0, 'admin_id' => 4, 'role_id' => [3]]) ?? []), + 'the ID card is returned only to accounts that manage the diagnosis'); + $edit = static fn (array $fields): array => ['id' => $contactRx, 'diagnosis_id' => 10, 'herbs' => $params['herbs'], + 'prescription_date' => $params['prescription_date']] + $fields; + $assert(!PrescriptionLogic::edit($edit(['id_card' => '110101199001011237']), 1, $doctor) + && str_contains(PrescriptionLogic::getError(), '已登记') + && Db::name('tcm_diagnosis')->where('id', 10)->value('id_card') === '11010119800101123X', + 'a duplicate ID card is refused and nothing is saved'); + $assert(!PrescriptionLogic::edit($edit(['id_card' => '1234']), 1, $doctor) + && str_contains(PrescriptionLogic::getError(), '格式'), 'a malformed ID card is refused'); + $assert(!PrescriptionLogic::edit($edit(['phone' => '13900000002', 'id_card' => '110101200001011234']), 1) + && Db::name('tcm_prescription')->where('id', $contactRx)->value('phone') === '13900000001', + 'editing the ID card without a verified diagnosis scope is refused and rolls back the phone'); + $assert(PrescriptionLogic::edit($edit(['phone' => '13900000002', 'id_card' => '110101200001011234']), 1, $doctor), + 'phone and ID card can be edited together: ' . PrescriptionLogic::getError()); + $assert(Db::name('tcm_prescription')->where('id', $contactRx)->value('phone') === '13900000002' + && Db::name('tcm_diagnosis')->where('id', 10)->value('id_card') === '110101200001011234' + && (int) Db::name('tcm_prescription')->where('id', $contactRx)->value('age') === (int) Db::name('tcm_diagnosis')->where('id', 10)->value('age'), + 'edit saves the phone on the prescription and the ID card and age on the diagnosis'); $decimalRow = array_replace($sample, ['dosage_amount' => '10.0000', 'amount' => '20.00']); $floatRow = array_replace($sample, ['dosage_amount' => 10.0, 'amount' => 20]); $assert(Policy::hash($decimalRow) === Policy::hash($floatRow), 'raw DECIMAL and ORM float hashes agree');