药师签署完成后自动将双签处方 PDF 归档到私有 COS

- 药师签署验签通过后,立即把最终双签 PDF 以私有对象上传到后台配置的腾讯云 COS,
  对象键 private/esign/prescription/<环境>/<处方ID>-<sha256>.pdf,带 Content-MD5 校验,不返回任何 URL
- 上传失败不影响签署:记录原因并指数退避,由 esign:archive-work 每分钟补传(最长 1 小时一次)
- 签署日志新增「签署件已归档至云存储」/「归档未完成,系统将自动重试」
- 迁移 2026_11_27_prescription_review_archive.sql:归档字段 + 定时任务登记

Co-Authored-By: Claude Opus 5 (1M context) <[EMAIL]>
This commit is contained in:
Your Name
2026-11-27 14:47:45 +08:00
co-authored by Claude Opus 5 (1M context)
parent dc5467cfa7
commit 90b9fff76a
7 changed files with 288 additions and 20 deletions
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace app\command;
use app\common\service\esign\PrescriptionEsignArchive;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
/** 每分钟执行:补传药师签署后未成功归档到 COS 的处方 PDF。 */
final class EsignArchiveWork extends Command
{
protected function configure()
{
$this->setName('esign:archive-work')->setDescription('补传已签处方 PDF 到私有 COS')
->addOption('limit', null, Option::VALUE_REQUIRED, '最多处理的处方数,1至100', '20');
}
protected function execute(Input $input, Output $output): int
{
try {
$ids = PrescriptionEsignArchive::pending(max(1, min(100, (int) $input->getOption('limit'))));
} catch (\Throwable) {
// 抛出会让 Crontab 把任务置为错误并停止调度,归档补传就永久中断了。
$output->writeln('ESIGN_ARCHIVE_WORK database_unavailable');
return 1;
}
$archived = 0;
foreach ($ids as $id) {
$archived += PrescriptionEsignArchive::upload((int) $id) ? 1 : 0;
}
$output->writeln('ESIGN_ARCHIVE_WORK ' . json_encode(['selected' => count($ids), 'archived' => $archived,
'deferred' => count($ids) - $archived]));
return $archived === count($ids) ? 0 : 1;
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use DomainException;
use think\facade\Db;
/** 药师签署后的最终双签 PDF 归档到私有 COS;本地原件不变,归档失败不影响签署。 */
final class PrescriptionEsignArchive
{
private const TABLE = 'prescription_review_esign';
private const MAX_RETRY_DELAY = 3600;
/** 上传一张处方的最终 PDF。从不抛出:失败只记录并按退避时间交给 esign:archive-work 重试。 */
public static function upload(int $id): bool
{
try {
$signed = PrescriptionReviewEsignService::verifiedPdf($id);
if ($signed === null) {
throw new DomainException('药师签署尚未通过验签,暂不归档');
}
$archived = (string) Db::name(self::TABLE)->where('prescription_id', $id)->value('archive_hash');
if ($archived === $signed['sha256']) {
return true;
}
$cos = app(PrescriptionEsignCos::class);
$object = $cos->location() + ['key' => 'private/esign/prescription/' . $signed['environment'] . '/'
. $id . '-' . $signed['sha256'] . '.pdf'];
$cos->put($object, $signed['pdf']);
// 以 signed_hash 作条件:上传期间若重新签署,则不把旧文件记为新签署件的归档。
Db::name(self::TABLE)->where('prescription_id', $id)->where('signed_hash', $signed['sha256'])->update([
'archive_bucket' => $object['bucket'], 'archive_region' => $object['region'], 'archive_key' => $object['key'],
'archive_hash' => $signed['sha256'], 'archived_at' => time(), 'archive_attempts' => 0,
'archive_attempted_at' => time(), 'archive_next_retry_at' => 0, 'archive_error' => '',
]);
return true;
} catch (\Throwable $e) {
self::defer($id, $e);
return false;
}
}
/** 待归档:已签署、归档哈希与签署件不一致、且已到重试时间。 */
public static function pending(int $limit): array
{
return Db::name(self::TABLE)->where('state', 'signed')->where('signed_hash', '<>', '')
->whereColumn('archive_hash', '<>', 'signed_hash')->where('archive_next_retry_at', '<=', time())
->order('archive_next_retry_at')->limit($limit)->column('prescription_id');
}
private static function defer(int $id, \Throwable $error): void
{
try {
$attempts = (int) Db::name(self::TABLE)->where('prescription_id', $id)->value('archive_attempts') + 1;
$message = $error instanceof DomainException ? $error->getMessage() : '归档暂不可用,系统将自动重试';
Db::name(self::TABLE)->where('prescription_id', $id)->update([
'archive_attempts' => $attempts, 'archive_attempted_at' => time(),
'archive_next_retry_at' => time() + min(self::MAX_RETRY_DELAY, 60 * 2 ** min(6, $attempts - 1)),
'archive_error' => mb_substr($message, 0, 240),
]);
} catch (\Throwable) {
// 记录失败本身也不能影响签署;定时任务会再次选中该处方。
}
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace app\common\service\esign;
use app\common\service\ConfigService;
use DomainException;
use Qcloud\Cos\Client;
/** 已签处方 PDF 的私有 COS 适配器:对象 ACL 私有,不经 FileService/CDN,也不返回可访问 URL。 */
class PrescriptionEsignCos
{
public function location(): array
{
$config = $this->settings();
$location = ['bucket' => (string) ($config['bucket'] ?? ''), 'region' => (string) ($config['region'] ?? '')];
self::validateLocation($location);
return $location;
}
/** $object: bucket / region / key。Content-MD5 由本地字节计算,传输损坏时 COS 直接拒收。 */
public function put(array $object, string $pdf): void
{
self::validateLocation($object);
if (!preg_match('#^private/esign/prescription/(sandbox|production)/\d+-[a-f0-9]{64}\.pdf$#D', (string) ($object['key'] ?? ''))) {
throw new DomainException('处方归档对象键无效');
}
try {
$this->client($object['region'])->putObject([
'Bucket' => $object['bucket'], 'Key' => $object['key'], 'Body' => $pdf, 'ACL' => 'private',
'ContentType' => 'application/pdf', 'CacheControl' => 'private, no-store, max-age=0',
'ContentDisposition' => 'attachment; filename="prescription-signed.pdf"',
'Headers' => ['Content-MD5' => base64_encode(md5($pdf, true))],
'Metadata' => ['sha256' => hash('sha256', $pdf)],
'@http' => ['connect_timeout' => 3, 'timeout' => 10, 'read_timeout' => 10, 'allow_redirects' => false],
]);
} catch (\Throwable $e) {
$status = method_exists($e, 'getStatusCode') ? (int) $e->getStatusCode() : 0;
// 不保留原异常:其中可能带签名 URL 或密钥信息。
throw new DomainException($status === 401 || $status === 403
? '云存储授权不可用,请检查 COS 密钥与桶权限' : '云存储暂不可用' . ($status > 0 ? "(HTTP {$status})" : ''));
}
}
protected function settings(): array
{
$config = ConfigService::get('storage', 'qcloud', []);
if (!is_array($config) || empty($config['access_key']) || empty($config['secret_key'])) {
throw new DomainException('未配置腾讯云 COS 存储');
}
return $config;
}
protected function client(string $region): Client
{
$config = $this->settings();
// 已安装 SDK 2.6.5 使用 "schema" 而非 "scheme"。
return new Client(['schema' => 'https', 'region' => $region, 'retry' => 0,
'timeout' => 10, 'connect_timeout' => 3, 'allow_redirects' => false,
'credentials' => ['secretId' => $config['access_key'], 'secretKey' => $config['secret_key']]]);
}
private static function validateLocation(array $object): void
{
if (!preg_match('/^[a-z0-9][a-z0-9-]{1,62}-[0-9]{5,20}$/D', (string) ($object['bucket'] ?? ''))
|| !preg_match('/^[a-z]{2}-[a-z0-9-]{2,40}$/D', (string) ($object['region'] ?? ''))) {
throw new DomainException('COS 桶或地域配置无效');
}
}
}
@@ -171,6 +171,11 @@ final class PrescriptionReviewEsignService
if ($verifiedReview) {
$add('review_signed', '药师签署', (int) $review['signature_time'], $reviewer, 'tsa');
$add('review_verified', '药师签章验签通过', (int) $review['update_time']);
if (($review['archive_hash'] ?? '') === $review['signed_hash']) {
$add('review_archived', '签署件已归档至云存储', (int) $review['archived_at']);
} elseif ((int) ($review['archive_attempted_at'] ?? 0) > 0) {
$add('review_archive_pending', '签署件归档云存储未完成,系统将自动重试', (int) $review['archive_attempted_at']);
}
} elseif (in_array($review['state'], ['failed', 'uncertain'], true)) {
$add('review_' . $review['state'], $review['state'] === 'failed' ? '药师签署未完成' : '药师签署结果待核实',
(int) $review['update_time'], $reviewer);
@@ -242,6 +247,18 @@ final class PrescriptionReviewEsignService
'sha256' => $review['signed_hash'], 'content_base64' => base64_encode($pdf)];
}
/** 已验签的最终双签 PDF,供云存储归档;药师签署未通过验签时返回 null。 */
public static function verifiedPdf(int $id): ?array
{
$doctor = Db::name('prescription_esign')->where('prescription_id', $id)->find();
$review = self::review($id);
if (!$doctor || !self::hasVerifiedReview($doctor, $review)) {
return null;
}
return ['environment' => (string) $doctor['environment'], 'sha256' => $review['signed_hash'],
'pdf' => PrescriptionEsignService::readPdf(self::path($doctor), $review['signed_hash'])];
}
public static function status(int $id, int $orderId, int $actor, array $adminInfo): array
{
$context = self::context($id, $orderId, $actor, $adminInfo);
@@ -389,6 +406,7 @@ final class PrescriptionReviewEsignService
});
$received = $verifyOnly;
$signedNow = false;
try {
if ($verifyOnly) {
$dual = PrescriptionEsignService::readPdf(self::path($doctor), $work['signed_hash']);
@@ -404,6 +422,7 @@ final class PrescriptionReviewEsignService
$signature = self::verifiedReviewSignature($source, $dual, $client->verifyPdf($dual), $doctor, $work);
self::cacheSeal(self::sealPath($doctor, $work), $signature['seal']);
self::save($id, $token, ['state' => 'signed', 'signature_time' => $signature['time'], 'error_message' => '']);
$signedNow = true;
} catch (\Throwable $error) {
$definiteRejection = !$received && $error instanceof EsignProviderException && !($error instanceof EsignOutcomeUnknownException);
$details = $definiteRejection || $error instanceof DomainException ? $error->getMessage()
@@ -414,6 +433,10 @@ final class PrescriptionReviewEsignService
}
self::save($id, $token, $fields);
}
if ($signedNow) {
// 签署已落定;归档失败只记录,由 esign:archive-work 重试。
PrescriptionEsignArchive::upload($id);
}
return self::status($id, $orderId, $actor, $adminInfo);
}
+20 -19
View File
@@ -4,21 +4,22 @@
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
'commands' => [
'desktop-session:settle' => 'app\\command\\DesktopSessionSettle',
'esign:setup' => 'app\\command\\EsignSetup',
'esign:setup' => 'app\\command\\EsignSetup',
'esign:archive-work' => 'app\\command\\EsignArchiveWork',
'assistant-service:daily' => 'app\\command\\AssistantServiceDaily',
'assistant-service:alert' => 'app\\command\\AssistantServiceAlert',
'assistant-service:auto' => 'app\\command\\AssistantServiceAuto',
'assistant-service:work' => 'app\\command\\AssistantServiceWork',
'mobile-recording:cos-work' => 'app\\command\\MobileRecordingCosWork',
'mobile-recording:cos-migrate' => 'app\\command\\MobileRecordingCosMigrate',
'mobile-recording:cleanup' => 'app\\command\\MobileRecordingCleanup',
'followup-audio:work' => 'app\\command\\FollowupAudioWork',
'followup-audio:probe' => 'app\\command\\FollowupAudioProbe',
'followup-audio:cleanup' => 'app\\command\\FollowupAudioCleanup',
'prescription-ai:work' => 'app\\command\\PrescriptionAiWork',
'prescription-ai:backfill' => 'app\\command\\PrescriptionAiBackfill',
'assistant-service:auto' => 'app\\command\\AssistantServiceAuto',
'assistant-service:work' => 'app\\command\\AssistantServiceWork',
'mobile-recording:cos-work' => 'app\\command\\MobileRecordingCosWork',
'mobile-recording:cos-migrate' => 'app\\command\\MobileRecordingCosMigrate',
'mobile-recording:cleanup' => 'app\\command\\MobileRecordingCleanup',
'followup-audio:work' => 'app\\command\\FollowupAudioWork',
'followup-audio:probe' => 'app\\command\\FollowupAudioProbe',
'followup-audio:cleanup' => 'app\\command\\FollowupAudioCleanup',
'prescription-ai:work' => 'app\\command\\PrescriptionAiWork',
'prescription-ai:backfill' => 'app\\command\\PrescriptionAiBackfill',
// 定时任务
'crontab' => 'app\common\command\Crontab',
// 退款查询
@@ -44,13 +45,13 @@ return [
'qywx:scan-media-channel' => 'app\\command\\QywxScanMediaChannel',
// 企业微信会话内容存档同步(需开通会话存档 License 并配置 msgaudit_* 相关项 + 动态库)
'qywx:sync-msg-archive' => 'app\\command\\QywxSyncMsgArchive',
// 获客助手 ChatKey 仅 30 分钟有效,部署时应每分钟执行一次
'qywx:retry-customer-acquisition-events' => 'app\\command\\QywxRetryCustomerAcquisitionEvents',
// 回调确认实际承接成员后,按权重/上限切换同一条官方获客链接的成员范围
'qywx:sync-promotion-ranges' => 'app\\command\\QywxSyncPromotionRanges',
'qywx:work-promotion-automation' => 'app\\command\\QywxWorkPromotionAutomation',
'qywx:retry-promotion-automation' => 'app\\command\\QywxRetryPromotionAutomation',
'qywx:refresh-promotion-media' => 'app\\command\\QywxRefreshPromotionMedia',
// 获客助手 ChatKey 仅 30 分钟有效,部署时应每分钟执行一次
'qywx:retry-customer-acquisition-events' => 'app\\command\\QywxRetryCustomerAcquisitionEvents',
// 回调确认实际承接成员后,按权重/上限切换同一条官方获客链接的成员范围
'qywx:sync-promotion-ranges' => 'app\\command\\QywxSyncPromotionRanges',
'qywx:work-promotion-automation' => 'app\\command\\QywxWorkPromotionAutomation',
'qywx:retry-promotion-automation' => 'app\\command\\QywxRetryPromotionAutomation',
'qywx:refresh-promotion-media' => 'app\\command\\QywxRefreshPromotionMedia',
// 甘草订单物流路由同步(GET_TASK_ROUTE_LIST)
'gancao:sync-logistics' => 'app\\command\\GancaoSyncLogisticsRoute',
'ej-pharmacy:sync-catalog' => 'app\\command\\EjPharmacySyncCatalog',
@@ -0,0 +1,26 @@
-- 药师签署验签通过后,最终双签 PDF 以私有对象归档到后台配置的腾讯云 COS(storage.qcloud)。
-- 本地私有目录仍保留原件并用于验签;上传失败不影响签署,由 esign:archive-work 每分钟重试。
SET @has_archive_key = (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'zyt_prescription_review_esign' AND COLUMN_NAME = 'archive_key'
);
SET @ddl = IF(@has_archive_key = 0, 'ALTER TABLE `zyt_prescription_review_esign`
ADD COLUMN `archive_bucket` varchar(100) NOT NULL DEFAULT '''' COMMENT ''归档 COS 桶'',
ADD COLUMN `archive_region` varchar(48) NOT NULL DEFAULT '''' COMMENT ''归档 COS 地域'',
ADD COLUMN `archive_key` varchar(200) NOT NULL DEFAULT '''' COMMENT ''归档对象键(私有,不对外返回)'',
ADD COLUMN `archive_hash` char(64) NOT NULL DEFAULT '''' COMMENT ''已归档 PDF 的 SHA-256,等于 signed_hash 即归档完成'',
ADD COLUMN `archived_at` int unsigned NOT NULL DEFAULT 0 COMMENT ''归档完成时间'',
ADD COLUMN `archive_attempts` int unsigned NOT NULL DEFAULT 0 COMMENT ''连续失败次数'',
ADD COLUMN `archive_attempted_at` int unsigned NOT NULL DEFAULT 0 COMMENT ''最近一次尝试时间'',
ADD COLUMN `archive_next_retry_at` int unsigned NOT NULL DEFAULT 0 COMMENT ''下次重试时间'',
ADD COLUMN `archive_error` varchar(255) NOT NULL DEFAULT '''' COMMENT ''最近一次失败原因'',
ADD KEY `idx_review_archive` (`state`, `archive_next_retry_at`)', 'SELECT 1');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
INSERT INTO zyt_dev_crontab
(name,type,`system`,remark,command,params,status,expression,last_time,create_time,update_time)
SELECT '已签处方归档云存储',1,1,'补传药师签署后未成功上传 COS 的处方 PDF','esign:archive-work','',1,'* * * * *',
UNIX_TIMESTAMP(),UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
WHERE NOT EXISTS (SELECT 1 FROM zyt_dev_crontab WHERE command='esign:archive-work' AND delete_time IS NULL);
+45 -1
View File
@@ -203,6 +203,8 @@ namespace {
use app\common\service\esign\PrescriptionEsignService as Service;
use app\common\service\esign\PrescriptionEsignPolicy as Policy;
use app\common\service\esign\PrescriptionReviewEsignService as Review;
use app\common\service\esign\PrescriptionEsignArchive as Archive;
use app\common\service\esign\PrescriptionEsignCos;
use app\common\service\esign\PrescriptionPdf;
use app\common\service\esign\EsignClient as Fake;
use think\facade\Db;
@@ -210,6 +212,21 @@ namespace {
$app = new think\App(); // Never initialize or load .env / real DB credentials.
$app->instance('log', new Psr\Log\NullLogger());
// Only the COS boundary is fake; archive bookkeeping and the signed-PDF read path are real.
$cos = new class extends PrescriptionEsignCos {
public array $puts = [];
public int $failures = 0;
public function location(): array { return ['bucket' => 'fixture-1250000000', 'region' => 'ap-guangzhou']; }
public function put(array $object, string $pdf): void
{
if ($this->failures > 0) {
$this->failures--;
throw new \DomainException('云存储暂不可用(HTTP 503)');
}
$this->puts[] = $object + ['sha256' => hash('sha256', $pdf), 'pdf' => $pdf];
}
};
Container::getInstance()->instance(PrescriptionEsignCos::class, $cos);
$dir = sys_get_temp_dir() . '/zyt-esign-test-' . bin2hex(random_bytes(8));
mkdir($dir, 0700);
$manager = new think\DbManager();
@@ -279,6 +296,12 @@ namespace {
}
Db::execute('CREATE UNIQUE INDEX uk_doctor ON zyt_doctor_esign_account(doctor_id,environment,app_id)');
Db::execute('ALTER TABLE zyt_prescription_esign ADD review_required INTEGER NOT NULL DEFAULT 0');
preg_match_all('/ADD COLUMN `(\w+)` (\w+)/', file_get_contents(dirname(__DIR__)
. '/database/migrations/2026_11_27_prescription_review_archive.sql'), $archiveColumns, PREG_SET_ORDER);
foreach ($archiveColumns as [, $column, $type]) {
Db::execute("ALTER TABLE zyt_prescription_review_esign ADD $column "
. ($type === 'int' ? 'INTEGER NOT NULL DEFAULT 0' : "TEXT NOT NULL DEFAULT ''"));
}
$new = static function (int $id, bool $uploaded = true): void {
Db::name('tcm_prescription')->insert([
'id' => $id, 'sn' => 'RX-TEST-' . $id, 'creator_id' => 1, 'doctor_name' => '测试医师',
@@ -1303,9 +1326,29 @@ namespace {
$throws(fn () => Review::confirm(84, 0, 23, $otherAuditor, true), 'another reviewer cannot recover or reuse the operation');
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'a provider result that is already archived must not sign again');
Fake::$failReviewVerification = false;
$cos->failures = 1;
$result = Review::confirm(84, 0, 22, $auditor, true);
$assert($result['state'] === 'signed' && $result['can_approve'] && count(Fake::$reviewCalls) === 1,
'retry verifies the archived doctor and reviewer signatures without resubmitting the PDF to the signer');
$archiveRow = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
$assert($cos->puts === [] && $archiveRow['archive_hash'] === '' && (int) $archiveRow['archive_attempts'] === 1
&& $archiveRow['archive_error'] === '云存储暂不可用(HTTP 503)'
&& (int) $archiveRow['archive_next_retry_at'] > time() && Archive::pending(10) === [],
'a COS failure keeps the signature, records the reason and backs off before the next retry');
$pendingEvents = array_column(Service::status(84, 22, $auditor)['signing_log'], null, 'event');
$assert(isset($pendingEvents['review_verified'], $pendingEvents['review_archive_pending'])
&& !isset($pendingEvents['review_archived']), 'the signing log shows the archive retry is outstanding');
Db::name('prescription_review_esign')->where('prescription_id', 84)->update(['archive_next_retry_at' => 0]);
$assert(array_map('intval', Archive::pending(10)) === [84] && Archive::upload(84), 'the archive worker retries once due');
$archiveRow = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
$assert(count($cos->puts) === 1 && $cos->puts[0]['bucket'] === 'fixture-1250000000'
&& preg_match('#^private/esign/prescription/sandbox/84-[a-f0-9]{64}\.pdf$#D', $cos->puts[0]['key']) === 1
&& $cos->puts[0]['sha256'] === $archiveRow['signed_hash']
&& $cos->puts[0]['pdf'] === file_get_contents(glob($dir . '/pdf/84-*/review-signed.pdf')[0])
&& $archiveRow['archive_hash'] === $archiveRow['signed_hash'] && $archiveRow['archive_key'] === $cos->puts[0]['key']
&& (int) $archiveRow['archive_attempts'] === 0 && $archiveRow['archive_error'] === '' && Archive::pending(10) === [],
'the exact verified dual-signed PDF is archived as a private object keyed by its hash');
$assert(Archive::upload(84) && count($cos->puts) === 1, 'an archived prescription is not uploaded again');
$listMetadata = Service::describe($reviewRow, 22);
$assert($listMetadata['review_required'] && $listMetadata['review_state'] === 'signed'
&& $listMetadata['review_signature_time'] === $result['signature_time'] && !isset($listMetadata['review_signature'])
@@ -1371,7 +1414,8 @@ namespace {
&& $events['review_signed']['time'] === $result['signature_time']
&& $events['review_signed']['actor_name'] === $result['signer_name']
&& $events['doctor_signed']['source'] === 'tsa' && $events['review_signed']['source'] === 'tsa'
&& $events['review_verified']['source'] === 'system',
&& $events['review_verified']['source'] === 'system'
&& $events['review_archived']['source'] === 'system' && !isset($events['review_archive_pending']),
'signing log preserves the two verified provider times and distinguishes system milestones');
$assert(Service::status(89, 22, $auditor)['signing_log'] === [], 'an unenrolled prescription has no fabricated events');
$reopened = PrescriptionOrderLogic::revokeRxAudit(84, 23, $otherAuditor);