修复协议状态提示与历史文件下载

This commit is contained in:
limeng 2026-09-17 11:59:08 +08:00
parent da4888ac9c
commit 3fbddfa14a
10 changed files with 395 additions and 12 deletions

View File

@ -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, '归档文件不存在。');

View File

@ -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)

View File

@ -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);
}
}

View File

@ -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);

View File

@ -0,0 +1,55 @@
<?php
namespace App\Support;
use App\Models\Business\CourierAgreementSignature;
use App\Services\Esign\EsignClient;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
final class CourierAgreementFileArchive
{
public function sourcePath(CourierAgreementSignature $signature): string
{
$path = trim((string) $signature->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;
}
}

View File

@ -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]);

View File

@ -0,0 +1,32 @@
<?php
namespace App\Support;
final class EsignErrorMessage
{
public static function sanitize(?string $message, int $limit = 240): ?string
{
$message = trim((string) preg_replace('/[[:cntrl:]]+/u', ' ', (string) $message));
if ($message === '') {
return null;
}
$message = (string) preg_replace('/(?<!\d)(1[3-9]\d)\d{4}(\d{4})(?!\d)/u', '$1****$2', $message);
$message = (string) preg_replace_callback(
'/(?<![A-Z0-9._%+\-])([A-Z0-9._%+\-]+)@([A-Z0-9.\-]+\.[A-Z]{2,})(?![A-Z0-9._%+\-])/iu',
static fn (array $matches): string => mb_substr($matches[1], 0, 1) . '***@' . $matches[2],
$message,
);
$message = (string) preg_replace('/(?<!\d)(\d{6})\d{8}(\d{3}[0-9Xx])(?!\d)/u', '$1********$2', $message);
return mb_substr($message, 0, $limit);
}
public static function isDefinitiveFailure(?string $message): bool
{
$message = (string) $message;
return preg_match('/E\s*签宝接口返回业务错误/u', $message) === 1
|| preg_match('/E\s*签宝接口请求失败(HTTP\s+4\d{2})/iu', $message) === 1;
}
}

View File

@ -162,6 +162,21 @@
color: var(--agreement-danger, #B80000);
}
.agreement-status-cell {
min-width: 13rem;
}
.agreement-error-summary {
display: block;
max-width: 24rem;
margin-top: 0.4rem;
color: var(--agreement-danger, #B80000);
font-size: 0.75rem;
line-height: 1.45;
overflow-wrap: anywhere;
white-space: normal;
}
.agreement-panel[hidden] {
display: none;
}
@ -1208,11 +1223,17 @@
<tbody>
@foreach ($agreementQuoteSignatures as $quoteSignature)
@php($quoteVersion = $quoteSignature->version)
@php($quoteError = $quoteSignature->lastErrorSummary())
<tr>
<td>{{ $quoteVersion?->version_code ?? ('报价版本 #' . $quoteSignature->quote_version_id) }}</td>
<td>{{ $quoteVersion?->carrier_name ?? $quoteSignature->organization_name }}</td>
<td>报价确认单</td>
<td><span class="agreement-status agreement-status--{{ in_array($quoteSignature->status, ['archived', 'completed'], true) ? 'success' : (in_array($quoteSignature->status, ['failed', 'rejected', 'expired', 'revoked'], true) ? 'danger' : 'warning') }}">{{ $quoteSignature->statusLabel() }}</span></td>
<td class="agreement-status-cell">
<span class="agreement-status agreement-status--{{ in_array($quoteSignature->status, ['archived', 'completed'], true) ? 'success' : (in_array($quoteSignature->status, ['failed', 'rejected', 'expired', 'revoked'], true) ? 'danger' : 'warning') }}">{{ $quoteSignature->statusLabel() }}</span>
@if ($quoteError)
<span class="agreement-error-summary" title="{{ $quoteError }}">{{ $quoteError }}</span>
@endif
</td>
<td>{{ $agreementCompanyName }}</td>
<td>{{ optional($quoteSignature->updated_at)->format('Y-m-d H:i') }}</td>
<td class="agreement-table-actions">
@ -1235,11 +1256,18 @@
</tr>
@endforeach
@foreach ($agreementTasks as $task)
@php($taskError = $task->lastErrorSummary())
@php($taskFailed = $task->status === 'failed' || ($task->status === 'unknown' && $task->hasDefinitiveFailure()))
<tr>
<td>{{ $task->business_no }}</td>
<td>{{ $task->courier_name }}</td>
<td>{{ $task->documentLabel() }}</td>
<td><span class="agreement-status agreement-status--{{ in_array($task->status, ['archived', 'completed'], true) ? 'success' : (in_array($task->status, ['failed', 'rejected', 'expired', 'revoked'], true) ? 'danger' : 'warning') }}">{{ $task->statusLabel() }}</span></td>
<td class="agreement-status-cell">
<span class="agreement-status agreement-status--{{ in_array($task->status, ['archived', 'completed'], true) ? 'success' : ($taskFailed || in_array($task->status, ['rejected', 'expired', 'revoked'], true) ? 'danger' : 'warning') }}">{{ $task->statusLabel() }}</span>
@if ($taskError)
<span class="agreement-error-summary" title="{{ $taskError }}">{{ $taskError }}</span>
@endif
</td>
<td>{{ $task->initiatorName() }}</td>
<td>{{ optional($task->updated_at)->format('Y-m-d H:i') }}</td>
<td class="agreement-table-actions">

View File

@ -114,6 +114,56 @@ class AgreementSigningPageTest extends FeatureTestCase
->assertDontSee('<td>张经理</td>', 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();

View File

@ -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));
}
}