fix: 报价签署使用真实合同主体并支持个人签署 (#1251)

This commit is contained in:
limeng 2026-11-18 18:24:40 +08:00
parent 301caa112d
commit 8277d066e8
11 changed files with 163 additions and 25 deletions

View File

@ -118,6 +118,8 @@ class CourierQuoteChanges extends Controller
$reviewAllowed = $this->canReview($quoteChange);
$quoteWorkflow = app(CourierQuoteWorkflowPermissions::class)->settings();
$canManageSignature = $this->canAdminister() || $reviewAllowed;
$signingDetails = $canManageSignature && $onboarding === null && $quoteChange->version?->signature?->canSend()
? $this->signingDetailsFor($quoteChange->version) : [];
return view('business.pages.courier-payables.quote-change-show', [
'change' => $quoteChange,
@ -136,9 +138,8 @@ class CourierQuoteChanges extends Controller
'canManageSignature' => $canManageSignature,
'canCorrectPeriods' => $reviewAllowed && !$quoteChange->isStockQuote()
&& app(\App\Support\CourierQuotePeriodCorrection::class)->available($quoteChange),
'quoteSigningAccount' => $canManageSignature && $onboarding === null && $quoteChange->version?->signature?->canSend()
&& blank($quoteChange->version->signature->operator_account)
? $this->signingAccountFor($quoteChange->version) : '',
'quoteSigningAccount' => $signingDetails['account'] ?? '',
'quoteSigningParty' => $signingDetails['party_b'] ?? '',
'canVoidQuote' => $this->canAdminister(),
'quoteWorkflow' => $quoteWorkflow,
'esignConfigured' => EsignClient::configured(),
@ -146,23 +147,26 @@ class CourierQuoteChanges extends Controller
]);
}
private function signingAccountFor(CourierQuoteVersion $version): string
private function signingDetailsFor(CourierQuoteVersion $version): array
{
try {
$row = app(CourierInformationMirrorRepository::class)->signingAccountSource(
(string) $version->courier_expcode, (string) $version->carrier_name,
);
if ($row === null) {
return '';
return [];
}
$profiles = app(CourierProfileData::class);
$row = $profiles->apply($row, $profiles->overrides([(string) $row->expcode])[(string) $row->expcode] ?? []);
return trim((string) ($row->dzqzjbr ?? ''));
return [
'account' => trim((string) ($row->dzqzjbr ?? '')),
'party_b' => trim((string) ($row->tradebody ?? '')),
];
} catch (Throwable $exception) {
report($exception);
return '';
return [];
}
}

View File

@ -27,11 +27,13 @@ class CourierQuoteSignatures extends Controller
abort_unless($quoteVersion->status === 'approved', 422, '只有已审核报价版本可以生成签署文件。');
$data = $request->validate([
'signature_date' => ['required', 'date'],
'organization_name' => ['nullable', 'string', 'min:2', 'max:255'],
]);
$signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date']);
$signature = $this->service->prepareVersion($quoteVersion, user_id(), $data['signature_date'], null, $data['organization_name'] ?? null);
return redirect()->route('business.courier-quote-changes.show', $quoteVersion->source_change_id)
->with('success', "{$quoteVersion->version_code} 的签署 PDF 已生成,文件校验值已固定。")
->withInput($request->only(['signer_type', 'organization_name', 'operator_account', 'notice_type', 'signature_date', 'expires_at']))
->with('signature_id', $signature->id);
}
@ -41,6 +43,7 @@ class CourierQuoteSignatures extends Controller
abort_unless($quoteSignature->version?->status === 'approved', 422, '只有已审核报价版本可以发起签署。');
abort_unless(EsignClient::configured(), 422, 'E 签宝沙箱尚未配置 App ID 或 AppSecret。');
$data = $request->validate([
'signer_type' => ['nullable', 'in:organization,person'],
'organization_name' => ['required', 'string', 'min:2', 'max:255'],
'signing_subject' => ['nullable', 'string', 'min:2', 'max:255'],
'operator_name' => ['nullable', 'string', 'min:2', 'max:100'],
@ -55,6 +58,7 @@ class CourierQuoteSignatures extends Controller
user_id(),
$data['signature_date'],
$data['signing_subject'] ?? null,
$data['organization_name'],
);
$signature = $this->service->send($quoteSignature, $data, user_id());
$environment = $signature->environment === 'sandbox' ? '沙箱' : '正式环境';

View File

@ -373,7 +373,7 @@ class CourierOnboardingService
}
$quoteSignatures = app(CourierQuoteSignatureService::class);
$signature = $quoteSignatures->prepareVersion($version, $userId, today()->toDateString());
$signature = $quoteSignatures->prepareVersion($version, $userId, today()->toDateString(), null, (string) $onboarding->company_full_name);
$signature = $quoteSignatures->send($signature, [
'signer_type' => $onboarding->isPerson() ? 'person' : 'organization',
'organization_name' => (string) $onboarding->company_full_name,

View File

@ -2,11 +2,38 @@
namespace App\Support;
use App\Models\Business\CourierOnboarding;
use App\Models\Business\CourierQuoteVersion;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use Throwable;
final class CourierQuoteConfirmation
{
public function data(CourierQuoteVersion $version, ?string $signingSubject = null): array
public function counterpartyName(CourierQuoteVersion $version): string
{
$onboardings = CourierOnboarding::query()
->whereIn('status', [CourierOnboarding::STATUS_APPROVED, CourierOnboarding::STATUS_ACTIVATED])
->where(filled($version->courier_expcode) ? 'workplatform_expcode' : 'courier_name',
filled($version->courier_expcode) ? $version->courier_expcode : $version->carrier_name)
->limit(2)->get(['company_full_name']);
if ($onboardings->count() === 1 && filled($onboardings->first()->company_full_name)) {
return trim((string) $onboardings->first()->company_full_name);
}
try {
$row = app(CourierInformationMirrorRepository::class)->signingAccountSource(
(string) $version->courier_expcode, (string) $version->carrier_name,
);
return trim((string) ($row->tradebody ?? ''));
} catch (Throwable $exception) {
report($exception);
return '';
}
}
public function data(CourierQuoteVersion $version, ?string $signingSubject = null, ?string $counterpartyName = null): array
{
$partyA = trim((string) $signingSubject) ?: trim((string) config('services.esign.default_initiator'));
$version->loadMissing(['change']);
@ -42,7 +69,7 @@ final class CourierQuoteConfirmation
'version_id' => $version->id,
'version_code' => $version->version_code,
'party_a' => $partyA ?: (company((int) $version->company_id)?->name ?: '当前公司'),
'party_b' => $version->carrier_name,
'party_b' => $counterpartyName === null ? $this->counterpartyName($version) : trim($counterpartyName),
'carrier_name' => $version->carrier_name,
'quote_type' => $version->quote_type,
'effective_date' => $version->effective_date?->toDateString(),

View File

@ -12,9 +12,9 @@ final class CourierQuotePdf
{
}
public function render(CourierQuoteVersion $version, ?string $signatureDate = null, ?string $signingSubject = null): string
public function render(CourierQuoteVersion $version, ?string $signatureDate = null, ?string $signingSubject = null, ?string $counterpartyName = null): string
{
$data = $this->confirmation->data($version, $signingSubject);
$data = $this->confirmation->data($version, $signingSubject, $counterpartyName);
$signatureDate = Carbon::parse($signatureDate ?: now())->format('Y年n月j日');
$html = view('business.pdf.courier-quote', [
'version' => $version,
@ -22,6 +22,7 @@ final class CourierQuotePdf
'values' => $data['values'],
'formulas' => $data['formulas'],
'partyA' => $data['party_a'],
'partyB' => $data['party_b'],
'expiryDate' => $data['expiry_date'],
'temporaryNote' => $data['temporary_note'] ?? null,
'billingRules' => $data['billing_rules'],

View File

@ -19,14 +19,14 @@ final class CourierQuoteSignatureService
{
}
public function prepareVersion(CourierQuoteVersion $version, int $userId, ?string $signatureDate = null, ?string $signingSubject = null): CourierQuoteSignature
public function prepareVersion(CourierQuoteVersion $version, int $userId, ?string $signatureDate = null, ?string $signingSubject = null, ?string $counterpartyName = null): CourierQuoteSignature
{
return DB::transaction(function () use ($version, $userId, $signatureDate, $signingSubject): CourierQuoteSignature {
return DB::transaction(function () use ($version, $userId, $signatureDate, $signingSubject, $counterpartyName): CourierQuoteSignature {
$version = CourierQuoteVersion::query()->disableCache()->lockForUpdate()->findOrFail($version->id);
$existing = CourierQuoteSignature::query()->disableCache()
->where('quote_version_id', $version->id)->lockForUpdate()->first();
if ($signatureDate === null && $signingSubject === null && $existing && $this->sourcePdfIsIntact($existing)) {
if ($signatureDate === null && $signingSubject === null && $counterpartyName === null && $existing && $this->sourcePdfIsIntact($existing)) {
return $existing;
}
@ -44,7 +44,8 @@ final class CourierQuoteSignatureService
}
}
$bytes = $this->pdf->render($version, $signatureDate, $signingSubject);
$counterpartyName = trim($counterpartyName ?? app(CourierQuoteConfirmation::class)->counterpartyName($version));
$bytes = $this->pdf->render($version, $signatureDate, $signingSubject, $counterpartyName);
// Every attempt owns its files, including PDFs regenerated before sending.
$path = $this->path($version, Str::uuid() . '/source.pdf');
$sha256 = hash('sha256', $bytes);
@ -61,7 +62,7 @@ final class CourierQuoteSignatureService
'provider' => 'esign',
'environment' => (string) config('services.esign.environment', 'sandbox'),
'status' => CourierQuoteSignature::STATUS_PREPARED,
'organization_name' => $version->carrier_name,
'organization_name' => $counterpartyName,
'source_pdf_path' => $path,
'source_pdf_sha256' => $sha256,
'source_pdf_generated_at' => now(),
@ -118,7 +119,8 @@ final class CourierQuoteSignatureService
$locked->update([
'status' => CourierQuoteSignature::STATUS_SENDING,
'organization_name' => $data['organization_name'],
'operator_name' => $data['operator_name'] ?? null,
'operator_name' => ($data['signer_type'] ?? 'organization') === 'person'
? $data['organization_name'] : ($data['operator_name'] ?? null),
'operator_account' => $data['operator_account'],
'notice_types' => (string) $data['notice_type'],
'expires_at' => Carbon::parse($data['expires_at']),

View File

@ -319,7 +319,7 @@ class CourierInformationMirrorRepository
}
$rows = $this->connection->table($this->dataset()->targetTable())
->select(['expcode', 'dzqzjbr'])
->select(['expcode', 'dzqzjbr', 'tradebody'])
->where($code !== '' ? 'expcode' : 'expname', $code !== '' ? $code : $name)
->where(static fn (Builder $query) => $query->whereNull('is_delete')->orWhere('is_delete', '<>', 1))
->limit(2)

View File

@ -204,7 +204,7 @@
<div><dt>运行环境</dt><dd>{{ $esignEnvironment==='sandbox'?'沙箱环境':'正式环境' }}</dd></div>
<div><dt>原文校验值</dt><dd title="{{ $quoteSignature->source_pdf_sha256 }}">{{ substr($quoteSignature->source_pdf_sha256,0,16) }}…</dd></div>
<div><dt>最近同步</dt><dd>{{ $quoteSignature->last_synced_at?->format('Y-m-d H:i') ?? '尚未同步' }}</dd></div>
<div><dt>签署企业</dt><dd>{{ $quoteSignature->organization_name }}</dd></div>
<div><dt>乙方签约主体</dt><dd>{{ $quoteSignature->organization_name ?: '尚未填写' }}</dd></div>
<div><dt>签署账号</dt><dd>{{ $quoteSignature->operator_account ?: '尚未填写' }}</dd></div>
<div><dt>签署流程</dt><dd>{{ $quoteSignature->esign_sign_flow_id ?: '尚未创建' }}</dd></div>
<div><dt>归档时间</dt><dd>{{ $quoteSignature->archived_at?->format('Y-m-d H:i') ?? '尚未归档' }}</dd></div>
@ -219,16 +219,19 @@
@if($canManageSignature && $quoteSignature->canSend() && !$onboarding && !$change->version->isVoided())
@php($signatureAccount=old('operator_account',$quoteSignature->operator_account ?: ($quoteSigningAccount ?? '')))
@php($signatureNoticeType=(string)old('notice_type',filter_var($signatureAccount,FILTER_VALIDATE_EMAIL) ? '2' : '1'))
@php($signatureParty=$quoteSignature->organization_name !== $change->version->carrier_name ? $quoteSignature->organization_name : '')
<form class="quote-review__form" method="POST" action="{{ route('business.courier-quote-signatures.send',$quoteSignature) }}">@csrf
<div class="quote-review__form-grid">
<div class="quote-review__field"><label for="organization_name">签署企业全称</label><input class="quote-review__control" id="organization_name" name="organization_name" value="{{ old('organization_name',$quoteSignature->organization_name) }}" maxlength="255" required></div>
<div class="quote-review__field"><label for="signer_type">乙方签署身份</label><select class="quote-review__control" id="signer_type" name="signer_type" required><option value="">请选择签署身份</option><option value="organization" @selected(old('signer_type')==='organization')>企业签署</option><option value="person" @selected(old('signer_type')==='person')>个人签署</option></select></div>
<div class="quote-review__field"><label for="organization_name">乙方签约主体(企业全称或个人姓名)</label><input class="quote-review__control" id="organization_name" name="organization_name" value="{{ old('organization_name',$signatureParty ?: ($quoteSigningParty ?? '')) }}" maxlength="255" required></div>
<div class="quote-review__field"><label for="operator_account">e签宝签署账号(手机号或邮箱)</label><input class="quote-review__control" id="operator_account" name="operator_account" value="{{ $signatureAccount }}" maxlength="255" placeholder="快递公司签署人员的手机号或邮箱" aria-describedby="quote-signer-account-hint" required></div>
<div class="quote-review__field"><label for="signature_date">签署日期</label><input class="quote-review__control" id="signature_date" name="signature_date" type="date" value="{{ old('signature_date',now()->toDateString()) }}" required></div>
<div class="quote-review__field"><label for="expires_at">签署截止时间</label><input class="quote-review__control" id="expires_at" name="expires_at" type="datetime-local" value="{{ old('expires_at',now()->addDays(7)->format('Y-m-d\TH:i')) }}" required></div>
</div>
<p class="quote-review__hint" id="quote-signer-account-hint" style="margin:10px 0 0">账号默认取自快递资料的“电子签章经办人”,可手动修改;资料未维护时请补填。企业与账号须已完成 e签宝实名认证,系统自动核验,无需填写姓名;手机号选择短信通知,邮箱选择邮件通知。</p>
<p class="quote-review__hint" id="quote-signer-account-hint" style="margin:10px 0 0">乙方默认取自快递资料的合同主体,请按实际签约方选择企业或个人;生成原文和推送使用同一主体。账号默认取自快递资料的“电子签章经办人”,可手动修改;资料未维护时请补填。企业签署自动核验经办人,无需填写姓名;个人签署使用上方乙方姓名。手机号选择短信通知,邮箱选择邮件通知。</p>
<div class="quote-review__form-actions">
<div class="quote-review__choice" role="radiogroup" aria-label="通知方式"><label><input type="radio" name="notice_type" value="1" {{ $signatureNoticeType==='1'?'checked':'' }}>短信</label><label><input type="radio" name="notice_type" value="2" {{ $signatureNoticeType==='2'?'checked':'' }}>邮件</label></div>
<button class="quote-review__button" type="submit" formaction="{{ route('business.courier-quote-signatures.prepare',$change->version) }}"><span class="material-icons-outlined" aria-hidden="true">picture_as_pdf</span><span>更新签署原文</span></button>
<button class="quote-review__button quote-review__button--primary" type="submit" @disabled(!$esignConfigured)><span class="material-icons-outlined" aria-hidden="true">send</span><span>推送到 E 签宝</span></button>
</div>
@if(!$esignConfigured)<div class="quote-review__hint" role="status" style="margin-top:8px">E 签宝沙箱配置缺失,当前不能创建签署流程。</div>@endif

View File

@ -82,7 +82,7 @@
<tbody>
<tr>
<th>甲方</th><td>{!! $mixedText($partyA) !!}</td>
<th>乙方</th><td>{!! $mixedText($version->carrier_name) !!}</td>
<th>乙方</th><td>{!! $mixedText(($partyB ?? '') ?: '待填写签约主体') !!}</td>
<th>报价类型</th><td>{!! $mixedText($version->quote_type) !!}</td>
</tr>
<tr>

View File

@ -92,6 +92,102 @@ class CourierQuoteSignatureWorkflowTest extends FeatureTestCase
$this->assertStringNotContainsString($this->company->name, $rendered);
}
public function test_pdf_party_b_uses_the_unique_contract_subject_instead_of_the_courier_display_name(): void
{
$version = $this->createVersion();
$version->update(['courier_expcode' => 'EXP-QUOTE']);
$mirror = \Mockery::mock(CourierInformationMirrorRepository::class);
$mirror->shouldReceive('signingAccountSource')->once()->with('EXP-QUOTE', '新北中通')
->andReturn((object) ['tradebody' => '示例签约有限公司']);
$this->app->instance(CourierInformationMirrorRepository::class, $mirror);
$text = [];
$pdf = app('dompdf.wrapper');
$pdf->getDomPDF()->setCallbacks([['event' => 'end_frame', 'f' => static function ($frame) use (&$text): void {
if ($frame instanceof \Dompdf\FrameDecorator\Text) $text[] = $frame->get_text();
}]]);
app()->instance('dompdf.wrapper', $pdf);
$signature = app(CourierQuoteSignatureService::class)->prepareVersion($version, $this->user->id);
$this->assertSame('示例签约有限公司', $signature->organization_name);
$rendered = preg_replace('/\s+/u', '', implode('', $text));
$this->assertStringContainsString('乙方示例签约有限公司', $rendered);
$this->assertStringNotContainsString('乙方新北中通', $rendered);
$this->assertSame($version->values_json, $version->fresh()->values_json);
}
public function test_missing_contract_subject_is_not_replaced_with_the_courier_display_name(): void
{
$version = $this->createVersion();
$mirror = \Mockery::mock(CourierInformationMirrorRepository::class);
$mirror->shouldReceive('signingAccountSource')->once()->andReturn(null);
$this->app->instance(CourierInformationMirrorRepository::class, $mirror);
$signature = app(CourierQuoteSignatureService::class)->prepareVersion($version, $this->user->id);
$this->assertSame('', $signature->organization_name);
}
public function test_failed_legacy_task_prefills_the_contract_subject_and_can_update_the_pdf_without_sending(): void
{
Http::preventStrayRequests();
$signature = $this->createPreparedSignature(['status' => 'failed']);
$oldPath = $signature->source_pdf_path;
$mirror = \Mockery::mock(CourierInformationMirrorRepository::class);
$mirror->shouldReceive('signingAccountSource')->once()->andReturn((object) [
'expcode' => 'EXP-QUOTE', 'tradebody' => '示例个人', 'dzqzjbr' => '13800138000',
]);
$this->app->instance(CourierInformationMirrorRepository::class, $mirror);
$html = $this->loginAs()->get(route('business.courier-quote-changes.show', $signature->version->source_change_id))
->assertOk()->assertSee('更新签署原文')->assertSee('个人签署')->getContent();
$this->assertStringContainsString('name="organization_name" value="示例个人"', $html);
$this->post(route('business.courier-quote-signatures.prepare', $signature->version), [
'signature_date' => now()->toDateString(), 'organization_name' => '示例个人',
])->assertSessionHasNoErrors()->assertRedirect();
$signature->refresh();
$this->assertSame('示例个人', $signature->organization_name);
$this->assertSame('prepared', $signature->status);
$this->assertNotSame($oldPath, $signature->source_pdf_path);
Storage::disk('uploads')->assertExists($oldPath);
$this->assertNull($signature->esign_sign_flow_id);
Http::assertNothingSent();
}
public function test_personal_quote_signing_uses_the_same_person_in_the_pdf_and_signer_without_enterprise_lookup(): void
{
Http::preventStrayRequests();
$signature = $this->createPreparedSignature();
Http::fake([
'https://smlopenapi.esign.test/v3/files/file-upload-url' => Http::response(['code' => 0, 'data' => ['fileId' => 'file-person', 'fileUploadUrl' => 'https://upload.esign.test/file-person']]),
'https://upload.esign.test/file-person' => Http::response(['errCode' => 0]),
'https://smlopenapi.esign.test/v3/files/file-person' => Http::response(['code' => 0, 'data' => ['status' => 2]]),
'https://smlopenapi.esign.test/v3/sign-flow/create-by-file' => Http::response(['code' => 0, 'data' => ['signFlowId' => 'flow-person']]),
]);
$text = [];
$pdf = app('dompdf.wrapper');
$pdf->getDomPDF()->setCallbacks([['event' => 'end_frame', 'f' => static function ($frame) use (&$text): void {
if ($frame instanceof \Dompdf\FrameDecorator\Text) $text[] = $frame->get_text();
}]]);
app()->instance('dompdf.wrapper', $pdf);
$this->loginAs()->post(route('business.courier-quote-signatures.send', $signature), [
'signer_type' => 'person', 'organization_name' => '示例个人', 'operator_name' => '其他经办人',
'operator_account' => '13800138000', 'notice_type' => '1', 'signature_date' => now()->toDateString(),
'expires_at' => now()->addDays(7)->toDateTimeString(),
])->assertSessionHasNoErrors()->assertRedirect();
$this->assertSame('signing', $signature->fresh()->status);
$this->assertSame('示例个人', $signature->fresh()->organization_name);
$this->assertStringContainsString('乙方示例个人', preg_replace('/\s+/u', '', implode('', $text)));
Http::assertNotSent(fn (ClientRequest $request) => str_contains($request->url(), '/identity-info'));
Http::assertSent(fn (ClientRequest $request) => str_ends_with($request->url(), '/sign-flow/create-by-file')
&& $request['signers'][0]['signerType'] === 0
&& data_get($request['signers'][0], 'psnSignerInfo.psnInfo.psnName') === '示例个人'
&& data_get($request['signers'][0], 'orgSignerInfo') === null);
}
public function test_signature_pdf_contains_only_approved_prices_in_horizontal_weight_columns(): void
{
$version = $this->createVersion();

View File

@ -129,11 +129,12 @@ class CourierInformationMirrorRepositoryTest extends TestCase
{
$this->markReady(4);
$this->insertExpress(1, ['expcode' => 'EXP-A', 'expname' => '同名快递', 'dzqzjbr' => '13800000001']);
$this->insertExpress(2, ['expcode' => 'EXP-B', 'expname' => '同名快递', 'dzqzjbr' => '13800000002']);
$this->insertExpress(2, ['expcode' => 'EXP-B', 'expname' => '同名快递', 'dzqzjbr' => '13800000002', 'tradebody' => '示例签约有限公司']);
$this->insertExpress(3, ['expcode' => 'EXP-C', 'expname' => '唯一快递', 'dzqzjbr' => 'courier@example.com']);
$this->insertExpress(4, ['expcode' => 'EXP-D', 'expname' => '唯一快递', 'dzqzjbr' => 'deleted@example.com', 'is_delete' => 1]);
$this->assertSame('13800000002', $this->repository->signingAccountSource('EXP-B', '旧名称')->dzqzjbr);
$this->assertSame('示例签约有限公司', $this->repository->signingAccountSource('EXP-B', '旧名称')->tradebody);
$this->assertSame('courier@example.com', $this->repository->signingAccountSource('', '唯一快递')->dzqzjbr);
$this->assertNull($this->repository->signingAccountSource('', '同名快递'));
$this->assertNull($this->repository->signingAccountSource('EXP-D', '唯一快递'));