fix: 供应商合作合同正文及附件乙方盖章设为必签 #1391

Closed
limeng wants to merge 2 commits from fix/limeng-supplier-required-seals into main
8 changed files with 179 additions and 6 deletions

View File

@ -273,6 +273,20 @@ final class EsignClient
]],
];
if (! empty($signer['signing_positions'])) {
$payload['signFields'] = array_map(static fn (array $position): array => [
'fileId' => $fileId,
'mustSign' => true,
'normalSignFieldConfig' => [
'freeMode' => false,
'movableSignField' => false,
'signFieldStyle' => 1,
'signFieldSize' => '120',
'signFieldPosition' => $position,
],
], $signer['signing_positions']);
}
if ($type === 0) {
$payload['psnSignerInfo'] = [
'psnAccount' => $signer['operator_account'],

View File

@ -4,6 +4,7 @@ namespace App\Support;
use App\Models\Business\CourierAgreementSignature;
use DOMDocument;
use DOMElement;
use DOMXPath;
use Dompdf\FrameReflower\Text;
use Illuminate\Support\Carbon;
@ -12,6 +13,12 @@ use RuntimeException;
final class CourierAgreementPdf
{
public function render(CourierAgreementSignature $signature): string
{
return $this->renderForSigning($signature)['bytes'];
}
/** Return positions from the same render as the uploaded PDF, so pagination cannot drift. */
public function renderForSigning(CourierAgreementSignature $signature): array
{
$payload = $signature->payload ?? [];
$signatureDate = (string) ($payload['signature_date'] ?? $payload['entity_proof_date'] ?? $payload['shared_proof_date'] ?? '');
@ -34,6 +41,30 @@ final class CourierAgreementPdf
$pdf->setPaper('a4', 'portrait');
$pdf->loadHTML($html, 'UTF-8');
$this->applyLatinFont($pdf->getDomPDF()->getDom());
$positions = [];
$callbacks = [];
foreach ($pdf->getDomPDF()->getCallbacks() as $event => $handlers) {
foreach ($handlers as $handler) {
$callbacks[] = ['event' => $event, 'f' => $handler];
}
}
if ($supplierContract) {
$pdf->getDomPDF()->setCallbacks([...$callbacks, [
'event' => 'end_frame',
'f' => static function ($frame, $canvas) use (&$positions): void {
$node = $frame->get_node();
if (! $node instanceof DOMElement || $node->getAttribute('data-supplier-signature-party') !== 'b') {
return;
}
$box = $frame->get_position();
$positions[] = [
'positionPage' => (string) $canvas->get_page_number(),
'positionX' => round($box['x'] + $frame->get_margin_width() / 2, 2),
'positionY' => round($canvas->get_height() - $box['y'] - $frame->get_margin_height() / 2, 2),
];
},
]]);
}
// Dompdf otherwise treats uninterrupted Chinese text as one word,
// moving a whole clause to the next line after its Latin number.
$wordBreakPattern = Text::$_wordbreak_pattern;
@ -42,13 +73,18 @@ final class CourierAgreementPdf
$bytes = $pdf->output();
} finally {
Text::$_wordbreak_pattern = $wordBreakPattern;
$pdf->getDomPDF()->setCallbacks($callbacks);
}
if (! is_string($bytes) || ! str_starts_with($bytes, '%PDF-')) {
throw new RuntimeException('协议 PDF 生成失败。');
}
return $bytes;
if ($supplierContract && count($positions) !== 1 + app(SupplierCooperationTemplates::class)->metadata($payload['supplier_contract_template'])['attachments']) {
throw new RuntimeException('供应商合同的必签盖章位置不完整,未推送,请检查合同模板。');
}
return ['bytes' => $bytes, 'signing_positions' => $positions];
}
private function applyLatinFont(DOMDocument $document): void

View File

@ -32,6 +32,7 @@ final class CourierAgreementSignatureService
}
$payload = is_array($data['payload'] ?? null) ? $data['payload'] : $data;
unset($payload['supplier_signing_positions']);
$payload['authorization_items'] = array_values(array_map('strval', $data['authorization_items'] ?? []));
$idempotencyKey = 'agreement-' . hash('sha256', $companyId . '|' . (string) ($data['idempotency_key'] ?? ''));
$businessNo = 'AGR-' . strtoupper(substr(hash('sha256', $idempotencyKey), 0, 20));
@ -98,7 +99,11 @@ final class CourierAgreementSignatureService
$signature->payload = $storedPayload;
$signature->save();
}
$bytes = $this->pdf->render($signature);
$rendered = $this->pdf->renderForSigning($signature);
$bytes = $rendered['bytes'];
if ($rendered['signing_positions'] !== []) {
$signature->payload = [...$signature->payload, 'supplier_signing_positions' => $rendered['signing_positions']];
}
$signature->source_pdf_sha256 = hash('sha256', $bytes);
if (! Storage::disk('uploads')->put($signature->source_pdf_path, $bytes)) {
throw new RuntimeException('协议 PDF 无法写入私有业务存储。');
@ -396,11 +401,20 @@ final class CourierAgreementSignatureService
if ($signature->document_type === 'cooperation-contract') {
$counterpartyIsPerson = ($payload['counterparty_signer_type'] ?? 'organization') === 'person';
$positions = [];
if (app(SupplierCooperationTemplates::class)->isSupplierContract($signature)) {
$positions = $payload['supplier_signing_positions'] ?? [];
$expected = 1 + app(SupplierCooperationTemplates::class)->metadata($payload['supplier_contract_template'])['attachments'];
if (count($positions) !== $expected) {
throw new RuntimeException('旧任务缺少必签盖章位置,请重新发起供应商合作合同。');
}
}
return [[
'signer_type' => $counterpartyIsPerson ? 0 : 1,
'organization_name' => $counterpartyIsPerson ? null : ($payload['cooperation_party_b_name'] ?? $signature->courier_name),
'operator_name' => $signature->operator_name,
'operator_account' => $signature->operator_account,
'signing_positions' => $positions,
]];
}

View File

@ -79,7 +79,7 @@
.supplier-contract-signatures { width: 100%; table-layout: fixed; margin: 18px 0; }
.supplier-contract-signatures td { width: 50%; vertical-align: top; padding: 8px; }
.supplier-contract-signatures p { margin: 0 0 8px; }
.supplier-contract-seal-space { height: 85px; }
.supplier-contract-seal-space { height: 128px; }
.supplier-contract-image { margin: 12px 0; text-align: center; }
.supplier-contract-image img { max-width: 100%; height: auto; }

View File

@ -13,7 +13,7 @@
<p>{{ $label }}:{!! $supplierTemplates->text('[[party_' . $party . ']]', $supplierValues, $supplierPreview) !!}</p>
<p>授权代表:{!! $supplierTemplates->text('[[party_' . $party . '_signer]]', $supplierValues, $supplierPreview) !!}</p>
<p>签字/盖章:</p>
<div class="supplier-contract-seal-space"></div>
<div class="supplier-contract-seal-space" data-supplier-signature-party="{{ $party }}"></div>
<p>合同签订日期:{!! $supplierTemplates->text('[[signature_date]]', $supplierValues, $supplierPreview) !!}</p>
</td>
@endforeach

View File

@ -19,7 +19,7 @@
.supplier-contract-signatures { width: 100%; table-layout: fixed; page-break-inside: avoid; margin: 18px 0; }
.supplier-contract-signatures td { width: 50%; vertical-align: top; padding: 8px; }
.supplier-contract-signatures p { margin: 0 0 8px; }
.supplier-contract-seal-space { height: 85px; }
.supplier-contract-seal-space { height: 128px; }
.meta { color: #595959; font-size: 9px; text-align: right; margin-bottom: 14px; }
</style>
</head>

View File

@ -233,15 +233,35 @@ class CourierAgreementSignatureWorkflowTest extends FeatureTestCase
$source = Storage::disk('uploads')->get($signature->source_pdf_path);
$this->assertStringStartsWith('%PDF-', $source);
$this->assertSame(hash('sha256', $source), $signature->source_pdf_sha256);
Http::assertSent(function (ClientRequest $request): bool {
$positions = $signature->payload['supplier_signing_positions'];
$this->assertCount(1 + $metadata['attachments'], $positions);
Http::assertSent(function (ClientRequest $request) use ($positions): bool {
if ($request->url() !== 'https://smlopenapi.esign.test/v3/sign-flow/create-by-file') return false;
$signers = $request->data()['signers'] ?? [];
$fixedFields = array_values(array_filter($signers[0]['signFields'], static fn (array $field): bool => data_get($field, 'normalSignFieldConfig.signFieldStyle') === 1));
$this->assertCount(count($positions), $fixedFields);
$this->assertCount(count($positions) + 1, $signers[0]['signFields']);
foreach ($fixedFields as $index => $field) {
$this->assertTrue($field['mustSign']);
$this->assertFalse($field['normalSignFieldConfig']['freeMode']);
$this->assertFalse($field['normalSignFieldConfig']['movableSignField']);
$this->assertSame($positions[$index], $field['normalSignFieldConfig']['signFieldPosition']);
}
$this->assertSame(2, data_get($signers[0]['signFields'], count($positions) . '.normalSignFieldConfig.signFieldStyle'));
return count($signers) === 1
&& data_get($signers, '0.signConfig.signOrder') === 1
&& data_get($signers, '0.orgSignerInfo.orgName') === '测试供应商有限公司'
&& data_get($signers, '0.orgSignerInfo.transactorInfo.psnAccount') === '13800138000'
&& data_get($signers, '0.orgSignerInfo.transactorInfo.psnInfo.psnName') === '张经理';
});
$again = app(\App\Support\CourierAgreementSignatureService::class)->send([
'document_type' => 'cooperation-contract', 'partner_type' => 'supplier',
'supplier_contract_template' => $template, 'idempotency_key' => $payload['idempotency_key'],
'payload' => ['supplier_signing_positions' => [['positionPage' => '1']]],
], $this->user->id);
$this->assertSame($signature->id, $again->id);
$this->assertSame($positions, $again->payload['supplier_signing_positions']);
$this->assertCount(1, Http::recorded(fn (ClientRequest $request) => str_ends_with($request->url(), '/create-by-file')));
Http::swap(new \Illuminate\Http\Client\Factory());
Http::fake([
'https://smlopenapi.esign.test/v3/sign-flow/flow-agreement-001/detail' => Http::response(['code' => 0, 'data' => ['signFlowStatus' => 2]]),
@ -255,6 +275,34 @@ class CourierAgreementSignatureWorkflowTest extends FeatureTestCase
$this->assertSame($source, Storage::disk('uploads')->get($archived->source_pdf_path));
}
public function test_legacy_supplier_retry_without_fixed_positions_stops_before_any_remote_request(): void
{
Http::preventStrayRequests();
$key = 'legacy-supplier-no-fixed-fields';
$task = CourierAgreementSignature::create([
'company_id' => $this->company->id, 'business_no' => 'AGR-LEGACY-SUPPLIER',
'idempotency_key' => 'agreement-' . hash('sha256', $this->company->id . '|' . $key),
'document_type' => 'cooperation-contract', 'template_code' => 'TPL-SUPPLIER-DROPSHIPPING-V1',
'template_version' => '1', 'source_file_name' => '产品代发协议', 'status' => 'failed',
'courier_name' => '示例供应商', 'organization_name' => '示例供应商有限公司',
'company_full_name' => $this->company->name, 'source_pdf_path' => 'legacy/source.pdf',
'source_pdf_sha256' => hash('sha256', '%PDF-legacy'), 'environment' => 'sandbox',
'payload' => ['partner_type' => 'supplier', 'supplier_contract_template' => 'dropshipping'],
'created_by' => $this->user->id, 'updated_by' => $this->user->id,
]);
try {
app(\App\Support\CourierAgreementSignatureService::class)->send([
'document_type' => 'cooperation-contract', 'partner_type' => 'supplier',
'supplier_contract_template' => 'dropshipping', 'idempotency_key' => $key,
], $this->user->id);
$this->fail('A legacy document must not fall back to free signing.');
} catch (\Illuminate\Validation\ValidationException $exception) {
$this->assertStringContainsString('旧任务缺少必签盖章位置', $exception->getMessage());
$this->assertSame('failed', $task->fresh()->status);
}
Http::assertNothingSent();
}
public static function supplierTemplateProvider(): array
{
return [['dropshipping'], ['consignment'], ['production']];

View File

@ -0,0 +1,61 @@
<?php
namespace Tests\Unit;
use App\Models\Business\CourierAgreementSignature;
use App\Support\CourierAgreementPdf;
use App\Support\SupplierCooperationTemplates;
use DOMElement;
use Illuminate\Foundation\Testing\TestCase;
use Tests\CreatesApplication;
class SupplierContractSigningPositionsTest extends TestCase
{
use CreatesApplication;
/** @dataProvider templates */
public function test_every_body_and_appendix_seal_tracks_its_actual_rendered_counterparty_box(string $template, bool $longValues): void
{
$metadata = SupplierCooperationTemplates::TEMPLATES[$template];
$payload = [
'partner_type' => 'supplier', 'supplier_contract_template' => $template,
'cooperation_party_a_name' => '示例甲方有限公司',
'cooperation_party_b_name' => $longValues ? str_repeat('较长企业名称', 12) : '示例乙方有限公司',
'signature_date' => '2026-10-01',
'supplier_contract_fields' => ['number' => 'SUP-FIXED-SEALS', 'location' => '常州市武进区',
'party_b_address' => $longValues ? str_repeat('较长的地址内容', 30) : '示例地址'],
];
$signature = new CourierAgreementSignature(['document_type' => 'cooperation-contract',
'business_no' => 'AGR-POSITIONS', 'template_code' => $metadata['code'], 'payload' => $payload]);
$pdf = app('dompdf.wrapper');
$this->app->instance('dompdf.wrapper', $pdf);
$boxes = [];
$pdf->getDomPDF()->setCallbacks([['event' => 'end_frame', 'f' => static function ($frame, $canvas) use (&$boxes): void {
$node = $frame->get_node();
if ($node instanceof DOMElement && $node->getAttribute('data-supplier-signature-party') === 'b') {
$boxes[] = ['page' => $canvas->get_page_number(), 'box' => $frame->get_position(),
'width' => $frame->get_margin_width(), 'height' => $frame->get_margin_height()];
}
}]]);
$rendered = app(CourierAgreementPdf::class)->renderForSigning($signature);
$this->assertStringStartsWith('%PDF-', $rendered['bytes']);
$this->assertCount(1 + $metadata['attachments'], $rendered['signing_positions']);
$this->assertCount(count($rendered['signing_positions']), $boxes);
foreach ($rendered['signing_positions'] as $index => $position) {
$box = $boxes[$index];
$this->assertSame((string) $box['page'], $position['positionPage']);
$this->assertGreaterThan(90, $box['height'], 'A full 120px seal needs enough vertical clearance.');
$this->assertGreaterThan(300, $position['positionX'], 'Only the counterparty column receives signing fields.');
$this->assertEqualsWithDelta($box['box']['x'] + $box['width'] / 2, $position['positionX'], 0.01);
$this->assertEqualsWithDelta($pdf->getDomPDF()->getCanvas()->get_height() - $box['box']['y'] - $box['height'] / 2, $position['positionY'], 0.01);
$this->assertGreaterThan(48, $position['positionY']);
$this->assertLessThan(790, $position['positionY']);
}
$this->app->forgetInstance('dompdf.wrapper');
}
public static function templates(): array
{
return [['dropshipping', false], ['consignment', false], ['production', false], ['dropshipping', true]];
}
}