diff --git a/app/Http/Controllers/Business/CourierAgreementSignatures.php b/app/Http/Controllers/Business/CourierAgreementSignatures.php new file mode 100644 index 00000000..7f156c36 --- /dev/null +++ b/app/Http/Controllers/Business/CourierAgreementSignatures.php @@ -0,0 +1,325 @@ +ensureCanManage(); + abort_unless(EsignClient::configured(), 422, 'E 签宝沙箱尚未配置 App ID 或 AppSecret。'); + abort_unless(Schema::hasTable('business_courier_agreement_signatures'), 503, '协议签署数据表尚未完成迁移,请先执行数据库迁移。'); + + $data = $request->validate($this->rules()); + $type = $data['document_type']; + if ($type === 'authorization' && count($data['authorization_items'] ?? []) === 0) { + throw ValidationException::withMessages(['authorization_items' => '授权委托书至少选择一项授权事项。']); + } + $this->validateEsignAccount($data['esign_account'], 'esign_account'); + if (! empty($data['secondary_esign_account'])) { + $this->validateEsignAccount($data['secondary_esign_account'], 'secondary_esign_account'); + } + + $data['organization_name'] = $data['signing_subject']; + $data['operator_name'] = $data['operator_name'] ?? $data['courier_name']; + $data['operator_account'] = $data['esign_account']; + $data['payload'] = $this->payload($data); + + $signature = $this->service->send($data, user_id()); + + return redirect() + ->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks']) + ->with('success', $signature->status === CourierAgreementSignature::STATUS_SIGNING + ? "{$signature->documentLabel()}已推送到 E 签宝,等待对方签署。" + : "{$signature->documentLabel()}签署任务已受理。") + ->with('agreement_signature_id', $signature->id); + } + + /** + * Create a signing subject for the current tenant. + * + * The subject is deliberately kept separate from the global companies table: + * one tenant may need to sign agreements using more than one legal entity. + */ + public function storeSubject(Request $request): JsonResponse + { + $this->ensureCanManage(); + + if ($response = $this->subjectsTableUnavailable()) { + return $response; + } + + $data = $this->subjectData($request); + $subject = DB::transaction(function () use ($data): CourierSigningSubject { + $this->ensureSubjectNameAvailable($data['name']); + + $isFirst = ! CourierSigningSubject::query()->exists(); + + return CourierSigningSubject::create([ + 'company_id' => company_id(), + 'name' => $data['name'], + 'unified_social_credit_code' => $data['unified_social_credit_code'], + 'is_default' => $isFirst, + 'created_by' => user_id(), + 'updated_by' => user_id(), + ]); + }); + + return $this->subjectResponse($subject, '公司主体已新增。'); + } + + public function updateSubject(Request $request, CourierSigningSubject $subject): JsonResponse + { + $this->ensureCanManage(); + $this->ensureSubjectBelongsToCurrentCompany($subject); + + if ($response = $this->subjectsTableUnavailable()) { + return $response; + } + + $data = $this->subjectData($request); + $this->ensureSubjectNameAvailable($data['name'], $subject); + + $subject->update([ + 'name' => $data['name'], + 'unified_social_credit_code' => $data['unified_social_credit_code'], + 'updated_by' => user_id(), + ]); + + return $this->subjectResponse($subject->fresh(), '公司主体已更新。'); + } + + public function setDefaultSubject(CourierSigningSubject $subject): JsonResponse + { + $this->ensureCanManage(); + $this->ensureSubjectBelongsToCurrentCompany($subject); + + if ($response = $this->subjectsTableUnavailable()) { + return $response; + } + + DB::transaction(function () use ($subject): void { + CourierSigningSubject::query() + ->where('is_default', true) + ->update([ + 'is_default' => false, + 'updated_by' => user_id(), + 'updated_at' => now(), + ]); + + $subject->forceFill([ + 'is_default' => true, + 'updated_by' => user_id(), + ])->save(); + }); + + return $this->subjectResponse($subject->fresh(), '默认签署主体已切换。'); + } + + public function synchronize(CourierAgreementSignature $agreementSignature): RedirectResponse + { + $this->ensureCanManage(); + $signature = $this->service->synchronize($agreementSignature, user_id()); + + return redirect() + ->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks']) + ->with('success', "{$signature->documentLabel()}状态已同步:{$signature->statusLabel()}。"); + } + + public function archive(CourierAgreementSignature $agreementSignature): RedirectResponse + { + $this->ensureCanManage(); + abort_unless($agreementSignature->status === CourierAgreementSignature::STATUS_COMPLETED && $agreementSignature->remote_status === '2', 422, '只有签署完成的协议可以人工归档。'); + $signature = $this->service->archive($agreementSignature, null, user_id()); + + return redirect() + ->route('business.pages.show', ['section' => 'courier-payables', 'page' => 'agreement-signing', 'agreement_view' => 'tasks']) + ->with('success', "{$signature->documentLabel()}已人工确认并归档。"); + } + + public function download(CourierAgreementSignature $agreementSignature, string $kind): StreamedResponse + { + $this->ensureCanManage(); + [$path, $suffix] = match ($kind) { + 'source' => [$agreementSignature->source_pdf_path, '签署原文'], + 'signed' => [$agreementSignature->signed_pdf_path, '已签署协议'], + 'certificate' => [$agreementSignature->certificate_path, '签署完成证书'], + default => abort(404), + }; + + abort_if(blank($path) || ! \Storage::disk('uploads')->exists($path), 404, '归档文件不存在。'); + + return \Storage::disk('uploads')->download($path, $agreementSignature->business_no . '-' . $suffix . '.pdf', ['Content-Type' => 'application/pdf']); + } + + private function rules(): array + { + $date = ['required', 'date', 'after_or_equal:today', 'before_or_equal:' . now()->addDays(90)->toDateString()]; + + return [ + 'idempotency_key' => ['required', 'string', 'max:80', 'regex:/^[A-Za-z0-9_-]+$/'], + 'courier_name' => ['required', 'string', 'max:255'], + 'document_type' => ['required', 'in:' . implode(',', array_keys(CourierAgreementSignature::DOCUMENTS))], + 'signing_subject' => ['required', 'string', 'min:2', 'max:255'], + 'company_full_name' => ['required', 'string', 'min:2', 'max:255'], + 'signing_deadline' => $date, + 'esign_account' => ['required', 'string', 'max:255'], + 'secondary_esign_account' => ['required_if:document_type,entity-change,cooperation-contract,authorization', 'nullable', 'string', 'max:255'], + 'operator_name' => ['nullable', 'string', 'max:100'], + 'archive_mode' => ['required', 'in:auto,manual'], + 'account_proof_effective_date' => ['required_if:document_type,account-proof', 'date'], + 'account_proof_account_name' => ['required_if:document_type,account-proof', 'string', 'max:255'], + 'account_proof_bank_name' => ['required_if:document_type,account-proof', 'string', 'max:255'], + 'account_proof_bank_account' => ['required_if:document_type,account-proof', 'string', 'max:64', 'regex:/^[0-9A-Za-z-]+$/'], + 'account_change_date' => ['required_if:document_type,account-change', 'date'], + 'old_account_name' => ['required_if:document_type,account-change', 'string', 'max:255'], + 'old_account_number' => ['required_if:document_type,account-change', 'string', 'max:64', 'regex:/^[0-9A-Za-z-]+$/'], + 'old_account_stop_date' => ['required_if:document_type,account-change', 'date'], + 'new_account_effective_date' => ['required_if:document_type,account-change', 'date'], + 'new_account_name' => ['required_if:document_type,account-change', 'string', 'max:255'], + 'new_bank_name' => ['required_if:document_type,account-change', 'string', 'max:255'], + 'new_bank_account' => ['required_if:document_type,account-change', 'string', 'max:64', 'regex:/^[0-9A-Za-z-]+$/'], + 'former_company_name' => ['required_if:document_type,entity-change', 'string', 'max:255'], + 'entity_change_date' => ['required_if:document_type,entity-change', 'date'], + 'changed_company_name' => ['required_if:document_type,entity-change', 'string', 'max:255'], + 'changed_company_start_date' => ['required_if:document_type,entity-change', 'date'], + 'entity_proof_date' => ['required_if:document_type,entity-change', 'date'], + 'contract_partner_name' => ['required_if:document_type,shared-contract', 'string', 'max:255'], + 'shared_courier_name' => ['required_if:document_type,shared-contract', 'string', 'max:255'], + 'shared_proof_date' => ['required_if:document_type,shared-contract', 'date'], + 'cooperation_party_a_name' => ['required_if:document_type,cooperation-contract', 'string', 'max:255'], + 'cooperation_party_a_phone' => ['required_if:document_type,cooperation-contract', 'string', 'max:64'], + 'cooperation_party_b_name' => ['required_if:document_type,cooperation-contract', 'string', 'max:255'], + 'cooperation_party_b_phone' => ['required_if:document_type,cooperation-contract', 'string', 'max:64'], + 'cooperation_start_date' => ['required_if:document_type,cooperation-contract', 'date'], + 'cooperation_end_date' => ['required_if:document_type,cooperation-contract', 'date', 'after_or_equal:cooperation_start_date'], + 'principal_name' => ['required_if:document_type,authorization', 'string', 'max:100'], + 'principal_id_number' => ['required_if:document_type,authorization', 'string', 'max:64'], + 'trustee_name' => ['required_if:document_type,authorization', 'string', 'max:100'], + 'trustee_id_number' => ['required_if:document_type,authorization', 'string', 'max:64'], + 'authorization_items' => ['nullable', 'array'], + 'authorization_items.*' => ['in:1,2,3,4'], + 'bill_counterparty' => ['required_if:document_type,authorization', 'string', 'max:255'], + 'loan_counterparty' => ['required_if:document_type,authorization', 'string', 'max:255'], + 'payment_counterparty' => ['required_if:document_type,authorization', 'string', 'max:255'], + 'authorization_start_date' => ['required_if:document_type,authorization', 'date'], + 'authorization_end_date' => ['required_if:document_type,authorization', 'date', 'after_or_equal:authorization_start_date'], + ]; + } + + private function payload(array $data): array + { + $allowed = array_keys($this->rules()); + $payload = array_intersect_key($data, array_flip($allowed)); + unset($payload['esign_account'], $payload['idempotency_key'], $payload['operator_name']); + $payload['authorization_items'] = array_values(array_map('strval', $data['authorization_items'] ?? [])); + return $payload; + } + + private function ensureCanManage(): void + { + abort_unless( + in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true), + 403, + '当前账号没有协议签署管理权限。', + ); + } + + private function subjectData(Request $request): array + { + $data = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + 'unified_social_credit_code' => ['nullable', 'string', 'max:32', 'regex:/^[0-9A-Za-z]{18}$/'], + ]); + + $data['name'] = trim($data['name']); + if (mb_strlen($data['name']) < 2) { + throw ValidationException::withMessages(['name' => '公司名称至少填写 2 个字符。']); + } + + $data['unified_social_credit_code'] = trim((string) ($data['unified_social_credit_code'] ?? '')) ?: null; + + return $data; + } + + private function ensureSubjectNameAvailable(string $name, ?CourierSigningSubject $except = null): void + { + $query = CourierSigningSubject::query()->where('name', $name); + + if ($except) { + $query->where($query->getModel()->getQualifiedKeyName(), '<>', $except->getKey()); + } + + if ($query->exists()) { + throw ValidationException::withMessages(['name' => '当前公司下已有同名签署主体。']); + } + } + + private function subjectResponse(CourierSigningSubject $subject, string $message): JsonResponse + { + return response()->json([ + 'message' => $message, + 'subject' => $this->serializeSubject($subject), + 'subjects' => CourierSigningSubject::query() + ->orderByDesc('is_default') + ->orderBy('name') + ->get() + ->map(fn (CourierSigningSubject $item): array => $this->serializeSubject($item)) + ->values(), + ]); + } + + private function serializeSubject(CourierSigningSubject $subject): array + { + return [ + 'id' => $subject->id, + 'name' => $subject->name, + 'unified_social_credit_code' => $subject->unified_social_credit_code, + 'is_default' => (bool) $subject->is_default, + ]; + } + + private function subjectsTableUnavailable(): ?JsonResponse + { + if (Schema::hasTable('business_courier_signing_subjects')) { + return null; + } + + return response()->json([ + 'message' => '公司主体数据表尚未完成迁移,请先执行数据库迁移。', + ], 503); + } + + private function ensureSubjectBelongsToCurrentCompany(CourierSigningSubject $subject): void + { + abort_unless((int) $subject->company_id === (int) company_id(), 404, '签署主体不存在。'); + } + + private function validateEsignAccount(string $account, string $field): void + { + $valid = preg_match('/^1\d{10}$/', $account) === 1 + || filter_var($account, FILTER_VALIDATE_EMAIL) !== false; + + if (! $valid) { + throw ValidationException::withMessages([$field => 'E签宝账号必须是 11 位手机号或有效邮箱。']); + } + } +} diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index a1d54431..6e62f11e 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -6,6 +6,8 @@ use App\Business\BusinessTableImporter; use App\Business\TableRegistry; use App\Business\UpstreamBusinessInformation; use App\Models\Banking\MarketingAccountBill; +use App\Models\Business\CourierAgreementSignature; +use App\Models\Business\CourierSigningSubject; use App\Models\StoreReceivables\StoreZhongcaiReconciliation; use App\Utilities\SidebarPermissions; use Illuminate\Http\Request; @@ -13,8 +15,10 @@ use Illuminate\Routing\Controller; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use Illuminate\Support\Collection; +use Illuminate\Database\QueryException; use Modules\EcommerceFinance\Exceptions\UpstreamSnapshotPendingException; use Modules\EcommerceFinance\Repositories\AlibabaBillRepository; +use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository; use Modules\EcommerceFinance\Repositories\EdgeBandingRepository; use Modules\EcommerceFinance\Repositories\InventoryRepository; use Modules\EcommerceFinance\Repositories\JdWalletBillRepository; @@ -33,6 +37,17 @@ use Throwable; class Pages extends Controller { + /** @var list 快递签署页当前可选的合作方名称 */ + private const AGREEMENT_COURIER_NAMES = [ + '新北中通', + '新北中通其他', + '新德邦快递', + '睢宁中通', + '武进极兔', + '沭阳德邦', + '常州圆通其他', + ]; + private const EDGE_BANDING_SOURCE = 'jiansun'; private const INVENTORY_SOURCE = 'jiansun'; @@ -45,6 +60,7 @@ class Pages extends Controller private readonly NonJingxiRefundMirrorRepository $nonJingxiRefunds, private readonly ProductCatalogMirrorRepository $productCatalog, private readonly ProductPriceMirrorRepository $productPrices, + private readonly CourierInformationMirrorRepository $courierInformation, private readonly RawBoardPayablesRepository $rawBoardPayables, private readonly DingPayableWorkflowMirrorRepository $dingPayableWorkflows, private readonly SupplierPayableReportRepository $supplierPayableReports, @@ -196,6 +212,9 @@ class Pages extends Controller 'edgeBanding' => $this->edgeBandingContent($page['slug']), 'inventoryData' => $this->inventoryContent($page['slug']), 'rawBoardData' => $this->rawBoardContent($page['slug']), + 'agreementTasks' => $this->agreementTasks($page['slug']), + 'agreementSubjects' => $this->agreementSubjects($page['slug']), + 'agreementCourierAccounts' => $this->agreementCourierAccounts($page['slug']), ]; } @@ -233,9 +252,64 @@ class Pages extends Controller 'edgeBanding' => $page ? $this->edgeBandingContent($page['slug']) : null, 'inventoryData' => $page ? $this->inventoryContent($page['slug']) : null, 'rawBoardData' => $page ? $this->rawBoardContent($page['slug']) : null, + 'agreementTasks' => $this->agreementTasks($page['slug'] ?? null), + 'agreementSubjects' => $this->agreementSubjects($page['slug'] ?? null), + 'agreementCourierAccounts' => $this->agreementCourierAccounts($page['slug'] ?? null), ]; } + /** @return array */ + protected function agreementCourierAccounts(?string $page): array + { + if ($page !== 'agreement-signing') { + return []; + } + + try { + return $this->courierInformation->signingAccountsByName(self::AGREEMENT_COURIER_NAMES); + } catch (Throwable $exception) { + // 快递镜像不可用时仍可手工填写 E 签宝账号,不能阻断签署页。 + report($exception); + return []; + } + } + + protected function agreementTasks(?string $page): Collection + { + if ($page !== 'agreement-signing') { + return collect(); + } + + try { + return CourierAgreementSignature::query() + ->latest('id') + ->limit(50) + ->get(); + } catch (QueryException $exception) { + // 迁移尚未执行时仍允许打开页面;发送接口会明确提示数据库未就绪。 + report($exception); + return collect(); + } + } + + protected function agreementSubjects(?string $page): Collection + { + if ($page !== 'agreement-signing') { + return collect(); + } + + try { + return CourierSigningSubject::query() + ->orderByDesc('is_default') + ->orderBy('name') + ->get(); + } catch (QueryException $exception) { + // 主体管理迁移尚未执行时仍允许打开签署页面,默认使用当前公司名称。 + report($exception); + return collect(); + } + } + protected function resolveContent(string $page, ?string $tab): ?array { return match ($page) { @@ -245,6 +319,7 @@ class Pages extends Controller 'zhongcai-reconciliation' => $this->contentForZhongcaiReconciliation(), 'normal-products' => $this->contentForNormalProducts(), 'product-prices' => $this->contentForProductPrices(), + 'courier-information' => $this->contentForCourierInformation(), 'board-deductions' => $this->contentForBoardDeductions(), 'supplier-payables-report' => $this->contentForSupplierPayablesReport(), 'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(), @@ -1137,6 +1212,67 @@ class Pages extends Controller ]); } + public function exportCourierInformation(Request $request): StreamedResponse + { + abort_unless($this->courierInformation->available() && $this->courierInformation->ready(), 503); + + $filters = $this->courierInformationFilters($request); + + return response()->streamDownload(function () use ($filters): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建快递资料导出流。'); + } + + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, [ + 'ID', '快递公司代码', '快递公司名称', '外部编码', '杉橙快递代码', '运费打款方式', + '是否启用', '可达服务', '是否快运', '自动寻号', '配货单号寻号', '数量拆单', '重量0寻号', + '停运时间', '合同开始时间', '合同结束时间', '联系人', '联系电话', '自定义1', '自定义2', '自定义3', + '体积0寻号', '手工单号', '解密', '电子签章经办人', '最后修改', + ]); + + $bool = static fn (mixed $value): string => in_array(strtolower((string) $value), ['1', 'true', 'yes', 'y'], true) || $value === true ? '是' : '否'; + $date = static fn (mixed $value): string => $value === null || $value === '' ? '' : substr((string) $value, 0, 10); + + foreach ($this->courierInformation->exportRows($filters) as $row) { + fputcsv($csv, [ + $row->Id, + $this->csvText($row->expcode), + $this->csvText($row->expname), + $this->csvText($row->outcode), + $this->csvText($row->scexpcode), + $this->csvText($row->paymethod), + $bool($row->status), + $bool($row->addvalidsgn), + $bool($row->kuaiyunsgn), + $bool($row->autonosgn), + $bool($row->packnosgn), + $bool($row->skucountsplitsgn), + $bool($row->weight0sgn), + $date($row->stopdate), + $date($row->tradebtime), + $date($row->tradeetime), + $this->csvText($row->linker), + $this->csvText($row->linkmobile), + $this->csvText($row->undefined1), + $this->csvText($row->undefined2), + $this->csvText($row->undefined3), + $bool($row->volume0sgn), + $bool($row->handnosgn), + $bool($row->decryptsgn), + $this->csvText($row->dzqzjbr), + $date($row->modified), + ]); + } + + fclose($csv); + }, '快递资料_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + /** @return array */ private function normalProductFilters(Request $request): array { @@ -1207,6 +1343,129 @@ class Pages extends Controller ]; } + protected function contentForCourierInformation(): array + { + $filters = $this->courierInformationFilters(request()); + $tab = (string) request()->query('courier_tab', 'express'); + $tab = in_array($tab, ['express', 'networks', 'accounts', 'logs'], true) ? $tab : 'express'; + $page = max((int) request()->query('page', 1), 1); + $limit = min(max((int) setting('default.list_limit', 25), 1), 100); + $rows = new LengthAwarePaginator([], 0, $limit, $page, [ + 'path' => request()->url(), + 'query' => request()->except('page'), + ]); + $error = null; + $pending = false; + $state = null; + $syncStatus = ['code' => 'unavailable', 'lag_minutes' => null]; + $relatedAvailability = $this->courierInformation->relatedAvailability(); + + try { + if ($tab === 'express') { + if (! $this->courierInformation->available()) { + $error = '共享业务镜像尚未建立,快递资料暂时无法读取。'; + } else { + $state = $this->courierInformation->state(); + $syncStatus = $this->courierInformation->syncStatus($state); + if (! $this->courierInformation->ready()) { + $pending = true; + $error = '快递资料正在执行首次全量同步,完成前不会把未同步数据误判为无数据。'; + } else { + $result = $this->courierInformation->paginate($filters, $page, $limit); + $rows = $this->courierPaginator($result['data'] ?? [], $result['total'] ?? 0, $limit, $page); + } + } + } elseif ($tab === 'networks') { + if (! ($relatedAvailability['networks'] ?? false)) { + $error = '快递网点镜像尚未建立,请先完成 wp_express_expNet 的首次同步。'; + } elseif (! ($relatedAvailability['network_ready'] ?? false)) { + $pending = true; + $error = '快递网点正在执行首次全量同步,完成前不会把未同步数据误判为无数据。'; + } else { + $result = $this->courierInformation->paginateNetworks($filters['expcode'] ?: null, $page, $limit); + $rows = $this->courierPaginator($result['data'] ?? [], $result['total'] ?? 0, $limit, $page); + } + } elseif ($tab === 'accounts') { + if (! ($relatedAvailability['accounts'] ?? false)) { + $error = '打款账户镜像尚未建立,请先完成 wp_express_account 的首次同步。'; + } elseif (! ($relatedAvailability['account_ready'] ?? false)) { + $pending = true; + $error = '打款账户正在执行首次全量同步,完成前不会把未同步数据误判为无数据。'; + } else { + $result = $this->courierInformation->paginateAccounts($filters['expcode'] ?: null, $page, $limit); + $rows = $this->courierPaginator($result['data'] ?? [], $result['total'] ?? 0, $limit, $page); + } + } else { + if (! ($relatedAvailability['logs'] ?? false)) { + $error = '操作日志镜像尚未建立,请先完成 wp_express_extension 的首次同步。'; + } elseif (! ($relatedAvailability['log_ready'] ?? false)) { + $pending = true; + $error = '操作日志正在执行首次全量同步,完成前不会把未同步数据误判为无数据。'; + } else { + $result = $this->courierInformation->paginateLogs($filters['expcode'] ?: null, $page, $limit); + $rows = $this->courierPaginator($result['data'] ?? [], $result['total'] ?? 0, $limit, $page); + } + } + } catch (Throwable $exception) { + report($exception); + $error = '快递资料共享镜像暂时无法读取,请稍后重试。'; + } + + return [ + 'view' => 'business.pages.courier-payables.courier-information', + 'courierTab' => $tab, + 'courierFilters' => $filters, + 'courierRows' => $rows, + 'courierState' => $state, + 'courierSyncStatus' => $syncStatus, + 'courierError' => $error, + 'courierPending' => $pending, + 'courierRelatedAvailability' => $relatedAvailability, + ]; + } + + /** @return array */ + private function courierInformationFilters(Request $request): array + { + $filters = [ + 'expcode' => mb_substr(trim((string) $request->query('expcode', '')), 0, 64), + 'expname' => mb_substr(trim((string) $request->query('expname', '')), 0, 100), + 'undefined1' => mb_substr(trim((string) $request->query('undefined1', '')), 0, 100), + 'undefined2' => mb_substr(trim((string) $request->query('undefined2', '')), 0, 100), + 'undefined3' => mb_substr(trim((string) $request->query('undefined3', '')), 0, 100), + 'tradebtime_from' => $this->dateFilter($request->query('tradebtime_from')), + 'tradebtime_to' => $this->dateFilter($request->query('tradebtime_to')), + 'status' => in_array((string) $request->query('status', ''), ['0', '1'], true) + ? (string) $request->query('status') + : '', + ]; + + if ($filters['tradebtime_from'] !== '' + && $filters['tradebtime_to'] !== '' + && $filters['tradebtime_from'] > $filters['tradebtime_to']) { + [$filters['tradebtime_from'], $filters['tradebtime_to']] = [ + $filters['tradebtime_to'], + $filters['tradebtime_from'], + ]; + } + + return $filters; + } + + private function courierPaginator(array $rows, int $total, int $limit, int $page): LengthAwarePaginator + { + return new LengthAwarePaginator( + Collection::make($rows), + $total, + $limit, + $page, + [ + 'path' => request()->url(), + 'query' => request()->except('page'), + ], + ); + } + protected function contentForProductPrices(): array { $filters = [ diff --git a/app/Http/Controllers/Integrations/EsignCallbacks.php b/app/Http/Controllers/Integrations/EsignCallbacks.php index 2bf8778e..41ad7511 100644 --- a/app/Http/Controllers/Integrations/EsignCallbacks.php +++ b/app/Http/Controllers/Integrations/EsignCallbacks.php @@ -3,7 +3,10 @@ namespace App\Http\Controllers\Integrations; use App\Jobs\Business\ArchiveCourierQuoteSignature; +use App\Jobs\Business\ArchiveCourierAgreementSignature; +use App\Models\Business\CourierAgreementSignature; use App\Models\Business\CourierQuoteSignature; +use App\Support\CourierAgreementSignatureService; use App\Support\CourierQuoteSignatureService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; @@ -11,7 +14,7 @@ use Illuminate\Routing\Controller; class EsignCallbacks extends Controller { - public function __invoke(Request $request, CourierQuoteSignatureService $service): JsonResponse + public function __invoke(Request $request, CourierQuoteSignatureService $service, CourierAgreementSignatureService $agreementService): JsonResponse { $appId = trim((string) config('services.esign.app_id')); $appSecret = trim((string) config('services.esign.app_secret')); @@ -60,7 +63,24 @@ class EsignCallbacks extends Controller return $this->success(); } - $signatureRecord = $service->acceptCallback($signFlowId, $remoteStatus, hash('sha256', $rawBody)); + $payloadHash = hash('sha256', $rawBody); + $signatureRecord = $service->acceptCallback($signFlowId, $remoteStatus, $payloadHash); + + if ($signatureRecord === null) { + $agreementRecord = $agreementService->acceptCallback($signFlowId, $remoteStatus, $payloadHash, [ + 'event_key' => hash('sha256', $timestamp . '|' . ($payload['action'] ?? '') . '|' . $signFlowId . '|' . $payloadHash), + 'action' => (string) ($payload['action'] ?? 'SIGN_FLOW_COMPLETE'), + 'timestamp' => $timestamp, + 'raw_body' => $rawBody, + ]); + + if ($agreementRecord + && $remoteStatus === '2' + && $agreementService->autoArchive($agreementRecord) + && $agreementRecord->status !== CourierAgreementSignature::STATUS_ARCHIVED) { + ArchiveCourierAgreementSignature::dispatch($agreementRecord->id); + } + } if ($signatureRecord && $remoteStatus === '2' diff --git a/app/Jobs/Business/ArchiveCourierAgreementSignature.php b/app/Jobs/Business/ArchiveCourierAgreementSignature.php new file mode 100644 index 00000000..2333ce0e --- /dev/null +++ b/app/Jobs/Business/ArchiveCourierAgreementSignature.php @@ -0,0 +1,31 @@ +find($this->signatureId); + if ($signature) { + $service->synchronize($signature); + } + } +} diff --git a/app/Models/Business/CourierAgreementSignature.php b/app/Models/Business/CourierAgreementSignature.php new file mode 100644 index 00000000..285c760e --- /dev/null +++ b/app/Models/Business/CourierAgreementSignature.php @@ -0,0 +1,109 @@ + [ + 'code' => 'TPL-ACCOUNT-CERT-V2', + 'version' => '2', + 'name' => '收款账户证明', + 'file' => '收款账户证明文件.doc', + ], + 'account-change' => [ + 'code' => 'TPL-ACCOUNT-CHANGE-V1', + 'version' => '1', + 'name' => '收款账户变更', + 'file' => '收款账户变更证明.doc', + ], + 'entity-change' => [ + 'code' => 'TPL-ENTITY-CHANGE-V1', + 'version' => '1', + 'name' => '公司主体变更', + 'file' => '公司主体变更证明.docx', + ], + 'shared-contract' => [ + 'code' => 'TPL-SHARED-CONTRACT-V1', + 'version' => '1', + 'name' => '共用合同证明', + 'file' => '共用合同证明.docx', + ], + 'cooperation-contract' => [ + 'code' => 'TPL-COOPERATION-CONTRACT-V1', + 'version' => '1', + 'name' => '合作合同', + 'file' => '保丟不保损-合同发快递2024.8.doc', + ], + 'authorization' => [ + 'code' => 'TPL-AUTHORIZATION-V1', + 'version' => '1', + 'name' => '授权委托书', + 'file' => '授权委托书(快递).docx', + ], + ]; + + protected $table = 'business_courier_agreement_signatures'; + + protected $fillable = [ + 'company_id', 'business_no', 'idempotency_key', 'document_type', 'template_code', + 'template_version', 'source_file_name', 'status', 'courier_name', 'company_full_name', + 'organization_name', 'operator_name', 'operator_account', 'payload', 'environment', + 'expires_at', 'source_pdf_path', 'source_pdf_sha256', 'esign_file_id', + 'esign_sign_flow_id', 'remote_status', 'signed_pdf_path', 'signed_pdf_sha256', + 'certificate_path', 'certificate_sha256', 'sent_at', 'completed_at', 'archived_at', + 'last_synced_at', 'last_error', 'callback_payload_hash', 'created_by', 'updated_by', + ]; + + protected $casts = [ + 'company_id' => 'integer', + 'expires_at' => 'datetime', + 'sent_at' => 'datetime', + 'completed_at' => 'datetime', + 'archived_at' => 'datetime', + 'last_synced_at' => 'datetime', + 'payload' => 'encrypted:array', + 'operator_account' => 'encrypted', + ]; + + public function statusLabel(): string + { + return match ($this->status) { + self::STATUS_PREPARED => '待推送', + self::STATUS_SENDING => '推送中', + self::STATUS_SIGNING => '待签署', + self::STATUS_COMPLETED => '签署完成,待归档', + self::STATUS_ARCHIVED => '已签署并归档', + self::STATUS_REVOKED => '已撤销', + self::STATUS_EXPIRED => '已过期', + self::STATUS_REJECTED => '已拒签', + self::STATUS_FAILED => '处理失败', + self::STATUS_UNKNOWN => '状态未知,请人工核对', + default => $this->status, + }; + } + + public function canSend(): bool + { + return in_array($this->status, [self::STATUS_PREPARED, self::STATUS_FAILED], true) + && blank($this->esign_sign_flow_id); + } + + public function documentLabel(): string + { + return self::DOCUMENTS[$this->document_type]['name'] ?? $this->document_type; + } +} diff --git a/app/Models/Business/CourierAgreementSignatureEvent.php b/app/Models/Business/CourierAgreementSignatureEvent.php new file mode 100644 index 00000000..28416815 --- /dev/null +++ b/app/Models/Business/CourierAgreementSignatureEvent.php @@ -0,0 +1,26 @@ + 'integer', + 'agreement_signature_id' => 'integer', + 'event_timestamp' => 'integer', + 'verified' => 'boolean', + 'processed' => 'boolean', + 'raw_body' => 'encrypted', + 'received_at' => 'datetime', + 'processed_at' => 'datetime', + ]; +} diff --git a/app/Models/Business/CourierSigningSubject.php b/app/Models/Business/CourierSigningSubject.php new file mode 100644 index 00000000..1fa9b11c --- /dev/null +++ b/app/Models/Business/CourierSigningSubject.php @@ -0,0 +1,26 @@ + 'integer', + 'is_default' => 'boolean', + 'created_by' => 'integer', + 'updated_by' => 'integer', + ]; +} diff --git a/app/Services/Esign/EsignClient.php b/app/Services/Esign/EsignClient.php index ab9d06ca..20b8086b 100644 --- a/app/Services/Esign/EsignClient.php +++ b/app/Services/Esign/EsignClient.php @@ -32,6 +32,18 @@ final class EsignClient public function uploadPdf(string $bytes, string $fileName): string { + if (! str_starts_with($bytes, '%PDF-')) { + throw new RuntimeException('只能向 E 签宝上传有效 PDF 文件。'); + } + + if (strlen($bytes) > 50 * 1024 * 1024) { + throw new RuntimeException('E 签宝单文件不能超过 50 MB。'); + } + + if (preg_match('/[\\/:*"<>|??\x00-\x1F]/u', $fileName) === 1 || ! str_ends_with(strtolower($fileName), '.pdf')) { + throw new RuntimeException('E 签宝文件名必须是安全的 PDF 文件名。'); + } + $contentMd5 = base64_encode(md5($bytes, true)); $data = $this->request('POST', '/v3/files/file-upload-url', [ 'contentMd5' => $contentMd5, @@ -68,6 +80,7 @@ final class EsignClient 'signFlowExpireTime' => $expiresAtMs, 'autoStart' => true, 'autoFinish' => true, + 'identityVerify' => true, ]; $notifyUrl = trim((string) config('services.esign.notify_url')); @@ -75,13 +88,10 @@ final class EsignClient $flowConfig['notifyUrl'] = $notifyUrl; } - $data = $this->request('POST', '/v3/sign-flow/create-by-file', [ - 'docs' => [[ - 'fileId' => $fileId, - 'fileName' => $fileName, - ]], - 'signFlowConfig' => $flowConfig, - 'signers' => [[ + $signers = $signer['signers'] ?? null; + $signerPayload = is_array($signers) && $signers !== [] + ? array_map(fn (array $item, int $index): array => $this->signerPayload($fileId, $item, $index), array_values($signers), array_keys(array_values($signers))) + : [[ 'signerType' => 1, 'signConfig' => ['signOrder' => 1], 'noticeConfig' => ['noticeTypes' => $signer['notice_types']], @@ -100,7 +110,15 @@ final class EsignClient 'signFieldSize' => '159', ], ]], + ]]; + + $data = $this->request('POST', '/v3/sign-flow/create-by-file', [ + 'docs' => [[ + 'fileId' => $fileId, + 'fileName' => $fileName, ]], + 'signFlowConfig' => $flowConfig, + 'signers' => $signerPayload, ]); $signFlowId = (string) ($data['signFlowId'] ?? ''); @@ -111,6 +129,41 @@ final class EsignClient return $signFlowId; } + private function signerPayload(string $fileId, array $signer, int $index): array + { + $type = (int) ($signer['signer_type'] ?? 1); + $payload = [ + 'signerType' => $type, + 'signConfig' => ['signOrder' => $index + 1], + 'noticeConfig' => ['noticeTypes' => (string) ($signer['notice_types'] ?? '1')], + 'signFields' => [[ + 'fileId' => $fileId, + 'normalSignFieldConfig' => [ + 'freeMode' => true, + 'movableSignField' => true, + 'signFieldSize' => '159', + ], + ]], + ]; + + if ($type === 0) { + $payload['psnSignerInfo'] = [ + 'psnAccount' => $signer['operator_account'], + 'psnInfo' => ['psnName' => $signer['operator_name']], + ]; + } else { + $payload['orgSignerInfo'] = [ + 'orgName' => $signer['organization_name'], + 'transactorInfo' => [ + 'psnAccount' => $signer['operator_account'], + 'psnInfo' => ['psnName' => $signer['operator_name']], + ], + ]; + } + + return $payload; + } + public function signFlowDetail(string $signFlowId): array { return $this->request('GET', "/v3/sign-flow/{$signFlowId}/detail"); diff --git a/app/Support/CourierAgreementPdf.php b/app/Support/CourierAgreementPdf.php new file mode 100644 index 00000000..d64ae502 --- /dev/null +++ b/app/Support/CourierAgreementPdf.php @@ -0,0 +1,43 @@ + $signature, + 'type' => $signature->document_type, + 'title' => $this->title($signature), + 'payload' => $signature->payload ?? [], + 'fontPath' => str_replace('\\', '/', resource_path('fonts/DroidSansFallback.ttf')), + ])->render(); + + $pdf = app('dompdf.wrapper'); + $pdf->setPaper('a4', 'portrait'); + $pdf->loadHTML($html, 'UTF-8'); + $bytes = $pdf->output(); + + if (! is_string($bytes) || ! str_starts_with($bytes, '%PDF-')) { + throw new RuntimeException('协议 PDF 生成失败。'); + } + + return $bytes; + } + + private function title(CourierAgreementSignature $signature): string + { + return match ($signature->document_type) { + 'account-proof' => '收款帐户资料证明', + 'account-change' => '收款帐户资料变更证明', + 'entity-change' => '公司主体变更证明', + 'shared-contract' => '证明', + 'cooperation-contract' => '服务协议', + default => '授权委托书', + }; + } +} diff --git a/app/Support/CourierAgreementSignatureService.php b/app/Support/CourierAgreementSignatureService.php new file mode 100644 index 00000000..967a28a4 --- /dev/null +++ b/app/Support/CourierAgreementSignatureService.php @@ -0,0 +1,333 @@ + '不支持的协议文件类型。']); + } + + $payload = is_array($data['payload'] ?? null) ? $data['payload'] : $data; + $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)); + + $signature = DB::transaction(function () use ($companyId, $document, $data, $payload, $idempotencyKey, $businessNo, $userId): CourierAgreementSignature { + $existing = CourierAgreementSignature::allCompanies() + ->where('company_id', $companyId) + ->where('idempotency_key', $idempotencyKey) + ->lockForUpdate() + ->first(); + + if ($existing) { + if ($existing->esign_sign_flow_id || in_array($existing->status, [CourierAgreementSignature::STATUS_SENDING, CourierAgreementSignature::STATUS_SIGNING, CourierAgreementSignature::STATUS_COMPLETED, CourierAgreementSignature::STATUS_ARCHIVED], true)) { + return $existing; + } + + if (! $existing->canSend()) { + throw ValidationException::withMessages(['signature' => '该协议已进入不可重复发起状态。']); + } + + return $existing; + } + + $signature = new CourierAgreementSignature([ + 'company_id' => $companyId, + 'business_no' => $businessNo, + 'idempotency_key' => $idempotencyKey, + 'document_type' => $data['document_type'], + 'template_code' => $document['code'], + 'template_version' => $document['version'], + 'source_file_name' => $document['file'], + 'status' => CourierAgreementSignature::STATUS_SENDING, + 'courier_name' => $data['courier_name'], + 'company_full_name' => $data['company_full_name'], + 'organization_name' => $data['organization_name'], + 'operator_name' => $data['operator_name'] ?? null, + 'operator_account' => $data['operator_account'] ?? null, + 'payload' => $payload, + 'environment' => (string) config('services.esign.environment', 'sandbox'), + 'expires_at' => Carbon::parse($data['signing_deadline'])->endOfDay(), + 'source_pdf_path' => "courier-agreements/{$companyId}/{$businessNo}/source.pdf", + 'source_pdf_sha256' => '', + 'created_by' => $userId, + 'updated_by' => $userId, + ]); + $signature->save(); + + $bytes = $this->pdf->render($signature); + $signature->source_pdf_sha256 = hash('sha256', $bytes); + if (! Storage::disk('uploads')->put($signature->source_pdf_path, $bytes)) { + throw new RuntimeException('协议 PDF 无法写入私有业务存储。'); + } + $signature->save(); + + return $signature; + }); + + if ($signature->esign_sign_flow_id || $signature->status === CourierAgreementSignature::STATUS_SIGNING) { + return $signature->fresh(); + } + + $flowCreationStarted = false; + try { + $client = app(EsignClient::class); + $bytes = Storage::disk('uploads')->get($signature->source_pdf_path); + $fileName = 'agreement-' . $signature->business_no . '.pdf'; + $fileId = $client->uploadPdf($bytes, $fileName); + $signer = [ + 'flow_title' => $this->safeTitle($signature->company_full_name . ' ' . $signature->documentLabel()), + 'organization_name' => $signature->organization_name, + 'operator_name' => $signature->operator_name ?: $signature->courier_name, + 'operator_account' => $signature->operator_account, + 'notice_types' => '1', + ]; + $signer['signers'] = $this->signersFor($signature); + $flowCreationStarted = true; + $signFlowId = $client->createSignFlow($fileId, $fileName, $signer, $signature->expires_at->getTimestampMs()); + + $signature->update([ + 'status' => CourierAgreementSignature::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, + ]); + + return $signature->fresh(); + } catch (Throwable $exception) { + $signature->update([ + 'status' => $flowCreationStarted ? CourierAgreementSignature::STATUS_UNKNOWN : CourierAgreementSignature::STATUS_FAILED, + 'last_error' => mb_substr((string) preg_replace('/[[:cntrl:]]+/u', ' ', $exception->getMessage()), 0, 1000), + 'updated_by' => $userId, + ]); + throw ValidationException::withMessages(['signature' => $signature->last_error]); + } + } + + public function synchronize(CourierAgreementSignature $signature, ?int $userId = null): CourierAgreementSignature + { + if (blank($signature->esign_sign_flow_id)) { + throw ValidationException::withMessages(['signature' => '该协议尚未创建 E 签宝签署流程。']); + } + + if ($signature->status === CourierAgreementSignature::STATUS_ARCHIVED) { + return $signature; + } + + 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 ?: (int) $signature->updated_by); + + return $remoteStatus === '2' && $this->autoArchive($signature) + ? $this->archive($signature, $client, $userId ?: (int) $signature->updated_by) + : $signature; + } catch (Throwable $exception) { + $signature->update(['last_error' => mb_substr($exception->getMessage(), 0, 1000), 'last_synced_at' => now()]); + throw ValidationException::withMessages(['signature' => $signature->last_error]); + } + } + + public function acceptCallback(string $signFlowId, string $remoteStatus, string $payloadHash, array $event = []): ?CourierAgreementSignature + { + return DB::transaction(function () use ($signFlowId, $remoteStatus, $payloadHash, $event): ?CourierAgreementSignature { + $signature = CourierAgreementSignature::allCompanies()->disableCache()->where('esign_sign_flow_id', $signFlowId)->lockForUpdate()->first(); + if (! $signature) { + return null; + } + $eventKey = (string) ($event['event_key'] ?? hash('sha256', $signFlowId . '|' . $payloadHash)); + $audit = CourierAgreementSignatureEvent::query()->disableCache()->where('event_key', $eventKey)->lockForUpdate()->first(); + if ($audit || $signature->callback_payload_hash === $payloadHash) { + return null; + } + if (in_array($signature->status, [ + CourierAgreementSignature::STATUS_COMPLETED, + CourierAgreementSignature::STATUS_ARCHIVED, + CourierAgreementSignature::STATUS_REVOKED, + CourierAgreementSignature::STATUS_EXPIRED, + CourierAgreementSignature::STATUS_REJECTED, + ], true) && $remoteStatus === $signature->remote_status) { + return null; + } + if ($event !== []) { + $audit = CourierAgreementSignatureEvent::create([ + 'company_id' => $signature->company_id, + 'agreement_signature_id' => $signature->id, + 'event_key' => $eventKey, + 'action' => (string) ($event['action'] ?? 'SIGN_FLOW_COMPLETE'), + 'esign_sign_flow_id' => $signFlowId, + 'event_timestamp' => (int) ($event['timestamp'] ?? now()->getTimestampMs()), + 'verified' => true, + 'raw_body' => (string) ($event['raw_body'] ?? ''), + 'received_at' => now(), + ]); + } + $signature->callback_payload_hash = $payloadHash; + $result = $this->applyRemoteStatus($signature, $remoteStatus, (int) $signature->updated_by); + if ($audit) { + $audit->update(['processed' => true, 'processed_at' => now()]); + } + return $result; + }); + } + + public function archive(CourierAgreementSignature $signature, ?EsignClient $client = null, ?int $userId = null): CourierAgreementSignature + { + if ($signature->status === CourierAgreementSignature::STATUS_ARCHIVED) { + return $signature; + } + $client ??= app(EsignClient::class); + $urls = $client->downloadUrls($signature->esign_sign_flow_id); + $signedUrl = (string) data_get($urls, 'files.0.downloadUrl', ''); + $certificateUrl = (string) ($urls['certificateDownloadUrl'] ?? ''); + if ($signedUrl === '' || $certificateUrl === '') { + throw new RuntimeException('E 签宝未返回签署文件或完成证书下载地址。'); + } + $signedBytes = $client->download($signedUrl); + $certificateBytes = $client->download($certificateUrl); + if (! str_starts_with($signedBytes, '%PDF-') || ! str_starts_with($certificateBytes, '%PDF-')) { + throw new RuntimeException('E 签宝返回的签署文件或完成证书不是有效 PDF。'); + } + $base = "courier-agreements/{$signature->company_id}/{$signature->business_no}"; + $signedPath = $base . '/signed.pdf'; + $certificatePath = $base . '/completion-certificate.pdf'; + $disk = Storage::disk('uploads'); + if (! $disk->put($signedPath, $signedBytes) || ! $disk->put($certificatePath, $certificateBytes)) { + throw new RuntimeException('签署归档文件无法写入私有业务存储。'); + } + $signature->update([ + 'status' => CourierAgreementSignature::STATUS_ARCHIVED, + 'signed_pdf_path' => $signedPath, + 'signed_pdf_sha256' => hash('sha256', $signedBytes), + 'certificate_path' => $certificatePath, + 'certificate_sha256' => hash('sha256', $certificateBytes), + 'archived_at' => now(), + 'last_synced_at' => now(), + 'last_error' => null, + 'updated_by' => $userId ?: (int) $signature->updated_by, + ]); + return $signature->fresh(); + } + + public function autoArchive(CourierAgreementSignature $signature): bool + { + return ($signature->payload['archive_mode'] ?? 'auto') === 'auto'; + } + + private function applyRemoteStatus(CourierAgreementSignature $signature, string $remoteStatus, int $userId): CourierAgreementSignature + { + $status = match ($remoteStatus) { + '1' => CourierAgreementSignature::STATUS_SIGNING, + '2' => CourierAgreementSignature::STATUS_COMPLETED, + '3' => CourierAgreementSignature::STATUS_REVOKED, + '5' => CourierAgreementSignature::STATUS_EXPIRED, + '7' => CourierAgreementSignature::STATUS_REJECTED, + default => $signature->status, + }; + $terminal = [CourierAgreementSignature::STATUS_COMPLETED, CourierAgreementSignature::STATUS_REVOKED, CourierAgreementSignature::STATUS_EXPIRED, CourierAgreementSignature::STATUS_REJECTED, CourierAgreementSignature::STATUS_ARCHIVED]; + if (in_array($signature->status, $terminal, true) && $status === CourierAgreementSignature::STATUS_SIGNING) { + return $signature; + } + $signature->forceFill([ + 'status' => $status, + 'remote_status' => $remoteStatus, + 'completed_at' => $remoteStatus === '2' ? ($signature->completed_at ?? now()) : $signature->completed_at, + 'last_synced_at' => now(), + 'updated_by' => $userId, + ])->save(); + return $signature->refresh(); + } + + private function signersFor(CourierAgreementSignature $signature): array + { + $payload = $signature->payload ?? []; + $primary = [ + 'signer_type' => 1, + 'organization_name' => $signature->organization_name, + 'operator_name' => $signature->operator_name ?: $signature->courier_name, + 'operator_account' => $signature->operator_account, + ]; + + if ($signature->document_type === 'cooperation-contract') { + return [ + [ + 'signer_type' => 1, + 'organization_name' => $payload['cooperation_party_a_name'] ?? $signature->company_full_name, + 'operator_name' => $payload['cooperation_party_a_name'] ?? $signature->company_full_name, + 'operator_account' => $payload['secondary_esign_account'] ?? $signature->operator_account, + ], + [ + 'signer_type' => 1, + 'organization_name' => $payload['cooperation_party_b_name'] ?? $signature->courier_name, + 'operator_name' => $signature->operator_name ?: ($payload['cooperation_party_b_name'] ?? $signature->courier_name), + 'operator_account' => $signature->operator_account, + ], + ]; + } + + if ($signature->document_type === 'entity-change') { + return [ + array_merge($primary, ['organization_name' => $payload['former_company_name'] ?? $signature->organization_name]), + [ + 'signer_type' => 1, + 'organization_name' => $payload['changed_company_name'] ?? $signature->organization_name, + 'operator_name' => $payload['changed_company_name'] ?? $signature->courier_name, + 'operator_account' => $payload['secondary_esign_account'] ?? $signature->operator_account, + ], + ]; + } + + if ($signature->document_type === 'authorization') { + return [ + array_merge($primary, [ + 'organization_name' => $payload['principal_name'] ?? $signature->organization_name, + 'operator_name' => $payload['principal_name'] ?? $signature->operator_name, + ]), + [ + 'signer_type' => 1, + 'organization_name' => $payload['trustee_name'] ?? $signature->organization_name, + 'operator_name' => $payload['trustee_name'] ?? $signature->courier_name, + 'operator_account' => $payload['secondary_esign_account'] ?? $signature->operator_account, + ], + ]; + } + + return [$primary]; + } + + private function safeTitle(string $title): string + { + $title = preg_replace('/[^\p{Han}\p{L}\p{N}_ -]/u', '-', $title) ?: '协议签署'; + return mb_substr(trim($title), 0, 180); + } +} diff --git a/config/business_navigation.php b/config/business_navigation.php index 35bc03f9..2631123a 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -418,6 +418,7 @@ return [ 'icon' => 'local_shipping', 'pages' => [ ['slug' => 'quote-management', 'title' => '报价管理'], + ['slug' => 'courier-information', 'title' => '快递资料'], ['slug' => 'agreement-signing', 'title' => '协议签署'], ['slug' => 'freight-reconciliation', 'title' => '运费对账'], ['slug' => 'bookkeeping-details', 'title' => '记账明细'], diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index ddd826c1..80b376ec 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -55,6 +55,10 @@ return [ 'reconcile_window_hours' => (int) env('PRODUCT_PURCHASE_PRICE_MIRROR_RECONCILE_WINDOW_HOURS', 6), ], + 'courier_information' => [ + 'stale_after_minutes' => (int) env('COURIER_INFORMATION_MIRROR_STALE_MINUTES', 60), + ], + /* |-------------------------------------------------------------------------- | 上游原表镜像目录 @@ -174,5 +178,50 @@ return [ 'jiansun.dbo.fys_supplierGoods_sttlement_purchase' => ['source_key' => 'jiansun', 'schema' => 'dbo', 'object' => 'fys_supplierGoods_sttlement_purchase', 'target' => 'js_supplier_goods_purchase', 'keys' => ['Id'], 'watermark' => 'createTime'], 'jiansun.dbo.fys_supplierGoods_sttlement_sale' => ['source_key' => 'jiansun', 'schema' => 'dbo', 'object' => 'fys_supplierGoods_sttlement_sale', 'target' => 'js_supplier_goods_sale', 'keys' => ['Id'], 'watermark' => 'createTime'], 'jiansun.dbo.pm_purchaseIn' => ['source_key' => 'jiansun', 'schema' => 'dbo', 'object' => 'pm_purchaseIn', 'target' => 'js_pm_purchase_in', 'keys' => ['id'], 'watermark' => 'updateTime'], + + // 工作平台 2.0:快递资料及其网点、打款账户。页面只读取共享镜像, + // 首次使用前需由刷新节点显式执行对应数据集的 --full 同步。 + 'jiansun.dbo.wp_express' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'wp_express', + 'target' => 'js_wp_express', + 'keys' => ['Id'], + 'watermark' => 'modified', + 'indexes' => [ + ['expcode'], + ['status', 'Id'], + ], + ], + 'jiansun.dbo.wp_express_expNet' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'wp_express_expNet', + 'target' => 'js_wp_express_exp_net', + 'keys' => ['id'], + 'indexes' => [ + ['expid', 'id'], + ['status', 'id'], + ], + ], + 'jiansun.dbo.wp_express_account' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'wp_express_account', + 'target' => 'js_wp_express_account', + 'keys' => ['Id'], + 'indexes' => [ + ['expcode', 'Id'], + ['accountType', 'Id'], + ], + ], + 'jiansun.dbo.wp_express_extension' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'wp_express_extension', + 'target' => 'js_wp_express_extension', + 'keys' => ['Id'], + 'watermark' => 'modifyTime', + ], ], ]; diff --git a/database/migrations/2026_08_28_000000_create_business_courier_agreement_signatures_table.php b/database/migrations/2026_08_28_000000_create_business_courier_agreement_signatures_table.php new file mode 100644 index 00000000..cb7f4037 --- /dev/null +++ b/database/migrations/2026_08_28_000000_create_business_courier_agreement_signatures_table.php @@ -0,0 +1,60 @@ +increments('id'); + $table->unsignedInteger('company_id'); + $table->string('business_no', 80); + $table->string('idempotency_key', 80); + $table->string('document_type', 40); + $table->string('template_code', 80); + $table->string('template_version', 20)->default('1'); + $table->string('source_file_name', 255); + $table->string('status', 32)->default('prepared'); + $table->string('courier_name', 255); + $table->string('company_full_name', 255); + $table->string('organization_name', 255); + $table->string('operator_name', 100)->nullable(); + $table->text('operator_account')->nullable(); + $table->text('payload'); + $table->string('environment', 32)->default('sandbox'); + $table->timestamp('expires_at')->nullable(); + $table->string('source_pdf_path', 1024); + $table->string('source_pdf_sha256', 64); + $table->string('esign_file_id', 128)->nullable(); + $table->string('esign_sign_flow_id', 128)->nullable(); + $table->string('remote_status', 32)->nullable(); + $table->string('signed_pdf_path', 1024)->nullable(); + $table->string('signed_pdf_sha256', 64)->nullable(); + $table->string('certificate_path', 1024)->nullable(); + $table->string('certificate_sha256', 64)->nullable(); + $table->timestamp('sent_at')->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->timestamp('archived_at')->nullable(); + $table->timestamp('last_synced_at')->nullable(); + $table->text('last_error')->nullable(); + $table->string('callback_payload_hash', 64)->nullable(); + $table->unsignedInteger('created_by'); + $table->unsignedInteger('updated_by'); + $table->timestamps(); + $table->softDeletes(); + + $table->unique(['company_id', 'business_no'], 'courier_agreement_signatures_business_unique'); + $table->unique(['company_id', 'idempotency_key'], 'courier_agreement_signatures_idempotency_unique'); + $table->unique('esign_sign_flow_id', 'courier_agreement_signatures_flow_unique'); + $table->index(['company_id', 'status'], 'courier_agreement_signatures_company_status_index'); + }); + } + + public function down(): void + { + Schema::dropIfExists('business_courier_agreement_signatures'); + } +}; diff --git a/database/migrations/2026_08_28_000100_create_business_courier_agreement_signature_events_table.php b/database/migrations/2026_08_28_000100_create_business_courier_agreement_signature_events_table.php new file mode 100644 index 00000000..d4143242 --- /dev/null +++ b/database/migrations/2026_08_28_000100_create_business_courier_agreement_signature_events_table.php @@ -0,0 +1,36 @@ +increments('id'); + $table->unsignedInteger('company_id'); + $table->unsignedInteger('agreement_signature_id')->nullable(); + $table->string('event_key', 128); + $table->string('action', 80); + $table->string('esign_sign_flow_id', 128); + $table->unsignedBigInteger('event_timestamp'); + $table->boolean('verified')->default(true); + $table->boolean('processed')->default(false); + $table->text('raw_body'); + $table->timestamp('received_at'); + $table->timestamp('processed_at')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->unique('event_key', 'courier_agreement_signature_events_key_unique'); + $table->index(['company_id', 'esign_sign_flow_id'], 'courier_agreement_signature_events_flow_index'); + }); + } + + public function down(): void + { + Schema::dropIfExists('business_courier_agreement_signature_events'); + } +}; diff --git a/database/migrations/2026_08_28_000200_create_business_courier_signing_subjects_table.php b/database/migrations/2026_08_28_000200_create_business_courier_signing_subjects_table.php new file mode 100644 index 00000000..219ec321 --- /dev/null +++ b/database/migrations/2026_08_28_000200_create_business_courier_signing_subjects_table.php @@ -0,0 +1,31 @@ +increments('id'); + $table->unsignedInteger('company_id'); + $table->string('name', 255); + $table->string('unified_social_credit_code', 32)->nullable(); + $table->boolean('is_default')->default(false); + $table->unsignedInteger('created_by'); + $table->unsignedInteger('updated_by'); + $table->timestamps(); + $table->softDeletes(); + + $table->unique(['company_id', 'name', 'deleted_at'], 'courier_signing_subjects_name_unique'); + $table->index(['company_id', 'is_default'], 'courier_signing_subjects_default_index'); + }); + } + + public function down(): void + { + Schema::dropIfExists('business_courier_signing_subjects'); + } +}; diff --git a/docs/esign-agreement-integration.md b/docs/esign-agreement-integration.md new file mode 100644 index 00000000..598d3c8e --- /dev/null +++ b/docs/esign-agreement-integration.md @@ -0,0 +1,51 @@ +# E签宝协议签署接入说明 + +## 已实现范围 + +- 五份原始文件使用独立类型和字段映射:`account-proof`、`account-change`、`entity-change`、`shared-contract`、`authorization`。 +- 每次发起先在 `business_courier_agreement_signatures` 落库,生成唯一 `business_no` 和 `idempotency_key`,再生成 PDF、上传文件并创建签署流程。 +- 保存 `fileId`、`signFlowId`、模板版本、原文哈希、签署文件哈希和完成证书哈希。 +- 回调复用现有 E签宝验签入口,校验原始 Body、时间戳、AppId 和 HmacSHA256;协议回调按流程 ID 幂等更新并排队归档。 +- 签署完成后只归档文件,不自动启用收款账户;账户、生效日期和收款人仍须财务复核。 + +## 配置步骤 + +在本地 `runtime/.env` 或受控部署环境中配置,禁止提交到 Git: + +```dotenv +ESIGN_ENVIRONMENT=sandbox +ESIGN_BASE_URL=https://smlopenapi.esign.cn +ESIGN_APP_ID=替换为沙箱AppId +ESIGN_APP_SECRET=替换为沙箱AppSecret +ESIGN_NOTIFY_URL=https://你的公网域名/integrations/esign/callback +ESIGN_CALLBACK_TOLERANCE_SECONDS=900 +ESIGN_TIMEOUT=20 +``` + +正式环境单独使用 `https://openapi.esign.cn`、正式 AppId/AppSecret、独立 Webhook 和独立数据库记录。不要把沙箱凭证切换到生产域名,也不要在日志中输出 Secret、完整手机号、邮箱、身份证号或临时下载 URL。 + +在 E签宝开放平台完成:企业认证、SaaS API V3 应用、出口 IP 白名单、Webhook、`SIGN_FLOW_COMPLETE` 订阅,以及短信/邮件和企业签署服务开通。 + +## 联调步骤 + +1. 在页面“协议签署 → 发起签章”选择文件类型,填写该类型专属字段和对方实名绑定的手机号/邮箱。 +2. 点击“推送至E签宝”,确认本地任务进入“待签署”,并记录任务的 `business_no`、`fileId`、`signFlowId`。 +3. 在沙箱签署页完成实名认证、签字或盖章;验证单页和多页文件的签章位置。 +4. 模拟或等待 `SIGN_FLOW_COMPLETE`:只有 `signFlowStatus=2` 才会下载已签 PDF 和完成证书。 +5. 检查任务变为“已签署并归档”,下载原文、已签协议和证书,核对哈希值。 +6. 不发回调时使用任务行的“同步状态”按钮验证主动查单补偿;重复点击推送或重复回调不得产生第二个 `signFlowId`。 + +## 安全审计要点 + +- 业务单号、文件 ID、流程 ID 分开保存;发起前有唯一键,超时后不得直接重发。 +- 回调使用恒定时间比较和时间戳窗口,先验签再解析;回调状态不能把已完成状态回退为处理中。 +- 原文和归档文件存私有 `uploads` 盘并校验 SHA-256;临时下载地址只在服务端短时使用。 +- 个人证件和账号字段采用加密 cast 存储;权限仅允许管理员发起、同步和下载。 +- 企业名称不能作为模糊账号匹配依据;应在 E签宝实名账号确认后填写手机号/邮箱。 +- 电子签署完成不等于财务数据生效,收款账户变更必须保留人工复核和原档案电话核验。 + +## 真实环境上线前 + +- 使用密钥管理系统或受控环境变量保存正式 Secret,并完成轮换/吊销流程。 +- 配置公网 HTTPS、出口 IP 白名单和回调来源 IP 白名单。 +- 为签章坐标、个人/企业签署、拒签/撤销/过期、下载 URL 过期和回调丢失分别留存验收记录。 diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 8a08a0b1..11710982 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -2,7 +2,7 @@ ## 结论 -项目不是只使用 `rpt.Bulk_Price_Limit` 一张表。当前主线代码直接读取两套上游中的约 40 个表或视图,覆盖组织资料、订单、退款、营销账户、供应商应付、板材、封边条和库存。 +项目不是只使用 `rpt.Bulk_Price_Limit` 一张表。当前主线代码直接读取两套上游中的约 43 个表或视图,覆盖组织资料、订单、退款、营销账户、供应商应付、快递资料、板材、封边条和库存。 `caiwu_business_mirror` 的目标是把项目实际使用的上游原表数据保存为共享业务镜像。网页只读镜像,后台刷新节点在低压、可断点的条件下完成首次全量和后续增量;不得再按页码或筛选条件临时生成不完整的数据副本。 @@ -14,6 +14,7 @@ | 已完成 | `operations_replica/rpt.jst_sku` 已进入 `ops_jst_sku`,普通商品资料页面固定读取 `sku_type = normal` 的共享镜像,并支持稳定分页和业务筛选。 | | 已接入校准 | 聚水潭“普通商品资料”完整 XLSX 导出通过 `product-catalog:import-authoritative-export` 流式导入;导出中不存在的经营分析副本历史行写入 `product_catalog_exclusions`,页面与导出统一排除,但不删除 `ops_jst_sku` 原始镜像行。 | | 本次接入 | `jiansun/dbo.jst_purchase + dbo.jst_purchaseItem` 通过固定联表查询进入 `product_purchase_price_mirror_rows`;普通商品资料只读取 `Finished` 且带“1688一键代发”标签的最近采购单价,并与原商品采购价分别标注来源。 | +| 本次接入 | 工作平台快递资料页面读取 `wp_express` 主表,并预留网点 `wp_express_expNet`、打款账户 `wp_express_account` 标签;三张表均登记为独立镜像数据集,首次同步完成前页面明确显示同步状态。 | | 本次建立 | `config/upstream_mirrors.php` 中登记全部当前代码引用的原表;通用表级同步框架负责建表、稳定游标、断点续传、增量重叠和全量校准。 | | 已开始逐域切换 | 公司、店铺、商标页面在对应镜像完成首次全量后自动改读完整镜像表;首次全量前保留旧快照作为兼容回滚。其他业务域仍需逐项切换,不得宣称全项目已经完成。 | @@ -42,6 +43,7 @@ | 封边条 | `dbo.pm_edgeBandData`、`dbo.pm_edgeBandApplyDetail`、`dbo.pm_edgeBandProfitInfo`、`dbo.finance_edgeBandDeductio`、`dbo.pm_averageUnitPrice` | | 库存与货款对账 | `dbo.pm_boardInventoryDetail_snapshot`、`dbo.fys_supplierGoods_sttlement_purchase`、`dbo.fys_supplierGoods_sttlement_sale`、`dbo.pm_purchaseIn` | | 采购单价 | `dbo.jst_purchase`、`dbo.jst_purchaseItem`(受控字段联表镜像,不复制其他采购业务字段) | +| 快递资料 | `dbo.wp_express`、`dbo.wp_express_expNet`、`dbo.wp_express_account`、`dbo.wp_express_extension` | 其中 `fys_supplierGoods_sttlement_sale` 当前约 280 万行,是首次全量同步的最大对象。必须在低峰期小批量、可断点执行,禁止把全量同步塞进发布流程。 @@ -60,8 +62,9 @@ 1. 公司、店铺、商标等小型维表。 2. 营销账户五张单表账单。 -3. 供应商应付与货款对账。 -4. 订单、退款和推广费用。 -5. 板材、封边条和库存的跨表查询。 +3. 快递资料、网点和打款账户。 +4. 供应商应付与货款对账。 +5. 订单、退款和推广费用。 +6. 板材、封边条和库存的跨表查询。 每个阶段都必须先完成首次全量和数量核对,再将对应 Repository 切到镜像;任一阶段失败时保留上一版镜像和旧只读链路用于回滚。 diff --git a/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php b/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php new file mode 100644 index 00000000..068afcf2 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/CourierInformationMirrorRepository.php @@ -0,0 +1,365 @@ +connection = $mirror->connection(); + } + + public function available(): bool + { + $schema = Schema::connection($this->connection->getName()); + + return $schema->hasTable('business_mirror_table_states') + && $schema->hasTable($this->dataset()->targetTable()); + } + + public function ready(): bool + { + return $this->mirror->ready($this->dataset()); + } + + /** @return array|null */ + public function state(): ?array + { + return $this->mirror->state($this->dataset()); + } + + /** + * @param array|null $state + * @return array{code:string,lag_minutes:?int} + */ + public function syncStatus(?array $state = null, ?CarbonInterface $at = null): array + { + $state ??= $this->state(); + if (! is_array($state)) { + return ['code' => 'unavailable', 'lag_minutes' => null]; + } + + $lastSucceeded = $this->timestamp($state['last_succeeded_at'] ?? null); + $lagMinutes = $lastSucceeded === null + ? null + : (int) ceil(max(0, ($at ?? now())->getTimestamp() - $lastSucceeded) / 60); + $status = (string) ($state['status'] ?? 'pending'); + + if (($state['initial_completed_at'] ?? null) === null) { + $code = $status === 'failed' + ? 'initial_failed' + : ($status === 'running' ? 'initializing' : 'pending'); + } elseif ($status === 'failed') { + $code = 'failed'; + } elseif ($status === 'running') { + $code = ($state['run_mode'] ?? null) === 'full' ? 'reconciling' : 'syncing'; + } elseif ($lagMinutes === null + || $lagMinutes > max((int) config('upstream_mirrors.courier_information.stale_after_minutes', 60), 1)) { + $code = 'delayed'; + } else { + $code = 'healthy'; + } + + return ['code' => $code, 'lag_minutes' => $lagMinutes]; + } + + /** + * @param array $filters + * @return array{data:list,total:int} + */ + public function paginate(array $filters, int $page, int $perPage): array + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $query = $this->filteredExpressQuery($filters); + $total = (clone $query)->count(); + $rows = $query->orderBy('Id') + ->forPage($page, $perPage) + ->get() + ->all(); + + return ['data' => $rows, 'total' => $total]; + } + + /** + * @param array $filters + * @return \Generator + */ + public function exportRows(array $filters, int $batchSize = 500): \Generator + { + if (! $this->ready()) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $batchSize = min(max($batchSize, 1), 5000); + $lastId = null; + + while (true) { + $query = $this->filteredExpressQuery($filters); + if ($lastId !== null) { + $query->where('Id', '>', $lastId); + } + + $rows = $query->orderBy('Id')->limit($batchSize)->get()->all(); + if ($rows === []) { + return; + } + + foreach ($rows as $row) { + yield $row; + } + + $lastId = (int) $rows[array_key_last($rows)]->Id; + if (count($rows) < $batchSize) { + return; + } + } + } + + /** + * 网点标签数据。快递编码为空时返回全部网点;传入编码时只返回对应网点。 + * @return array{data:list,total:int} + */ + public function paginateNetworks(?string $expcode, int $page, int $perPage): array + { + $dataset = $this->datasets->get(self::NETWORK_DATASET_KEY); + if (! $this->mirror->ready($dataset)) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $query = $this->connection->table($dataset->targetTable())->select([ + 'id', 'expid', 'expcode', 'netcode', 'netno', 'netname', 'isbill', + 'province', 'city', 'area', 'town', 'address', 'linker', 'linkermobile', + 'status', 'apitype', 'apipltmname', 'created', 'expnum', + ]); + if ($expcode !== null && $expcode !== '') { + $query->where('expcode', $expcode); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $total = (clone $query)->count(); + + return [ + 'data' => $query->orderByDesc('id')->forPage($page, $perPage)->get()->all(), + 'total' => $total, + ]; + } + + /** + * 打款账户标签数据。 + * @return array{data:list,total:int} + */ + public function paginateAccounts(?string $expcode, int $page, int $perPage): array + { + $dataset = $this->datasets->get(self::ACCOUNT_DATASET_KEY); + if (! $this->mirror->ready($dataset)) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $query = $this->connection->table($dataset->targetTable())->select([ + 'Id', 'expcode', 'expname', 'accountType', 'account', 'accountName', + 'accountkhh', 'createTime', 'invoice', 'erpId', 'erpAccountId', + ]); + if ($expcode !== null && $expcode !== '') { + $query->where('expcode', $expcode); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $total = (clone $query)->count(); + + return [ + 'data' => $query->orderByDesc('Id')->forPage($page, $perPage)->get()->all(), + 'total' => $total, + ]; + } + + /** + * 返回指定快递名称对应的电子签章经办人账号。 + * + * 工作平台将该值保存在 wp_express.dzqzjbr 中,不能用联系人电话 + * 代替;两者在部分快递资料中可能不同。镜像未完成首次同步时返回空 + * 数组,避免影响协议签署页面的正常打开。 + * + * @param list $expnames + * @return array + */ + public function signingAccountsByName(array $expnames): array + { + if (! $this->ready()) { + return []; + } + + $expnames = array_values(array_unique(array_filter(array_map( + static fn ($name): string => trim((string) $name), + $expnames, + ), static fn (string $name): bool => $name !== ''))); + + if ($expnames === []) { + return []; + } + + return $this->connection + ->table($this->dataset()->targetTable()) + ->select(['expname', 'dzqzjbr', 'Id']) + ->whereIn('expname', $expnames) + ->orderBy('Id') + ->get() + ->groupBy(static fn ($row): string => (string) ($row->expname ?? '')) + ->map(static function ($rows): string { + foreach ($rows as $row) { + $account = trim((string) ($row->dzqzjbr ?? '')); + if ($account !== '') { + return $account; + } + } + + return ''; + }) + ->filter(static fn (string $account): bool => $account !== '') + ->all(); + } + + /** + * 快递资料操作日志。 + * @return array{data:list,total:int} + */ + public function paginateLogs(?string $expcode, int $page, int $perPage): array + { + $dataset = $this->datasets->get(self::LOG_DATASET_KEY); + if (! $this->mirror->ready($dataset)) { + throw new RuntimeException('business_mirror_dataset_not_ready'); + } + + $query = $this->connection->table($dataset->targetTable())->select([ + 'Id', 'expcode', 'doTime', 'createTime', 'modifyTime', + ]); + if ($expcode !== null && $expcode !== '') { + $query->where('expcode', $expcode); + } + + $page = max($page, 1); + $perPage = min(max($perPage, 1), 100); + $total = (clone $query)->count(); + + return [ + 'data' => $query->orderByDesc('Id')->forPage($page, $perPage)->get()->all(), + 'total' => $total, + ]; + } + + /** @return array{main:bool,networks:bool,accounts:bool,logs:bool,network_ready:bool,account_ready:bool,log_ready:bool} */ + public function relatedAvailability(): array + { + try { + $schema = Schema::connection($this->connection->getName()); + $networkDataset = $this->datasets->get(self::NETWORK_DATASET_KEY); + $accountDataset = $this->datasets->get(self::ACCOUNT_DATASET_KEY); + $logDataset = $this->datasets->get(self::LOG_DATASET_KEY); + + return [ + 'main' => $schema->hasTable($this->dataset()->targetTable()), + 'networks' => $schema->hasTable($networkDataset->targetTable()), + 'accounts' => $schema->hasTable($accountDataset->targetTable()), + 'logs' => $schema->hasTable($logDataset->targetTable()), + 'network_ready' => $this->mirror->ready($networkDataset), + 'account_ready' => $this->mirror->ready($accountDataset), + 'log_ready' => $this->mirror->ready($logDataset), + ]; + } catch (Throwable) { + return ['main' => false, 'networks' => false, 'accounts' => false, 'logs' => false, 'network_ready' => false, 'account_ready' => false, 'log_ready' => false]; + } + } + + /** @param array $filters */ + private function filteredExpressQuery(array $filters): Builder + { + $query = $this->connection->table($this->dataset()->targetTable())->select([ + 'Id', 'expcode', 'expname', 'outcode', 'scexpcode', 'status', 'paymethod', + 'addvalidsgn', 'kuaiyunsgn', 'autonosgn', 'packnosgn', 'skucountsplitsgn', + 'weight0sgn', 'stopdate', 'tradebtime', 'tradeetime', 'signcom', 'signmode', + 'linker', 'linkmobile', 'paytype', 'undefined1', 'undefined2', 'undefined3', + 'volume0sgn', 'handnosgn', 'decryptsgn', 'pj1sgn', 'undefinedtype', + 'undefined4', 'undefined5', 'dzqzjbr', 'guid', 'is_delete', 'exp_properties', + 'modified', + ]); + + if (($filters['expcode'] ?? '') !== '') { + $query->where('expcode', $filters['expcode']); + } + if (($filters['expname'] ?? '') !== '') { + $query->whereRaw("expname LIKE ? ESCAPE '!'", [$this->contains($filters['expname'])]); + } + foreach (['undefined1', 'undefined2', 'undefined3'] as $column) { + if (($filters[$column] ?? '') !== '') { + $query->whereRaw($column . " LIKE ? ESCAPE '!'", [$this->contains($filters[$column])]); + } + } + if (($filters['tradebtime_from'] ?? '') !== '') { + $query->whereDate('tradebtime', '>=', $filters['tradebtime_from']); + } + if (($filters['tradebtime_to'] ?? '') !== '') { + $query->whereDate('tradebtime', '<=', $filters['tradebtime_to']); + } + if (($filters['status'] ?? '') !== '') { + $query->where('status', (int) $filters['status']); + } + + return $query; + } + + private function dataset(): \Modules\EcommerceFinance\Contracts\BusinessMirrorDataset + { + return $this->datasets->get(self::DATASET_KEY); + } + + private function contains(string $value): string + { + return '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($value)) . '%'; + } + + private function timestamp(mixed $value): ?int + { + if (! is_string($value) || $value === '') { + return null; + } + + try { + return Carbon::parse($value)->getTimestamp(); + } catch (Throwable) { + return null; + } + } +} diff --git a/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php b/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php index dcef66f7..167b2894 100644 --- a/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/DingPayableWorkflowMirrorSynchronizer.php @@ -5,6 +5,7 @@ namespace Modules\EcommerceFinance\Services; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; +use Illuminate\Support\Carbon; use Illuminate\Support\Str; use RuntimeException; use Throwable; @@ -49,29 +50,28 @@ class DingPayableWorkflowMirrorSynchronizer } $mode = $full ? 'full' : 'incremental'; + $stateCursor = $this->decodeJson($state['cursor'] ?? null); + $highWatermark = $this->cursorFromState($this->decodeJson($state['high_watermark'] ?? null)); $resume = is_array($state) && ($state['run_mode'] ?? null) === $mode && in_array($state['status'] ?? null, ['running', 'failed'], true) && is_string($state['generation'] ?? null) - && is_array($state['cursor'] ?? null); + && $this->isCompatibleCursor($stateCursor); $generation = $resume ? (string) $state['generation'] : (string) Str::uuid(); - $cursor = $resume - ? (string) ($state['cursor']['processInstanceId'] ?? '') - : ($full - ? '' - : (string) ($this->decodeJson($state['high_watermark'] ?? null)['processInstanceId'] ?? '')); + [$windowStart, $windowEnd] = $this->window($state, $mode, $resume); + $cursor = $resume ? $this->cursorFromState($stateCursor) : null; $rows = $resume ? (int) ($state['last_upserted_rows'] ?? 0) : 0; $batchSize = min(max($batchSize ?? (int) ($config['batch_size'] ?? 100), 1), 500); $maxBatches = max($maxBatches ?? (int) ($config['max_batches_per_run'] ?? 2), 0); - $this->start($dataset, $target, $source, $mode, $generation, $cursor, $resume); + $this->start($dataset, $target, $source, $mode, $generation, $resume, $windowStart, $windowEnd); $batches = 0; try { while (true) { - $workflows = $this->readWorkflows($source, $processCode, $cursor, $batchSize); + $workflows = $this->readWorkflows($source, $processCode, $cursor, $windowStart, $windowEnd, $batchSize); if ($workflows === []) { - $this->complete($dataset, $target, $mode, $generation, $rows, $cursor); + $this->complete($dataset, $target, $mode, $generation, $rows, $cursor ?? $highWatermark); return ['status' => 'succeeded', 'mode' => $mode, 'batches' => $batches, 'rows' => $rows, 'dataset' => $dataset]; } @@ -116,7 +116,11 @@ class DingPayableWorkflowMirrorSynchronizer ]; } - $cursor = (string) ($workflows[array_key_last($workflows)]['processInstanceId'] ?? $cursor); + $nextCursor = $this->cursorFromWorkflow($workflows[array_key_last($workflows)]); + if ($nextCursor === null) { + throw new RuntimeException('ding_payable_workflow_missing_watermark'); + } + $cursor = $nextCursor; $rows += count($payloads); $batches++; $this->connection->transaction(function () use ($dataset, $target, $payloads, $cursor, $generation, $rows, $now): void { @@ -130,7 +134,9 @@ class DingPayableWorkflowMirrorSynchronizer $this->connection->table('business_mirror_table_states') ->where('dataset_key', $dataset) ->update([ - 'cursor' => json_encode(['processInstanceId' => $cursor], JSON_UNESCAPED_UNICODE), + 'cursor' => $cursor === null + ? null + : json_encode($cursor, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'last_upserted_rows' => $rows, 'updated_at' => $now, ]); @@ -184,7 +190,16 @@ class DingPayableWorkflowMirrorSynchronizer return $state; } - private function start(string $dataset, string $target, string $source, string $mode, string $generation, string $cursor, bool $resume): void + private function start( + string $dataset, + string $target, + string $source, + string $mode, + string $generation, + bool $resume, + ?Carbon $windowStart, + ?Carbon $windowEnd, + ): void { $now = now(); $values = [ @@ -199,7 +214,12 @@ class DingPayableWorkflowMirrorSynchronizer 'updated_at' => $now, ]; if (! $resume) { - $values += ['cursor' => null, 'window_started_at' => null, 'window_ends_at' => null, 'last_upserted_rows' => 0]; + $values += [ + 'cursor' => null, + 'window_started_at' => $windowStart, + 'window_ends_at' => $windowEnd, + 'last_upserted_rows' => 0, + ]; } $query = $this->connection->table('business_mirror_table_states')->where('dataset_key', $dataset); $query->exists() @@ -207,7 +227,7 @@ class DingPayableWorkflowMirrorSynchronizer : $this->connection->table('business_mirror_table_states')->insert(['dataset_key' => $dataset, 'created_at' => $now] + $values); } - private function complete(string $dataset, string $target, string $mode, string $generation, int $rows, string $cursor): void + private function complete(string $dataset, string $target, string $mode, string $generation, int $rows, ?array $cursor): void { $now = now(); $this->connection->transaction(function () use ($dataset, $target, $mode, $generation, $rows, $cursor, $now): void { @@ -219,7 +239,9 @@ class DingPayableWorkflowMirrorSynchronizer $values = [ 'status' => 'succeeded', 'cursor' => null, - 'high_watermark' => json_encode(['processInstanceId' => $cursor], JSON_UNESCAPED_UNICODE), + 'high_watermark' => $cursor === null + ? null + : json_encode($cursor, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'last_succeeded_at' => $now, 'last_upserted_rows' => $rows, 'mirror_row_count' => $this->connection->table($target)->count(), @@ -248,20 +270,97 @@ class DingPayableWorkflowMirrorSynchronizer } /** @return list> */ - private function readWorkflows(string $source, string $processCode, string $cursor, int $limit): array + private function readWorkflows( + string $source, + string $processCode, + ?array $cursor, + ?Carbon $windowStart, + ?Carbon $windowEnd, + int $limit, + ): array { + $watermark = 'COALESCE([updateAt], [createAt])'; $where = '[processCode] = ?'; $bindings = [$processCode]; - if ($cursor !== '') { - $where .= ' AND [processInstanceId] > ?'; - $bindings[] = $cursor; + if ($windowStart !== null && $windowEnd !== null) { + $where .= ' AND ' . $watermark . ' >= ? AND ' . $watermark . ' < ?'; + $bindings[] = $this->sqlServerDateTime($windowStart); + $bindings[] = $this->sqlServerDateTime($windowEnd); + } + if ($cursor !== null) { + $where .= ' AND (' . $watermark . ' > ? OR (' . $watermark . ' = ? AND [processInstanceId] > ?))'; + $bindings[] = (string) ($cursor['updateAt'] ?? ''); + $bindings[] = (string) ($cursor['updateAt'] ?? ''); + $bindings[] = (string) ($cursor['processInstanceId'] ?? ''); } return $this->queries->forSource($source)->select( - 'SELECT TOP (' . $limit . ') [finishTime],[businessId],[title],[result],[originatorUserId],[originatorDeptId],[originatorDeptName],[status],[bizAction],[processInstanceId],[joinAt],[updateAt],[createAt],[processCode],[flowType] FROM [rpt].[ding_Workflow] WHERE ' . $where . ' ORDER BY [processInstanceId]', + 'SELECT TOP (' . $limit . ') [finishTime],[businessId],[title],[result],[originatorUserId],[originatorDeptId],[originatorDeptName],[status],[bizAction],[processInstanceId], [joinAt], COALESCE([updateAt], [createAt]) AS [updateAt], [createAt], [processCode], [flowType] FROM [rpt].[ding_Workflow] WHERE ' . $where . ' ORDER BY ' . $watermark . ', [processInstanceId]', $bindings, ); } + /** @return array{0:?Carbon,1:?Carbon} */ + private function window(?array $state, string $mode, bool $resume): array + { + if ($mode === 'full') { + return [null, null]; + } + + if ($resume && ($state['window_started_at'] ?? null) !== null && ($state['window_ends_at'] ?? null) !== null) { + return [ + Carbon::parse((string) $state['window_started_at']), + Carbon::parse((string) $state['window_ends_at']), + ]; + } + + $overlap = max((int) config('upstream_mirrors.table_sync.overlap_hours', 48), 1); + $lastSucceeded = ($state['last_succeeded_at'] ?? null) !== null + ? Carbon::parse((string) $state['last_succeeded_at']) + : now(); + + return [$lastSucceeded->copy()->subHours($overlap), now()->addSecond()]; + } + + /** @return array{updateAt:string,processInstanceId:string}|null */ + private function cursorFromState(array $cursor): ?array + { + if (($cursor['updateAt'] ?? '') === '' && ($cursor['processInstanceId'] ?? '') === '') { + return null; + } + + if (($cursor['updateAt'] ?? '') === '') { + return null; + } + + return [ + 'updateAt' => (string) $cursor['updateAt'], + 'processInstanceId' => (string) ($cursor['processInstanceId'] ?? ''), + ]; + } + + /** @param array $workflow @return array{updateAt:string,processInstanceId:string}|null */ + private function cursorFromWorkflow(array $workflow): ?array + { + $id = trim((string) ($workflow['processInstanceId'] ?? '')); + $updateAt = trim((string) ($workflow['updateAt'] ?? $workflow['createAt'] ?? '')); + + if ($id === '' || $updateAt === '') { + return null; + } + + return ['updateAt' => $updateAt, 'processInstanceId' => $id]; + } + + private function isCompatibleCursor(array $cursor): bool + { + return $cursor === [] || array_key_exists('updateAt', $cursor); + } + + private function sqlServerDateTime(Carbon $value): string + { + return $value->format('Y-m-d\TH:i:s.v'); + } + /** @param list $ids @param list $columns @return list> */ private function readRelated(string $source, string $table, array $columns, array $ids, string $order): array { diff --git a/resources/views/business/pages/courier-payables/agreement-signing.blade.php b/resources/views/business/pages/courier-payables/agreement-signing.blade.php index 254b37e5..6fcbf6b4 100644 --- a/resources/views/business/pages/courier-payables/agreement-signing.blade.php +++ b/resources/views/business/pages/courier-payables/agreement-signing.blade.php @@ -1,4 +1,10 @@ -@php($agreementCompanyName = company()?->name ?: '当前公司') +@php($agreementTasks = $agreementTasks ?? collect()) +@php($agreementSubjects = $agreementSubjects ?? collect()) +@php($agreementCourierAccounts = $agreementCourierAccounts ?? []) +@php($agreementDefaultSubject = $agreementSubjects->firstWhere('is_default', true) ?: $agreementSubjects->first()) +@php($agreementCompanyName = $agreementDefaultSubject?->name ?: company()?->name ?: '当前公司') +@php($agreementSubjectPayload = $agreementSubjects->map(fn ($subject) => ['id' => $subject->id, 'name' => $subject->name, 'unified_social_credit_code' => $subject->unified_social_credit_code, 'is_default' => (bool) $subject->is_default])->values()) +@php($esignConfigured = \App\Services\Esign\EsignClient::configured())
+ +
+
+
+ + {{ $statusLabels[$sync['code'] ?? 'unavailable'] ?? '镜像状态未知' }} +
+
+ @if (!empty($state['last_succeeded_at'])) + 最近同步 {{ $datetime($state['last_succeeded_at']) }} + @endif + @if (($sync['lag_minutes'] ?? null) !== null) + 数据延迟 {{ number_format((int) $sync['lag_minutes']) }} 分钟 + @endif + @if (isset($state['mirror_row_count'])) + 主表 {{ number_format((int) $state['mirror_row_count']) }} 条 + @endif + @if ($rows && !$courierError) + 当前结果 {{ number_format($rows->total()) }} 条 + @endif +
+
+ + + + @if ($tab === 'express') +
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + 导出 + 重置 +
+
+ @elseif (in_array($tab, ['networks', 'accounts'], true)) +
+ +
+ + +
+
+ +
+
+ @endif + + @if ($courierError) + + @elseif ($courierPending) +
+ + 首次全量同步完成后刷新本页,即可查询工作平台中的快递资料。 +
+ @endif + + @if ($tab === 'logs') +
+ + + + @forelse ($rows ?? [] as $row) + + @empty + + @endforelse + +
ID快递代码操作时间创建时间修改时间
{{ $row->Id ?? '-' }}{{ $row->expcode ?? '-' }}{{ $row->doTime ?? '-' }}{{ $datetime($row->createTime ?? null) }}{{ $datetime($row->modifyTime ?? null) }}
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有操作日志。' }}
+ @if ($rows && !$courierError) + + @endif +
+ @elseif ($tab === 'express') +
+ + + + + + + + + + + @forelse ($rows ?? [] as $row) + @php $enabled = $bool($row->status ?? null) === '是'; @endphp + + + + + + + + + + + + + + + + + + @empty + + @endforelse + +
ID快递公司代码快递公司名称外部编码杉橙快递代码运费打款方式是否启用可达服务是否快运自动寻号配货单号寻号数量拆单重量0寻号停运时间合同开始时间合同结束时间联系人联系电话自定义1自定义2自定义3体积0寻号手工单号解密电子签章经办人最后修改
{{ $row->Id ?? '-' }}{{ $row->expcode ?? '-' }}{{ $row->expname ?? '-' }}{{ $row->outcode ?? '-' }}{{ $row->scexpcode ?? '-' }}{{ $row->paymethod ?? '-' }}{{ $enabled ? '是' : '否' }}{{ $bool($row->addvalidsgn ?? null) }}{{ $bool($row->kuaiyunsgn ?? null) }}{{ $bool($row->autonosgn ?? null) }}{{ $bool($row->packnosgn ?? null) }}{{ $bool($row->skucountsplitsgn ?? null) }}{{ $bool($row->weight0sgn ?? null) }}{{ $date($row->stopdate ?? null) }}{{ $date($row->tradebtime ?? null) }}{{ $date($row->tradeetime ?? null) }}{{ $row->linker ?? '-' }}{{ $row->linkmobile ?? '-' }}{{ $row->undefined1 ?? '-' }}{{ $row->undefined2 ?? '-' }}{{ $row->undefined3 ?? '-' }}{{ $bool($row->volume0sgn ?? null) }}{{ $bool($row->handnosgn ?? null) }}{{ $bool($row->decryptsgn ?? null) }}{{ $row->dzqzjbr ?? '-' }}{{ $datetime($row->modified ?? null) }}
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有快递资料。' }}
+ @if ($rows && !$courierError) + + @endif +
+ @elseif ($tab === 'networks') +
+ + + + @forelse ($rows ?? [] as $row) + + @empty + + @endforelse + +
ID快递代码网点代码网点名称网点号省市区乡镇地址联系人联系电话是否启用接口平台创建时间剩余单号
{{ $row->id ?? '-' }}{{ $row->expcode ?? '-' }}{{ $row->netcode ?? '-' }}{{ $row->netname ?? '-' }}{{ $row->netno ?? '-' }}{{ $row->province ?? '-' }}{{ $row->city ?? '-' }}{{ $row->area ?? '-' }}{{ $row->town ?? '-' }}{{ $row->address ?? '-' }}{{ $row->linker ?? '-' }}{{ $row->linkermobile ?? '-' }}{{ $bool($row->status ?? null) }}{{ $row->apipltmname ?? ($row->apitype ?? '-') }}{{ $datetime($row->created ?? null) }}{{ $row->expnum ?? '-' }}
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有网点资料。' }}
+ @if ($rows && !$courierError) + + @endif +
+ @else +
+ + + + @forelse ($rows ?? [] as $row) + + @empty + + @endforelse + +
ID快递代码快递名称账户类型账户账户名称开户行创建时间发票信息ERP账户ID
{{ $row->Id ?? '-' }}{{ $row->expcode ?? '-' }}{{ $row->expname ?? '-' }}{{ $row->accountType ?? '-' }}{{ $row->account ?? '-' }}{{ $row->accountName ?? '-' }}{{ $row->accountkhh ?? '-' }}{{ $datetime($row->createTime ?? null) }}{{ $row->invoice ?? '-' }}{{ $row->erpAccountId ?? '-' }}
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有打款账户。' }}
+ @if ($rows && !$courierError) + + @endif +
+ @endif +
diff --git a/resources/views/business/partials/cooperation-contract.blade.php b/resources/views/business/partials/cooperation-contract.blade.php new file mode 100644 index 00000000..0d75cf80 --- /dev/null +++ b/resources/views/business/partials/cooperation-contract.blade.php @@ -0,0 +1,137 @@ +@php + $preview = ($mode ?? 'pdf') === 'preview'; + $payload = is_array($payload ?? null) ? $payload : []; +@endphp + +@if ($preview) +
+
甲 方:待填写电 话:待填写
+
乙 方:待填写电 话:待填写
+
+@else +
+
甲 方:{{ $payload['cooperation_party_a_name'] ?? '' }}电 话:{{ $payload['cooperation_party_a_phone'] ?? '' }}
+
乙 方:{{ $payload['cooperation_party_b_name'] ?? '' }}电 话:{{ $payload['cooperation_party_b_phone'] ?? '' }}
+
+@endif + +

甲、乙双方根据《中国人民共和国合同法》、国内物流速递服务业等相关法律法规、地方性法规,双方经友好协商,在平等自愿的基础上就乙方为甲方提供国内、国际物流(速递)服务,签订如下协议条款,以期共同遵守:

+

本协议包括:1、协议文件;2、附件一:报价表; 3.附件二:乙方营业执照、授权代表委托书等资质文件。

+ +

第一条:服务内容、区域

+

乙方受甲方委托办理国内范围内各省、市、县物流速递服务业务,包含线上、线下、甲方内部等交易平台形成的订单速递,服务过程受甲方委托、指示和监督,乙方保证以最快捷、最快响应速度完成甲方之受托业务。

+ +

第二条:协议期限

+

2.1 本协议有效期:自 +@if ($preview)待填写@else{{ $payload['cooperation_start_date'] ?? '' }}@endif +至 +@if ($preview)待填写@else{{ $payload['cooperation_end_date'] ?? '' }}@endif +。

+

2.2 本协议有效期满后,双方若未重新签订协议,则本协议将自动延续至下一年度,延长协议有效期为一年。

+ +

第三条:甲方的权利和义务

+

3.1对所托运的货物进行妥善包装,该包装应符合运输的要求及仓储保管的要求。如果托运易碎、易渗漏货物及危险品等特殊货物,应事先向乙方说明,视必要情况并向乙方提供必要的仓储保管、运输技术资料或文件。需特殊包装、加固时,乙方有义务提供此类服务, 相关费用由甲方承担,同时甲方负有协助、支持乙方开箱验货的义务。同时甲方有监督乙方开箱验货的权利。

+

3.2认真填写运输面单,将货物的名称、数量、收件人的地址、单位名称、收件人、联系方式等信息详细提供给乙方,如由于甲方提供信息错误,导致货物遗失的,乙方不承担赔偿责任,但负有甲方货物运输过程中根据本协议相关约定防止货物丢失或遗失的基本义务,乙方故意行为导致货物丢失或遗失的除外。

+

3.3不得交寄易燃、易爆、易腐蚀或货币、非法出版物等国家明令禁止的禁运品。

+

3.4 按照约定价格和支付方式支付运费的义务。

+

3.5甲方有权对乙方的服务进行考核管理,考核结果由甲方书面通知乙方,乙方应在三日内针对考核结果不达标项目做出书面整改,整改结果不佳的,甲方有权要求乙方持续整改,连续三个考核期不达标的,甲方有权单方面解除合同,追究乙方等过失违约及赔偿责任。

+ +

第四条:乙方的权利和义务

+

4.1乙方应准备充足的寄件辅料(如面单纸)。有关寄件辅料的费用包含于运输费用中,乙方不得向甲方另行计价。当天货物乙方应及时运走不得在甲方仓库存放延误运输时效。乙方需储备一周以上物资(包括但不限于辅料、单号等),物资不足3日应向甲方支付500元每次的违约金;延误超过1小时以上不足24小时的,应向甲方支付1000元每次的违约金;超过24小时的,应向甲方支付2000元每次的违约金,违约金甲方有权直接从当月运费中扣减。

+

4.2在合约派送时效内,最大延误时间不得超过48小时;如延误超过48小时,乙方需要以书面的形式通知甲方,并给出改善措施,且根据甲方的要求进行操作,不得单方面擅自决定。

+

4.3乙方在承运我司货物之后,72小时内无下一步运输记录时或者是在运输过程中超过72小时内无下一步运输信息。我方将默认为乙方丢件,给客户进行成品补发,所产生的全部费用由乙方承担;如遇到放假影响时效,需要乙方以书面的形式通知到我方。

+

4.4乙方为甲方提供快递服务,对甲方交付的物件应谨慎、妥善地进行装卸、搬运、仓储,保证其安全和完整。将甲方交付的货物安全、完好、准时送达到甲方指定的地址和收件人或收件单位。

+

4.5双方在货物交接时,应确认货物原始包装的完好,若发现包装有破损情况,乙方应及时通知甲方沟通调换事宜,如乙方已经接收甲方货物并未就包装和货物提出异议视为甲方的包装与货物符合乙方的运输标准。

+

4.6免费为甲方提供货物运输、签收的查询服务,并定期(每天)向甲方相关人员进行在途数据实时汇报:如因线路问题、查罚超载、交通事故等一系列原因导致货物时效发生变化,乙方必须第一时间将变化后的相关信息告知甲方,否则因此造成的损失,全部由乙方承担。

+

4.6.1、针对甲方客服录入“CRM-查件软件 ”软件中的问题,乙方需在30分钟之内给予有效回复,每延迟10分钟承担10元违约金,上限为2000元/日,违约金甲方有权直接从当月运费中扣减;

+

4.6.2、针对甲方客服录入“CRM-查件软件 ”软件中的问题,乙方每天有效回复率不得低于95%,每天回复率低于95%的,乙方按照1000元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.6.3、针对甲方客服导入“CRM-查件软件 ”软件中查件类型为“快递100”的问题,甲方每天于12点之前导入系统,乙方每天16点之前针对该类型为题的回复率不得低于95%,每天回复率低于95%的,乙方按照1000元/次的标准向甲方支付违约金,从当月运费中扣减。如若因甲方导入数据延迟导致回复率不达标,乙方免责。

+

4.7若乙方发货前需要核对物流点,则免费为甲方提供核对物流点服务,并每天及时在ERP快递工单系统中回复查询结果,乙方每天16点之前回复率低于95%的,乙方按照1000元/次的标准向甲方支付违约金,从当月运费中扣减,若因甲方ERP系统故障导致回复率不达标,乙方免责。

+

4.8及时向甲方通报货物运输的进展情况,出现异常情况,应在24小时内及时通知甲方,商议处理。在紧急情况下,乙方可以自行采取有利于甲方的处理办法,并及时将结果通知甲方。乙方的运输车辆、作业人员必须每天上午10:00前到达甲方指定装车区域,如甲方存在特殊情况会另行通知。因乙方原因,延误一次向甲方支付100元违约金,超过1小时的向甲方支付500元/次违约金,违约金甲方有权直接从当月运费中扣减。

+

4.9甲方在将所托运货物操作出库处理以后,乙方未与甲方现场人员做其他交接确认手续的,则视为乙方对甲方出库货物数量无异议,该出库手续中记载的数量视为乙方实际承运数量。

+

4.10因不可控因素(天灾,突发意外等)导致时效延误的,在甲乙双方协商下共同决定,不得单方面擅自决定。

+

4.11乙方如野蛮装卸、摔托盘、摔货物或未经甲方书面同意私自拉走甲方资产、物资,由乙方承担损坏货物、资产所造成的全部经济损失,且乙方按照1000元/次的标准向甲方支付违约金,违约金用甲方有权直接从当月运费中扣减。

+

4.12由于乙方原因运输途中损坏等货物被退回的或者发生物流被盗、抢、骗等不可抗力因素导致货物灭失或者损坏的,未按时退回仓库的按照丢件赔付。

+

4.13如果甲方要求在同一派送区域内改变送货目的地,乙方有义务无偿提供服务。

+

4.14如甲方中途更改地址,同省区域内,乙方免费变更;跨省更改地址,经甲方确定后额外产生的费用由甲方承担,乙方负责更改。

+

4.15对甲方委托给乙方承运的商品,在未将货物交付到甲方指定的收件人之前,若出现货物丢失、损坏、遭遇盗窃、抢劫等任何异常情况,乙方应立即通知甲方根据甲方的要求操作,并积极配合甲方完成相关货物损失的核实、清点和赔偿。

+

4.16乙方在此同意并完全承认甲方及甲方货主对合同下货物的所有合法权利,并不可撤销的放弃对合同下任何货物的留置权。乙方作为本合同下的服务供应商对任何货物没有也将不会有任何权利。

+

4.17乙方的现场人员需服从甲方管理,遵守甲方公司管理制度,若违反规定造成相关违约金,甲方有权直接从当月运费中扣减。

+

4.17.1、如现场操作人员敷衍或拒不配合,甲方有权要求更换乙方现场负责人,并乙方按照500元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.2、乙方工作人员在非规定区域吸烟的,乙方按照1000元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.3、作业完毕,乙方需按规定整理托盘,清理现场区域垃圾,如无,则乙方按照500元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.4、乙方肆意扰乱现场作业或在仓库内打架闹事,乙方按照1000元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.5、乙方工作人员不得私自进入库区,如有,则乙方按照500元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.6、乙方作业期间需减小噪音,夜间禁止使用油叉车,托盘轻拿轻放,若出现投诉将由乙方承当一切后果,且乙方按照1000元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.7、乙方作业期间叉车行驶速度不得超过5KM/H,如超,则乙方按照200元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.8、乙方操作人员严禁酒后驾驶;一经发现立即通报;且乙方按照5000元/次的标准向甲方支付违约金,从当月运费中扣减;

+

4.17.9、乙方需确保客退件及时返回,如未及时返回甲方有权拒签。

+

4.17.10、每日甲方发货结束后,乙方需48小时内校核出库接收数据并到物流现场办公室签订确认单,未在时效内签订的,视为默认甲方提供交接单数据无问题,对账无争议。

+ +

第五条:送达及退回

+

5.1 收件人收到乙方送达的货物时,经检验发现货物有损坏、有缺失的,有权拒绝签收,乙方须及时通知甲方,在得到甲方许可后,把货物退回甲方。

+

5.2 乙方未经甲方同意私自退回或承运中由于乙方原因未能送达收货地址正常签收的退回,乙方需要承担来回运输费用以及商品损伤带来的损失;异常件乙方反馈48小时后甲方未回复,乙方可自行将货物退回甲方发货地址处。

+

5.3 货物到达目的地,因当天联系不到收件人或无法找到收货地址的,乙方应在24小时内告知甲方,三日内仍无法正常派送的,乙方应及时通知甲方,经甲方同意后将货物退回,产生费用由责任方承担。

+

5.4 乙方无条件负责将所承运的快件派送至收件人收货地址,超区件乙方不得通知收件人自提、补送货费等,额外费用与均由乙方自行承担。

+

5.5 甲方原因货物需退回且在派件前通知乙方拦截,乙方需履行拦截职责,拦截成功货物退回甲方仓库,甲方承担发出运费以及货物损耗,乙方原因货物需退回,货物退回甲方仓库,乙方承担发出运费以及货物损耗,若该件未退回仓库,不论责任方是谁,按丢件处理,乙方承担所有损失。甲方通知乙方在派件后签收前拦截,拦截失败产生的损失由甲方承担。

+

5.6 所有退回件,乙方应在发货之日起3个月内退回甲方仓库,超时退回的将不再补款或者取消扣款。

+

5.7 所有退回件,乙方应在送到甲方仓库时,与甲方人员共同核对入库,完成交接后48小时内签订退货交接清单,未在时效内签订的,视为默认甲方提供退货交接单数据无问题,对账无争议。

+

5.8 仓库复核发货时间起24小时内有揽收信息,24小时有发件信息,48小时内有下一站流转信息,且之后的每一步中转不得超过平台规定时效,违反时效,导致的甲方平台产生的赔付全部由乙方承担,甲方有权从每月结算运费中扣除。

+ +

第六条:费用与结算

+

6.1 费用的支付形式为:银行转账。结算账户信息如下:

+

开户银行:

+

账号:

+

开户行名称:

+

账单接收邮箱:

+

注:

+

6.1.1 后期如银行卡号、账单接收邮箱有变动,应及时通知甲方;因乙方通知延误,造成的一切损失,由乙方自行承担。

+

6.1.2 确认账单以甲方收到纸质签字单为准;若甲方没有收到纸质签字单,为防止乙方故意拖延核对账单,则以乙方邮箱接收到的账单为准,乙方邮箱接收账单7天后,默认乙方确认账单。

+

6.2 乙方应于每月3日前向甲方提供电子对账单,甲方需在每月20日前反馈上月账单,双方账单确认后,甲方需在每月底26日前向乙方结清上月对账无争议运输费用,如若账单未确认,甲方有权拒绝支付上月运输费用。

+

6.3 乙方应于每月向甲方提供电子对账单时,附上相应账期内的退货退回时与仓库签订的退货交接清单,未提供交接清单的,视为默认甲方提供退货交接数据无问题,对账无争议。

+

6.4 乙方应于每月5号之前,在甲方TMS记账管理系统,针对每笔记账进行核实与回复,超过每月5号甲方不再协助乙方核实上月记账问题;乙方未处理记账部分默认同意甲方记账,当月已经核对完毕的记账款项,直接在账单上扣除。

+

6.5 每个结算周期结束后,乙方可通过电子邮件、微信、qq等形式向甲方提供上个周期的结算账单供甲方审核,甲方审核结果于每月20号之前反馈乙方,乙方如对甲方反馈的结算账单有异议,双方应在提出异议之日起2个工作日内共同完成相关费用的核对和确认,乙方对甲方的反馈账单有异议,但无法提供证据证明甲方的反馈账单存在错误,以甲方反馈账单为准。

+

6.6 甲方在收到乙方签字盖章的确认版纸质账单后3个工作日内完成付款(非工作日顺延)。

+

6.7 若当月停止合作,上月及当月货款需循环合并押款40%,押款时间3个月,用于处理售后问题。例如:2月货款10万,3月货款5万,3月停止合作,3月结算6万(10*60%);4月结算5.4万((10-6+5)*60%),5月结算2.16万((15-6-5.4)*60%),6月底结清所有款项。

+ +

第七条:保险及理赔

+

7.1 发生遗失的,乙方按该票快件的货物售价对甲方进行赔偿,但最高不超过壹万元每票,且甲方有权优先从上月的运费中扣除。

+

7.2 运输过程中造成货物破损的,对于破损物品,乙方承担破损零部件补发运费。甲方有权选择任意一家承运商进行配件承运,若配件承运商和成品承运商均为乙方的情况下,且成品和配件均破损;甲方有权使用其他快递进行补发,费用由乙方承担。

+

7.3 除不可抗力外,乙方应承担由于货物错运等原因造成的延误交付的责任。

+

7.4 若因甲方/乙方未履行各自的义务或者职责,所造成的损失,另一方具有进一步追责的权利。

+

7.5 因乙方快递员私下赔付造成重复赔付我司概不负责,我司统一所有赔付从线上走,有我司负责与乙方结算赔付。

+ +

第八条:保密

+

履行本合同过程中,甲乙双方都应向另一方提供相关操作信息、产品信息和电子档的客户汇总信息等其他营业信息。被提供的信息将被视为机密,所有权只属于提供信息方。接收信息方只能把另一方提供的信息用于本合同义务和职责的执行中。除本合同允许外,任何一方不应向其他第三方公开机密信息,若违反本规定给对方造成损失的一方应承担全部赔偿责任。

+ +

第九条:违约责任

+

9.1 若乙方单方面终止合同,需提前1个月以书面形式通知甲方;若不能提前提出私自停止快递运输服务或单方面解除合作关系的,将付与甲方100万的违约金,甲方有权直接从当月运费中扣除,甲乙双方确定不合作关系时,签订《合作关系解除两清协议》,并在停止合作后3个月内处理好所有后续售后问题。如若未处理完,所有产生的经济损失由乙方承担。

+

9.2 合同期内,以签订《报价表》为价格结算依据,乙方未经甲方同意私自调整报价,甲方不予认可,最终结算以双方确定报价表为准。

+

9.3 每天17:30(含)前出库的订单接单率不低于98%(含),乙方接单率低于98%的应向甲方支付每单20元的违约金,甲方有权直接从当月运费中扣除。

+

9.4 乙方不得有任何对客户(收货人)恶意骚扰行为,如客户投诉乙方骚扰行为成立,应向甲方支付壹万元整的违约金。

+

9.5 因乙方运输或服务不当导致产生中差评的,应向甲方支付每单200元的违约金,甲方有权从当月运费中扣除。

+ +

第十条:其他

+

10.1 乙方在此同意并完全承认甲方及甲方货主对协议下货物的所有合法权利,并不可撤销的放弃对协议下任何货物的留置权。乙方作为本协议下的服务供应商对任何货物没有也将不会有任何权利。

+

10.2 本协议一式贰份,甲乙双方各执壹份,具有同等法律效力。

+

10.3 本协议未尽事宜,双方另行协商并签订补充协议约定,签订的补充协议作为本协议的有效附件,与其具有同等法律效力。

+

10.4 本协议终止后,协议双方仍承担协议终止前本协议规定的双方应当履行而尚未履行完毕的一切责任与义务。

+

10.5 如在履行本合同时产生纠纷,双方应当按照协议中的内容履行,如无法履行的,则约定在甲方所在地人民法院解决纠纷。

+

10.6 关于退件拒收,乙方每日退件如因客户拒收或其他原因退回的,退货到达甲方退货仓如存在以下情况甲方有权拒签,且由乙方承担全额损失:

+

外包装存在明显泡水痕迹

+

内件明显缺失20%(内件明细依照内包装所附带安装图计算)

+

外包装丢失,以蛇皮袋、麻袋、胶带等方式包裹退回

+ +@if ($preview) +
+

甲 方:待填写

+

乙 方:待填写

+

代表人:

+

代表人:

+

日 期:签署后生成

+

日 期:签署后生成

+

签约地:常州市

+
+@else +

甲 方:{{ $payload['cooperation_party_a_name'] ?? '' }}

乙 方:{{ $payload['cooperation_party_b_name'] ?? '' }}

代表人:

代表人:

日 期:签署后生成

日 期:签署后生成

签约地:常州市

+@endif diff --git a/resources/views/business/pdf/courier-agreement.blade.php b/resources/views/business/pdf/courier-agreement.blade.php new file mode 100644 index 00000000..a7be743d --- /dev/null +++ b/resources/views/business/pdf/courier-agreement.blade.php @@ -0,0 +1,79 @@ + + + + + + + +
业务单号:{{ $signature->business_no }} 模板:{{ $signature->template_code }}
+

{{ $title }}

+ +@if ($type === 'account-proof') +

TO {{ $payload['company_full_name'] }}:

+

基于我公司正规化管理的需要,同时保证广大客户的汇款安全,我司同意自 {{ $payload['account_proof_effective_date'] }} 起我司货款(运费),请汇款至以下账户:

+ +

请贵公司按照上述汇款资料付款,如因我司提供收款银行帐户资料错误,导致相关款项支付不到位,则由此产生的一切经济纠纷和责任由我司承担。我司承诺若上述收款银行帐户资料发生变化及时书面通知贵公司。

+

以上收款账户的变更,以我司的盖章为有效。

+

{{ $payload['courier_name'] }} 公司盖章:

日期:签署后生成

+@elseif ($type === 'account-change') +

TO {{ $payload['company_full_name'] }}:

+

基于我公司正规化管理的需要,同时保证广大客户的汇款安全,我司收款账户将于 {{ $payload['account_change_date'] }} 变更账户,之前相应的账户(收款账户为:{{ $payload['old_account_name'] }},账号:{{ $payload['old_account_number'] }})于 {{ $payload['old_account_stop_date'] }} 停止使用,即日起我司收款的银行帐户进行变更,自 {{ $payload['new_account_effective_date'] }} 起我司与贵司往来款项请汇款至以下新账户,新汇款资料如下:

+ +

如因我司提供收款银行帐户资料错误导致相关款项支付不到位,由此产生的一切经济纠纷和责任由我司承担。以上收款账户的变更,以我司的盖章为有效。

+

{{ $payload['courier_name'] }} 公司盖章:

日期:签署后生成

+@elseif ($type === 'entity-change') +

致 {{ $payload['company_full_name'] }}:

+

我司由于企业名称变更,原公司名称 {{ $payload['former_company_name'] }} 于 {{ $payload['entity_change_date'] }} 变更为 {{ $payload['changed_company_name'] }},自 {{ $payload['changed_company_start_date'] }} 开始,我司将启用变更后的公司与贵公司开展工作,原公司名称停止使用。

+

变更后,原公司的各项事宜由变更后的公司继续执行。原公司的结算未付款项,由变更之后的公司提供的收款账户收款。原公司的业务和款项若出现法律上的纠纷,由变更后的公司承担责任。

+

特此证明!

+

变更前公司法人签字盖公章:{{ $payload['former_company_name'] }}

变更后公司法人签字盖公章:{{ $payload['changed_company_name'] }}

日期:{{ $payload['entity_proof_date'] }}

+@elseif ($type === 'shared-contract') +

与 {{ $payload['contract_partner_name'] }} 合作的 {{ $payload['shared_courier_name'] }} 快递共用同一份合同,打款资料为同一份资料,同一个签字人以及同一个法人!

+

特此证明!

+

法人签字并公司盖章:

日期:{{ $payload['shared_proof_date'] }}

+@elseif ($type === 'cooperation-contract') + @include('business.partials.cooperation-contract', ['mode' => 'pdf', 'payload' => $payload]) +@else + +

兹委托 {{ $payload['trustee_name'] }} 为我或我司的代理人,全权代表我或我司办理下列第 {{ implode('、', $payload['authorization_items'] ?? []) }} 条事项:

+
    +
  1. 代表委托方代签与 {{ $payload['bill_counterparty'] }} 的往来业务每月账单。
  2. +
  3. 代表委托方代签与 {{ $payload['loan_counterparty'] }} 借支协议的事项。
  4. +
  5. 代表委托方代签汇款账号变更的事项。
  6. +
  7. 代表委托方代收 {{ $payload['payment_counterparty'] }} 的往来货款。
  8. +
+

委托有效期:从 {{ $payload['authorization_start_date'] }} 至 {{ $payload['authorization_end_date'] }} 止。

+

委托方:{{ $payload['principal_name'] }}

受托方:{{ $payload['trustee_name'] }}

日期:签署后生成

+@endif + + diff --git a/routes/admin.php b/routes/admin.php index 607ebe84..58ced581 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -2,6 +2,7 @@ use App\Http\Controllers\Business\CourierQuoteChanges; use App\Http\Controllers\Business\CourierQuoteSignatures; +use App\Http\Controllers\Business\CourierAgreementSignatures; use Illuminate\Support\Facades\Route; use Modules\EcommerceFinance\Http\Controllers\AccountBills; use Modules\EcommerceFinance\Http\Controllers\AlipayBills; @@ -88,6 +89,19 @@ Route::prefix('workspace/courier-payables/quote-management/signatures') Route::get('{quoteSignature}/files/{kind}', [CourierQuoteSignatures::class, 'download'])->name('download'); }); +Route::prefix('workspace/courier-payables/agreement-signatures') + ->name('business.courier-agreement-signatures.') + ->middleware('business.page:courier-payables,agreement-signing') + ->group(function () { + Route::post('/', [CourierAgreementSignatures::class, 'store'])->name('store'); + Route::post('subjects', [CourierAgreementSignatures::class, 'storeSubject'])->name('subjects.store'); + Route::post('subjects/{subject}/update', [CourierAgreementSignatures::class, 'updateSubject'])->name('subjects.update'); + Route::post('subjects/{subject}/default', [CourierAgreementSignatures::class, 'setDefaultSubject'])->name('subjects.default'); + Route::post('{agreementSignature}/synchronize', [CourierAgreementSignatures::class, 'synchronize'])->name('synchronize'); + Route::post('{agreementSignature}/archive', [CourierAgreementSignatures::class, 'archive'])->name('archive'); + Route::get('{agreementSignature}/files/{kind}', [CourierAgreementSignatures::class, 'download'])->name('download'); + }); + Route::get('workspace/product-inventory/normal-products/export', 'Business\Pages@exportNormalProducts') ->middleware('business.page:product-inventory,normal-products') ->name('business.product-inventory.normal-products.export'); @@ -96,6 +110,10 @@ Route::get('workspace/refunds/non-jingxi-refund-data/export', 'Business\Pages@ex ->middleware('business.page:refunds,non-jingxi-refund-data') ->name('business.refunds.non-jingxi-refund-data.export'); +Route::get('workspace/courier-payables/courier-information/export', 'Business\Pages@exportCourierInformation') + ->middleware('business.page:courier-payables,courier-information') + ->name('business.courier-payables.courier-information.export'); + Route::get('workspace/{section}/{page}/{tab}/export', 'Business\Pages@export') ->name('business.pages.export'); diff --git a/tests/Feature/Business/AgreementSigningPageTest.php b/tests/Feature/Business/AgreementSigningPageTest.php index ddbbf745..92da62aa 100644 --- a/tests/Feature/Business/AgreementSigningPageTest.php +++ b/tests/Feature/Business/AgreementSigningPageTest.php @@ -104,6 +104,13 @@ class AgreementSigningPageTest extends FeatureTestCase ->assertSeeText('合同合作方') ->assertSeeText('共用合同的快递名称') ->assertSeeText('共用同一份合同,打款资料为同一份资料') + ->assertSee('data-template-fields="cooperation-contract"', false) + ->assertSee('data-template-preview="cooperation-contract"', false) + ->assertSeeText('甲方名称') + ->assertSeeText('乙方电话') + ->assertSeeText('协议开始日期') + ->assertSeeText('协议结束日期') + ->assertSeeText('甲、乙双方根据') ->assertSee('data-template-fields="authorization"', false) ->assertSee('data-template-preview="authorization"', false) ->assertSeeText('委托方(个人或公司)') diff --git a/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php b/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php new file mode 100644 index 00000000..5f577373 --- /dev/null +++ b/tests/Feature/Business/CourierAgreementSignatureWorkflowTest.php @@ -0,0 +1,200 @@ + 'sandbox', + 'services.esign.base_url' => 'https://smlopenapi.esign.test', + 'services.esign.app_id' => 'sandbox-app-id', + 'services.esign.app_secret' => 'sandbox-app-secret', + 'services.esign.notify_url' => null, + ]); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + } + + public function test_account_proof_uses_its_own_document_mapping_and_pushes_once(): void + { + $this->fakeEsign(); + $payload = $this->accountProofPayload('request-001'); + + $this->loginAs() + ->post(route('business.courier-agreement-signatures.store'), $payload) + ->assertRedirect(route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'agreement-signing', + 'agreement_view' => 'tasks', + ])); + + $signature = CourierAgreementSignature::query()->firstOrFail(); + $this->assertSame('TPL-ACCOUNT-CERT-V2', $signature->template_code); + $this->assertSame(CourierAgreementSignature::STATUS_SIGNING, $signature->status); + $this->assertSame('flow-agreement-001', $signature->esign_sign_flow_id); + Storage::disk('uploads')->assertExists($signature->source_pdf_path); + $this->assertSame('新北中通快递有限公司', $signature->payload['account_proof_account_name']); + + $this->loginAs()->post(route('business.courier-agreement-signatures.store'), $payload)->assertRedirect(); + Http::assertSentCount(4); + $this->assertSame(1, CourierAgreementSignature::query()->count()); + } + + public function test_cooperation_contract_maps_party_variables_and_creates_two_signers(): void + { + $this->fakeEsign(); + $payload = [ + 'idempotency_key' => 'cooperation-001', + 'courier_name' => '新北中通', + 'document_type' => 'cooperation-contract', + 'signing_subject' => $this->company->name, + 'company_full_name' => $this->company->name, + 'signing_deadline' => now()->addDays(7)->toDateString(), + 'esign_account' => '13800138000', + 'secondary_esign_account' => '13900139000', + 'operator_name' => '张经理', + 'archive_mode' => 'auto', + 'cooperation_party_a_name' => $this->company->name, + 'cooperation_party_a_phone' => '0519-88886666', + 'cooperation_party_b_name' => '新北中通快递有限公司', + 'cooperation_party_b_phone' => '18112896651', + 'cooperation_start_date' => '2026-01-01', + 'cooperation_end_date' => '2026-12-31', + ]; + + $this->loginAs() + ->post(route('business.courier-agreement-signatures.store'), $payload) + ->assertRedirect(); + + $signature = CourierAgreementSignature::query()->firstOrFail(); + $this->assertSame('cooperation-contract', $signature->document_type); + $this->assertSame('TPL-COOPERATION-CONTRACT-V1', $signature->template_code); + $this->assertSame('0519-88886666', $signature->payload['cooperation_party_a_phone']); + $this->assertSame('2026-12-31', $signature->payload['cooperation_end_date']); + + Http::assertSent(function (ClientRequest $request): bool { + if ($request->url() !== 'https://smlopenapi.esign.test/v3/sign-flow/create-by-file') { + return false; + } + + $json = $request->data(); + $signers = $json['signers'] ?? []; + + return count($signers) === 2 + && ($signers[0]['orgSignerInfo']['orgName'] ?? null) === $this->company->name + && ($signers[1]['orgSignerInfo']['orgName'] ?? null) === '新北中通快递有限公司'; + }); + } + + public function test_verified_agreement_callback_is_idempotent_and_queues_archive(): void + { + Queue::fake(); + $signature = CourierAgreementSignature::create([ + 'company_id' => $this->company->id, + 'business_no' => 'AGR-CALLBACK-001', + 'idempotency_key' => 'callback-001', + 'document_type' => 'account-proof', + 'template_code' => 'TPL-ACCOUNT-CERT-V2', + 'template_version' => '2', + 'source_file_name' => '收款账户证明文件.doc', + 'status' => CourierAgreementSignature::STATUS_SIGNING, + 'courier_name' => '新北中通', + 'company_full_name' => $this->company->name, + 'organization_name' => '新北中通快递有限公司', + 'operator_name' => '张经理', + 'operator_account' => '13800138000', + 'payload' => ['company_full_name' => $this->company->name, 'courier_name' => '新北中通'], + 'environment' => 'sandbox', + 'source_pdf_path' => 'courier-agreements/test/source.pdf', + 'source_pdf_sha256' => hash('sha256', '%PDF-source'), + 'esign_file_id' => 'file-agreement-001', + 'esign_sign_flow_id' => 'flow-agreement-callback', + 'remote_status' => '1', + 'created_by' => $this->user->id, + 'updated_by' => $this->user->id, + ]); + $payload = json_encode([ + 'action' => 'SIGN_FLOW_COMPLETE', + 'signFlowId' => 'flow-agreement-callback', + 'signFlowStatus' => '2', + ], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); + $timestamp = (string) now()->getTimestampMs(); + $callbackSignature = hash_hmac('sha256', $timestamp . '12' . $payload, 'sandbox-app-secret'); + + $server = [ + 'HTTP_X_TSIGN_OPEN_TIMESTAMP' => $timestamp, + 'HTTP_X_TSIGN_OPEN_SIGNATURE_ALGORITHM' => 'HmacSHA256', + 'HTTP_X_TSIGN_OPEN_APP_ID' => 'sandbox-app-id', + 'HTTP_X_TSIGN_OPEN_SIGNATURE' => $callbackSignature, + 'CONTENT_TYPE' => 'application/json', + ]; + $this->call('POST', route('integrations.esign.callback') . '?zeta=2&alpha=1', [], [], [], $server, $payload) + ->assertOk(); + + $signature->refresh(); + $this->assertSame(CourierAgreementSignature::STATUS_COMPLETED, $signature->status); + $this->assertSame(hash('sha256', $payload), $signature->callback_payload_hash); + Queue::assertPushed(ArchiveCourierAgreementSignature::class, 1); + $this->assertNull(app(\App\Support\CourierAgreementSignatureService::class)->acceptCallback( + 'flow-agreement-callback', '2', hash('sha256', $payload), + )); + + $this->call('POST', route('integrations.esign.callback') . '?zeta=2&alpha=1', [], [], [], $server, $payload) + ->assertOk(); + Queue::assertPushed(ArchiveCourierAgreementSignature::class, 1); + } + + private function fakeEsign(): 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-agreement-001', 'fileUploadUrl' => 'https://upload.esign.test/agreement-001'], + ]), + $request->url() === 'https://upload.esign.test/agreement-001' => Http::response(['ok' => true]), + $request->url() === 'https://smlopenapi.esign.test/v3/files/file-agreement-001' => Http::response([ + 'code' => 0, + 'data' => ['status' => 2], + ]), + $request->url() === 'https://smlopenapi.esign.test/v3/sign-flow/create-by-file' => Http::response([ + 'code' => 0, + 'data' => ['signFlowId' => 'flow-agreement-001'], + ]), + default => Http::response(['code' => 404], 404), + }; + }); + } + + private function accountProofPayload(string $idempotencyKey): array + { + return [ + 'idempotency_key' => $idempotencyKey, + 'courier_name' => '新北中通', + 'document_type' => 'account-proof', + 'signing_subject' => $this->company->name, + 'company_full_name' => $this->company->name, + 'signing_deadline' => now()->addDays(7)->toDateString(), + 'esign_account' => '13800138000', + 'operator_name' => '张经理', + 'archive_mode' => 'auto', + 'account_proof_effective_date' => now()->toDateString(), + 'account_proof_account_name' => '新北中通快递有限公司', + 'account_proof_bank_name' => '中国工商银行', + 'account_proof_bank_account' => '6222000012345678', + ]; + } +} diff --git a/tests/Feature/Business/CourierInformationPageTest.php b/tests/Feature/Business/CourierInformationPageTest.php new file mode 100644 index 00000000..56d6e3aa --- /dev/null +++ b/tests/Feature/Business/CourierInformationPageTest.php @@ -0,0 +1,91 @@ +user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + + $repository = Mockery::mock(CourierInformationMirrorRepository::class); + $repository->shouldReceive('relatedAvailability')->once()->andReturn([ + 'main' => false, 'networks' => false, 'accounts' => false, + 'network_ready' => false, 'account_ready' => false, + ]); + $repository->shouldReceive('available')->once()->andReturnFalse(); + $repository->shouldNotReceive('state'); + $repository->shouldNotReceive('syncStatus'); + $repository->shouldNotReceive('ready'); + $repository->shouldNotReceive('paginate'); + $this->app->instance(CourierInformationMirrorRepository::class, $repository); + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'courier-information', + ])) + ->assertOk() + ->assertSeeText('快递资料') + ->assertSeeText('共享业务镜像尚未建立,快递资料暂时无法读取。') + ->assertSeeText('网点') + ->assertSeeText('打款信息') + ->assertSeeText('操作日志'); + } + + public function test_page_renders_mirrored_courier_rows_and_filters(): void + { + $this->user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + + $repository = Mockery::mock(CourierInformationMirrorRepository::class); + $repository->shouldReceive('relatedAvailability')->once()->andReturn([ + 'main' => true, 'networks' => false, 'accounts' => false, + 'network_ready' => false, 'account_ready' => false, + ]); + $repository->shouldReceive('available')->once()->andReturnTrue(); + $repository->shouldReceive('state')->once()->andReturn([ + 'status' => 'succeeded', + 'initial_completed_at' => '2026-08-28 10:00:00', + 'last_succeeded_at' => '2026-08-28 10:00:00', + 'mirror_row_count' => 1, + ]); + $repository->shouldReceive('syncStatus')->once()->andReturn(['code' => 'healthy', 'lag_minutes' => 3]); + $repository->shouldReceive('ready')->once()->andReturnTrue(); + $repository->shouldReceive('paginate')->once()->withArgs(function (array $filters, int $page, int $limit): bool { + return $filters['expcode'] === 'SF' && $filters['status'] === '1' && $page === 1 && $limit > 0; + })->andReturn([ + 'data' => [(object) [ + 'Id' => 1, + 'expcode' => 'SF', + 'expname' => '顺丰速运', + 'status' => 1, + 'tradebtime' => '2026-01-01 00:00:00', + ]], + 'total' => 1, + ]); + $this->app->instance(CourierInformationMirrorRepository::class, $repository); + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'courier-payables', + 'page' => 'courier-information', + 'expcode' => 'SF', + 'status' => '1', + ])) + ->assertOk() + ->assertSeeText('顺丰速运') + ->assertSeeText('SF') + ->assertSeeText('同步正常') + ->assertSeeText('可达服务') + ->assertSee('name="expcode"', false); + } +} diff --git a/tests/Feature/Business/CourierSigningSubjectTest.php b/tests/Feature/Business/CourierSigningSubjectTest.php new file mode 100644 index 00000000..ecf7ed2f --- /dev/null +++ b/tests/Feature/Business/CourierSigningSubjectTest.php @@ -0,0 +1,74 @@ +user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + } + + public function testAdminCanCreateUpdateAndSwitchSigningSubjects(): void + { + $this->grantWorkspaceAccess(); + + $first = $this->loginAs()->postJson( + route('business.courier-agreement-signatures.subjects.store'), + ['name' => '甲公司', 'unified_social_credit_code' => '91320100MA1TEST001'], + ); + + $first->assertOk() + ->assertJsonPath('subject.name', '甲公司') + ->assertJsonPath('subject.is_default', true); + + $firstSubject = CourierSigningSubject::query()->where('name', '甲公司')->firstOrFail(); + + $second = $this->postJson( + route('business.courier-agreement-signatures.subjects.store'), + ['name' => '乙公司'], + ); + + $second->assertOk()->assertJsonPath('subject.is_default', false); + $secondSubject = CourierSigningSubject::query()->where('name', '乙公司')->firstOrFail(); + + $this->postJson( + route('business.courier-agreement-signatures.subjects.default', $secondSubject), + )->assertOk()->assertJsonPath('subject.is_default', true); + + $this->assertFalse($firstSubject->fresh()->is_default); + $this->assertTrue($secondSubject->fresh()->is_default); + + $this->postJson( + route('business.courier-agreement-signatures.subjects.update', $secondSubject), + ['name' => '乙公司(新)', 'unified_social_credit_code' => '91320100MA1TEST002'], + )->assertOk()->assertJsonPath('subject.name', '乙公司(新)'); + + $this->assertDatabaseHas('business_courier_signing_subjects', [ + 'id' => $secondSubject->id, + 'name' => '乙公司(新)', + 'is_default' => 1, + ]); + } + + public function testDuplicateSubjectNameIsRejected(): void + { + $this->grantWorkspaceAccess(); + $this->loginAs()->postJson( + route('business.courier-agreement-signatures.subjects.store'), + ['name' => '甲公司'], + )->assertOk(); + + $this->withExceptionHandling()->postJson( + route('business.courier-agreement-signatures.subjects.store'), + ['name' => '甲公司'], + )->assertStatus(422) + ->assertJsonValidationErrors(['name']); + } +} diff --git a/tests/Unit/EcommerceFinance/CourierInformationMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/CourierInformationMirrorRepositoryTest.php new file mode 100644 index 00000000..0fc35785 --- /dev/null +++ b/tests/Unit/EcommerceFinance/CourierInformationMirrorRepositoryTest.php @@ -0,0 +1,211 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'upstream_mirrors.datasets' => [ + CourierInformationMirrorRepository::DATASET_KEY => $this->definition('wp_express', 'js_wp_express', ['Id'], 'modified'), + CourierInformationMirrorRepository::NETWORK_DATASET_KEY => $this->definition('wp_express_expNet', 'js_wp_express_exp_net', ['id']), + CourierInformationMirrorRepository::ACCOUNT_DATASET_KEY => $this->definition('wp_express_account', 'js_wp_express_account', ['Id']), + CourierInformationMirrorRepository::LOG_DATASET_KEY => $this->definition('wp_express_extension', 'js_wp_express_extension', ['Id'], 'modifyTime'), + ], + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + $table->string('status')->nullable(); + $table->string('run_mode')->nullable(); + $table->json('cursor')->nullable(); + $table->json('high_watermark')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('mirror_row_count')->default(0); + }); + $this->createExpressTable(); + $this->createRelatedTables(); + + $this->repository = new CourierInformationMirrorRepository( + new BusinessMirrorDatasetRegistry(), + new GenericBusinessMirrorRepository(app('db')), + ); + } + + public function test_it_filters_and_pages_mirrored_courier_records(): void + { + $this->markReady(2); + $this->insertExpress(1, ['expcode' => 'SF', 'expname' => '顺丰', 'status' => 1]); + $this->insertExpress(2, ['expcode' => 'YD', 'expname' => '韵达', 'status' => 0]); + + $result = $this->repository->paginate([ + 'expcode' => 'SF', + 'expname' => '', + 'undefined1' => '', + 'undefined2' => '', + 'undefined3' => '', + 'tradebtime_from' => '', + 'tradebtime_to' => '', + 'status' => '1', + ], 1, 1); + + $this->assertSame(1, $result['total']); + $this->assertSame('SF', $result['data'][0]->expcode); + $this->assertTrue($this->repository->available()); + $this->assertTrue($this->repository->ready()); + } + + public function test_it_reads_networks_and_accounts_by_courier_code(): void + { + $this->markReady(1); + $this->markDatasetReady(CourierInformationMirrorRepository::NETWORK_DATASET_KEY); + $this->markDatasetReady(CourierInformationMirrorRepository::ACCOUNT_DATASET_KEY); + $this->markDatasetReady(CourierInformationMirrorRepository::LOG_DATASET_KEY); + DB::connection('business_mirror')->table('js_wp_express_exp_net')->insert([ + '_mirror_key' => 'network-1', 'id' => 1, 'expid' => 1, 'expcode' => 'SF', 'netname' => '浦东网点', + ]); + DB::connection('business_mirror')->table('js_wp_express_account')->insert([ + '_mirror_key' => 'account-1', 'Id' => 1, 'expcode' => 'SF', 'accountName' => '顺丰账户', + ]); + DB::connection('business_mirror')->table('js_wp_express_extension')->insert([ + '_mirror_key' => 'log-1', 'Id' => 1, 'expcode' => 'SF', 'doTime' => 2, + 'createTime' => '2026-08-28 10:00:00', 'modifyTime' => '2026-08-28 10:00:00', + ]); + + $networks = $this->repository->paginateNetworks('SF', 1, 20); + $accounts = $this->repository->paginateAccounts('SF', 1, 20); + $logs = $this->repository->paginateLogs('SF', 1, 20); + + $this->assertSame(1, $networks['total']); + $this->assertSame('浦东网点', $networks['data'][0]->netname); + $this->assertSame(1, $accounts['total']); + $this->assertSame('顺丰账户', $accounts['data'][0]->accountName); + $this->assertSame(1, $logs['total']); + $this->assertSame(2, $logs['data'][0]->doTime); + } + + public function test_it_reads_esign_accounts_from_the_dzqzjbr_field(): void + { + $this->markReady(2); + $this->insertExpress(1, [ + 'expname' => '常州圆通其他', + 'dzqzjbr' => '13800000001', + ]); + $this->insertExpress(2, [ + 'expname' => '没有账号的快递', + 'dzqzjbr' => null, + ]); + + $accounts = $this->repository->signingAccountsByName([ + '常州圆通其他', + '没有账号的快递', + ]); + + $this->assertSame(['常州圆通其他' => '13800000001'], $accounts); + } + + private function createExpressTable(): void + { + Schema::connection('business_mirror')->create('js_wp_express', function (Blueprint $table): void { + $table->string('_mirror_key')->primary(); + $table->integer('Id'); + foreach (['expcode', 'expname', 'outcode', 'scexpcode', 'paymethod', 'signcom', 'signmode', 'linker', 'linkmobile', 'paytype', 'undefined1', 'undefined2', 'undefined3', 'undefinedtype', 'undefined4', 'undefined5', 'dzqzjbr', 'guid', 'exp_properties'] as $column) { + $table->string($column)->nullable(); + } + foreach (['status', 'addvalidsgn', 'kuaiyunsgn', 'autonosgn', 'packnosgn', 'skucountsplitsgn', 'weight0sgn', 'volume0sgn', 'handnosgn', 'decryptsgn', 'pj1sgn', 'is_delete'] as $column) { + $table->integer($column)->nullable(); + } + foreach (['stopdate', 'tradebtime', 'tradeetime', 'modified'] as $column) { + $table->dateTime($column)->nullable(); + } + }); + } + + private function createRelatedTables(): void + { + Schema::connection('business_mirror')->create('js_wp_express_exp_net', function (Blueprint $table): void { + $table->string('_mirror_key')->primary(); + $table->integer('id'); + $table->integer('expid')->nullable(); + foreach (['expcode', 'netcode', 'netno', 'netname', 'isbill', 'province', 'city', 'area', 'town', 'address', 'linker', 'linkermobile', 'status', 'apitype', 'apipltmname', 'created', 'expnum'] as $column) { + $table->string($column)->nullable(); + } + }); + Schema::connection('business_mirror')->create('js_wp_express_account', function (Blueprint $table): void { + $table->string('_mirror_key')->primary(); + $table->integer('Id'); + foreach (['expcode', 'expname', 'accountType', 'account', 'accountName', 'accountkhh', 'createTime', 'invoice', 'erpId', 'erpAccountId'] as $column) { + $table->string($column)->nullable(); + } + }); + Schema::connection('business_mirror')->create('js_wp_express_extension', function (Blueprint $table): void { + $table->string('_mirror_key')->primary(); + $table->integer('Id'); + $table->string('expcode')->nullable(); + $table->integer('doTime')->nullable(); + $table->dateTime('createTime')->nullable(); + $table->dateTime('modifyTime')->nullable(); + }); + } + + private function insertExpress(int $id, array $overrides): void + { + DB::connection('business_mirror')->table('js_wp_express')->insert(array_merge([ + '_mirror_key' => 'express-' . $id, + 'Id' => $id, + 'expcode' => 'EXP-' . $id, + 'expname' => '测试快递', + 'status' => 1, + 'modified' => '2026-08-28 10:00:00', + ], $overrides)); + } + + private function markReady(int $rows): void + { + $this->markDatasetReady(CourierInformationMirrorRepository::DATASET_KEY, $rows); + } + + private function markDatasetReady(string $key, int $rows = 1): void + { + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => $key, + 'status' => 'succeeded', + 'initial_completed_at' => '2026-08-28 10:00:00', + 'last_succeeded_at' => '2026-08-28 10:00:00', + 'mirror_row_count' => $rows, + ]); + } + + private function definition(string $object, string $target, array $keys, ?string $watermark = null): array + { + return [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => $object, + 'target' => $target, + 'keys' => $keys, + 'watermark' => $watermark, + ]; + } +} diff --git a/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php new file mode 100644 index 00000000..0018d5d6 --- /dev/null +++ b/tests/Unit/EcommerceFinance/DingPayableWorkflowMirrorSynchronizerTest.php @@ -0,0 +1,199 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'upstream_mirrors.table_sync.overlap_hours' => 48, + 'upstream_mirrors.ding_payable_workflows' => [ + 'dataset_key' => 'operations_replica.rpt.ding_payable_workflows', + 'source_key' => 'operations_replica', + 'process_code' => 'PROC-TEST', + 'target_table' => 'ding_payable_workflow_mirror', + 'batch_size' => 100, + 'max_batches_per_run' => 2, + ], + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + $table->string('source_key'); + $table->string('source_object'); + $table->string('target_table'); + $table->string('status')->default('pending'); + $table->string('run_mode')->nullable(); + $table->string('generation')->nullable(); + $table->json('cursor')->nullable(); + $table->json('high_watermark')->nullable(); + $table->dateTime('window_started_at')->nullable(); + $table->dateTime('window_ends_at')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_full_succeeded_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('last_upserted_rows')->default(0); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->string('last_error_code')->nullable(); + $table->timestamps(); + }); + + $this->query = new FakeDingPayableWorkflowQuery(); + $factory = new class($this->query) extends UpstreamReadOnlyQueryFactory { + public function __construct(private readonly UpstreamReadOnlyQuery $query) {} + + public function forSource(string $source): UpstreamReadOnlyQuery + { + return $this->query; + } + }; + $this->synchronizer = new DingPayableWorkflowMirrorSynchronizer($factory); + } + + public function test_full_sync_resumes_with_update_time_and_process_id_tie_breaker(): void + { + $sameUpdateAt = '2026-08-29 10:00:00.1234567'; + $this->query->workflowBatches = [[ + $this->workflow('A-process', $sameUpdateAt), + $this->workflow('B-process', $sameUpdateAt), + ]]; + + $result = $this->synchronizer->sync(true, 2, 1); + + $this->assertSame('running', $result['status']); + $this->assertStringContainsString('ORDER BY COALESCE([updateAt], [createAt]), [processInstanceId]', $this->query->calls[0]['sql']); + $state = DB::connection('business_mirror')->table('business_mirror_table_states')->first(); + $this->assertSame([ + 'updateAt' => $sameUpdateAt, + 'processInstanceId' => 'B-process', + ], json_decode((string) $state->cursor, true)); + + $this->query->calls = []; + $this->query->workflowBatches = [[ + $this->workflow('C-process', $sameUpdateAt), + ]]; + + $result = $this->synchronizer->sync(true, 2, 0); + + $this->assertSame('succeeded', $result['status']); + $this->assertStringContainsString( + 'COALESCE([updateAt], [createAt]) > ? OR (COALESCE([updateAt], [createAt]) = ? AND [processInstanceId] > ?', + $this->query->calls[0]['sql'], + ); + $this->assertSame([$sameUpdateAt, $sameUpdateAt, 'B-process'], array_slice($this->query->calls[0]['bindings'], -3)); + $this->assertSame(3, DB::connection('business_mirror')->table('ding_payable_workflow_mirror')->count()); + } + + public function test_incremental_sync_uses_overlap_window_and_keeps_fixed_process_code(): void + { + $this->query->workflowBatches = [[ + $this->workflow('existing-process', now()->subHour()->format('Y-m-d H:i:s.u')), + ]]; + $this->synchronizer->sync(true, 10, 0); + + $this->query->calls = []; + $this->query->workflowBatches = [[ + $this->workflow('new-process', now()->format('Y-m-d H:i:s.u'), 'RUNNING'), + ]]; + + $result = $this->synchronizer->sync(false, 10, 0); + + $this->assertSame('succeeded', $result['status']); + $sql = $this->query->calls[0]['sql']; + $this->assertStringContainsString('[processCode] = ?', $sql); + $this->assertStringContainsString('COALESCE([updateAt], [createAt]) >= ? AND COALESCE([updateAt], [createAt]) < ?', $sql); + $this->assertStringContainsString('ORDER BY COALESCE([updateAt], [createAt]), [processInstanceId]', $sql); + $this->assertCount(3, $this->query->calls[0]['bindings']); + $this->assertSame('PROC-TEST', $this->query->calls[0]['bindings'][0]); + $this->assertSame('RUNNING', json_decode( + (string) DB::connection('business_mirror')->table('ding_payable_workflow_mirror')->where('process_instance_id', 'new-process')->value('workflow_payload'), + true, + )['status']); + + $state = DB::connection('business_mirror')->table('business_mirror_table_states')->first(); + $this->assertArrayHasKey('updateAt', json_decode((string) $state->high_watermark, true)); + } + + public function test_legacy_process_id_only_watermark_does_not_skip_new_processes(): void + { + $this->query->workflowBatches = [[ + $this->workflow('existing-process', now()->subHour()->format('Y-m-d H:i:s.u')), + ]]; + $this->synchronizer->sync(true, 10, 0); + + DB::connection('business_mirror')->table('business_mirror_table_states')->update([ + 'high_watermark' => json_encode(['processInstanceId' => 'z-last-process']), + ]); + $this->query->calls = []; + $this->query->workflowBatches = [[ + $this->workflow('a-new-process', now()->format('Y-m-d H:i:s.u')), + ]]; + + $this->synchronizer->sync(false, 10, 0); + + $this->assertStringNotContainsString('AND [processInstanceId] > ?', $this->query->calls[0]['sql']); + $this->assertSame(2, DB::connection('business_mirror')->table('ding_payable_workflow_mirror')->count()); + } + + /** @return array */ + private function workflow(string $id, string $updateAt, string $status = 'COMPLETED'): array + { + return [ + 'processInstanceId' => $id, + 'processCode' => 'PROC-TEST', + 'updateAt' => $updateAt, + 'createAt' => $updateAt, + 'status' => $status, + 'originatorUserId' => '', + ]; + } +} + +class FakeDingPayableWorkflowQuery extends UpstreamReadOnlyQuery +{ + /** @var list>> */ + public array $workflowBatches = []; + + /** @var list */ + public array $calls = []; + + public function __construct() + { + parent::__construct('operations_replica'); + } + + public function select(string $sql, array $bindings = []): array + { + $this->calls[] = compact('sql', 'bindings'); + + if (str_contains($sql, 'FROM [rpt].[ding_Workflow]')) { + return array_shift($this->workflowBatches) ?? []; + } + + return []; + } +}