From 3fbddfa14a20f6d4ec3b53518ca206ccb338a497 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Thu, 17 Sep 2026 11:59:08 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8D=8F=E8=AE=AE=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E6=8F=90=E7=A4=BA=E4=B8=8E=E5=8E=86=E5=8F=B2=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=B8=8B=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Business/CourierAgreementSignatures.php | 27 ++- .../Business/CourierAgreementSignature.php | 13 +- app/Models/Business/CourierQuoteSignature.php | 6 + app/Services/Esign/EsignClient.php | 14 ++ app/Support/CourierAgreementFileArchive.php | 55 ++++++ .../CourierAgreementSignatureService.php | 11 +- app/Support/EsignErrorMessage.php | 32 ++++ .../agreement-signing.blade.php | 32 +++- .../Business/AgreementSigningPageTest.php | 50 ++++++ .../CourierAgreementSignatureWorkflowTest.php | 167 ++++++++++++++++++ 10 files changed, 395 insertions(+), 12 deletions(-) create mode 100644 app/Support/CourierAgreementFileArchive.php create mode 100644 app/Support/EsignErrorMessage.php diff --git a/app/Http/Controllers/Business/CourierAgreementSignatures.php b/app/Http/Controllers/Business/CourierAgreementSignatures.php index 6d65dbbe..b6e27238 100644 --- a/app/Http/Controllers/Business/CourierAgreementSignatures.php +++ b/app/Http/Controllers/Business/CourierAgreementSignatures.php @@ -7,6 +7,7 @@ use App\Models\Business\CourierQuoteSignature; use App\Models\Business\CourierQuoteVersion; use App\Models\Business\CourierSigningSubject; use App\Services\Esign\EsignClient; +use App\Support\CourierAgreementFileArchive; use App\Support\CourierAgreementSignatureService; use App\Support\CourierQuoteConfirmation; use App\Support\CourierQuoteSignatureService; @@ -18,6 +19,7 @@ use Illuminate\Routing\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; +use RuntimeException; use Symfony\Component\HttpFoundation\StreamedResponse; class CourierAgreementSignatures extends Controller @@ -28,6 +30,7 @@ class CourierAgreementSignatures extends Controller private readonly CourierAgreementSignatureService $service, private readonly CourierQuoteSignatureService $quoteSignatureService, private readonly CourierQuoteConfirmation $quoteConfirmation, + private readonly CourierAgreementFileArchive $agreementFileArchive, ) { } @@ -205,15 +208,25 @@ class CourierAgreementSignatures extends Controller ->with('success', "{$signature->documentLabel()}已人工确认并归档。"); } - public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse + public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse|RedirectResponse { $this->ensureCanManage(); - [$path, $suffix] = match ($kind) { - 'source' => [$agreementSignature->source_pdf_path, '签署原文'], - 'signed' => [$agreementSignature->signed_pdf_path, '已签署协议'], - 'certificate' => [$agreementSignature->certificate_path, '签署完成证书'], - default => abort(404), - }; + try { + [$path, $suffix] = match ($kind) { + 'source' => [$this->agreementFileArchive->sourcePath($agreementSignature), '签署原文'], + 'signed' => [$agreementSignature->signed_pdf_path, '已签署协议'], + 'certificate' => [$agreementSignature->certificate_path, '签署完成证书'], + default => abort(404), + }; + } catch (RuntimeException $exception) { + return redirect() + ->route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'agreement-signing', + 'agreement_view' => 'tasks', + ]) + ->with('error', $exception->getMessage()); + } abort_if(blank($path) || ! \Storage::disk('uploads')->exists($path), 404, '归档文件不存在。'); diff --git a/app/Models/Business/CourierAgreementSignature.php b/app/Models/Business/CourierAgreementSignature.php index 8087cced..59190e8a 100644 --- a/app/Models/Business/CourierAgreementSignature.php +++ b/app/Models/Business/CourierAgreementSignature.php @@ -3,6 +3,7 @@ namespace App\Models\Business; use App\Abstracts\Model; +use App\Support\EsignErrorMessage; class CourierAgreementSignature extends Model { @@ -97,11 +98,21 @@ class CourierAgreementSignature extends Model self::STATUS_EXPIRED => '已过期', self::STATUS_REJECTED => '已拒签', self::STATUS_FAILED => '处理失败', - self::STATUS_UNKNOWN => '状态未知,请人工核对', + self::STATUS_UNKNOWN => $this->hasDefinitiveFailure() ? '处理失败' : '状态未知,请人工核对', default => $this->status, }; } + public function hasDefinitiveFailure(): bool + { + return EsignErrorMessage::isDefinitiveFailure($this->last_error); + } + + public function lastErrorSummary(): ?string + { + return EsignErrorMessage::sanitize($this->last_error); + } + public function canSend(): bool { return in_array($this->status, [self::STATUS_PREPARED, self::STATUS_FAILED], true) diff --git a/app/Models/Business/CourierQuoteSignature.php b/app/Models/Business/CourierQuoteSignature.php index 09474c94..9c8b5b91 100644 --- a/app/Models/Business/CourierQuoteSignature.php +++ b/app/Models/Business/CourierQuoteSignature.php @@ -3,6 +3,7 @@ namespace App\Models\Business; use App\Abstracts\Model; +use App\Support\EsignErrorMessage; use Illuminate\Database\Eloquent\Relations\BelongsTo; class CourierQuoteSignature extends Model @@ -65,4 +66,9 @@ class CourierQuoteSignature extends Model return in_array($this->status, [self::STATUS_PREPARED, self::STATUS_FAILED], true) && blank($this->esign_sign_flow_id); } + + public function lastErrorSummary(): ?string + { + return EsignErrorMessage::sanitize($this->last_error); + } } diff --git a/app/Services/Esign/EsignClient.php b/app/Services/Esign/EsignClient.php index 0f64f3be..8b99694a 100644 --- a/app/Services/Esign/EsignClient.php +++ b/app/Services/Esign/EsignClient.php @@ -184,6 +184,20 @@ final class EsignClient ]); } + public function downloadUploadedPdf(string $fileId): string + { + $data = $this->request('GET', "/v3/files/{$fileId}"); + $downloadUrl = (string) ($data['fileDownloadUrl'] + ?? $data['downloadUrl'] + ?? data_get($data, 'files.0.downloadUrl', '')); + + if ($downloadUrl === '') { + throw new RuntimeException('E 签宝未返回历史原文件下载地址。'); + } + + return $this->download($downloadUrl); + } + public function download(string $url): string { $response = Http::timeout($this->timeout())->get($url); diff --git a/app/Support/CourierAgreementFileArchive.php b/app/Support/CourierAgreementFileArchive.php new file mode 100644 index 00000000..a31150d1 --- /dev/null +++ b/app/Support/CourierAgreementFileArchive.php @@ -0,0 +1,55 @@ +source_pdf_path); + if ($path === '') { + throw new RuntimeException('该历史任务没有保存签署原文路径,无法下载。'); + } + + $disk = Storage::disk('uploads'); + if ($disk->exists($path)) { + return $path; + } + + if (blank($signature->esign_file_id)) { + throw new RuntimeException('本地历史文件缺失,且该任务未成功上传至 E 签宝,无法自动恢复。'); + } + + $expectedHash = strtolower(trim((string) $signature->source_pdf_sha256)); + if (preg_match('/^[a-f0-9]{64}$/', $expectedHash) !== 1) { + throw new RuntimeException('本地历史文件缺失,且没有可用于校验的原文件摘要,已停止自动恢复。'); + } + + $bytes = app(EsignClient::class)->downloadUploadedPdf((string) $signature->esign_file_id); + if (! str_starts_with($bytes, '%PDF-')) { + throw new RuntimeException('E 签宝返回的历史原文件不是有效 PDF,已停止自动恢复。'); + } + + if (! hash_equals($expectedHash, hash('sha256', $bytes))) { + throw new RuntimeException('E 签宝历史原文件与系统留存摘要不一致,已停止自动恢复。'); + } + + if (! $disk->put($path, $bytes)) { + throw new RuntimeException('历史原文件无法写回私有业务存储。'); + } + + $storedBytes = $disk->get($path); + if (! str_starts_with($storedBytes, '%PDF-') + || ! hash_equals($expectedHash, hash('sha256', $storedBytes))) { + $disk->delete($path); + throw new RuntimeException('历史原文件写回后校验失败,已移除不完整文件。'); + } + + return $path; + } +} diff --git a/app/Support/CourierAgreementSignatureService.php b/app/Support/CourierAgreementSignatureService.php index 37987323..49149f11 100644 --- a/app/Support/CourierAgreementSignatureService.php +++ b/app/Support/CourierAgreementSignatureService.php @@ -96,6 +96,10 @@ final class CourierAgreementSignatureService $bytes = Storage::disk('uploads')->get($signature->source_pdf_path); $fileName = 'agreement-' . $signature->business_no . '.pdf'; $fileId = $client->uploadPdf($bytes, $fileName); + $signature->update([ + 'esign_file_id' => $fileId, + 'updated_by' => $userId, + ]); $signer = [ 'flow_title' => $this->safeTitle($signature->company_full_name . ' ' . $signature->documentLabel()), 'organization_name' => $signature->organization_name, @@ -120,9 +124,12 @@ final class CourierAgreementSignatureService return $signature->fresh(); } catch (Throwable $exception) { + $error = EsignErrorMessage::sanitize($exception->getMessage(), 1000) ?? 'E 签宝处理失败。'; $signature->update([ - 'status' => $flowCreationStarted ? CourierAgreementSignature::STATUS_UNKNOWN : CourierAgreementSignature::STATUS_FAILED, - 'last_error' => mb_substr((string) preg_replace('/[[:cntrl:]]+/u', ' ', $exception->getMessage()), 0, 1000), + 'status' => $flowCreationStarted && ! EsignErrorMessage::isDefinitiveFailure($exception->getMessage()) + ? CourierAgreementSignature::STATUS_UNKNOWN + : CourierAgreementSignature::STATUS_FAILED, + 'last_error' => $error, 'updated_by' => $userId, ]); throw ValidationException::withMessages(['signature' => $signature->last_error]); diff --git a/app/Support/EsignErrorMessage.php b/app/Support/EsignErrorMessage.php new file mode 100644 index 00000000..0796ef48 --- /dev/null +++ b/app/Support/EsignErrorMessage.php @@ -0,0 +1,32 @@ + mb_substr($matches[1], 0, 1) . '***@' . $matches[2], + $message, + ); + $message = (string) preg_replace('/(? @foreach ($agreementQuoteSignatures as $quoteSignature) @php($quoteVersion = $quoteSignature->version) + @php($quoteError = $quoteSignature->lastErrorSummary()) {{ $quoteVersion?->version_code ?? ('报价版本 #' . $quoteSignature->quote_version_id) }} {{ $quoteVersion?->carrier_name ?? $quoteSignature->organization_name }} 报价确认单 - {{ $quoteSignature->statusLabel() }} + + {{ $quoteSignature->statusLabel() }} + @if ($quoteError) + {{ $quoteError }} + @endif + {{ $agreementCompanyName }} {{ optional($quoteSignature->updated_at)->format('Y-m-d H:i') }} @@ -1235,11 +1256,18 @@ @endforeach @foreach ($agreementTasks as $task) + @php($taskError = $task->lastErrorSummary()) + @php($taskFailed = $task->status === 'failed' || ($task->status === 'unknown' && $task->hasDefinitiveFailure())) {{ $task->business_no }} {{ $task->courier_name }} {{ $task->documentLabel() }} - {{ $task->statusLabel() }} + + {{ $task->statusLabel() }} + @if ($taskError) + {{ $taskError }} + @endif + {{ $task->initiatorName() }} {{ optional($task->updated_at)->format('Y-m-d H:i') }} diff --git a/tests/Feature/Business/AgreementSigningPageTest.php b/tests/Feature/Business/AgreementSigningPageTest.php index 53eb80d1..19f871c7 100644 --- a/tests/Feature/Business/AgreementSigningPageTest.php +++ b/tests/Feature/Business/AgreementSigningPageTest.php @@ -114,6 +114,56 @@ class AgreementSigningPageTest extends FeatureTestCase ->assertDontSee('张经理', false); } + public function testAgreementSigningPageDistinguishesDefinitiveFailureFromUnknownResult(): void + { + $this->grantWorkspaceAccess(); + + foreach ([ + [ + 'business_no' => 'AGR-DEFINITIVE-FAILURE', + 'last_error' => 'E 签宝接口返回业务错误(1435002):签署账号 18810726376 与身份信息不一致', + ], + [ + 'business_no' => 'AGR-UNKNOWN-RESULT', + 'last_error' => '创建签署流程时连接超时,无法确认远端结果。', + ], + ] as $index => $error) { + CourierAgreementSignature::create([ + 'company_id' => $this->company->id, + 'business_no' => $error['business_no'], + 'idempotency_key' => 'status-display-' . $index, + 'document_type' => 'authorization', + 'template_code' => 'TPL-AUTHORIZATION-V1', + 'template_version' => '1', + 'source_file_name' => '授权委托书(快递).docx', + 'status' => CourierAgreementSignature::STATUS_UNKNOWN, + 'courier_name' => '测试快递', + 'company_full_name' => $this->company->name, + 'organization_name' => '测试快递有限公司', + 'operator_name' => '测试人员', + 'operator_account' => '18810726376', + 'payload' => ['signing_subject' => $this->company->name], + 'environment' => 'production', + 'source_pdf_path' => "courier-agreements/status-{$index}/source.pdf", + 'source_pdf_sha256' => hash('sha256', '%PDF-source-' . $index), + 'last_error' => $error['last_error'], + 'created_by' => $this->user->id, + 'updated_by' => $this->user->id, + ]); + } + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'agreement-signing', + ])) + ->assertOk() + ->assertSeeText('处理失败') + ->assertSeeText('状态未知,请人工核对') + ->assertSeeText('E 签宝接口返回业务错误(1435002):签署账号 188****6376 与身份信息不一致') + ->assertDontSee('签署账号 18810726376', false); + } + public function testAgreementSigningPageKeepsRenderingWhenLegacyPayloadCannotBeDecrypted(): void { $this->grantWorkspaceAccess(); diff --git a/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php b/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php index f0035d1e..652075cc 100644 --- a/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php +++ b/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php @@ -369,6 +369,148 @@ class CourierAgreementSignatureWorkflowTest extends FeatureTestCase $this->assertNull($result->certificate_sha256); } + public function test_source_download_uses_existing_local_history_file_without_remote_request(): void + { + Http::fake(); + $bytes = '%PDF-local-history'; + $signature = $this->agreementSignature([ + 'source_pdf_sha256' => hash('sha256', $bytes), + ]); + Storage::disk('uploads')->put($signature->source_pdf_path, $bytes); + + $this->loginAs() + ->get(route('business.courier-agreement-signatures.download', [$signature, 'source'])) + ->assertOk() + ->assertDownload(); + + Http::assertNothingSent(); + } + + public function test_source_download_restores_missing_history_file_from_esign_after_hash_verification(): void + { + $bytes = '%PDF-remote-history'; + $signature = $this->agreementSignature([ + 'source_pdf_sha256' => hash('sha256', $bytes), + 'esign_file_id' => 'file-history-001', + ]); + Http::fake([ + 'https://smlopenapi.esign.test/v3/files/file-history-001' => Http::response([ + 'code' => 0, + 'data' => ['fileDownloadUrl' => 'https://download.esign.test/source-history-001'], + ]), + 'https://download.esign.test/source-history-001' => Http::response($bytes), + ]); + + $this->loginAs() + ->get(route('business.courier-agreement-signatures.download', [$signature, 'source'])) + ->assertOk() + ->assertDownload(); + + Storage::disk('uploads')->assertExists($signature->source_pdf_path); + $this->assertSame($bytes, Storage::disk('uploads')->get($signature->source_pdf_path)); + Http::assertSentCount(2); + } + + public function test_source_download_rejects_remote_history_file_when_hash_does_not_match(): void + { + $signature = $this->agreementSignature([ + 'source_pdf_sha256' => hash('sha256', '%PDF-expected-history'), + 'esign_file_id' => 'file-history-mismatch', + ]); + Http::fake([ + 'https://smlopenapi.esign.test/v3/files/file-history-mismatch' => Http::response([ + 'code' => 0, + 'data' => ['downloadUrl' => 'https://download.esign.test/source-history-mismatch'], + ]), + 'https://download.esign.test/source-history-mismatch' => Http::response('%PDF-different-history'), + ]); + + $this->withExceptionHandling()->loginAs() + ->get(route('business.courier-agreement-signatures.download', [$signature, 'source'])) + ->assertRedirect(route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'agreement-signing', + 'agreement_view' => 'tasks', + ])) + ->assertSessionHas('error', 'E 签宝历史原文件与系统留存摘要不一致,已停止自动恢复。'); + + Storage::disk('uploads')->assertMissing($signature->source_pdf_path); + } + + public function test_source_download_explains_when_missing_history_was_never_uploaded(): void + { + $signature = $this->agreementSignature(); + + $this->withExceptionHandling()->loginAs() + ->get(route('business.courier-agreement-signatures.download', [$signature, 'source'])) + ->assertRedirect(route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'agreement-signing', + 'agreement_view' => 'tasks', + ])) + ->assertSessionHas('error', '本地历史文件缺失,且该任务未成功上传至 E 签宝,无法自动恢复。'); + } + + public function test_esign_business_error_is_saved_as_failed_and_preserves_uploaded_file_id(): void + { + Http::fake(function (ClientRequest $request) { + return match (true) { + $request->url() === 'https://smlopenapi.esign.test/v3/files/file-upload-url' => Http::response([ + 'code' => 0, + 'data' => ['fileId' => 'file-business-error', 'fileUploadUrl' => 'https://upload.esign.test/business-error'], + ]), + $request->url() === 'https://upload.esign.test/business-error' => Http::response(['ok' => true]), + $request->url() === 'https://smlopenapi.esign.test/v3/files/file-business-error' => Http::response([ + 'code' => 0, + 'data' => ['status' => 2], + ]), + $request->url() === 'https://smlopenapi.esign.test/v3/sign-flow/create-by-file' => Http::response([ + 'code' => 1435002, + 'message' => '签署账号 18810726376 与身份信息不一致', + ]), + default => Http::response(['code' => 404], 404), + }; + }); + + $this->withExceptionHandling()->loginAs() + ->post(route('business.courier-agreement-signatures.store'), $this->accountProofPayload('business-error')) + ->assertSessionHasErrors('signature'); + + $signature = CourierAgreementSignature::query()->firstOrFail(); + $this->assertSame(CourierAgreementSignature::STATUS_FAILED, $signature->status); + $this->assertSame('file-business-error', $signature->esign_file_id); + $this->assertStringContainsString('1435002', $signature->last_error); + $this->assertStringContainsString('188****6376', $signature->last_error); + $this->assertStringNotContainsString('18810726376', $signature->last_error); + } + + public function test_server_error_during_flow_creation_keeps_unknown_status(): void + { + Http::fake(function (ClientRequest $request) { + return match (true) { + $request->url() === 'https://smlopenapi.esign.test/v3/files/file-upload-url' => Http::response([ + 'code' => 0, + 'data' => ['fileId' => 'file-server-error', 'fileUploadUrl' => 'https://upload.esign.test/server-error'], + ]), + $request->url() === 'https://upload.esign.test/server-error' => Http::response(['ok' => true]), + $request->url() === 'https://smlopenapi.esign.test/v3/files/file-server-error' => Http::response([ + 'code' => 0, + 'data' => ['status' => 2], + ]), + $request->url() === 'https://smlopenapi.esign.test/v3/sign-flow/create-by-file' => Http::response([], 500), + default => Http::response(['code' => 404], 404), + }; + }); + + $this->withExceptionHandling()->loginAs() + ->post(route('business.courier-agreement-signatures.store'), $this->accountProofPayload('server-error')) + ->assertSessionHasErrors('signature'); + + $signature = CourierAgreementSignature::query()->firstOrFail(); + $this->assertSame(CourierAgreementSignature::STATUS_UNKNOWN, $signature->status); + $this->assertSame('file-server-error', $signature->esign_file_id); + } + private function fakeEsign(): void { Http::fake(function (ClientRequest $request) { @@ -409,4 +551,29 @@ class CourierAgreementSignatureWorkflowTest extends FeatureTestCase 'account_proof_bank_account' => '6222000012345678', ]; } + + private function agreementSignature(array $attributes = []): CourierAgreementSignature + { + return CourierAgreementSignature::create(array_merge([ + 'company_id' => $this->company->id, + 'business_no' => 'AGR-DOWNLOAD-HISTORY-001', + 'idempotency_key' => 'download-history-001', + 'document_type' => 'account-proof', + 'template_code' => 'TPL-ACCOUNT-CERT-V2', + 'template_version' => '2', + 'source_file_name' => '收款账户证明文件.doc', + 'status' => CourierAgreementSignature::STATUS_FAILED, + 'courier_name' => '测试快递', + 'company_full_name' => $this->company->name, + 'organization_name' => '测试快递有限公司', + 'operator_name' => '测试人员', + 'operator_account' => '13800138000', + 'payload' => ['signing_subject' => $this->company->name], + 'environment' => 'sandbox', + 'source_pdf_path' => 'courier-agreements/history/source.pdf', + 'source_pdf_sha256' => hash('sha256', '%PDF-history-source'), + 'created_by' => $this->user->id, + 'updated_by' => $this->user->id, + ], $attributes)); + } }