CaiWuXiTong/app/Support/CourierQuoteSignatureService.php
limeng 71652c5a64 feat(快递入驻): 快递扫码填写入驻资料 + 两级审核 + 首版报价 + 签署开通
快递应付 → 快递报价 下新增「快递入驻」页:生成入驻二维码发给快递方,
对方免登录在手机上填写主体、联系人、e签宝签署人、结算账户、报价并上传资质,
内部对接人初审、管理员财务复审后生成首版报价,并自动生成报价确认单 PDF
推送到快递填写的 e签宝账号,签署归档后开通。

- 新增三张表 business_courier_onboardings / _files / _events(纯新增,不改旧表)
- 免登录填报页 /onboarding/courier/{token}:40 位随机 token,可暂存、提交、退回后补件,
  链接有效期可延长、可作废;银行账号加密存储;附件存 uploads 盘
- 新增 COURIER_ONBOARDING_PUBLIC_URL 配置二维码里的站点地址(留空用当前访问地址)
- 内置纯 PHP 二维码生成(App\Support\QrCode,SVG 输出,无新增依赖)
- 生成二维码时必须定好系统快递名称(唯一,快递方不可见);财务复审沿用该名称,快递所填报价写成报价管理的 CourierQuoteVersion,
  复用 CourierQuoteSignatureService 生成报价确认单并推送 e签宝(失败可重推/同步状态);初审人默认不能复审(COURIER_ONBOARDING_ALLOW_SAME_REVIEWER=true 可在测试环境放开)
- 支持公司 / 个人两种入驻:个人填姓名+身份证号(加密)、传身份证和银行卡,报价确认单按个人身份在 e签宝签署
- 扫码先选入驻方式;证件改为 营业执照 / 法人身份证正反面 / 银行卡正反面 各一张(个人营业执照选填),手机端上传前自动压缩,超限回到填报页提示
- 报价支持 4 种计费方式(面单+费率 / 首重+续重 / 按重量段一口价 / 小重量一口价+超出另算,费率可分段)+「其他」上传报价表;附加规则:计泡、起算重量、取整、每票加收(CourierQuoteStructure)
- 不再要求上传盖章报价单,至少填写一行在线报价
- 开通:报价确认单签署归档、或匹配到已签署协议、或填写线下签署说明
- 生成二维码前必填「快递公司代码」(自动大写、不可重复),入驻信息按代码对齐快递资料
- 公司入驻对公(营业执照主体)+ 对私(法定代表人)两个打款账户必填并自动核对;个人入驻对私必填、对公选填
- 变价:报价管理里后台改价 → 审核 → 自动推送快递 e签宝 → 回签;回签单导出 xlsx/zip;误发版本可作废
- 短期(临时)变价:变价单/报价版本加选填「结束日期」(end_date);按日期取价,期间用临时价,到期次日自动恢复原长期报价,
  不用重签;报价管理显示 生效中(临时)/ 暂停中 / 已到期,确认单写明执行期间和到期后恢复的版本,审核提醒期间重叠
- 快递资料分四类:快递资料 / 网点 / 打款信息 / 操作日志,支持查询、导出、重置、编辑;
  财务系统入驻的快递直接作为快递资料行,合同起止取协议签署里已签署的合作合同;
  点开一行在下方看该快递的网点 / 打款信息(完整账号)/ 操作日志
- 编辑存财务系统覆盖值(business_courier_profiles,不回写工作平台),改动记操作日志(business_courier_profile_events)
- 打款信息新增 / 变更(business_courier_payment_accounts,账号加密)保存后跳到协议签署,自动预填收款账户证明 / 收款账户变更,
  按签署状态显示 待推送协议 / 签署中 / 已生效;入口在快递资料明细和「打款信息」页签(表格每个账户可直接「变更」)
- ERP 开通:入驻开通后标「待 ERP 开通」,可手动补录(钉钉「新建快递」流程同步待接入)
- 新增 CourierOnboardingWorkflowTest(8 个用例),更新快递报价目录顺序断言

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019gzfsnV3fJ89CoUy1D9V9g
2026-10-14 13:47:00 +08:00

383 lines
16 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support;
use App\Models\Business\CourierQuoteSignature;
use App\Models\Business\CourierQuoteVersion;
use App\Services\Esign\EsignClient;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use RuntimeException;
use Throwable;
final class CourierQuoteSignatureService
{
public function __construct(private readonly CourierQuotePdf $pdf)
{
}
public function prepareVersion(CourierQuoteVersion $version, int $userId, ?string $signatureDate = null): CourierQuoteSignature
{
if (CourierQuoteSignature::onlyTrashed()->where('quote_version_id', $version->id)->exists()) {
throw ValidationException::withMessages(['signature' => '该报价版本的签署任务已删除,请使用新报价版本发起新的签署任务。']);
}
$existing = $version->signature;
if ($signatureDate === null && $existing && $this->sourcePdfIsIntact($existing)) {
return $existing;
}
if ($existing && ! $existing->canSend()) {
throw ValidationException::withMessages([
'signature' => '该报价已经进入签署流程,签署原文不可重新生成。',
]);
}
$bytes = $this->pdf->render($version, $signatureDate);
$path = $this->path($version, 'source.pdf');
$sha256 = hash('sha256', $bytes);
if (! Storage::disk('uploads')->put($path, $bytes)) {
throw new RuntimeException('报价 PDF 无法写入私有业务存储。');
}
$signature = CourierQuoteSignature::updateOrCreate(
['company_id' => $version->company_id, 'quote_version_id' => $version->id],
[
'provider' => 'esign',
'environment' => (string) config('services.esign.environment', 'sandbox'),
'status' => CourierQuoteSignature::STATUS_PREPARED,
'organization_name' => $version->carrier_name,
'source_pdf_path' => $path,
'source_pdf_sha256' => $sha256,
'source_pdf_generated_at' => now(),
'last_error' => null,
'created_by' => $existing?->created_by ?? $userId,
'updated_by' => $userId,
],
);
$this->updateVersionStatus($signature, $signature->statusLabel());
return $signature->fresh('version');
}
public function send(CourierQuoteSignature $signature, array $data, int $userId): CourierQuoteSignature
{
$signature = DB::transaction(function () use ($signature, $data, $userId): CourierQuoteSignature {
$locked = CourierQuoteSignature::query()->lockForUpdate()->findOrFail($signature->id);
if (! $locked->canSend()) {
throw ValidationException::withMessages(['signature' => '当前报价版本已经进入签署流程,不能重复推送。']);
}
if (! $this->sourcePdfIsIntact($locked)) {
throw ValidationException::withMessages(['signature' => '待签报价 PDF 缺失或校验不一致,请重新生成后再推送。']);
}
$locked->update([
'status' => CourierQuoteSignature::STATUS_SENDING,
'organization_name' => $data['organization_name'],
'operator_name' => $data['operator_name'],
'operator_account' => $data['operator_account'],
'notice_types' => (string) $data['notice_type'],
'expires_at' => Carbon::parse($data['expires_at']),
'last_error' => null,
'updated_by' => $userId,
]);
return $locked->fresh('version');
});
$this->updateVersionStatus($signature, '推送中');
try {
$client = app(EsignClient::class);
$bytes = Storage::disk('uploads')->get($signature->source_pdf_path);
$fileName = 'quote-' . $signature->version->version_code . '.pdf';
$fileId = $client->uploadPdf($bytes, $fileName);
$signer = [
'flow_title' => $signature->version->carrier_name . ' ' . $signature->version->version_code . ' 报价确认',
'organization_name' => $signature->organization_name,
'operator_name' => $signature->operator_name,
'operator_account' => $signature->operator_account,
'notice_types' => $signature->notice_types,
];
if (($data['signer_type'] ?? 'organization') === 'person') {
// 个人快递以本人身份签署,不走企业经办人。
$signer['signers'] = [[
'signer_type' => 0,
'operator_name' => $signature->operator_name,
'operator_account' => $signature->operator_account,
'notice_types' => $signature->notice_types,
]];
}
$signFlowId = $client->createSignFlow($fileId, $fileName, $signer, $signature->expires_at->getTimestampMs());
$signature->update([
'status' => CourierQuoteSignature::STATUS_SIGNING,
'esign_file_id' => $fileId,
'esign_sign_flow_id' => $signFlowId,
'remote_status' => '1',
'sent_at' => now(),
'last_synced_at' => now(),
'last_error' => null,
'updated_by' => $userId,
]);
$this->updateVersionStatus($signature, '待签署');
return $signature->fresh('version');
} catch (Throwable $exception) {
$signature->update([
'status' => CourierQuoteSignature::STATUS_FAILED,
'last_error' => $this->safeError($exception),
'updated_by' => $userId,
]);
$this->updateVersionStatus($signature, '推送失败');
throw ValidationException::withMessages(['signature' => $signature->last_error]);
}
}
public function synchronize(CourierQuoteSignature $signature, int $userId): CourierQuoteSignature
{
if (blank($signature->esign_sign_flow_id)) {
throw ValidationException::withMessages(['signature' => '该报价版本尚未创建 E 签宝签署流程。']);
}
if ($signature->status === CourierQuoteSignature::STATUS_ARCHIVED) {
return $signature;
}
// 同一份确认单同时只查一次:几个页面同时打开时,避免后到的查询把已归档的状态又写回「签署完成,待归档」。
$lock = \Illuminate\Support\Facades\Cache::lock('esign-quote-sync-' . $signature->id, 120);
if (! $lock->get()) {
return $signature->fresh() ?? $signature;
}
try {
$signature = $signature->fresh() ?? $signature;
if ($signature->status === CourierQuoteSignature::STATUS_ARCHIVED) {
return $signature;
}
return $this->synchronizeUnlocked($signature, $userId);
} finally {
$lock->release();
}
}
private function synchronizeUnlocked(CourierQuoteSignature $signature, int $userId): CourierQuoteSignature
{
try {
$client = app(EsignClient::class);
$detail = $client->signFlowDetail($signature->esign_sign_flow_id);
$remoteStatus = (string) ($detail['signFlowStatus'] ?? $detail['status'] ?? '');
if ($remoteStatus === '') {
throw new RuntimeException('E 签宝未返回签署流程状态。');
}
$signature = $this->applyRemoteStatus($signature, $remoteStatus, $userId);
return $remoteStatus === '2' ? $this->archive($signature, $client, $userId) : $signature;
} catch (Throwable $exception) {
$signature->update([
'last_error' => $this->safeError($exception),
'last_synced_at' => now(),
'updated_by' => $userId,
]);
throw ValidationException::withMessages(['signature' => $signature->last_error]);
}
}
/**
* 打开报价页面时顺手查一下还在签署中的报价确认单(未开启定时轮询、回调又到不了本系统时,
* 签完能尽快显示「已签署并归档」)。每次最多查几条,距上次查询不足 $minAgeSeconds 秒的跳过,失败不影响页面。
*/
public function refreshPending(int $limit = 5, int $minAgeSeconds = 60): int
{
if (! EsignClient::configured() || ! \Illuminate\Support\Facades\Schema::hasTable('business_courier_quote_signatures')) {
return 0;
}
// 已归档但版本上的文字状态没跟上的,补成「已签署并归档」。
$archivedVersionIds = CourierQuoteSignature::query()
->where('status', CourierQuoteSignature::STATUS_ARCHIVED)
->pluck('quote_version_id');
if ($archivedVersionIds->isNotEmpty()) {
CourierQuoteVersion::query()
->whereIn('id', $archivedVersionIds->all())
->where('signature_status', '<>', '已签署并归档')
->update(['signature_status' => '已签署并归档']);
}
$environment = strtolower(trim((string) config('services.esign.environment', 'sandbox')));
$cutoff = now()->subSeconds($minAgeSeconds);
$pending = CourierQuoteSignature::query()
->where('environment', $environment)
->whereNotNull('esign_sign_flow_id')
->where('esign_sign_flow_id', '<>', '')
->whereIn('status', [CourierQuoteSignature::STATUS_SIGNING, CourierQuoteSignature::STATUS_COMPLETED])
->where(fn ($query) => $query->whereNull('last_synced_at')->orWhere('last_synced_at', '<=', $cutoff))
->orderBy('last_synced_at')
->limit($limit)
->get();
$refreshed = 0;
foreach ($pending as $signature) {
try {
$this->synchronize($signature, (int) ($signature->updated_by ?: $signature->created_by));
$refreshed++;
} catch (Throwable) {
// 查询失败已记在 last_error,页面照常显示,可手动「同步签署状态」。
}
}
return $refreshed;
}
public function synchronizeById(int $signatureId): void
{
$signature = CourierQuoteSignature::allCompanies()->find($signatureId);
if (! $signature) {
return;
}
$this->synchronize($signature, $signature->updated_by);
}
public function acceptCallback(string $signFlowId, string $remoteStatus, string $payloadHash): ?CourierQuoteSignature
{
return DB::transaction(function () use ($signFlowId, $remoteStatus, $payloadHash): ?CourierQuoteSignature {
$signature = CourierQuoteSignature::allCompanies()
->where('esign_sign_flow_id', $signFlowId)
->lockForUpdate()
->first();
if (! $signature) {
return null;
}
if ($signature->callback_payload_hash === $payloadHash) {
return null;
}
$signature->callback_payload_hash = $payloadHash;
return $this->applyRemoteStatus($signature, $remoteStatus, $signature->updated_by);
});
}
public function sourcePdfIsIntact(CourierQuoteSignature $signature): bool
{
if (blank($signature->source_pdf_path) || blank($signature->source_pdf_sha256)) {
return false;
}
$disk = Storage::disk('uploads');
return $disk->exists($signature->source_pdf_path)
&& hash_equals($signature->source_pdf_sha256, hash('sha256', $disk->get($signature->source_pdf_path)));
}
private function applyRemoteStatus(CourierQuoteSignature $signature, string $remoteStatus, int $userId): CourierQuoteSignature
{
[$status, $label] = match ($remoteStatus) {
'1' => [CourierQuoteSignature::STATUS_SIGNING, '待签署'],
'2' => [CourierQuoteSignature::STATUS_COMPLETED, '签署完成,待归档'],
'3' => [CourierQuoteSignature::STATUS_REVOKED, '已撤销'],
'5' => [CourierQuoteSignature::STATUS_EXPIRED, '已过期'],
'7' => [CourierQuoteSignature::STATUS_REJECTED, '已拒签'],
default => [$signature->status, $signature->statusLabel()],
};
$signature->forceFill([
'status' => $status,
'remote_status' => $remoteStatus,
'completed_at' => $remoteStatus === '2' ? ($signature->completed_at ?? now()) : $signature->completed_at,
'last_synced_at' => now(),
'last_error' => null,
'updated_by' => $userId,
])->save();
$this->updateVersionStatus($signature, $label);
$signature->refresh();
return $signature;
}
private function archive(CourierQuoteSignature $signature, EsignClient $client, int $userId): CourierQuoteSignature
{
if ($signature->status === CourierQuoteSignature::STATUS_ARCHIVED) {
return $signature;
}
$urls = $client->downloadUrls($signature->esign_sign_flow_id);
$signedUrl = (string) data_get($urls, 'files.0.downloadUrl', '');
$certificateUrl = (string) ($urls['certificateDownloadUrl'] ?? '');
if ($signedUrl === '') {
throw new RuntimeException('E 签宝未返回签署文件下载地址。');
}
$signedBytes = $client->download($signedUrl);
$certificateBytes = $certificateUrl === '' ? null : $client->download($certificateUrl);
if (! str_starts_with($signedBytes, '%PDF-')
|| ($certificateBytes !== null && ! str_starts_with($certificateBytes, '%PDF-'))) {
throw new RuntimeException('E 签宝返回的签署文件或完成证书不是有效 PDF。');
}
$version = CourierQuoteVersion::allCompanies()->findOrFail($signature->quote_version_id);
$signedPath = $this->path($version, 'signed.pdf');
$certificatePath = $this->path($version, 'completion-certificate.pdf');
$disk = Storage::disk('uploads');
if (! $disk->put($signedPath, $signedBytes)
|| ($certificateBytes !== null && ! $disk->put($certificatePath, $certificateBytes))) {
throw new RuntimeException('签署归档文件无法写入私有业务存储。');
}
$archive = [
'status' => CourierQuoteSignature::STATUS_ARCHIVED,
'signed_pdf_path' => $signedPath,
'signed_pdf_sha256' => hash('sha256', $signedBytes),
'archived_at' => now(),
'last_synced_at' => now(),
'last_error' => null,
'updated_by' => $userId,
];
if ($certificateBytes !== null) {
$archive['certificate_path'] = $certificatePath;
$archive['certificate_sha256'] = hash('sha256', $certificateBytes);
}
$signature->update($archive);
$this->updateVersionStatus($signature, '已签署并归档');
return $signature->fresh('version');
}
private function path(CourierQuoteVersion $version, string $fileName): string
{
$versionCode = preg_replace('/[^A-Za-z0-9_-]/', '-', $version->version_code) ?: (string) $version->id;
return "courier-quotes/{$version->company_id}/{$versionCode}/{$fileName}";
}
private function updateVersionStatus(CourierQuoteSignature $signature, string $label): void
{
CourierQuoteVersion::allCompanies()
->whereKey($signature->quote_version_id)
->update(['signature_status' => $label]);
}
private function safeError(Throwable $exception): string
{
$message = preg_replace('/[[:cntrl:]]+/u', ' ', $exception->getMessage()) ?: 'E 签宝处理失败。';
return mb_substr($message, 0, 1000);
}
}