i更新
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
# Merge this section into deployment environment configuration; never commit real credentials.
|
||||
# SDK 3.1.13+ is required for queryWillingnessValidity. Keep this service private.
|
||||
# Initialize the SDK once per JVM startup. Restart it before changing app or environment.
|
||||
[ESIGN]
|
||||
ENABLED = false
|
||||
ENVIRONMENT = sandbox
|
||||
APP_ID =
|
||||
APP_SECRET =
|
||||
SDK_URL = http://127.0.0.1:8091/paas-sdk-service
|
||||
TIMEOUT = 60
|
||||
# Optional private persistent directory; default is server/storage/esign.
|
||||
# STORAGE_PATH = /srv/zyt-private/esign
|
||||
@@ -7,6 +7,7 @@ namespace app\adminapi\controller\tcm;
|
||||
use app\adminapi\controller\BaseAdminController;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\validate\tcm\PrescriptionValidate;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
|
||||
/**
|
||||
* 中医处方单控制器
|
||||
@@ -32,7 +33,7 @@ class PrescriptionController extends BaseAdminController
|
||||
if ($id === null) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
return $this->success('保存成功', ['id' => $id]);
|
||||
return $this->success('保存成功', ['id' => $id, 'esign' => PrescriptionEsignService::status($id, (int) $this->adminId, $this->adminInfo)]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,7 +46,7 @@ class PrescriptionController extends BaseAdminController
|
||||
if (!$result) {
|
||||
return $this->fail(PrescriptionLogic::getError());
|
||||
}
|
||||
return $this->success('编辑成功');
|
||||
return $this->success('编辑成功', ['id' => (int) $params['id'], 'esign' => PrescriptionEsignService::status((int) $params['id'], (int) $this->adminId, $this->adminInfo)]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,4 +182,50 @@ class PrescriptionController extends BaseAdminController
|
||||
}
|
||||
return $this->success('作废成功');
|
||||
}
|
||||
|
||||
public function esignConfig()
|
||||
{
|
||||
return $this->data(PrescriptionEsignService::capability());
|
||||
}
|
||||
|
||||
public function esignStatus()
|
||||
{
|
||||
return $this->esignOperation('status', false);
|
||||
}
|
||||
|
||||
public function esignStart()
|
||||
{
|
||||
return $this->esignOperation('start', true);
|
||||
}
|
||||
|
||||
public function esignComplete()
|
||||
{
|
||||
return $this->esignOperation('complete', true);
|
||||
}
|
||||
|
||||
public function esignDownload()
|
||||
{
|
||||
return $this->esignOperation('download', false);
|
||||
}
|
||||
|
||||
private function esignOperation(string $operation, bool $post)
|
||||
{
|
||||
if ($post && !$this->request->isPost()) {
|
||||
return $this->fail('请使用 POST 请求');
|
||||
}
|
||||
$id = (int) ($post ? $this->request->post('id', 0) : $this->request->get('id', 0));
|
||||
if ($id <= 0) {
|
||||
return $this->fail('处方ID无效');
|
||||
}
|
||||
if ($operation === 'complete') {
|
||||
// A browser disconnect must not interrupt archival after signing.
|
||||
ignore_user_abort(true);
|
||||
set_time_limit(300);
|
||||
}
|
||||
try {
|
||||
return $this->data(PrescriptionEsignService::{$operation}($id, (int) $this->adminId, $this->adminInfo));
|
||||
} catch (\Throwable $e) {
|
||||
return $this->fail($e instanceof \DomainException ? $e->getMessage() : '电子签署暂不可用,请联系管理员');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,24 @@ class AuthMiddleware
|
||||
// 当前访问路径
|
||||
$accessUri = strtolower($request->controller() . '/' . $request->action());
|
||||
|
||||
// Explicit gate: these new endpoints must not use unregistered-route bypass.
|
||||
if (str_starts_with($accessUri, 'tcm.prescription/esign')) {
|
||||
$action = substr($accessUri, strlen('tcm.prescription/'));
|
||||
if ($action === 'esignconfig') {
|
||||
return $next($request); // Only exposes enabled + environment, to logged-in users.
|
||||
}
|
||||
$uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []);
|
||||
$writes = ['tcm.prescription/add', 'tcm.prescription/edit', 'cf.prescription/add', 'cf.prescription/edit',
|
||||
'tcm.diagnosis/chufang', 'tcm.diagnosis/kaifang'];
|
||||
$reads = array_merge($writes, ['tcm.prescription/detail', 'tcm.prescription/lists', 'cf.prescription/lists',
|
||||
'cf.prescription/detail', 'cf.prescription/audit', 'tcm.prescription/audit',
|
||||
'tcm.prescriptionorder/lists', 'tcm.prescriptionorder/detail', 'tcm.prescriptionorder/auditprescription']);
|
||||
$grants = in_array($action, ['esignstart', 'esigncomplete'], true) ? $writes : $reads;
|
||||
return in_array($action, ['esignstart', 'esigncomplete', 'esignstatus', 'esigndownload'], true)
|
||||
&& array_intersect($grants, $uris) !== []
|
||||
? $next($request) : JsonService::fail('权限不足,无法访问电子签署');
|
||||
}
|
||||
|
||||
// 患者列表的部门筛选复用列表权限;只允许 GET 查询显式启用数据范围的部门树。
|
||||
// 必须与 DeptController::all 读取同一个 GET 参数,避免请求体参数意外放行全量部门。
|
||||
if ($accessUri === 'dept.dept/all'
|
||||
|
||||
@@ -296,6 +296,7 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
|
||||
|
||||
// 处理字段格式
|
||||
foreach ($lists as &$item) {
|
||||
$item['esign'] = \app\common\service\esign\PrescriptionEsignService::describe($item, (int) $this->adminId);
|
||||
// 设置默认值
|
||||
$item['usage_time'] = $item['usage_time'] ?? '饭前';
|
||||
$item['usage_way'] = $item['usage_way'] ?? '温水送服';
|
||||
|
||||
@@ -19,6 +19,8 @@ use think\facade\Log;
|
||||
use think\facade\Db;
|
||||
use app\common\service\prescriptionai\PrescriptionAiStore;
|
||||
use app\common\service\prescriptionai\PrescriptionAiRequest;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
|
||||
class PrescriptionLogic
|
||||
{
|
||||
@@ -394,6 +396,10 @@ class PrescriptionLogic
|
||||
'assistant_id' => $assistantIdForRx,
|
||||
];
|
||||
|
||||
if (PrescriptionEsignService::enabled()) {
|
||||
$data['esign_required'] = 1;
|
||||
$data['esign_status'] = 'pending';
|
||||
}
|
||||
try {
|
||||
return Db::transaction(static function () use ($data, $params, $adminId, $adminInfo, $diagnosisIdRule, $dateYmd): int {
|
||||
$replayed = PrescriptionAiRequest::replay($params, $adminId, true);
|
||||
@@ -457,6 +463,7 @@ class PrescriptionLogic
|
||||
}
|
||||
|
||||
// 已通过且未作废:不可编辑
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
if ((int) ($prescription->audit_status ?? 1) === 1 && (int) ($prescription->void_status ?? 0) === 0) {
|
||||
self::setError('该处方已通过审核,不可编辑');
|
||||
return false;
|
||||
@@ -555,7 +562,7 @@ class PrescriptionLogic
|
||||
'usage_way' => $params['usage_way'] ?? $prescription->usage_way,
|
||||
'dietary_taboo' => is_array($params['dietary_taboo'] ?? null) ? implode(',', $params['dietary_taboo']) : ($params['dietary_taboo'] ?? $prescription->dietary_taboo),
|
||||
'usage_notes' => $params['usage_notes'] ?? $prescription->usage_notes,
|
||||
'doctor_name' => $params['doctor_name'] ?? $prescription->doctor_name,
|
||||
'doctor_name' => (string) $prescription->doctor_name,
|
||||
'doctor_signature' => $params['doctor_signature'] ?? $prescription->doctor_signature,
|
||||
'is_shared' => (int)($params['is_shared'] ?? $prescription->is_shared),
|
||||
'visible_role_ids' => array_key_exists('visible_role_ids', $params)
|
||||
@@ -571,6 +578,10 @@ class PrescriptionLogic
|
||||
'audit_remark' => '',
|
||||
];
|
||||
|
||||
if (PrescriptionEsignService::enabled()) {
|
||||
$data['esign_required'] = 1;
|
||||
$data['esign_status'] = 'pending';
|
||||
}
|
||||
if ($wasVoid) {
|
||||
$data['void_status'] = 0;
|
||||
$data['void_time'] = null;
|
||||
@@ -631,7 +642,7 @@ class PrescriptionLogic
|
||||
private static function patchPatientContactLocked(int $rxId, string $patientName, string $phone, int $gender, int $adminId, array $adminInfo): bool
|
||||
{
|
||||
self::$error = '';
|
||||
$prescription = Prescription::find($rxId);
|
||||
$prescription = Prescription::where('id', $rxId)->lock(true)->find();
|
||||
if (!$prescription) {
|
||||
self::setError('处方不存在');
|
||||
|
||||
@@ -648,6 +659,7 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
$patientName = trim($patientName);
|
||||
$phone = trim($phone);
|
||||
if ($patientName === '') {
|
||||
@@ -767,6 +779,7 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
PrescriptionEsignPolicy::assertMutable($prescription->toArray());
|
||||
$prescription->delete();
|
||||
PrescriptionAiStore::invalidate($id, 'deleted');
|
||||
return true;
|
||||
@@ -792,6 +805,7 @@ class PrescriptionLogic
|
||||
return null;
|
||||
}
|
||||
$arr = $row->toArray();
|
||||
$arr['esign'] = PrescriptionEsignService::describe($arr, $viewerAdminId);
|
||||
$arr['gender_desc'] = $arr['gender'] == 1 ? '男' : '女';
|
||||
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
|
||||
|
||||
@@ -848,31 +862,24 @@ class PrescriptionLogic
|
||||
if ($prescriptionId <= 0) {
|
||||
return;
|
||||
}
|
||||
$row = Prescription::find($prescriptionId);
|
||||
if (!$row) {
|
||||
return;
|
||||
}
|
||||
if ((int) ($row->void_status ?? 0) === 1) {
|
||||
return;
|
||||
}
|
||||
if ((int) ($row->audit_status ?? 1) !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$lastAuditWecomNotify = null;
|
||||
$name = (string) ($adminInfo['name'] ?? '');
|
||||
$now = time();
|
||||
$finalRemark = trim($remark) !== '' ? trim($remark) : '业务订单处方审核通过';
|
||||
$finalRemark = mb_substr($finalRemark, 0, 500);
|
||||
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = $now;
|
||||
$row->audit_by = $adminId;
|
||||
$row->audit_by_name = $name;
|
||||
$row->audit_remark = $finalRemark;
|
||||
|
||||
try {
|
||||
if ($row->save()) {
|
||||
$row = Db::transaction(static function () use ($prescriptionId, $adminId, $adminInfo, $finalRemark): ?Prescription {
|
||||
$row = Prescription::where('id', $prescriptionId)->lock(true)->find();
|
||||
if (!$row || (int) ($row->void_status ?? 0) === 1 || (int) ($row->audit_status ?? 1) !== 0) {
|
||||
return null;
|
||||
}
|
||||
PrescriptionEsignService::assertSignedById($prescriptionId);
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = time();
|
||||
$row->audit_by = $adminId;
|
||||
$row->audit_by_name = (string) ($adminInfo['name'] ?? '');
|
||||
$row->audit_remark = $finalRemark;
|
||||
return $row->save() ? $row : null;
|
||||
});
|
||||
if ($row) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $finalRemark, $adminInfo);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
@@ -905,7 +912,29 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
$row = Prescription::find($id);
|
||||
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);
|
||||
} catch (\Throwable $exception) {
|
||||
if (self::getError() === '') {
|
||||
self::setError($exception->getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!$row) {
|
||||
return false;
|
||||
}
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, $action, $remark, $adminInfo);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function auditLocked(int $id, string $action, string $remark, int $adminId, array $adminInfo): Prescription|false
|
||||
{
|
||||
$row = Prescription::where('id', $id)->lock(true)->find();
|
||||
if (!$row) {
|
||||
self::setError('处方不存在');
|
||||
|
||||
@@ -918,7 +947,7 @@ class PrescriptionLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((int) ($row->audit_status ?? 1) !== 0) {
|
||||
if ((int) ($row->audit_status ?? 1) !== 0 || !empty($row->void_status)) {
|
||||
self::setError('当前状态不可审核');
|
||||
|
||||
return false;
|
||||
@@ -928,18 +957,19 @@ class PrescriptionLogic
|
||||
$now = time();
|
||||
|
||||
if ($action === 'approve') {
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById($id);
|
||||
} catch (\DomainException $e) {
|
||||
self::setError($e->getMessage());
|
||||
return false;
|
||||
}
|
||||
$row->audit_status = 1;
|
||||
$row->audit_time = $now;
|
||||
$row->audit_by = $adminId;
|
||||
$row->audit_by_name = $name;
|
||||
$row->audit_remark = $remark;
|
||||
|
||||
$ok = (bool) $row->save();
|
||||
if ($ok) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $remark, $adminInfo);
|
||||
}
|
||||
|
||||
return $ok;
|
||||
return $row->save() ? $row : false;
|
||||
}
|
||||
|
||||
if ($action === 'reject') {
|
||||
@@ -958,19 +988,11 @@ class PrescriptionLogic
|
||||
$row->void_by = $adminId;
|
||||
$row->void_by_name = $name;
|
||||
|
||||
$ok = Db::transaction(static function () use ($row, $id): bool {
|
||||
Prescription::where('id', $id)->lock(true)->find();
|
||||
$saved = (bool) $row->save();
|
||||
if ($saved) {
|
||||
PrescriptionAiStore::invalidate($id, 'voided');
|
||||
}
|
||||
return $saved;
|
||||
});
|
||||
$ok = (bool) $row->save();
|
||||
if ($ok) {
|
||||
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'reject', $remark, $adminInfo);
|
||||
PrescriptionAiStore::invalidate($id, 'voided');
|
||||
}
|
||||
|
||||
return $ok;
|
||||
return $ok ? $row : false;
|
||||
}
|
||||
|
||||
self::setError('无效的审核操作');
|
||||
@@ -1067,10 +1089,14 @@ class PrescriptionLogic
|
||||
*/
|
||||
private static function filterViewablePrescriptions(array $rows, int $viewerAdminId, array $viewerAdminInfo): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$visible = array_values(array_filter(
|
||||
$rows,
|
||||
static fn (array $row): bool => self::canViewPrescription($row, $viewerAdminId, $viewerAdminInfo)
|
||||
));
|
||||
return array_map(static function (array $row) use ($viewerAdminId): array {
|
||||
$row['esign'] = PrescriptionEsignService::describe($row, $viewerAdminId);
|
||||
return $row;
|
||||
}, $visible);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1107,7 +1133,9 @@ class PrescriptionLogic
|
||||
return null;
|
||||
}
|
||||
|
||||
return $row->toArray();
|
||||
$result = $row->toArray();
|
||||
$result['esign'] = PrescriptionEsignService::describe($result, $viewerAdminId);
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1234,6 +1262,10 @@ class PrescriptionLogic
|
||||
'assistant_id' => $assistantIdForRx,
|
||||
];
|
||||
|
||||
if (PrescriptionEsignService::enabled()) {
|
||||
$data['esign_required'] = 1;
|
||||
$data['esign_status'] = 'pending';
|
||||
}
|
||||
$prescription = new Prescription();
|
||||
$prescription->save($data);
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ use app\common\service\pharmacy\PharmacySubmissionClaimWorkflow;
|
||||
use app\common\service\pharmacy\PharmacySupplyMode;
|
||||
use app\common\service\tcm\RevisitDueHook;
|
||||
use think\db\Query;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use think\facade\Log;
|
||||
@@ -58,6 +60,17 @@ class PrescriptionOrderLogic
|
||||
return self::$error;
|
||||
}
|
||||
|
||||
private static function assertEsignApproved(PrescriptionOrder $order, bool $forDispensing = false): bool
|
||||
{
|
||||
try {
|
||||
PrescriptionEsignService::assertSignedById((int) $order->prescription_id, $forDispensing);
|
||||
return true;
|
||||
} catch (\DomainException $e) {
|
||||
self::$error = $e->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function assertTrackingAuditApproved(PrescriptionOrder $order): bool
|
||||
{
|
||||
if ((int) $order->prescription_audit_status !== 1 || (int) $order->payment_slip_audit_status !== 1) {
|
||||
@@ -66,7 +79,7 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
return self::assertEsignApproved($order, true);
|
||||
}
|
||||
|
||||
private static function assertRemoteSnapshotMutable(PrescriptionOrder $order): bool
|
||||
@@ -1429,12 +1442,13 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
$rx = Prescription::where('id', $rxId)->whereNull('delete_time')->find();
|
||||
$rx = Prescription::where('id', $rxId)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$rx) {
|
||||
self::setError('处方不存在');
|
||||
|
||||
return false;
|
||||
}
|
||||
PrescriptionEsignPolicy::assertMutable($rx->toArray());
|
||||
if (!PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
|
||||
self::setError('无权限修改此处方');
|
||||
|
||||
@@ -2352,7 +2366,32 @@ class PrescriptionOrderLogic
|
||||
public static function auditPrescription(int $id, string $action, string $remark, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find();
|
||||
try {
|
||||
$out = Db::transaction(static function () use ($id, $action, $remark, $adminId, $adminInfo) {
|
||||
$result = self::auditPrescriptionLocked($id, $action, $remark, $adminId, $adminInfo);
|
||||
if ($result === false) {
|
||||
throw new \DomainException(self::$error ?: '审核未完成');
|
||||
}
|
||||
return $result;
|
||||
});
|
||||
} catch (\Throwable $exception) {
|
||||
self::$error = $exception->getMessage();
|
||||
return false;
|
||||
}
|
||||
if ($out !== false && $action === 'approve') {
|
||||
// Notify only after the audit transaction releases its locks.
|
||||
PrescriptionLogic::syncApproveConsumerPrescriptionIfPending(
|
||||
(int) $out['prescription_id'], $adminId, $adminInfo,
|
||||
trim($remark) !== '' ? trim($remark) : '业务订单处方审核通过'
|
||||
);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function auditPrescriptionLocked(int $id, string $action, string $remark, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$order) {
|
||||
self::$error = '订单不存在';
|
||||
|
||||
@@ -2375,9 +2414,17 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!in_array($action, ['approve', 'reject'], true)) {
|
||||
self::$error = '无效的审核操作';
|
||||
return false;
|
||||
}
|
||||
if ($action === 'reject' && trim($remark) === '') {
|
||||
self::$error = '驳回时请填写审核意见';
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === 'approve' && !self::assertEsignApproved($order)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2403,16 +2450,6 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($action === 'approve') {
|
||||
$syncRemark = trim($remark) !== '' ? trim($remark) : '业务订单处方审核通过';
|
||||
PrescriptionLogic::syncApproveConsumerPrescriptionIfPending(
|
||||
(int) $order->prescription_id,
|
||||
$adminId,
|
||||
$adminInfo,
|
||||
$syncRemark
|
||||
);
|
||||
}
|
||||
|
||||
$actionName = $action === 'approve' ? 'audit_rx_approve' : 'audit_rx_reject';
|
||||
$summary = $action === 'approve' ? '处方审核通过' . ($remark ? ',意见:' . $remark : '') : '处方审核驳回,意见:' . $remark;
|
||||
self::writeLog((int) $order->id, $adminId, $adminInfo, $actionName, $summary);
|
||||
@@ -2776,6 +2813,23 @@ class PrescriptionOrderLogic
|
||||
public static function addLog(array $params, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
try {
|
||||
return Db::transaction(static function () use ($params, $adminId, $adminInfo) {
|
||||
$result = self::addLogLocked($params, $adminId, $adminInfo);
|
||||
if ($result === false) {
|
||||
throw new \DomainException(self::$error ?: '日志变更未完成');
|
||||
}
|
||||
return $result;
|
||||
});
|
||||
} catch (\Throwable $exception) {
|
||||
self::$error = $exception->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function addLogLocked(array $params, int $adminId, array $adminInfo)
|
||||
{
|
||||
self::$error = '';
|
||||
$id = (int) ($params['id'] ?? 0);
|
||||
$summary = mb_substr(trim((string) ($params['summary'] ?? '')), 0, 500);
|
||||
if ($summary === '') {
|
||||
@@ -2784,7 +2838,7 @@ class PrescriptionOrderLogic
|
||||
return false;
|
||||
}
|
||||
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->find();
|
||||
$order = PrescriptionOrder::where('id', $id)->whereNull('delete_time')->lock(true)->find();
|
||||
if (!$order) {
|
||||
self::$error = '订单不存在';
|
||||
|
||||
@@ -2814,6 +2868,9 @@ class PrescriptionOrderLogic
|
||||
if (!in_array($newRx, [0, 1, 2], true)) {
|
||||
self::$error = '处方审核状态无效';
|
||||
|
||||
return false;
|
||||
}
|
||||
if ($newRx === 1 && !self::assertEsignApproved($order)) {
|
||||
return false;
|
||||
}
|
||||
$oldRx = (int) $order->prescription_audit_status;
|
||||
@@ -4947,6 +5004,9 @@ class PrescriptionOrderLogic
|
||||
self::$error = '无权限操作';
|
||||
return false;
|
||||
}
|
||||
if (!self::assertEsignApproved($order, true)) {
|
||||
return false;
|
||||
}
|
||||
$target = self::normalizeShipMode((string) ($order->ship_mode ?? 'gancao')) === 'direct'
|
||||
? 'direct'
|
||||
: 'gancao';
|
||||
@@ -5083,6 +5143,9 @@ class PrescriptionOrderLogic
|
||||
/** @return array<string,mixed>|false */
|
||||
private static function uploadEjRemote(PrescriptionOrder $order, int $adminId, array $adminInfo, array $claim)
|
||||
{
|
||||
if (!self::assertEsignApproved($order, true)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$prescription = PrescriptionLogic::detail((int) $order->prescription_id, $adminId, $adminInfo);
|
||||
if ($prescription === null) {
|
||||
@@ -5203,6 +5266,9 @@ class PrescriptionOrderLogic
|
||||
if (!self::canAccessOrder($order, $adminId, $adminInfo)) {
|
||||
self::$error = '无权限操作';
|
||||
|
||||
return false;
|
||||
}
|
||||
if (!self::assertEsignApproved($order, true)) {
|
||||
return false;
|
||||
}
|
||||
$item = $order->toArray();
|
||||
@@ -5817,6 +5883,7 @@ class PrescriptionOrderLogic
|
||||
|
||||
return false;
|
||||
}
|
||||
PrescriptionEsignPolicy::assertMutable($rx->toArray());
|
||||
if (!PrescriptionLogic::canViewPrescription($rx, $adminId, $adminInfo)) {
|
||||
self::setError('无权限修改此处方');
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ class PrescriptionValidate extends BaseValidate
|
||||
|
||||
public function sceneAdd()
|
||||
{
|
||||
if (\app\common\service\esign\PrescriptionEsignService::enabled()) {
|
||||
$this->remove('doctor_signature', 'require');
|
||||
}
|
||||
return $this->only([
|
||||
'prescription_type', 'dosage_amount', 'dosage_unit', 'dosage_bag_count', 'need_decoction', 'bags_per_dose',
|
||||
'prescription_name', 'patient_id', 'patient_name', 'phone', 'gender', 'age',
|
||||
@@ -54,6 +57,9 @@ class PrescriptionValidate extends BaseValidate
|
||||
|
||||
public function sceneEdit()
|
||||
{
|
||||
if (\app\common\service\esign\PrescriptionEsignService::enabled()) {
|
||||
$this->remove('doctor_signature', 'require');
|
||||
}
|
||||
return $this->only([
|
||||
'id', 'prescription_type', 'dosage_amount', 'dosage_unit', 'dosage_bag_count', 'need_decoction', 'bags_per_dose',
|
||||
'prescription_name', 'patient_id', 'patient_name', 'phone', 'gender', 'age',
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\service\esign\EsignClient;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\console\input\Option;
|
||||
use think\facade\Config;
|
||||
|
||||
final class EsignSetup extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->setName('esign:setup')->setDescription('检查 e签宝配置、初始化内网 SDK 或恢复已归档签署结果')
|
||||
->addOption('initialize', null, Option::VALUE_NONE, '初始化已部署的 SDK;不创建医生、认证或处方签署')
|
||||
->addOption('recover', null, Option::VALUE_REQUIRED, '重新验签已归档的处方 ID;不会再次签署');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output): int
|
||||
{
|
||||
$config = (array) Config::get('esign', []);
|
||||
$output->writeln('environment=' . ($config['environment'] ?? 'sandbox'));
|
||||
$output->writeln('enabled=' . (PrescriptionEsignService::enabled() ? 'true' : 'false'));
|
||||
$output->writeln('credentials=' . (!empty($config['app_id']) && !empty($config['app_secret']) ? 'configured' : 'missing'));
|
||||
try {
|
||||
if ($input->getOption('recover') !== null) {
|
||||
$id = filter_var($input->getOption('recover'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
if (!$id) {
|
||||
throw new \DomainException('recover 必须为正整数处方ID');
|
||||
}
|
||||
PrescriptionEsignService::recover($id);
|
||||
$output->writeln('原件验签及状态恢复完成;未发送新的签署请求');
|
||||
} elseif ($input->getOption('initialize')) {
|
||||
// Deployment may initialize before enabling the new clinical workflow.
|
||||
$client = new EsignClient(array_merge($config, ['enabled' => true]));
|
||||
$client->assertConfigured();
|
||||
$client->initialize();
|
||||
$output->writeln('SDK 初始化成功;尚未执行医生核身或处方签署');
|
||||
} else {
|
||||
$output->writeln('配置检查完成;部署 SDK 后使用 --initialize,完成数据库迁移后再启用签署');
|
||||
}
|
||||
return 0;
|
||||
} catch (\Throwable $e) {
|
||||
$output->writeln('<error>' . ($e instanceof \DomainException ? $e->getMessage() : 'SDK 操作失败,请检查内网服务、应用环境和 e签宝 IP 白名单') . '</error>');
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use Closure;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/** Safe public errors deliberately omit provider messages, bodies and transport diagnostics. */
|
||||
class EsignProviderException extends RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode)
|
||||
{
|
||||
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
|
||||
}
|
||||
}
|
||||
|
||||
/** Do not retry a signature after this exception without reconciling its outcome. */
|
||||
class EsignOutcomeUnknownException extends EsignProviderException
|
||||
{
|
||||
public function __construct(string $code, public ?string $signServiceId = null)
|
||||
{
|
||||
parent::__construct('signPdf', $code);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK 3.x PaaS HTTP adapter. Identity uses the independent v2 identity service.
|
||||
*
|
||||
* Transport receives {method,url,headers,body,timeout} and returns
|
||||
* {status:int,body:string,errno?:int}. It must not log request bodies or credentials.
|
||||
* No method retries a request. initialize() is an explicit deployment operation:
|
||||
* an initialized JVM must be restarted before changing app/environment.
|
||||
*/
|
||||
final class EsignClient
|
||||
{
|
||||
private const JSON_TYPE = 'application/json; charset=UTF-8';
|
||||
private const MAX_PDF_BYTES = 20971520;
|
||||
private const ENVIRONMENTS = [
|
||||
'sandbox' => [
|
||||
'identity' => 'https://smlopenapi.esign.cn',
|
||||
'init' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
|
||||
'auth_hosts' => ['smlt.esign.cn', 'smlfront.esign.cn'],
|
||||
],
|
||||
'production' => [
|
||||
'identity' => 'https://openapi.esign.cn',
|
||||
'init' => 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2',
|
||||
'auth_hosts' => ['t.esign.cn', 'idverify.esign.cn'],
|
||||
],
|
||||
];
|
||||
|
||||
private array $configuration;
|
||||
private Closure $transport;
|
||||
private Closure $clock;
|
||||
|
||||
public function __construct(?array $configuration = null, ?callable $transport = null, ?callable $clock = null)
|
||||
{
|
||||
$this->configuration = $configuration ?? (array) \think\facade\Config::get('esign', []);
|
||||
$this->transport = $transport !== null ? Closure::fromCallable($transport) : Closure::fromCallable([self::class, 'curlTransport']);
|
||||
$this->clock = $clock !== null ? Closure::fromCallable($clock) : static fn (): int => (int) floor(microtime(true) * 1000);
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return filter_var($this->configuration['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
public function environment(): string
|
||||
{
|
||||
return strtolower(trim((string) ($this->configuration['environment'] ?? 'sandbox')));
|
||||
}
|
||||
|
||||
public function assertConfigured(): void
|
||||
{
|
||||
if (!$this->isEnabled()) {
|
||||
throw new EsignProviderException('configuration', 'DISABLED');
|
||||
}
|
||||
if (!isset(self::ENVIRONMENTS[$this->environment()])) {
|
||||
throw new EsignProviderException('configuration', 'ENVIRONMENT_INVALID');
|
||||
}
|
||||
foreach (['app_id', 'app_secret'] as $key) {
|
||||
if (!is_string($this->configuration[$key] ?? null)
|
||||
|| trim($this->configuration[$key]) === ''
|
||||
|| preg_match('/[\x00-\x1f\x7f]/', $this->configuration[$key])) {
|
||||
throw new EsignProviderException('configuration', 'CREDENTIALS_MISSING');
|
||||
}
|
||||
}
|
||||
$timeout = $this->configuration['timeout'] ?? 60;
|
||||
if (filter_var($timeout, FILTER_VALIDATE_INT) === false || (int) $timeout < 1 || (int) $timeout > 300) {
|
||||
throw new EsignProviderException('configuration', 'TIMEOUT_INVALID');
|
||||
}
|
||||
$url = (string) ($this->configuration['sdk_url'] ?? '');
|
||||
$parts = parse_url($url);
|
||||
if (!is_array($parts) || !isset($parts['host'])
|
||||
|| !in_array($parts['scheme'] ?? '', ['http', 'https'], true)
|
||||
|| isset($parts['user']) || isset($parts['pass'])
|
||||
|| isset($parts['query']) || isset($parts['fragment'])
|
||||
|| rtrim((string) ($parts['path'] ?? ''), '/') !== '/paas-sdk-service'
|
||||
|| preg_match('/[\x00-\x20\x7f]/', $url)) {
|
||||
throw new EsignProviderException('configuration', 'SDK_URL_INVALID');
|
||||
}
|
||||
// The SDK accepts credentials and patient documents: plain HTTP is local/private only.
|
||||
if ($parts['scheme'] === 'http' && !self::isPrivateHost((string) $parts['host'])) {
|
||||
throw new EsignProviderException('configuration', 'SDK_HTTP_REQUIRES_PRIVATE_HOST');
|
||||
}
|
||||
}
|
||||
|
||||
public function initialize(): void
|
||||
{
|
||||
$this->assertConfigured();
|
||||
$this->sdkJson('initialize', '/timevale/init', [
|
||||
'projectConfig' => [
|
||||
'projectId' => $this->configuration['app_id'],
|
||||
'projectSecret' => $this->configuration['app_secret'],
|
||||
'itsmApiUrl' => self::ENVIRONMENTS[$this->environment()]['init'],
|
||||
],
|
||||
'httpConfig' => ['httpType' => 'HTTPS', 'retry' => 0],
|
||||
'signConfig' => ['algorithm' => 'HMACSHA256'],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array{flow_id:string,auth_url:string} */
|
||||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||||
{
|
||||
$this->requireText($name, 'startIdentity');
|
||||
$this->requireText($contextId, 'startIdentity');
|
||||
$person = ['name' => $name, 'certType' => 'INDIVIDUAL_CH_IDCARD'];
|
||||
if ($accountId !== null) {
|
||||
$this->requireText($accountId, 'startIdentity');
|
||||
$person['sdkAccountId'] = $accountId;
|
||||
}
|
||||
$response = $this->identityJson('startIdentity', 'POST', '/v2/identity/auth/web/indivAuthUrl', [
|
||||
'indivInfo' => $person,
|
||||
'configParams' => ['indivUneditableInfo' => ['name', 'certType']],
|
||||
'contextInfo' => ['contextId' => $contextId, 'showResultPage' => true],
|
||||
]);
|
||||
$data = $response['data'] ?? null;
|
||||
if (!is_array($data) || !is_string($data['flowId'] ?? null) || trim($data['flowId']) === '') {
|
||||
throw new EsignProviderException('startIdentity', 'RESPONSE_INVALID');
|
||||
}
|
||||
$url = !empty($data['shortLink']) ? $data['shortLink'] : ($data['url'] ?? '');
|
||||
if (!is_string($url) || !$this->isTrustedAuthUrl($url)) {
|
||||
throw new EsignProviderException('startIdentity', 'AUTH_URL_INVALID');
|
||||
}
|
||||
return ['flow_id' => $data['flowId'], 'auth_url' => $url];
|
||||
}
|
||||
|
||||
public function identityDetail(string $flowId): array
|
||||
{
|
||||
$this->requireText($flowId, 'identityDetail');
|
||||
$response = $this->identityJson('identityDetail', 'GET', '/v2/identity/auth/api/common/' . rawurlencode($flowId) . '/detail');
|
||||
if (!is_array($response['data'] ?? null) || $response['data'] === []) {
|
||||
throw new EsignProviderException('identityDetail', 'RESPONSE_INVALID');
|
||||
}
|
||||
return $response['data'];
|
||||
}
|
||||
|
||||
public function checkWillingness(string $flowId): void
|
||||
{
|
||||
$this->requireText($flowId, 'checkWillingness');
|
||||
$data = $this->sdkJson('checkWillingness', '/timevale/auth/queryWillingnessValidity', ['willingnessId' => $flowId]);
|
||||
if (($data['status'] ?? null) !== 1
|
||||
|| !is_int($data['remainingTimes'] ?? null) || $data['remainingTimes'] < 1
|
||||
|| !is_int($data['expireAt'] ?? null) || $data['expireAt'] <= ($this->clock)()) {
|
||||
throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
public function createPerson(string $name, string $idNo, string $flowId): string
|
||||
{
|
||||
foreach ([$name, $idNo, $flowId] as $value) {
|
||||
$this->requireText($value, 'createPerson');
|
||||
}
|
||||
$data = $this->sdkJson('createPerson', '/timevale/account/addPerson', [
|
||||
'name' => $name, 'idNo' => $idNo, 'idNoType' => 'MAINLAND', 'identityAuthId' => $flowId,
|
||||
]);
|
||||
return $this->requiredResponseText($data, 'accountId', 'createPerson');
|
||||
}
|
||||
|
||||
public function createSeal(string $accountId): string
|
||||
{
|
||||
$this->requireText($accountId, 'createSeal');
|
||||
$data = $this->sdkJson('createSeal', '/timevale/seal/createPersonSeal', [
|
||||
'accountId' => $accountId, 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE',
|
||||
]);
|
||||
$seal = $this->requiredResponseText($data, 'sealData', 'createSeal');
|
||||
if (base64_decode($seal, true) === false) {
|
||||
throw new EsignProviderException('createSeal', 'RESPONSE_INVALID');
|
||||
}
|
||||
return $seal;
|
||||
}
|
||||
|
||||
/** @return array{sign_service_id:string,pdf:string} */
|
||||
public function signPdf(string $accountId, string $flowId, string $sealData, string $pdfBytes, string $fileName): array
|
||||
{
|
||||
foreach ([$accountId, $flowId, $sealData, $fileName] as $value) {
|
||||
$this->requireText($value, 'signPdf');
|
||||
}
|
||||
$this->requirePdf($pdfBytes, 'signPdf');
|
||||
if (base64_decode($sealData, true) === false) {
|
||||
throw new EsignProviderException('signPdf', 'SEAL_INVALID');
|
||||
}
|
||||
$data = $this->sdkMultipart('signPdf', '/timevale/user/sign/personSign', 'personSignParam', [
|
||||
'accountId' => $accountId, 'willingnessId' => $flowId, 'sealData' => $sealData,
|
||||
'signType' => 'Single', 'fileBean' => ['fileName' => $fileName],
|
||||
'posBeans' => [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]],
|
||||
], $pdfBytes, true);
|
||||
$serviceId = is_string($data['signServiceId'] ?? null) && trim($data['signServiceId']) !== '' ? $data['signServiceId'] : null;
|
||||
$pdf = is_string($data['stream'] ?? null) ? base64_decode($data['stream'], true) : false;
|
||||
if ($serviceId === null || !is_string($pdf) || !str_starts_with($pdf, '%PDF-') || strlen($pdf) > self::MAX_PDF_BYTES) {
|
||||
throw new EsignOutcomeUnknownException('SIGNED_FILE_UNAVAILABLE', $serviceId);
|
||||
}
|
||||
return ['sign_service_id' => $serviceId, 'pdf' => $pdf];
|
||||
}
|
||||
|
||||
public function verifyPdf(string $pdfBytes): array
|
||||
{
|
||||
$this->requirePdf($pdfBytes, 'verifyPdf');
|
||||
$data = $this->sdkMultipart('verifyPdf', '/timevale/verify/pdf', 'verifyPdfParam', ['fileName' => 'prescription.pdf'], $pdfBytes);
|
||||
$signatures = $data['signatures'] ?? null;
|
||||
if (!is_array($signatures) || $signatures === [] || array_keys($signatures) !== range(0, count($signatures) - 1)) {
|
||||
throw new EsignProviderException('verifyPdf', 'NO_SIGNATURES');
|
||||
}
|
||||
foreach ($signatures as $signature) {
|
||||
if (!is_array($signature) || ($signature['signature']['validate'] ?? null) !== true) {
|
||||
throw new EsignProviderException('verifyPdf', 'SIGNATURE_INVALID');
|
||||
}
|
||||
}
|
||||
return ['signatures' => $signatures];
|
||||
}
|
||||
|
||||
private function sdkJson(string $operation, string $path, array $data): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
return $this->request($operation, 'POST', rtrim($this->configuration['sdk_url'], '/') . $path,
|
||||
['Content-Type' => self::JSON_TYPE, 'Accept' => 'application/json'], $this->json($data, $operation), 'errCode');
|
||||
}
|
||||
|
||||
private function identityJson(string $operation, string $method, string $path, ?array $data = null): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
$body = $data !== null ? $this->json($data, $operation) : '';
|
||||
$md5 = $body === '' ? '' : base64_encode(md5($body, true));
|
||||
// Official HMACSHA256 canonical form: method, accept, MD5, type, empty date, resource.
|
||||
$canonical = $method . "\n*/*\n" . $md5 . "\n" . self::JSON_TYPE . "\n\n" . $path;
|
||||
$headers = [
|
||||
'Accept' => '*/*', 'Content-Type' => self::JSON_TYPE,
|
||||
'X-Tsign-Open-App-Id' => $this->configuration['app_id'],
|
||||
'X-Tsign-Open-Auth-Mode' => 'Signature',
|
||||
'X-Tsign-Open-Ca-Timestamp' => (string) ($this->clock)(),
|
||||
'X-Tsign-Open-Ca-Signature' => base64_encode(hash_hmac('sha256', $canonical, $this->configuration['app_secret'], true)),
|
||||
];
|
||||
if ($md5 !== '') {
|
||||
$headers['Content-MD5'] = $md5;
|
||||
}
|
||||
return $this->request($operation, $method, self::ENVIRONMENTS[$this->environment()]['identity'] . $path, $headers, $body, 'code');
|
||||
}
|
||||
|
||||
private function sdkMultipart(string $operation, string $path, string $parameter, array $data, string $pdf, bool $signing = false): array
|
||||
{
|
||||
$this->assertConfigured();
|
||||
$boundary = 'esign-' . bin2hex(random_bytes(24));
|
||||
// JSON part needs its own application/json media type; a PHP POSTFIELDS string is insufficient.
|
||||
$body = '--' . $boundary . "\r\nContent-Disposition: form-data; name=\"" . $parameter . "\"\r\nContent-Type: " . self::JSON_TYPE . "\r\n\r\n"
|
||||
. $this->json($data, $operation)
|
||||
. "\r\n--" . $boundary . "\r\nContent-Disposition: form-data; name=\"streamFile\"; filename=\"prescription.pdf\"\r\nContent-Type: application/octet-stream\r\n\r\n"
|
||||
. $pdf . "\r\n--" . $boundary . "--\r\n";
|
||||
return $this->request($operation, 'POST', rtrim($this->configuration['sdk_url'], '/') . $path,
|
||||
['Content-Type' => 'multipart/form-data; boundary=' . $boundary, 'Accept' => 'application/json', 'Expect' => ''], $body, 'errCode', $signing);
|
||||
}
|
||||
|
||||
private function request(string $operation, string $method, string $url, array $headers, string $body, string $codeKey, bool $signing = false): array
|
||||
{
|
||||
try {
|
||||
$response = ($this->transport)([
|
||||
'method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body,
|
||||
'timeout' => (int) ($this->configuration['timeout'] ?? 60),
|
||||
]);
|
||||
} catch (Throwable $exception) {
|
||||
// Never attach the original exception: its URL/body may contain identity or secret data.
|
||||
$this->fail($operation, 'TRANSPORT_ERROR', $signing);
|
||||
}
|
||||
if (!is_array($response) || (int) ($response['errno'] ?? 0) !== 0) {
|
||||
$this->fail($operation, is_array($response) && (int) ($response['errno'] ?? 0) === 28 ? 'TIMEOUT' : 'TRANSPORT_ERROR', $signing);
|
||||
}
|
||||
$status = (int) ($response['status'] ?? 0);
|
||||
if ($status < 200 || $status > 299) {
|
||||
$this->fail($operation, 'HTTP_' . $status, $signing);
|
||||
}
|
||||
$raw = $response['body'] ?? null;
|
||||
if (!is_string($raw) || trim($raw) === '') {
|
||||
$this->fail($operation, 'EMPTY_RESPONSE', $signing);
|
||||
}
|
||||
try {
|
||||
$data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
|
||||
} catch (Throwable $exception) {
|
||||
$this->fail($operation, 'INVALID_JSON', $signing);
|
||||
}
|
||||
if (!is_array($data) || !array_key_exists($codeKey, $data) || !is_int($data[$codeKey])) {
|
||||
$this->fail($operation, 'RESPONSE_INVALID', $signing);
|
||||
}
|
||||
if ($data[$codeKey] !== 0) {
|
||||
throw new EsignProviderException($operation, 'PROVIDER_' . $data[$codeKey]);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function fail(string $operation, string $code, bool $signing): void
|
||||
{
|
||||
if ($signing) {
|
||||
throw new EsignOutcomeUnknownException($code);
|
||||
}
|
||||
throw new EsignProviderException($operation, $code);
|
||||
}
|
||||
|
||||
private function json(array $data, string $operation): string
|
||||
{
|
||||
try {
|
||||
return json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
} catch (Throwable $exception) {
|
||||
throw new EsignProviderException($operation, 'INPUT_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requireText(string $text, string $operation): void
|
||||
{
|
||||
if (trim($text) === '' || strlen($text) > 1048576 || preg_match('/[\x00-\x1f\x7f]/', $text)) {
|
||||
throw new EsignProviderException($operation, 'INPUT_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requirePdf(string $bytes, string $operation): void
|
||||
{
|
||||
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > self::MAX_PDF_BYTES) {
|
||||
throw new EsignProviderException($operation, 'PDF_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
private function requiredResponseText(array $data, string $key, string $operation): string
|
||||
{
|
||||
if (!is_string($data[$key] ?? null) || trim($data[$key]) === '') {
|
||||
throw new EsignProviderException($operation, 'RESPONSE_INVALID');
|
||||
}
|
||||
return $data[$key];
|
||||
}
|
||||
|
||||
private function isTrustedAuthUrl(string $url): bool
|
||||
{
|
||||
$parts = parse_url($url);
|
||||
return is_array($parts) && ($parts['scheme'] ?? '') === 'https'
|
||||
&& !isset($parts['user']) && !isset($parts['pass'])
|
||||
&& !preg_match('/[\x00-\x20\x7f\\\\]/', $url)
|
||||
&& (!isset($parts['port']) || $parts['port'] === 443
|
||||
|| (($parts['host'] ?? '') === 'smlfront.esign.cn' && $parts['port'] === 8890))
|
||||
&& in_array(strtolower((string) ($parts['host'] ?? '')), self::ENVIRONMENTS[$this->environment()]['auth_hosts'], true);
|
||||
}
|
||||
|
||||
private static function isPrivateHost(string $host): bool
|
||||
{
|
||||
$host = strtolower(trim($host, '[]'));
|
||||
if (in_array($host, ['localhost', '::1'], true)) {
|
||||
return true;
|
||||
}
|
||||
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
|
||||
$octets = array_map('intval', explode('.', $host));
|
||||
return $octets[0] === 127 || $octets[0] === 10
|
||||
|| ($octets[0] === 172 && $octets[1] >= 16 && $octets[1] <= 31)
|
||||
|| ($octets[0] === 192 && $octets[1] === 168);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function curlTransport(array $request): array
|
||||
{
|
||||
if (!function_exists('curl_init')) {
|
||||
throw new RuntimeException('CURL_UNAVAILABLE');
|
||||
}
|
||||
$handle = curl_init($request['url']);
|
||||
$responseBody = '';
|
||||
$headers = [];
|
||||
foreach ($request['headers'] as $name => $value) {
|
||||
$headers[] = $name . ': ' . $value;
|
||||
}
|
||||
curl_setopt_array($handle, [
|
||||
CURLOPT_CUSTOMREQUEST => $request['method'], CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_FOLLOWLOCATION => false, CURLOPT_MAXREDIRS => 0,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
|
||||
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
|
||||
CURLOPT_CONNECTTIMEOUT => min(10, $request['timeout']), CURLOPT_TIMEOUT => $request['timeout'],
|
||||
CURLOPT_NOSIGNAL => true,
|
||||
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$responseBody): int {
|
||||
if (strlen($responseBody) + strlen($chunk) > 67108864) {
|
||||
return 0;
|
||||
}
|
||||
$responseBody .= $chunk;
|
||||
return strlen($chunk);
|
||||
},
|
||||
]);
|
||||
if ($request['method'] !== 'GET') {
|
||||
curl_setopt($handle, CURLOPT_POSTFIELDS, $request['body']);
|
||||
}
|
||||
curl_exec($handle);
|
||||
$response = ['status' => (int) curl_getinfo($handle, CURLINFO_HTTP_CODE), 'body' => $responseBody, 'errno' => curl_errno($handle)];
|
||||
curl_close($handle);
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use DomainException;
|
||||
|
||||
/** Pure rules shared by API, audit and dispensing boundaries. */
|
||||
final class PrescriptionEsignPolicy
|
||||
{
|
||||
public const CONTENT_FIELDS = [
|
||||
'id', 'sn', 'creator_id', 'doctor_name', 'diagnosis_id', 'appointment_id',
|
||||
'patient_id', 'patient_name', 'gender', 'age', 'phone', 'visit_no', 'prescription_date',
|
||||
'prescription_name', 'prescription_type', 'clinical_diagnosis', 'tongue', 'tongue_image',
|
||||
'pulse', 'pulse_condition', 'herbs', 'dose_count', 'dose_unit', 'dosage_amount',
|
||||
'dosage_unit', 'dosage_bag_count', 'need_decoction', 'bags_per_dose', 'usage_days',
|
||||
'times_per_day', 'aux_usage', 'usage_instruction', 'usage_time', 'usage_way',
|
||||
'dietary_taboo', 'usage_notes', 'case_record', 'amount',
|
||||
];
|
||||
|
||||
public static function snapshot(array $row): array
|
||||
{
|
||||
$out = [];
|
||||
foreach (self::CONTENT_FIELDS as $key) {
|
||||
$value = $row[$key] ?? null;
|
||||
if (in_array($key, ['herbs', 'aux_usage', 'case_record'], true) && is_string($value)) {
|
||||
$value = trim($value) === '' ? null : json_decode($value, true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
if (in_array($key, ['dosage_amount', 'amount'], true) && $value !== null && is_numeric($value)) {
|
||||
// ORM float casts and raw DECIMAL strings represent the same clinical quantity.
|
||||
$value = self::decimal((string) $value);
|
||||
}
|
||||
$out[$key] = self::canonical($value);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function canonical(mixed $value): mixed
|
||||
{
|
||||
if (!is_array($value)) {
|
||||
// DB raw rows and ORM numeric casts must fingerprint identically.
|
||||
return $value === null ? null : (is_bool($value) ? (string) (int) $value : (string) $value);
|
||||
}
|
||||
if ($value !== [] && array_keys($value) !== range(0, count($value) - 1)) {
|
||||
ksort($value);
|
||||
}
|
||||
return array_map([self::class, 'canonical'], $value);
|
||||
}
|
||||
|
||||
private static function decimal(string $value): string
|
||||
{
|
||||
if (strpbrk($value, 'eE') !== false) {
|
||||
$value = sprintf('%.12F', (float) $value);
|
||||
}
|
||||
if (str_contains($value, '.')) {
|
||||
$value = rtrim(rtrim($value, '0'), '.');
|
||||
}
|
||||
return in_array($value, ['-0', '+0'], true) ? '0' : $value;
|
||||
}
|
||||
|
||||
public static function hash(array $row): string
|
||||
{
|
||||
return hash('sha256', json_encode(self::snapshot($row), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public static function assertMutable(array $row): void
|
||||
{
|
||||
if (!empty($row['esign_required']) && ($row['esign_status'] ?? 'pending') !== 'pending') {
|
||||
throw new DomainException('处方已进入电子签署,内容已冻结;如需修改请作废后重新开方');
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertSigner(array $row, int $actor): void
|
||||
{
|
||||
if ($actor <= 0 || (int) ($row['creator_id'] ?? 0) !== $actor) {
|
||||
throw new DomainException('仅开方医生本人可以签署此处方');
|
||||
}
|
||||
if (!empty($row['void_status']) || !empty($row['delete_time'])) {
|
||||
throw new DomainException('处方已作废或删除,不能签署');
|
||||
}
|
||||
if (!empty($row['is_system_auto'])) {
|
||||
throw new DomainException('请先补全处方,再进行电子签署');
|
||||
}
|
||||
}
|
||||
|
||||
public static function assertSigned(array $row, ?array $evidence, bool $forDispensing = false): void
|
||||
{
|
||||
if (empty($row['esign_required'])) {
|
||||
return; // Explicit migration boundary: historical handwritten prescriptions.
|
||||
}
|
||||
if (!empty($row['void_status']) || !empty($row['delete_time']) || ($row['esign_status'] ?? '') !== 'signed'
|
||||
|| !$evidence || empty($evidence['signed_hash']) || empty($evidence['sign_service_id'])
|
||||
|| empty($evidence['signed_path']) || empty($evidence['signed_at']) || empty($evidence['account_id'])
|
||||
|| (int) ($evidence['prescription_id'] ?? 0) !== (int) ($row['id'] ?? 0)
|
||||
|| (int) ($evidence['doctor_id'] ?? 0) !== (int) ($row['creator_id'] ?? 0)
|
||||
|| !hash_equals((string) ($evidence['snapshot_hash'] ?? ''), self::hash($row))) {
|
||||
throw new DomainException('处方尚未完成有效电子签署,请开方医生完成签署后重试');
|
||||
}
|
||||
if ($forDispensing && ($evidence['environment'] ?? '') !== 'production') {
|
||||
throw new DomainException('沙箱签署处方仅供测试,不能用于正式发药');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\common\model\auth\Admin;
|
||||
use app\common\model\tcm\Prescription;
|
||||
use DomainException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
|
||||
/** The database is authoritative; browser redirects never complete a signature. */
|
||||
final class PrescriptionEsignService
|
||||
{
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return filter_var(Config::get('esign.enabled', false), FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
public static function capability(): array
|
||||
{
|
||||
return ['enabled' => self::enabled(), 'environment' => (string) Config::get('esign.environment', 'sandbox')];
|
||||
}
|
||||
|
||||
public static function status(int $id, int $actor, array $adminInfo): array
|
||||
{
|
||||
$model = Prescription::find($id);
|
||||
if (!$model || !PrescriptionLogic::canViewPrescription($model, $actor, $adminInfo)) {
|
||||
throw new DomainException('处方不存在或无权查看');
|
||||
}
|
||||
return self::describe($model->toArray(), $actor);
|
||||
}
|
||||
|
||||
public static function describe(array $row, int $actor): array
|
||||
{
|
||||
$required = !empty($row['esign_required']);
|
||||
$e = $required ? Db::name('prescription_esign')->where('prescription_id', (int) $row['id'])->find() : null;
|
||||
$state = $required ? (string) ($row['esign_status'] ?? 'pending') : 'legacy';
|
||||
$voided = !empty($row['void_status']) || !empty($row['delete_time']);
|
||||
if ($voided && $required) {
|
||||
$state = 'voided';
|
||||
}
|
||||
$sameApp = !$e || ($e['app_id'] === (string) Config::get('esign.app_id', '')
|
||||
&& $e['environment'] === (string) Config::get('esign.environment', 'sandbox'));
|
||||
$canSign = self::enabled() && $required && !$voided && $sameApp
|
||||
&& (int) ($row['creator_id'] ?? 0) === $actor && empty($row['is_system_auto']);
|
||||
$message = (string) ($e['error_message'] ?? '');
|
||||
if ($state === 'signing' && time() - (int) ($e['started_at'] ?? time()) > 180) {
|
||||
// Never release an expired signing lease to another sign request.
|
||||
$state = 'uncertain';
|
||||
$message = '签署结果待核实,请联系管理员核对签署流水,不要重复签署';
|
||||
}
|
||||
if (!$sameApp) {
|
||||
$message = '此处方属于其他签署环境或应用,请恢复对应配置后处理';
|
||||
}
|
||||
if ($e && !$voided && !hash_equals((string) $e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
|
||||
$state = 'uncertain';
|
||||
$message = '处方与冻结原文不一致,请管理员核实';
|
||||
$canSign = false;
|
||||
}
|
||||
if ($state === 'preparing') {
|
||||
$canSign = $canSign && time() - (int) ($e['started_at'] ?? time()) > 90;
|
||||
$state = 'authenticating';
|
||||
$message = '正在准备认证链接,请稍后刷新';
|
||||
}
|
||||
$labels = ['legacy' => '历史手写签名', 'pending' => '待电子签署', 'authenticating' => '待医生核身',
|
||||
'signing' => '签署中', 'signed' => '已电子签署', 'failed' => '签署未完成', 'uncertain' => '签署结果待核实', 'voided' => '已作废'];
|
||||
$out = [
|
||||
'enabled' => self::enabled(), 'required' => $required, 'status' => $state,
|
||||
'status_label' => $labels[$state] ?? '待电子签署',
|
||||
'environment' => $e['environment'] ?? Config::get('esign.environment', 'sandbox'),
|
||||
'can_sign' => $canSign && in_array($state, ['pending', 'authenticating', 'failed'], true),
|
||||
'can_download' => !empty($e['signed_path']) && !empty($e['signed_at']),
|
||||
'message' => $message, 'signed_at' => (int) ($e['signed_at'] ?? 0),
|
||||
];
|
||||
if ($canSign && $state === 'authenticating' && !empty($e['auth_url'])) {
|
||||
$out['auth_url'] = $e['auth_url'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public static function assertSignedById(int $id, bool $forDispensing = false): void
|
||||
{
|
||||
// Audit/dispatch callers retain this lock through their state write.
|
||||
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
|
||||
if (!$row) {
|
||||
throw new DomainException('处方不存在');
|
||||
}
|
||||
if (empty($row['esign_required'])) {
|
||||
return;
|
||||
}
|
||||
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
PrescriptionEsignPolicy::assertSigned($row, $e ?: null, $forDispensing);
|
||||
self::readPdf((string) $e['signed_path'], (string) $e['signed_hash']);
|
||||
}
|
||||
|
||||
public static function start(int $id, int $actor, array $adminInfo): array
|
||||
{
|
||||
$client = new EsignClient();
|
||||
$client->assertConfigured();
|
||||
$token = bin2hex(random_bytes(16));
|
||||
$work = Db::transaction(static function () use ($id, $actor, $token): ?array {
|
||||
$row = self::lockSigner($id, $actor);
|
||||
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
if ($e) {
|
||||
if ((int) $e['doctor_id'] !== $actor) {
|
||||
throw new DomainException('处方签署人与冻结记录不一致');
|
||||
}
|
||||
self::assertEnvironment($e);
|
||||
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
|
||||
throw new DomainException('处方内容与签署原文不一致,请作废后重新开方');
|
||||
}
|
||||
if (in_array($row['esign_status'], ['signed', 'signing', 'uncertain'], true)) {
|
||||
return null;
|
||||
}
|
||||
if ($row['esign_status'] === 'authenticating' && $e['flow_id'] !== '') {
|
||||
return null;
|
||||
}
|
||||
if ($row['esign_status'] === 'preparing' && time() - (int) $e['started_at'] < 90) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
$name = trim((string) Admin::where('id', $actor)->value('name'));
|
||||
if ($name === '' || $name !== trim((string) $row['doctor_name'])) {
|
||||
throw new DomainException('医师姓名与当前账号不一致,请修正处方后签署');
|
||||
}
|
||||
$herbs = is_string($row['herbs']) ? json_decode($row['herbs'], true) : $row['herbs'];
|
||||
if (empty($herbs) || trim((string) $row['clinical_diagnosis']) === '') {
|
||||
throw new DomainException('请先补全处方药品和临床诊断');
|
||||
}
|
||||
$snapshotHash = PrescriptionEsignPolicy::hash($row);
|
||||
$pdf = PrescriptionPdf::render($row, (string) Config::get('esign.environment', 'sandbox'));
|
||||
$path = $id . '-' . $snapshotHash . '/source.pdf';
|
||||
self::writePdf($path, $pdf);
|
||||
$e = [
|
||||
'prescription_id' => $id, 'doctor_id' => $actor,
|
||||
'environment' => Config::get('esign.environment', 'sandbox'),
|
||||
'app_id' => (string) Config::get('esign.app_id', ''),
|
||||
'snapshot_hash' => $snapshotHash, 'source_hash' => hash('sha256', $pdf), 'source_path' => $path,
|
||||
'create_time' => time(), 'update_time' => time(),
|
||||
];
|
||||
Db::name('prescription_esign')->insert($e);
|
||||
}
|
||||
Db::name('prescription_esign')->where('prescription_id', $id)->update([
|
||||
'operation_token' => $token, 'started_at' => time(), 'error_message' => '', 'update_time' => time(),
|
||||
'flow_id' => '', 'auth_url' => '',
|
||||
]);
|
||||
Db::name('tcm_prescription')->where('id', $id)->update(['esign_status' => 'preparing']);
|
||||
return $row;
|
||||
});
|
||||
if ($work === null) {
|
||||
return self::status($id, $actor, $adminInfo);
|
||||
}
|
||||
try {
|
||||
$account = self::account($actor);
|
||||
if ($account && $account['doctor_name'] !== $work['doctor_name']) {
|
||||
throw new DomainException('医师姓名已变更,请先由管理员核实签署账号');
|
||||
}
|
||||
$auth = $client->startIdentity($work['doctor_name'], 'prescription-' . $id, $account['account_id'] ?? null);
|
||||
self::finishOperation($id, $token, 'authenticating', [
|
||||
'flow_id' => $auth['flow_id'], 'auth_url' => $auth['auth_url'],
|
||||
// Records whether this particular authentication was bound to an existing SDK account.
|
||||
'account_id' => $account['account_id'] ?? '',
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
self::finishOperation($id, $token, 'failed', ['error_message' => self::safeError($e)]);
|
||||
}
|
||||
return self::status($id, $actor, $adminInfo);
|
||||
}
|
||||
|
||||
public static function complete(int $id, int $actor, array $adminInfo): array
|
||||
{
|
||||
$client = new EsignClient();
|
||||
$client->assertConfigured();
|
||||
$token = bin2hex(random_bytes(16));
|
||||
$work = Db::transaction(static function () use ($id, $actor, $token): ?array {
|
||||
$row = self::lockSigner($id, $actor);
|
||||
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
if (!$e) {
|
||||
throw new DomainException('请先发起电子签署');
|
||||
}
|
||||
if ((int) $e['doctor_id'] !== $actor) {
|
||||
throw new DomainException('处方签署人与冻结记录不一致');
|
||||
}
|
||||
self::assertEnvironment($e);
|
||||
if (in_array($row['esign_status'], ['signed', 'signing', 'uncertain'], true)) {
|
||||
return null;
|
||||
}
|
||||
if (!in_array($row['esign_status'], ['authenticating', 'failed'], true) || $e['flow_id'] === '') {
|
||||
throw new DomainException('请先完成医生核身认证');
|
||||
}
|
||||
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
|
||||
throw new DomainException('处方内容已变化,请作废后重新开方');
|
||||
}
|
||||
Db::name('prescription_esign')->where('prescription_id', $id)->update([
|
||||
'operation_token' => $token, 'started_at' => time(), 'error_message' => '', 'update_time' => time(),
|
||||
]);
|
||||
Db::name('tcm_prescription')->where('id', $id)->update(['esign_status' => 'signing']);
|
||||
return ['row' => $row, 'evidence' => $e];
|
||||
});
|
||||
if ($work === null) {
|
||||
return self::status($id, $actor, $adminInfo);
|
||||
}
|
||||
$attempted = false;
|
||||
$signedReceived = false;
|
||||
$accountId = '';
|
||||
try {
|
||||
$row = $work['row'];
|
||||
$e = $work['evidence'];
|
||||
$identity = $client->identityDetail($e['flow_id']);
|
||||
if (($identity['flowId'] ?? '') !== $e['flow_id']
|
||||
|| (isset($identity['appId']) && (string) $identity['appId'] !== (string) $e['app_id'])) {
|
||||
throw new DomainException('核身流程与本次处方签署不一致,请重新认证');
|
||||
}
|
||||
if (($identity['status'] ?? '') !== 'SUCCESS') {
|
||||
$failed = ($identity['status'] ?? '') === 'FAIL';
|
||||
self::finishOperation($id, $token, $failed ? 'failed' : 'authenticating', [
|
||||
'error_message' => $failed ? '核身未通过,请重新发起认证' : '尚未完成核身,请在认证页面完成后重试',
|
||||
...($failed ? ['flow_id' => '', 'auth_url' => ''] : []),
|
||||
]);
|
||||
return self::status($id, $actor, $adminInfo);
|
||||
}
|
||||
$person = $identity['indivInfo'] ?? [];
|
||||
if (($identity['objectType'] ?? '') !== 'INDIVIDUAL' || ($person['name'] ?? '') !== $row['doctor_name']
|
||||
|| ($person['certType'] ?? '') !== 'INDIVIDUAL_CH_IDCARD' || empty($person['certNo'])
|
||||
|| !preg_match('/^(?:\d{15}|\d{17}[\dXx])$/', (string) $person['certNo'])) {
|
||||
throw new DomainException('核身信息与开方医生不一致或证件类型不支持');
|
||||
}
|
||||
$client->checkWillingness($e['flow_id']);
|
||||
$account = self::account($actor);
|
||||
if ($account) {
|
||||
if ($account['doctor_name'] !== $row['doctor_name']
|
||||
|| empty($e['account_id']) || $account['account_id'] !== $e['account_id']) {
|
||||
// A concurrent first-time binding must not turn an unbound flow into a bound one.
|
||||
throw new DomainException('签署账号绑定已变化,请重新发起核身认证');
|
||||
}
|
||||
$accountId = $account['account_id'];
|
||||
} else {
|
||||
if (!empty($e['account_id'])) {
|
||||
throw new DomainException('签署账号绑定已变化,请联系管理员核实');
|
||||
}
|
||||
$accountId = $client->createPerson($person['name'], $person['certNo'], $e['flow_id']);
|
||||
try {
|
||||
Db::name('doctor_esign_account')->insert([
|
||||
'doctor_id' => $actor, 'environment' => $e['environment'], 'app_id' => $e['app_id'],
|
||||
'account_id' => $accountId, 'doctor_name' => $row['doctor_name'], 'create_time' => time(),
|
||||
]);
|
||||
} catch (\Throwable $insertError) {
|
||||
$existing = self::account($actor);
|
||||
if (!$existing || $existing['account_id'] !== $accountId) {
|
||||
throw new DomainException('签署账号绑定冲突,请联系管理员核实');
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($person, $identity); // Full identity document numbers are never persisted or logged.
|
||||
self::finishOperation($id, $token, 'signing', ['account_id' => $accountId]);
|
||||
$seal = $client->createSeal($accountId);
|
||||
$pdf = self::readPdf($e['source_path'], $e['source_hash']);
|
||||
// Recheck after authentication: a prescription may have been voided meanwhile.
|
||||
Db::transaction(static function () use ($id, $actor, $token, $accountId): void {
|
||||
$currentRow = self::lockSigner($id, $actor);
|
||||
$current = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
$boundAccount = self::account($actor);
|
||||
if (!$current || !hash_equals($current['operation_token'], $token)
|
||||
|| $currentRow['esign_status'] !== 'signing'
|
||||
|| !hash_equals($current['snapshot_hash'], PrescriptionEsignPolicy::hash($currentRow))
|
||||
|| !$boundAccount || $boundAccount['account_id'] !== $accountId) {
|
||||
throw new DomainException('签署状态已变化,请刷新');
|
||||
}
|
||||
});
|
||||
$attempted = true;
|
||||
$signed = $client->signPdf($accountId, $e['flow_id'], $seal, $pdf, 'prescription-' . $id . '.pdf');
|
||||
$signedReceived = true;
|
||||
// Save the supplier reference first: disk/archive failure must not lose a completed sign.
|
||||
self::finishOperation($id, $token, 'signing', [
|
||||
'sign_service_id' => $signed['sign_service_id'], 'account_id' => $accountId,
|
||||
]);
|
||||
$path = $id . '-' . $e['snapshot_hash'] . '/signed.pdf';
|
||||
self::writePdf($path, $signed['pdf']);
|
||||
// Persist the result before verification, so a verification outage cannot lose evidence.
|
||||
$proof = ['signed_path' => $path, 'signed_hash' => hash('sha256', $signed['pdf']),
|
||||
'sign_service_id' => $signed['sign_service_id'], 'account_id' => $accountId];
|
||||
self::finishOperation($id, $token, 'signing', $proof);
|
||||
$client->verifyPdf($signed['pdf']);
|
||||
self::finishOperation($id, $token, 'signed', $proof + ['signed_at' => time(), 'error_message' => ''], $seal);
|
||||
} catch (\Throwable $error) {
|
||||
// A definite provider rejection before a result can retry with a fresh auth flow.
|
||||
// Once bytes were signed, verification/storage failure must never re-enable signing.
|
||||
$unknown = $attempted && ($signedReceived || !($error instanceof EsignProviderException)
|
||||
|| $error instanceof EsignOutcomeUnknownException);
|
||||
$failure = ['error_message' => $unknown
|
||||
? '签署结果待核实,请管理员核对签署流水;不要重复签署' : self::safeError($error)];
|
||||
if ($error instanceof EsignOutcomeUnknownException && $error->signServiceId !== null) {
|
||||
$failure['sign_service_id'] = $error->signServiceId;
|
||||
$failure['account_id'] = $accountId;
|
||||
}
|
||||
if (!$unknown && ($attempted || $error instanceof DomainException
|
||||
|| ($error instanceof EsignProviderException && $error->providerCode === 'WILLINGNESS_INVALID'))) {
|
||||
$failure += ['flow_id' => '', 'auth_url' => ''];
|
||||
}
|
||||
self::finishOperation($id, $token, $unknown ? 'uncertain' : 'failed', $failure);
|
||||
}
|
||||
return self::status($id, $actor, $adminInfo);
|
||||
}
|
||||
|
||||
public static function download(int $id, int $actor, array $adminInfo): array
|
||||
{
|
||||
$status = self::status($id, $actor, $adminInfo);
|
||||
if (!$status['can_download']) {
|
||||
throw new DomainException('已签原件尚不可下载');
|
||||
}
|
||||
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
$pdf = self::readPdf($e['signed_path'], $e['signed_hash']);
|
||||
return ['filename' => 'prescription-' . $id . '-signed.pdf', 'sha256' => $e['signed_hash'], 'content_base64' => base64_encode($pdf)];
|
||||
}
|
||||
|
||||
/** Reverify an already archived result; never sends a second signature request. CLI only. */
|
||||
public static function recover(int $id): void
|
||||
{
|
||||
$work = Db::transaction(static function () use ($id): array {
|
||||
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
|
||||
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
if (!$row || !$e || empty($e['signed_path']) || empty($e['sign_service_id']) || empty($e['account_id'])) {
|
||||
throw new DomainException('本地没有可恢复的签署原件,请依据供应商签署流水人工核实;禁止自动重签');
|
||||
}
|
||||
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
|
||||
throw new DomainException('处方与冻结原文不一致,不能恢复签署状态');
|
||||
}
|
||||
return ['row' => $row, 'evidence' => $e];
|
||||
});
|
||||
$e = $work['evidence'];
|
||||
self::assertEnvironment($e);
|
||||
$client = new EsignClient();
|
||||
$client->assertConfigured();
|
||||
$pdf = self::readPdf($e['signed_path'], $e['signed_hash']);
|
||||
$verified = $client->verifyPdf($pdf);
|
||||
$seal = '';
|
||||
foreach ($verified['signatures'] ?? [] as $signature) {
|
||||
if (($signature['cert']['cn'] ?? '') === $work['row']['doctor_name']
|
||||
&& is_string($signature['sealData'] ?? null) && $signature['sealData'] !== ''
|
||||
&& base64_decode($signature['sealData'], true) !== false) {
|
||||
$seal = $signature['sealData'];
|
||||
}
|
||||
}
|
||||
self::finishOperation($id, $e['operation_token'], 'signed', ['signed_at' => time(), 'error_message' => ''], $seal);
|
||||
}
|
||||
|
||||
private static function lockSigner(int $id, int $actor): array
|
||||
{
|
||||
if (!self::enabled()) {
|
||||
throw new DomainException('电子签署尚未启用,请联系管理员');
|
||||
}
|
||||
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
|
||||
if (!$row || empty($row['esign_required'])) {
|
||||
throw new DomainException('此处方不属于电子签署流程');
|
||||
}
|
||||
PrescriptionEsignPolicy::assertSigner($row, $actor);
|
||||
if (trim((string) Admin::where('id', $actor)->value('name')) !== trim((string) $row['doctor_name'])) {
|
||||
throw new DomainException('医师姓名已变更,请作废原处方后重新开方');
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
private static function assertEnvironment(array $e): void
|
||||
{
|
||||
if ($e['environment'] !== Config::get('esign.environment', 'sandbox') || $e['app_id'] !== (string) Config::get('esign.app_id', '')) {
|
||||
throw new DomainException('签署环境或应用与原处方不一致');
|
||||
}
|
||||
}
|
||||
|
||||
private static function account(int $actor): ?array
|
||||
{
|
||||
return Db::name('doctor_esign_account')->where('doctor_id', $actor)
|
||||
->where('environment', Config::get('esign.environment', 'sandbox'))
|
||||
->where('app_id', (string) Config::get('esign.app_id', ''))->find() ?: null;
|
||||
}
|
||||
|
||||
private static function finishOperation(int $id, string $token, string $state, array $data, string $seal = ''): void
|
||||
{
|
||||
Db::transaction(static function () use ($id, $token, $state, $data, $seal): void {
|
||||
$row = Db::name('tcm_prescription')->where('id', $id)->lock(true)->find();
|
||||
$e = Db::name('prescription_esign')->where('prescription_id', $id)->find();
|
||||
if (!$row || !$e || !hash_equals($e['operation_token'], $token)) {
|
||||
return;
|
||||
}
|
||||
if (!hash_equals($e['snapshot_hash'], PrescriptionEsignPolicy::hash($row))) {
|
||||
$state = 'uncertain';
|
||||
$data['error_message'] = '处方与冻结原文不一致,请管理员核实';
|
||||
unset($data['signed_at']);
|
||||
}
|
||||
Db::name('prescription_esign')->where('prescription_id', $id)->update($data + ['update_time' => time()]);
|
||||
$updates = ['esign_status' => (!empty($row['void_status']) || !empty($row['delete_time'])) ? 'voided' : $state];
|
||||
if ($state === 'signed' && $seal !== '') {
|
||||
$updates['doctor_signature'] = 'data:image/png;base64,' . $seal;
|
||||
}
|
||||
Db::name('tcm_prescription')->where('id', $id)->update($updates);
|
||||
});
|
||||
}
|
||||
|
||||
private static function safeError(\Throwable $error): string
|
||||
{
|
||||
return $error instanceof DomainException || $error instanceof EsignProviderException
|
||||
? mb_substr($error->getMessage(), 0, 240) : '电子签署服务暂不可用,请稍后重试或联系管理员';
|
||||
}
|
||||
|
||||
private static function filePath(string $relative): string
|
||||
{
|
||||
if (!preg_match('#^\d+-[a-f0-9]{64}/(?:source|signed)\.pdf$#D', $relative)) {
|
||||
throw new DomainException('签署文件引用无效');
|
||||
}
|
||||
return rtrim((string) Config::get('esign.storage_path', root_path() . 'storage/esign'), '/\\') . DIRECTORY_SEPARATOR . $relative;
|
||||
}
|
||||
|
||||
private static function writePdf(string $relative, string $bytes): void
|
||||
{
|
||||
if (!str_starts_with($bytes, '%PDF-') || strlen($bytes) > 20 * 1024 * 1024) {
|
||||
throw new DomainException('签署服务返回的 PDF 无效或超出大小限制');
|
||||
}
|
||||
$path = self::filePath($relative);
|
||||
$dir = dirname($path);
|
||||
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
|
||||
throw new DomainException('签署文件存储不可用');
|
||||
}
|
||||
$tmp = $path . '.' . bin2hex(random_bytes(8)) . '.tmp';
|
||||
if (file_put_contents($tmp, $bytes, LOCK_EX) !== strlen($bytes)) {
|
||||
@unlink($tmp);
|
||||
throw new DomainException('签署文件保存失败');
|
||||
}
|
||||
@chmod($tmp, 0600);
|
||||
if (!rename($tmp, $path)) {
|
||||
@unlink($tmp);
|
||||
throw new DomainException('签署文件归档失败');
|
||||
}
|
||||
}
|
||||
|
||||
private static function readPdf(string $relative, string $hash): string
|
||||
{
|
||||
$path = self::filePath($relative);
|
||||
$bytes = is_file($path) && filesize($path) <= 20 * 1024 * 1024 ? file_get_contents($path) : false;
|
||||
if ($bytes === false || !str_starts_with($bytes, '%PDF-') || !hash_equals($hash, hash('sha256', $bytes))) {
|
||||
throw new DomainException('签署原件缺失或校验失败,请管理员恢复原件');
|
||||
}
|
||||
return $bytes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign;
|
||||
|
||||
/** Deterministic, text based A4 prescription; fixed first-page signature area. */
|
||||
final class PrescriptionPdf
|
||||
{
|
||||
public static function render(array $row, string $environment): string
|
||||
{
|
||||
$row = PrescriptionEsignPolicy::snapshot($row);
|
||||
$lines = [];
|
||||
$add = static function (string $label, mixed $value) use (&$lines): void {
|
||||
if ($value === null || $value === '' || $value === []) {
|
||||
return;
|
||||
}
|
||||
if (is_array($value)) {
|
||||
$value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$text = $label . ':' . (string) $value;
|
||||
foreach (preg_split('/\R/u', $text) as $paragraph) {
|
||||
$current = '';
|
||||
foreach (mb_str_split($paragraph) as $char) {
|
||||
if (mb_strwidth($current . $char, 'UTF-8') > 84) {
|
||||
$lines[] = $current;
|
||||
$current = ' ';
|
||||
}
|
||||
$current .= $char;
|
||||
}
|
||||
$lines[] = $current;
|
||||
}
|
||||
};
|
||||
$add('处方编号', $row['sn']);
|
||||
$add('日期', $row['prescription_date']);
|
||||
$add('患者', $row['patient_name'] . ' 性别:' . ($row['gender'] === '1' ? '男' : '女') . ' 年龄:' . $row['age']);
|
||||
$add('联系电话', $row['phone']);
|
||||
$add('门诊号', $row['visit_no']);
|
||||
$add('临床诊断', $row['clinical_diagnosis']);
|
||||
$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' => '组别',
|
||||
'group_type' => '组别', 'formula_type' => '方别', 'is_aux' => '辅方', 'price' => '价格'];
|
||||
foreach ((array) $row['herbs'] as $index => $herb) {
|
||||
$parts = [];
|
||||
foreach ((array) $herb as $key => $value) {
|
||||
if (in_array($key, ['id', 'medicine_id', 'herb_id', 'name_pinyin', 'pinyin'], true) || $value === '' || $value === null) {
|
||||
continue;
|
||||
}
|
||||
$parts[] = ($herbLabels[$key] ?? $key) . ' ' . (is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value);
|
||||
}
|
||||
$add('药品 ' . ($index + 1), implode(' / ', $parts));
|
||||
}
|
||||
foreach ([
|
||||
'dose_count' => '总剂数', 'dose_unit' => '剂数单位', 'dosage_amount' => '单次用量',
|
||||
'dosage_unit' => '用量单位', 'dosage_bag_count' => '单次袋数', 'bags_per_dose' => '每剂袋数',
|
||||
'usage_days' => '服用天数', 'times_per_day' => '每日次数', 'usage_instruction' => '服用说明',
|
||||
'usage_time' => '服药时间', 'usage_way' => '服用方式', 'dietary_taboo' => '忌口', 'usage_notes' => '医嘱',
|
||||
] as $key => $label) {
|
||||
$add($label, $row[$key]);
|
||||
}
|
||||
$add('代煎', $row['need_decoction'] === '1' ? '是' : '否');
|
||||
$add('金额(元)', $row['amount']);
|
||||
foreach ((array) $row['aux_usage'] as $key => $value) {
|
||||
$label = ['dosage_amount' => '单次用量', 'dosage_bag_count' => '单次袋数', 'need_decoction' => '代煎',
|
||||
'bags_per_dose' => '每剂袋数', 'times_per_day' => '每日次数', 'usage_days' => '服用天数',
|
||||
'prescription_name' => '方名'][$key] ?? $key;
|
||||
$add('辅方' . $label, $value);
|
||||
}
|
||||
$pages = array_chunk($lines, 33);
|
||||
$objects = [1 => '', 2 => '',
|
||||
3 => '<< /Type /Font /Subtype /Type0 /BaseFont /STSong-Light /Encoding /UniGB-UCS2-H /DescendantFonts [4 0 R] >>',
|
||||
4 => '<< /Type /Font /Subtype /CIDFontType0 /BaseFont /STSong-Light /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> /FontDescriptor 5 0 R /DW 1000 /W [1 95 500] >>',
|
||||
5 => '<< /Type /FontDescriptor /FontName /STSong-Light /Flags 6 /FontBBox [-25 -254 1000 880] /ItalicAngle 0 /Ascent 880 /Descent -254 /CapHeight 880 /StemV 80 >>',
|
||||
];
|
||||
$kids = [];
|
||||
foreach ($pages as $index => $pageLines) {
|
||||
$pageId = 6 + $index * 2;
|
||||
$streamId = $pageId + 1;
|
||||
$kids[] = $pageId . ' 0 R';
|
||||
$stream = self::text('中医处方笺', 235, 795, 20);
|
||||
if ($environment === 'sandbox') {
|
||||
$stream .= self::text('沙箱测试文件 · 不用于正式发药', 170, 770, 12);
|
||||
}
|
||||
$y = 738;
|
||||
foreach ($pageLines as $line) {
|
||||
$stream .= self::text($line, 45, $y, 11);
|
||||
$y -= 18;
|
||||
}
|
||||
$stream .= "0.7 w 45 133 m 550 133 l S\n";
|
||||
$stream .= self::text('开方医师:' . $row['doctor_name'], 45, 110, 12);
|
||||
if ($index === 0) {
|
||||
$stream .= self::text('医师电子签章', 420, 117, 11);
|
||||
}
|
||||
$stream .= self::text('处方快照 SHA-256', 45, 58, 8);
|
||||
$stream .= self::text(PrescriptionEsignPolicy::hash($row), 45, 44, 7);
|
||||
$stream .= self::text(($index + 1) . ' / ' . count($pages), 515, 30, 9);
|
||||
$objects[$pageId] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents ' . $streamId . ' 0 R >>';
|
||||
$objects[$streamId] = '<< /Length ' . strlen($stream) . ">>\nstream\n" . $stream . 'endstream';
|
||||
}
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
|
||||
$objects[2] = '<< /Type /Pages /Kids [' . implode(' ', $kids) . '] /Count ' . count($pages) . ' >>';
|
||||
ksort($objects);
|
||||
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
|
||||
$offsets = [0];
|
||||
foreach ($objects as $id => $object) {
|
||||
$offsets[$id] = strlen($pdf);
|
||||
$pdf .= "$id 0 obj\n$object\nendobj\n";
|
||||
}
|
||||
$xref = strlen($pdf);
|
||||
$pdf .= 'xref' . "\n0 " . (count($objects) + 1) . "\n0000000000 65535 f \n";
|
||||
foreach ($objects as $id => $_) {
|
||||
$pdf .= sprintf("%010d 00000 n \n", $offsets[$id]);
|
||||
}
|
||||
return $pdf . 'trailer << /Size ' . (count($objects) + 1) . " /Root 1 0 R >>\nstartxref\n$xref\n%%EOF\n";
|
||||
}
|
||||
|
||||
private static function text(string $text, int $x, int $y, int $size): string
|
||||
{
|
||||
return "BT /F1 $size Tf 1 0 0 1 $x $y Tm <" . bin2hex(mb_convert_encoding($text, 'UTF-16BE', 'UTF-8')) . "> Tj ET\n";
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ namespace app\common\service\pharmacy;
|
||||
use DomainException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
|
||||
final class PharmacySubmissionClaimService
|
||||
{
|
||||
@@ -57,6 +58,9 @@ final class PharmacySubmissionClaimService
|
||||
->where('source_revision', $revision)
|
||||
->lock(true)
|
||||
->find();
|
||||
// Lock the prescription through the claim write; void/edit use the
|
||||
// same order -> claim -> prescription lock order and honor PENDING.
|
||||
PrescriptionEsignService::assertSignedById((int) $order['prescription_id'], true);
|
||||
if ($claim) {
|
||||
$decision = PharmacySubmissionClaimPolicy::existingDecision($claim, $target);
|
||||
if ($decision['action'] === 'IDEMPOTENT') {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
return [
|
||||
// 指令定义
|
||||
'commands' => [
|
||||
'esign:setup' => 'app\\command\\EsignSetup',
|
||||
'assistant-service:daily' => 'app\\command\\AssistantServiceDaily',
|
||||
'assistant-service:alert' => 'app\\command\\AssistantServiceAlert',
|
||||
'assistant-service:auto' => 'app\\command\\AssistantServiceAuto',
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Secrets remain server-side. Identity/API initialization hosts are fixed by environment in EsignClient.
|
||||
return [
|
||||
'enabled' => env('esign.enabled', false),
|
||||
'environment' => env('esign.environment', 'sandbox'),
|
||||
'app_id' => env('esign.app_id', ''),
|
||||
'app_secret' => env('esign.app_secret', ''),
|
||||
'sdk_url' => env('esign.sdk_url', 'http://127.0.0.1:8091/paas-sdk-service'),
|
||||
'timeout' => env('esign.timeout', 60),
|
||||
'storage_path' => env('esign.storage_path', dirname(__DIR__) . '/storage/esign'),
|
||||
];
|
||||
@@ -0,0 +1,42 @@
|
||||
-- e签宝 SDK 3.0。先迁移,再启用 ESIGN_ENABLED;历史处方不回填为已签。
|
||||
SET @exists_column = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='zyt_tcm_prescription' AND COLUMN_NAME='esign_required');
|
||||
SET @ddl = IF(@exists_column=0, 'ALTER TABLE zyt_tcm_prescription ADD esign_required tinyint NOT NULL DEFAULT 0, ADD esign_status varchar(24) NOT NULL DEFAULT ''legacy''', 'SELECT 1');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `zyt_prescription_esign` (
|
||||
`prescription_id` int unsigned NOT NULL,
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`snapshot_hash` char(64) NOT NULL,
|
||||
`source_hash` char(64) NOT NULL,
|
||||
`source_path` varchar(255) NOT NULL,
|
||||
`signed_path` varchar(255) NOT NULL DEFAULT '',
|
||||
`signed_hash` char(64) NOT NULL DEFAULT '',
|
||||
`flow_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`auth_url` text,
|
||||
`account_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`sign_service_id` varchar(128) NOT NULL DEFAULT '',
|
||||
`operation_token` char(32) NOT NULL DEFAULT '',
|
||||
`error_message` varchar(255) NOT NULL DEFAULT '',
|
||||
`started_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`signed_at` int unsigned NOT NULL DEFAULT 0,
|
||||
`create_time` int unsigned NOT NULL,
|
||||
`update_time` int unsigned NOT NULL,
|
||||
PRIMARY KEY (`prescription_id`),
|
||||
UNIQUE KEY `uk_flow` (`environment`,`app_id`,`flow_id`,`prescription_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='冻结处方原文及签署证据,文件保存于私有存储';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `zyt_doctor_esign_account` (
|
||||
`id` int unsigned NOT NULL AUTO_INCREMENT,
|
||||
`doctor_id` int unsigned NOT NULL,
|
||||
`environment` varchar(16) NOT NULL,
|
||||
`app_id` varchar(64) NOT NULL,
|
||||
`account_id` varchar(128) NOT NULL,
|
||||
`doctor_name` varchar(100) NOT NULL,
|
||||
`create_time` int unsigned NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_doctor_app` (`doctor_id`,`environment`,`app_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='核身后医生签署账号,不保存身份证号码';
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Isolated adapter tests: no ThinkPHP bootstrap, credentials, database or network.
|
||||
require_once dirname(__DIR__) . '/app/common/service/esign/EsignClient.php';
|
||||
|
||||
use app\common\service\esign\EsignClient;
|
||||
use app\common\service\esign\EsignOutcomeUnknownException;
|
||||
use app\common\service\esign\EsignProviderException;
|
||||
|
||||
$checks = 0;
|
||||
function esignExpect(bool $condition, string $label): void
|
||||
{
|
||||
global $checks;
|
||||
++$checks;
|
||||
if (!$condition) {
|
||||
throw new RuntimeException('FAIL: ' . $label);
|
||||
}
|
||||
}
|
||||
|
||||
function esignThrows(callable $call, string $class, string $code): EsignProviderException
|
||||
{
|
||||
try {
|
||||
$call();
|
||||
} catch (EsignProviderException $exception) {
|
||||
esignExpect(get_class($exception) === $class, 'exception type ' . $code);
|
||||
esignExpect($exception->providerCode === $code, 'exception code ' . $code);
|
||||
esignExpect($exception->getPrevious() === null, 'no sensitive previous exception');
|
||||
return $exception;
|
||||
}
|
||||
throw new RuntimeException('Expected exception: ' . $code);
|
||||
}
|
||||
|
||||
function esignConfig(array $overrides = []): array
|
||||
{
|
||||
return array_replace([
|
||||
'enabled' => true, 'environment' => 'sandbox', 'app_id' => 'test-app', 'app_secret' => 'test-secret',
|
||||
'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service', 'timeout' => 45,
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
function esignResponse(array $data, int $status = 200): array
|
||||
{
|
||||
return ['status' => $status, 'body' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
|
||||
}
|
||||
|
||||
/** @return array<string,array{headers:string,body:string}> */
|
||||
function esignMultipartParts(array $request): array
|
||||
{
|
||||
$contentType = $request['headers']['Content-Type'];
|
||||
esignExpect(str_starts_with($contentType, 'multipart/form-data; boundary='), 'multipart envelope');
|
||||
$boundary = substr($contentType, strlen('multipart/form-data; boundary='));
|
||||
$parts = [];
|
||||
foreach (explode('--' . $boundary, $request['body']) as $part) {
|
||||
if (!str_contains($part, "\r\n\r\n")) {
|
||||
continue;
|
||||
}
|
||||
[$headers, $body] = explode("\r\n\r\n", ltrim($part, "\r\n"), 2);
|
||||
preg_match('/name="([^"]+)"/', $headers, $matches);
|
||||
$parts[$matches[1]] = ['headers' => $headers, 'body' => substr($body, 0, -2)];
|
||||
}
|
||||
return $parts;
|
||||
}
|
||||
|
||||
$requests = [];
|
||||
$responses = [];
|
||||
$transport = static function (array $request) use (&$requests, &$responses): array {
|
||||
$requests[] = $request;
|
||||
if ($responses === []) {
|
||||
throw new RuntimeException('No fake response');
|
||||
}
|
||||
return array_shift($responses);
|
||||
};
|
||||
$clock = static fn (): int => 1800000000000;
|
||||
$client = new EsignClient(esignConfig(), $transport, $clock);
|
||||
esignExpect($client->isEnabled() && $client->environment() === 'sandbox', 'configured environment');
|
||||
$client->assertConfigured();
|
||||
|
||||
foreach ([
|
||||
[['enabled' => 'false'], 'DISABLED'],
|
||||
[['environment' => 'prod'], 'ENVIRONMENT_INVALID'],
|
||||
[['app_secret' => ''], 'CREDENTIALS_MISSING'],
|
||||
[['app_id' => "app\r\nInjected:yes"], 'CREDENTIALS_MISSING'],
|
||||
[['timeout' => 0], 'TIMEOUT_INVALID'],
|
||||
[['timeout' => 301], 'TIMEOUT_INVALID'],
|
||||
[['sdk_url' => 'http://example.com/paas-sdk-service'], 'SDK_HTTP_REQUIRES_PRIVATE_HOST'],
|
||||
[['sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service?x=1'], 'SDK_URL_INVALID'],
|
||||
[['sdk_url' => 'https://user:pass@example.com/paas-sdk-service'], 'SDK_URL_INVALID'],
|
||||
[['sdk_url' => 'file:///tmp/paas-sdk-service'], 'SDK_URL_INVALID'],
|
||||
] as [$config, $code]) {
|
||||
esignThrows(fn () => (new EsignClient(esignConfig($config), $transport, $clock))->assertConfigured(), EsignProviderException::class, $code);
|
||||
}
|
||||
esignExpect($requests === [], 'configuration failures issue no request');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0]);
|
||||
$client->initialize();
|
||||
$init = json_decode($requests[0]['body'], true);
|
||||
esignExpect($requests[0]['url'] === 'http://127.0.0.1:8091/paas-sdk-service/timevale/init', 'SDK init endpoint');
|
||||
esignExpect($init['projectConfig'] === [
|
||||
'projectId' => 'test-app', 'projectSecret' => 'test-secret',
|
||||
'itsmApiUrl' => 'https://smlitsm.tsign.cn:8083/tgmonitor/rest/app!getAPIInfo2',
|
||||
], 'sandbox initialization parameters');
|
||||
esignExpect($init['httpConfig'] === ['httpType' => 'HTTPS', 'retry' => 0], 'SDK internal retry disabled');
|
||||
esignExpect($init['signConfig']['algorithm'] === 'HMACSHA256', 'SDK algorithm');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'shortLink' => 'https://smlt.esign.cn/identity7']]);
|
||||
$identity = $client->startIdentity('张医生', 'rx-7', 'sdk-account-1');
|
||||
$request = $requests[count($requests) - 1];
|
||||
$body = json_decode($request['body'], true);
|
||||
esignExpect($identity === ['flow_id' => 'flow-7', 'auth_url' => 'https://smlt.esign.cn/identity7'], 'identity result');
|
||||
esignExpect($request['url'] === 'https://smlopenapi.esign.cn/v2/identity/auth/web/indivAuthUrl', 'independent v2 identity API');
|
||||
esignExpect($body['indivInfo']['sdkAccountId'] === 'sdk-account-1' && !isset($body['sdkAccountId']), 'SDK account nested in indivInfo');
|
||||
esignExpect($body['configParams']['indivUneditableInfo'] === ['name', 'certType'], 'doctor name locked');
|
||||
// Fixed vectors independently calculated with Python hashlib/hmac; UTF-8 bytes must match exactly.
|
||||
esignExpect($request['headers']['Content-MD5'] === 'M2hjK+7n9RSpPC8C09vWVQ==', 'POST content MD5 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'i2dGU5UsRuMb6has/RBZN5BAsECYV4ziEDF17YHaL0g=', 'POST HMACSHA256 vector');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Timestamp'] === '1800000000000', 'timestamp in milliseconds');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Auth-Mode'] === 'Signature', 'signature auth mode');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => 'flow-7', 'status' => 'SUCCESS']]);
|
||||
esignExpect($client->identityDetail('flow-7')['status'] === 'SUCCESS', 'identity official data returned');
|
||||
$request = $requests[count($requests) - 1];
|
||||
esignExpect($request['method'] === 'GET' && $request['body'] === '' && !isset($request['headers']['Content-MD5']), 'GET no body MD5');
|
||||
esignExpect($request['headers']['X-Tsign-Open-Ca-Signature'] === 'wPILAWFFD+SOKXrMxguRUqiG1Iwl+k/X9O9Fukf7hes=', 'GET HMACSHA256 vector');
|
||||
|
||||
$valid = ['errCode' => 0, 'status' => 1, 'remainingTimes' => 1, 'expireAt' => $clock() + 1000];
|
||||
$responses[] = esignResponse($valid);
|
||||
$client->checkWillingness('flow-7');
|
||||
esignExpect(str_ends_with($requests[count($requests) - 1]['url'], '/timevale/auth/queryWillingnessValidity'), 'willingness endpoint');
|
||||
foreach ([['status' => 0], ['remainingTimes' => 0], ['expireAt' => $clock()], ['status' => '1'], ['expireAt' => 'not-a-date']] as $invalid) {
|
||||
$responses[] = esignResponse(array_replace($valid, $invalid));
|
||||
esignThrows(fn () => $client->checkWillingness('flow-7'), EsignProviderException::class, 'WILLINGNESS_INVALID');
|
||||
}
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0, 'accountId' => 'person-7']);
|
||||
esignExpect($client->createPerson('张医生', 'TEST-IDENTITY', 'flow-7') === 'person-7', 'created SDK account');
|
||||
$request = $requests[count($requests) - 1];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/account/addPerson'), 'account SDK endpoint');
|
||||
esignExpect(json_decode($request['body'], true) === ['name' => '张医生', 'idNo' => 'TEST-IDENTITY', 'idNoType' => 'MAINLAND', 'identityAuthId' => 'flow-7'], 'identity bound to SDK account');
|
||||
|
||||
$responses[] = esignResponse(['errCode' => 0, 'sealData' => base64_encode('seal-image')]);
|
||||
esignExpect($client->createSeal('person-7') === base64_encode('seal-image'), 'seal result');
|
||||
$sealBody = json_decode($requests[count($requests) - 1]['body'], true);
|
||||
esignExpect($sealBody === ['accountId' => 'person-7', 'type' => 'BORDERLESS', 'color' => 'BLACK', 'stampRule' => 'SEAL_NONE'], 'seal from account identity');
|
||||
|
||||
$pdf = "%PDF-1.7\n\x00\x01binary-pdf\r\n%%EOF";
|
||||
$signedPdf = "%PDF-1.7\nsigned\x00binary\n%%EOF";
|
||||
$responses[] = esignResponse(['errCode' => 0, 'signServiceId' => 'service-7', 'stream' => base64_encode($signedPdf)]);
|
||||
esignExpect($client->signPdf('person-7', 'flow-7', base64_encode('seal-image'), $pdf, 'rx-7.pdf') === ['sign_service_id' => 'service-7', 'pdf' => $signedPdf], 'decoded signed PDF bytes');
|
||||
$request = $requests[count($requests) - 1];
|
||||
esignExpect(str_ends_with($request['url'], '/timevale/user/sign/personSign'), 'SDK person sign endpoint');
|
||||
$parts = esignMultipartParts($request);
|
||||
esignExpect(array_keys($parts) === ['personSignParam', 'streamFile'], 'multipart field names');
|
||||
esignExpect(str_contains($parts['personSignParam']['headers'], 'Content-Type: application/json; charset=UTF-8'), 'JSON part media type');
|
||||
esignExpect(str_contains($parts['streamFile']['headers'], 'Content-Type: application/octet-stream'), 'file part media type');
|
||||
esignExpect($parts['streamFile']['body'] === $pdf, 'multipart preserves arbitrary binary bytes');
|
||||
$parameters = json_decode($parts['personSignParam']['body'], true);
|
||||
esignExpect($parameters['fileBean'] === ['fileName' => 'rx-7.pdf'] && !isset($parameters['fileBean']['dstPdfFile']), 'stream response requested');
|
||||
esignExpect($parameters['signType'] === 'Single' && $parameters['posBeans'] === [['posPage' => '1', 'posX' => 420, 'posY' => 70, 'width' => 100]], 'fixed prescription signature location');
|
||||
esignExpect($parameters['willingnessId'] === 'flow-7' && $parameters['accountId'] === 'person-7', 'signature identity binding');
|
||||
|
||||
$signatures = [['signature' => ['validate' => true], 'cert' => ['cn' => '张医生']], ['signature' => ['validate' => true]]];
|
||||
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $signatures]);
|
||||
esignExpect($client->verifyPdf($signedPdf) === ['signatures' => $signatures], 'all signatures verified');
|
||||
$parts = esignMultipartParts($requests[count($requests) - 1]);
|
||||
esignExpect(isset($parts['verifyPdfParam']) && $parts['streamFile']['body'] === $signedPdf, 'verify multipart');
|
||||
foreach ([[], [['signature' => ['validate' => true]], ['signature' => ['validate' => false]]], [['signature' => ['validate' => 1]]], [['cert' => []]]] as $invalid) {
|
||||
$responses[] = esignResponse(['errCode' => 0, 'signatures' => $invalid]);
|
||||
esignThrows(fn () => $client->verifyPdf($signedPdf), EsignProviderException::class, $invalid === [] ? 'NO_SIGNATURES' : 'SIGNATURE_INVALID');
|
||||
}
|
||||
|
||||
foreach ([
|
||||
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
|
||||
[['status' => 200, 'body' => '<html>secret identity data</html>'], 'INVALID_JSON'],
|
||||
[esignResponse(['msg' => 'private identity']), 'RESPONSE_INVALID'],
|
||||
[esignResponse(['errCode' => 42, 'msg' => 'private name/id/secret']), 'PROVIDER_42'],
|
||||
[['status' => 302, 'body' => 'Location: https://attacker.invalid'], 'HTTP_302'],
|
||||
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
|
||||
] as [$response, $code]) {
|
||||
$responses[] = $response;
|
||||
$before = count($requests);
|
||||
$exception = esignThrows(fn () => $client->createSeal('person-7'), EsignProviderException::class, $code);
|
||||
esignExpect(count($requests) === $before + 1, 'no retry ' . $code);
|
||||
esignExpect(!str_contains($exception->getMessage(), 'private') && !str_contains($exception->getMessage(), 'secret') && !str_contains($exception->getMessage(), 'attacker'), 'sanitized error ' . $code);
|
||||
}
|
||||
|
||||
foreach ([
|
||||
[['status' => 0, 'body' => '', 'errno' => 28], 'TIMEOUT'],
|
||||
[['status' => 200, 'body' => ''], 'EMPTY_RESPONSE'],
|
||||
[['status' => 502, 'body' => 'private server exception'], 'HTTP_502'],
|
||||
[esignResponse(['errCode' => 0, 'signServiceId' => 'already-signed']), 'SIGNED_FILE_UNAVAILABLE'],
|
||||
] as [$response, $code]) {
|
||||
$responses[] = $response;
|
||||
$before = count($requests);
|
||||
$exception = esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, $code);
|
||||
esignExpect(count($requests) === $before + 1, 'unknown signing outcome is never retried');
|
||||
if ($code === 'SIGNED_FILE_UNAVAILABLE') {
|
||||
esignExpect($exception->signServiceId === 'already-signed', 'known sign reference retained');
|
||||
}
|
||||
}
|
||||
$responses[] = esignResponse(['errCode' => 55, 'msg' => 'secret rejected identity']);
|
||||
esignThrows(fn () => $client->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignProviderException::class, 'PROVIDER_55');
|
||||
$throwing = new EsignClient(esignConfig(), static function (): array { throw new RuntimeException('https://secret:password/private'); }, $clock);
|
||||
esignThrows(fn () => $throwing->createSeal('person-7'), EsignProviderException::class, 'TRANSPORT_ERROR');
|
||||
esignThrows(fn () => $throwing->signPdf('person-7', 'flow-7', base64_encode('seal'), $pdf, 'rx.pdf'), EsignOutcomeUnknownException::class, 'TRANSPORT_ERROR');
|
||||
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://attacker.invalid/identity']]);
|
||||
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => 'https://t.esign.cn/identity']]);
|
||||
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => 'https://smlfront.esign.cn:8890/identity/login']]);
|
||||
esignExpect($client->startIdentity('医生', 'rx')['auth_url'] === 'https://smlfront.esign.cn:8890/identity/login', 'official sandbox long URL port');
|
||||
foreach (['https://smlfront.esign.cn:444/x', 'https://smlt.esign.cn:8890/x', 'https://smlt.esign.cn/a\\b'] as $invalidUrl) {
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'url' => $invalidUrl]]);
|
||||
esignThrows(fn () => $client->startIdentity('医生', 'rx'), EsignProviderException::class, 'AUTH_URL_INVALID');
|
||||
}
|
||||
|
||||
$production = new EsignClient(esignConfig(['environment' => 'production']), $transport, $clock);
|
||||
$responses[] = esignResponse(['errCode' => 0]);
|
||||
$production->initialize();
|
||||
$init = json_decode($requests[count($requests) - 1]['body'], true);
|
||||
esignExpect($init['projectConfig']['itsmApiUrl'] === 'https://sdkapi.esign.cn/tgmonitor/rest/app!getAPIInfo2', 'production init endpoint');
|
||||
$responses[] = esignResponse(['code' => 0, 'data' => ['flowId' => '7', 'shortLink' => '', 'url' => 'https://idverify.esign.cn/identity']]);
|
||||
$production->startIdentity('医生', 'rx');
|
||||
esignExpect(str_starts_with($requests[count($requests) - 1]['url'], 'https://openapi.esign.cn/v2/identity/'), 'production identity endpoint');
|
||||
|
||||
esignExpect($responses === [], 'all expected transport responses consumed');
|
||||
echo 'EsignClient: ' . $checks . " checks passed (offline)\n";
|
||||
@@ -0,0 +1,336 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
class EsignProviderException extends \RuntimeException
|
||||
{
|
||||
public function __construct(public string $operation, public string $providerCode)
|
||||
{
|
||||
parent::__construct('e签宝 ' . $operation . ' 失败(' . $providerCode . ')');
|
||||
}
|
||||
}
|
||||
class EsignOutcomeUnknownException extends EsignProviderException
|
||||
{
|
||||
public function __construct(string $code, public ?string $signServiceId = null) { parent::__construct('signPdf', $code); }
|
||||
}
|
||||
/** Only the external provider boundary is fake; service/ORM/files are real. */
|
||||
final class EsignClient
|
||||
{
|
||||
public static int $starts = 0;
|
||||
public static int $signs = 0;
|
||||
public static string $identityStatus = 'SUCCESS';
|
||||
public static string $identityName = '测试医师';
|
||||
public static bool $verifyFailure = false;
|
||||
public static ?string $verifyRejection = null;
|
||||
public static bool $signFailure = false;
|
||||
public static int $initializes = 0;
|
||||
public static ?string $signRejection = null;
|
||||
public static ?string $unknownServiceId = null;
|
||||
public static ?string $identityFlowId = null;
|
||||
public static bool $startFailure = false;
|
||||
public static bool $expiredWillingness = false;
|
||||
public static $duringSeal = null;
|
||||
public static $duringSign = null;
|
||||
public function assertConfigured(): void {}
|
||||
public function initialize(): void { self::$initializes++; }
|
||||
public function startIdentity(string $name, string $contextId, ?string $accountId = null): array
|
||||
{
|
||||
self::$starts++;
|
||||
if (self::$startFailure) { throw new EsignProviderException('startIdentity', 'HTTP_503'); }
|
||||
return ['flow_id' => 'flow-' . self::$starts, 'auth_url' => 'https://smlt.esign.cn/test'];
|
||||
}
|
||||
public function identityDetail(string $id): array
|
||||
{
|
||||
return ['flowId' => self::$identityFlowId ?? $id, 'appId' => 'fixture', 'status' => self::$identityStatus, 'objectType' => 'INDIVIDUAL',
|
||||
'indivInfo' => ['name' => self::$identityName, 'certNo' => '110101199001011234', 'certType' => 'INDIVIDUAL_CH_IDCARD']];
|
||||
}
|
||||
public function checkWillingness(string $id): void
|
||||
{
|
||||
if (self::$expiredWillingness) { throw new EsignProviderException('checkWillingness', 'WILLINGNESS_INVALID'); }
|
||||
}
|
||||
public function createPerson(string $name, string $idNo, string $flow): string { return 'account-test'; }
|
||||
public function createSeal(string $id): string
|
||||
{
|
||||
if (self::$duringSeal) { (self::$duringSeal)(); }
|
||||
return base64_encode('test-seal');
|
||||
}
|
||||
public function signPdf(string $account, string $flow, string $seal, string $pdf, string $name): array
|
||||
{
|
||||
self::$signs++;
|
||||
if (self::$duringSign) { (self::$duringSign)(); }
|
||||
if (self::$signRejection !== null) { throw new EsignProviderException('signPdf', self::$signRejection); }
|
||||
if (self::$signFailure) { throw new EsignOutcomeUnknownException('TIMEOUT', self::$unknownServiceId); }
|
||||
return ['pdf' => $pdf . "\n% provider signed fixture\n", 'sign_service_id' => 'sign-' . self::$signs];
|
||||
}
|
||||
public function verifyPdf(string $pdf): array
|
||||
{
|
||||
if (self::$verifyFailure) { throw new \RuntimeException('verify unavailable'); }
|
||||
if (self::$verifyRejection !== null) { throw new EsignProviderException('verifyPdf', self::$verifyRejection); }
|
||||
return ['signatures' => [['signature' => ['validate' => true], 'cert' => ['cn' => '测试医师'], 'sealData' => base64_encode('test-seal')]]];
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
use app\common\service\esign\PrescriptionEsignService as Service;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy as Policy;
|
||||
use app\common\service\esign\PrescriptionPdf;
|
||||
use app\common\service\esign\EsignClient as Fake;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
$app = new think\App(); // Never initialize or load .env / real DB credentials.
|
||||
$dir = sys_get_temp_dir() . '/zyt-esign-test-' . bin2hex(random_bytes(8));
|
||||
mkdir($dir, 0700);
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => $dir . '/fixture.sqlite', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$settings = ['enabled' => true, 'environment' => 'sandbox', 'app_id' => 'fixture', 'storage_path' => $dir . '/pdf'];
|
||||
$config->set($settings, 'esign');
|
||||
Container::getInstance()->instance('config', $config);
|
||||
$root = ['root' => 1, 'admin_id' => 1, 'name' => '测试医师'];
|
||||
$checks = 0;
|
||||
$assert = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) { throw new \RuntimeException($message); }
|
||||
$checks++;
|
||||
};
|
||||
$throws = static function (callable $fn, string $message) use ($assert): void {
|
||||
try { $fn(); } catch (\DomainException $e) { $assert(true, $message); return; }
|
||||
$assert(false, $message);
|
||||
};
|
||||
try {
|
||||
$fields = array_unique(array_merge(Policy::CONTENT_FIELDS, ['esign_required', 'esign_status', 'is_system_auto', 'void_status', 'delete_time', 'doctor_signature', 'update_time']));
|
||||
$columns = array_map(static fn ($field) => $field === 'id' ? 'id INTEGER PRIMARY KEY' : $field . ' TEXT', $fields);
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription (' . implode(',', $columns) . ')');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER)');
|
||||
Db::name('admin')->insert(['id' => 1, 'name' => '测试医师']);
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql');
|
||||
preg_match_all('/CREATE TABLE IF NOT EXISTS `(zyt_\w+)` \((.*?)\) ENGINE/s', $sql, $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $match) {
|
||||
$defs = [];
|
||||
foreach (explode("\n", $match[2]) as $line) {
|
||||
if (preg_match('/^\s*`(\w+)`\s+(.+?)(?:,)?$/', $line, $m)) {
|
||||
$type = preg_match('/\bint\b/', $m[2]) ? 'INTEGER' : 'TEXT';
|
||||
$def = '`' . $m[1] . '` ' . $type;
|
||||
if ($m[1] === 'id' || ($match[1] === 'zyt_prescription_esign' && $m[1] === 'prescription_id')) { $def .= ' PRIMARY KEY'; }
|
||||
if (preg_match("/DEFAULT ('[^']*'|\d+)/", $m[2], $d)) { $def .= ' DEFAULT ' . $d[1]; }
|
||||
$defs[] = $def;
|
||||
}
|
||||
}
|
||||
Db::execute('CREATE TABLE ' . $match[1] . ' (' . implode(',', $defs) . ')');
|
||||
}
|
||||
Db::execute('CREATE UNIQUE INDEX uk_doctor ON zyt_doctor_esign_account(doctor_id,environment,app_id)');
|
||||
$new = static function (int $id): void {
|
||||
Db::name('tcm_prescription')->insert([
|
||||
'id' => $id, 'sn' => 'RX-TEST-' . $id, 'creator_id' => 1, 'doctor_name' => '测试医师',
|
||||
'patient_name' => '虚构测试患者', 'gender' => 1, 'age' => 30, 'phone' => '13800000000',
|
||||
'clinical_diagnosis' => '仅用于软件测试', 'herbs' => json_encode([['name' => '测试药材', 'dosage' => 10, 'unit' => 'g']], JSON_UNESCAPED_UNICODE),
|
||||
'prescription_date' => '2026-11-17', 'esign_required' => 1, 'esign_status' => 'pending', 'void_status' => 0,
|
||||
]);
|
||||
};
|
||||
$new(1);
|
||||
$throws(fn () => Service::start(1, 2, $root), 'non-creator cannot start even with root role');
|
||||
$throws(fn () => Service::assertSignedById(1), 'pending prescription cannot pass audit');
|
||||
$a = Service::start(1, 1, $root);
|
||||
$assert($a['status'] === 'authenticating' && isset($a['auth_url']), 'start returns authentication URL');
|
||||
Service::start(1, 1, $root);
|
||||
$assert(Fake::$starts === 1, 'repeat start must reuse flow');
|
||||
$throws(fn () => Policy::assertMutable(Db::name('tcm_prescription')->find(1)), 'auth freezes content');
|
||||
Fake::$identityStatus = 'ING';
|
||||
$assert(Service::complete(1, 1, $root)['status'] === 'authenticating' && Fake::$signs === 0, 'not authenticated cannot sign');
|
||||
Fake::$identityStatus = 'SUCCESS';
|
||||
Fake::$identityName = '其他医师';
|
||||
$assert(Service::complete(1, 1, $root)['status'] === 'failed' && Fake::$signs === 0, 'wrong identity cannot sign');
|
||||
Fake::$identityName = '测试医师';
|
||||
Service::start(1, 1, $root); // A rejected identity must be replaced, never silently reused.
|
||||
Fake::$duringSign = static function () use ($assert, $root): void {
|
||||
$assert(Service::complete(1, 1, $root)['status'] === 'signing', 'concurrent complete must not repeat sign');
|
||||
};
|
||||
$done = Service::complete(1, 1, $root);
|
||||
Fake::$duringSign = null;
|
||||
$assert($done['status'] === 'signed' && $done['can_download'], 'verified sign archived');
|
||||
Service::complete(1, 1, $root);
|
||||
$assert(Fake::$signs === 1, 'signed replay returns same result');
|
||||
$download = Service::download(1, 1, $root);
|
||||
$bytes = base64_decode($download['content_base64'], true);
|
||||
$assert(hash('sha256', $bytes) === $download['sha256'] && str_contains($bytes, 'provider signed fixture'), 'download original bytes and digest');
|
||||
Service::assertSignedById(1);
|
||||
$throws(fn () => Service::assertSignedById(1, true), 'sandbox cannot dispense');
|
||||
$throws(fn () => Policy::assertMutable(Db::name('tcm_prescription')->find(1)), 'signed content immutable');
|
||||
Db::name('tcm_prescription')->where('id', 1)->update(['clinical_diagnosis' => 'changed']);
|
||||
$throws(fn () => Service::assertSignedById(1), 'out-of-band content mutation invalidates approval');
|
||||
$assert(Service::status(1, 1, $root)['status'] === 'uncertain', 'changed content is not displayed as signed');
|
||||
|
||||
$new(2); Service::start(2, 1, $root);
|
||||
Fake::$verifyFailure = true;
|
||||
$assert(Service::complete(2, 1, $root)['status'] === 'uncertain', 'verification outage preserves unknown state');
|
||||
$before = Fake::$signs;
|
||||
Service::start(2, 1, $root); Service::complete(2, 1, $root);
|
||||
$assert(Fake::$signs === $before, 'unknown outcome never automatically resigns');
|
||||
Fake::$verifyFailure = false;
|
||||
Service::recover(2);
|
||||
$assert(Service::status(2, 1, $root)['status'] === 'signed' && Fake::$signs === $before, 'recover re-verifies original without signing');
|
||||
$assert(Db::name('tcm_prescription')->where('id', 2)->value('doctor_signature') === 'data:image/png;base64,' . base64_encode('test-seal'), 'recovery restores supplier-verified display seal');
|
||||
|
||||
$new(3); Service::start(3, 1, $root);
|
||||
Fake::$duringSign = static fn () => Db::name('tcm_prescription')->where('id', 3)->update(['void_status' => 1]);
|
||||
$assert(Service::complete(3, 1, $root)['status'] === 'voided', 'late signature never restores voided prescription');
|
||||
Fake::$duringSign = null;
|
||||
$throws(fn () => Service::assertSignedById(3), 'voided prescription cannot pass');
|
||||
|
||||
$new(4); Service::start(4, 1, $root);
|
||||
Fake::$signFailure = true;
|
||||
$assert(Service::complete(4, 1, $root)['status'] === 'uncertain', 'sign timeout remains uncertain');
|
||||
Fake::$signFailure = false;
|
||||
$throws(fn () => Service::recover(4), 'missing signed file cannot be invented');
|
||||
|
||||
$new(6); Service::start(6, 1, $root);
|
||||
Fake::$signFailure = true; Fake::$unknownServiceId = 'supplier-uncertain-6';
|
||||
$assert(Service::complete(6, 1, $root)['status'] === 'uncertain', 'typed timeout outcome remains uncertain');
|
||||
Fake::$signFailure = false; Fake::$unknownServiceId = null;
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 6)->find();
|
||||
$assert($evidence['sign_service_id'] === 'supplier-uncertain-6' && $evidence['account_id'] === 'account-test', 'unknown exception supplier reference is retained');
|
||||
$before = Fake::$signs;
|
||||
Service::start(6, 1, $root); Service::complete(6, 1, $root);
|
||||
$assert(Fake::$signs === $before, 'typed unknown cannot automatically resign');
|
||||
|
||||
$new(7); Service::start(7, 1, $root);
|
||||
Fake::$signRejection = 'PROVIDER_50001';
|
||||
$rejected = Service::complete(7, 1, $root);
|
||||
Fake::$signRejection = null;
|
||||
$assert($rejected['status'] === 'failed' && $rejected['can_sign'], 'explicit supplier rejection is retryable');
|
||||
$assert(str_contains($rejected['message'], 'PROVIDER_50001'), 'safe supplier code is retained');
|
||||
$assert(Db::name('prescription_esign')->where('prescription_id', 7)->value('flow_id') === '', 'explicit rejection requires fresh authentication');
|
||||
$before = Fake::$signs;
|
||||
$throws(fn () => Service::complete(7, 1, $root), 'cannot reuse rejected sign authentication');
|
||||
Service::start(7, 1, $root);
|
||||
$assert(Service::complete(7, 1, $root)['status'] === 'signed' && Fake::$signs === $before + 1, 'new auth can complete definite rejection retry');
|
||||
|
||||
$new(8); Fake::$startFailure = true;
|
||||
$assert(Service::start(8, 1, $root)['status'] === 'failed', 'identity link outage records failed preparation');
|
||||
Fake::$startFailure = false;
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 8)->find();
|
||||
$assert($evidence['flow_id'] === '' && $evidence['auth_url'] === '', 'failed preparation has no stale identity URL');
|
||||
$assert(Service::start(8, 1, $root)['status'] === 'authenticating', 'identity preparation can safely retry');
|
||||
|
||||
$new(9); Service::start(9, 1, $root); $before = Fake::$signs;
|
||||
Fake::$expiredWillingness = true;
|
||||
$assert(Service::complete(9, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'expired willingness never dispatches sign');
|
||||
Fake::$expiredWillingness = false;
|
||||
$assert(Db::name('prescription_esign')->where('prescription_id', 9)->value('flow_id') === '', 'expired willingness requires new auth flow');
|
||||
|
||||
$new(10); Service::start(10, 1, $root); $before = Fake::$signs;
|
||||
Fake::$identityFlowId = 'foreign-flow';
|
||||
$assert(Service::complete(10, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'identity response must echo bound flow');
|
||||
Fake::$identityFlowId = null;
|
||||
|
||||
$new(11); Service::start(11, 1, $root); $before = Fake::$signs;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replacement-account']);
|
||||
$assert(Service::complete(11, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'account replacement cannot reuse auth for old account');
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'account-test']);
|
||||
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->delete();
|
||||
$new(12); Service::start(12, 1, $root); $before = Fake::$signs;
|
||||
Db::name('doctor_esign_account')->insert(['doctor_id' => 1, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||||
'account_id' => 'account-test', 'doctor_name' => '测试医师', 'create_time' => time()]);
|
||||
$assert(Service::complete(12, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'concurrent first binding cannot turn unbound auth into bound auth');
|
||||
Service::start(12, 1, $root);
|
||||
$assert(Service::complete(12, 1, $root)['status'] === 'signed', 'new auth binds the now existing account');
|
||||
|
||||
$new(13); Service::start(13, 1, $root);
|
||||
Db::name('tcm_prescription')->where('id', 13)->update(['esign_status' => 'signing']);
|
||||
Db::name('prescription_esign')->where('prescription_id', 13)->update(['started_at' => time() - 500]);
|
||||
$before = Fake::$signs;
|
||||
$stale = Service::status(13, 1, $root);
|
||||
Service::start(13, 1, $root); Service::complete(13, 1, $root);
|
||||
$assert($stale['status'] === 'uncertain' && !$stale['can_sign'] && Fake::$signs === $before, 'stale signing lease cannot trigger another sign');
|
||||
|
||||
$new(14); Service::start(14, 1, $root); $before = Fake::$signs;
|
||||
Fake::$duringSeal = static fn () => Db::name('tcm_prescription')->where('id', 14)->update(['usage_notes' => 'out-of-band mutation']);
|
||||
$assert(Service::complete(14, 1, $root)['status'] === 'uncertain' && Fake::$signs === $before, 'second fingerprint check prevents signing mutated prescription');
|
||||
Fake::$duringSeal = null;
|
||||
|
||||
$new(15); Service::start(15, 1, $root); $before = Fake::$signs;
|
||||
Fake::$duringSeal = static fn () => Db::name('tcm_prescription')->where('id', 15)->update(['void_status' => 1]);
|
||||
$assert(Service::complete(15, 1, $root)['status'] === 'voided' && Fake::$signs === $before, 'void during provider preparation prevents dispatch');
|
||||
Fake::$duringSeal = null;
|
||||
|
||||
$new(16); Service::start(16, 1, $root); Fake::$verifyFailure = true;
|
||||
Service::complete(16, 1, $root); Fake::$verifyFailure = false;
|
||||
Db::name('tcm_prescription')->where('id', 16)->update(['usage_notes' => 'modified after signing']);
|
||||
$before = Fake::$signs;
|
||||
$throws(fn () => Service::recover(16), 'recovery cannot approve a changed snapshot');
|
||||
$assert(Fake::$signs === $before && Service::status(16, 1, $root)['status'] === 'uncertain', 'changed recovery remains quarantined without signing');
|
||||
|
||||
$new(17); Service::start(17, 1, $root);
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 17)->find();
|
||||
$blockedPath = $dir . '/pdf/' . dirname($evidence['source_path']) . '/signed.pdf';
|
||||
mkdir($blockedPath);
|
||||
set_error_handler(static fn (): bool => true); // Expected rename failure, no sensitive error output.
|
||||
try { $archiveFailure = Service::complete(17, 1, $root); } finally { restore_error_handler(); rmdir($blockedPath); }
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 17)->find();
|
||||
$assert($archiveFailure['status'] === 'uncertain' && $evidence['sign_service_id'] !== '' && $evidence['signed_path'] === '', 'archive failure preserves successful supplier reference');
|
||||
$throws(fn () => Service::recover(17), 'archive failure requires manual retrieval, never resign');
|
||||
|
||||
$new(18); Service::start(18, 1, $root); $before = Fake::$signs;
|
||||
$evidence = Db::name('prescription_esign')->where('prescription_id', 18)->find();
|
||||
file_put_contents($dir . '/pdf/' . $evidence['source_path'], '%PDF-1.7 tampered');
|
||||
$assert(Service::complete(18, 1, $root)['status'] === 'failed' && Fake::$signs === $before, 'changed source file cannot be sent to provider');
|
||||
|
||||
$new(19); Service::start(19, 1, $root); $before = Fake::$signs;
|
||||
Db::name('admin')->where('id', 1)->update(['name' => '已改名医师']);
|
||||
$throws(fn () => Service::complete(19, 1, $root), 'doctor account rename invalidates pending identity binding');
|
||||
Db::name('admin')->where('id', 1)->update(['name' => '测试医师']);
|
||||
$assert(Fake::$signs === $before, 'renamed doctor does not send sign');
|
||||
|
||||
$new(20); Service::start(20, 1, $root);
|
||||
Fake::$verifyRejection = 'PROVIDER_70002';
|
||||
$invalidSigned = Service::complete(20, 1, $root);
|
||||
Fake::$verifyRejection = null;
|
||||
$assert($invalidSigned['status'] === 'uncertain' && !$invalidSigned['can_sign'], 'definite verification failure after signature is never a retryable sign failure');
|
||||
|
||||
$proof = Db::name('prescription_esign')->where('prescription_id', 2)->find();
|
||||
$proof['doctor_id'] = 99;
|
||||
$throws(fn () => Policy::assertSigned(Db::name('tcm_prescription')->find(2), $proof), 'proof author must match prescription creator');
|
||||
$assert(!str_contains(json_encode(Db::name('prescription_esign')->select()->toArray()), '110101199001011234')
|
||||
&& !str_contains(json_encode(Db::name('doctor_esign_account')->select()->toArray()), '110101199001011234'), 'identity document number never persisted');
|
||||
$assert(Fake::$initializes === 0, 'business operations and recovery never reinitialize shared SDK');
|
||||
|
||||
$new(5); Service::start(5, 1, $root);
|
||||
$config->set(array_merge($settings, ['environment' => 'production']), 'esign');
|
||||
$throws(fn () => Service::complete(5, 1, $root), 'environment switch cannot reuse sandbox identity');
|
||||
$config->set(array_merge($settings, ['enabled' => false]), 'esign');
|
||||
$throws(fn () => Service::start(5, 1, $root), 'disabled config blocks signing');
|
||||
$throws(fn () => Service::assertSignedById(5), 'feature off must not bypass existing signature requirement');
|
||||
$legacy = Db::name('tcm_prescription')->find(5); $legacy['esign_required'] = 0;
|
||||
Policy::assertSigned($legacy, null);
|
||||
$assert(true, 'historical handwritten record remains compatible');
|
||||
|
||||
$sample = Db::name('tcm_prescription')->find(2);
|
||||
$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');
|
||||
$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');
|
||||
$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');
|
||||
$assert(preg_match('#/Type /Pages /Kids \[.*?\] /Count ([2-9]\d*)#', $largePdf) === 1, 'long prescription paginates');
|
||||
$assert(str_contains($largePdf, bin2hex(mb_convert_encoding('药品 65:', 'UTF-16BE', 'UTF-8'))), 'last drug is not truncated');
|
||||
$assert(str_contains($largePdf, bin2hex(mb_convert_encoding('金额(元):18.5', 'UTF-16BE', 'UTF-8'))), 'amount is present in signed document');
|
||||
file_put_contents(dirname(__DIR__, 2) . '/artifacts/esign-prescription-test.pdf', $pdf);
|
||||
echo "Prescription eSign flow: $checks checks passed (isolated SQLite, fake provider)\n";
|
||||
} finally {
|
||||
$manager->connect()->close();
|
||||
foreach (glob($dir . '/pdf/*/*.pdf') ?: [] as $file) { unlink($file); }
|
||||
foreach (glob($dir . '/pdf/*', GLOB_ONLYDIR) ?: [] as $folder) { rmdir($folder); }
|
||||
if (is_dir($dir . '/pdf')) { rmdir($dir . '/pdf'); }
|
||||
if (is_file($dir . '/fixture.sqlite')) { unlink($dir . '/fixture.sqlite'); }
|
||||
rmdir($dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Disposable localhost MySQL only; never bootstraps the application environment. */
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
use app\common\service\pharmacy\PharmacySubmissionClaimService;
|
||||
use think\Container;
|
||||
use think\facade\Db;
|
||||
|
||||
$port = (int) getenv('ZYT_ESIGN_TEST_MYSQL_PORT');
|
||||
if ($port <= 0) {
|
||||
throw new RuntimeException('Set ZYT_ESIGN_TEST_MYSQL_PORT to an isolated localhost test MySQL');
|
||||
}
|
||||
$database = 'esign_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 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_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,
|
||||
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);
|
||||
$row = Db::name('tcm_prescription')->find(1);
|
||||
$expect((int) $row['esign_required'] === 0 && $row['esign_status'] === 'legacy', 'migration preserves historical rows and is repeatable');
|
||||
$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]);
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual audit explains signature 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' => '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');
|
||||
}
|
||||
$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);
|
||||
$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 === 3 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
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`");
|
||||
}
|
||||
Reference in New Issue
Block a user