connection = $database->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), ); } /** * @return array */ public function syncMonth(string $month, int $limit = 20, bool $force = false): array { if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { throw new RuntimeException('月份格式应为 YYYY-MM。'); } $limit = min(max($limit, 1), 100); $this->assertReady(); $scope = $this->scope(); $this->ensureFlowsForMonth($month, $scope); if ($force) { $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->update([ 'scan_status' => 'pending', 'scanned_at' => null, 'updated_at' => now(), ]); } $query = $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->whereNotNull('process_instance_id') ->where('process_instance_id', '!=', '') ->whereNull('scanned_at'); $flows = $query ->orderByDesc('paid_at') ->orderByDesc('business_id') ->limit($limit) ->get() ->all(); if ($flows === []) { $remaining = (int) $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->whereNotNull('process_instance_id') ->where('process_instance_id', '!=', '') ->whereNull('scanned_at') ->count(); return [ 'status' => 'succeeded', 'month' => $month, 'processed_flows' => 0, 'recognized_invoices' => 0, 'failed_flows' => 0, 'remaining_flows' => $remaining, 'ocr_configured' => $this->recognizerOcrConfigured(), ]; } $businessIds = array_values(array_filter(array_column($flows, 'business_id'))); [$workflows, $attachmentRows] = $this->loadUpstreamWorkflowsAndAttachments($businessIds); $attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows); $attachmentsByBusiness = $this->addCommentAttachmentFallback( $businessIds, $workflows, $attachmentsByBusiness, ); $metrics = [ 'processed_flows' => 0, 'recognized_invoices' => 0, 'failed_flows' => 0, 'remaining_flows' => 0, 'ocr_configured' => $this->recognizerOcrConfigured(), ]; $tempRoot = storage_path('app/temp/invoice-sync/' . $month . '-' . bin2hex(random_bytes(6))); if (! is_dir($tempRoot) && ! mkdir($tempRoot, 0755, true) && ! is_dir($tempRoot)) { throw new RuntimeException('无法创建发票抓取临时目录。'); } try { foreach ($flows as $flow) { $businessId = (string) $flow->business_id; $workflow = $workflows[$businessId] ?? []; $files = $attachmentsByBusiness[$businessId] ?? []; $flowResult = $this->scanFlow( $flow, $workflow, $files, $tempRoot . '/' . preg_replace('/[^A-Za-z0-9_-]/', '_', $businessId), ); $metrics['processed_flows']++; $metrics['recognized_invoices'] += $flowResult['invoice_count']; if ($flowResult['scan_status'] === 'failed') { $metrics['failed_flows']++; } } } finally { $this->removeDirectory($tempRoot); } $metrics['remaining_flows'] = (int) $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->whereNotNull('process_instance_id') ->where('process_instance_id', '!=', '') ->whereNull('scanned_at') ->count(); $this->updateState($metrics); return [ 'status' => 'succeeded', 'month' => $month, ...$metrics, ]; } private function assertReady(): void { if (! Schema::connection($this->connection->getName())->hasTable('ding_invoice_flow_mirror') || ! Schema::connection($this->connection->getName())->hasTable('ding_invoice_record_mirror') || ! Schema::connection($this->connection->getName())->hasTable('ding_process_payment_line_mirror') || ! Schema::connection($this->connection->getName())->hasTable('ding_process_detail_mirror')) { throw new RuntimeException('OA 流程镜像或发票镜像尚未准备完成。'); } } private function scope(): string { return trim((string) config( 'upstream_mirrors.ding_process_details.scope', 'personal_permission', )) ?: 'personal_permission'; } private function ensureFlowsForMonth(string $month, string $scope): void { $payments = $this->connection->table('ding_process_payment_line_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->get(); if ($payments->isEmpty()) { return; } $details = $this->connection->table('ding_process_detail_mirror') ->where('source_scope', $scope) ->whereIn('business_id', $payments->pluck('business_id')->unique()->all()) ->get() ->groupBy('business_id'); $existing = $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->get() ->keyBy('business_id'); $now = now(); foreach ($payments->groupBy('business_id') as $businessId => $businessPayments) { $businessId = trim((string) $businessId); $detail = ($details->get($businessId) ?? collect())->first(); $current = $existing->get($businessId); $values = [ 'source_scope' => $scope, 'business_id' => $businessId, 'process_instance_id' => trim((string) ( $businessPayments->firstWhere('process_instance_id', '!=', '') ?->process_instance_id ?? '' )), 'paid_month' => $month, 'title' => mb_substr($current?->title ?: ($detail?->purpose ?: ''), 0, 255) ?: null, 'originator_name' => mb_substr($current?->originator_name ?: ($detail?->originator_name ?: ''), 0, 100) ?: null, 'document_type' => mb_substr($current?->document_type ?: ($detail?->document_type ?: ''), 0, 100) ?: null, 'expense_type' => mb_substr($current?->expense_type ?: ($detail?->account_name ?: ''), 0, 255) ?: null, 'payee_name' => mb_substr($current?->payee_name ?: ($detail?->payee_name ?: ''), 0, 255) ?: null, 'paid_at' => $current?->paid_at ?: $businessPayments->min('paid_at'), 'payment_amount' => round((float) $businessPayments->sum('amount'), 2), 'payment_total' => round((float) $businessPayments->sum('amount'), 2), 'invoice_count' => (int) ($current?->invoice_count ?? 0), 'invoice_total' => (float) ($current?->invoice_total ?? 0), 'scan_status' => $current?->scan_status ?: 'pending', 'attachment_count' => (int) ($current?->attachment_count ?? 0), 'scanned_file_count' => (int) ($current?->scanned_file_count ?? 0), 'last_error' => $current?->last_error, 'source_name' => $current?->source_name ?: 'OA attachment scan', 'scanned_at' => $current?->scanned_at, 'updated_at' => $now, ]; if ($current) { $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('business_id', $businessId) ->update($values); } else { $this->connection->table('ding_invoice_flow_mirror')->insert([ ...$values, 'created_at' => $now, ]); } } } /** * @param list $businessIds * @return array{0:array>,1:list>} */ private function loadUpstreamWorkflowsAndAttachments(array $businessIds): array { if ($businessIds === []) { return [[], []]; } $query = $this->queries->forSourceWithTimeout('operations_replica', 120); $placeholders = implode(',', array_fill(0, count($businessIds), '?')); $workflowRows = $query->select( 'SELECT businessId, processInstanceId, title, status, result ' . 'FROM rpt.ding_Workflow ' . "WHERE businessId IN ({$placeholders}) ORDER BY businessId", $businessIds, ); $workflows = []; foreach ($workflowRows as $row) { $businessId = trim((string) ($row['businessId'] ?? '')); if ($businessId !== '') { $workflows[$businessId] = $row; } } $processIds = array_values(array_unique(array_filter(array_map( static fn (array $row): string => trim((string) ($row['processInstanceId'] ?? '')), $workflowRows, )))); if ($processIds === []) { return [$workflows, []]; } $processPlaceholders = implode(',', array_fill(0, count($processIds), '?')); $attachmentRows = $query->select( 'SELECT processInstanceId, name, value ' . 'FROM rpt.ding_WorkflowScheme ' . "WHERE processInstanceId IN ({$processPlaceholders}) " . "AND name LIKE N'%附件%' ORDER BY id", $processIds, ); return [$workflows, $attachmentRows]; } /** * @param list> $rows * @param array> $workflows * @return array>> */ private function groupAttachmentsByBusiness(array $rows, array $workflows): array { $byProcess = []; foreach ($workflows as $businessId => $workflow) { $byProcess[(string) ($workflow['processInstanceId'] ?? '')] = $businessId; } $result = []; foreach ($rows as $row) { $processId = trim((string) ($row['processInstanceId'] ?? '')); $businessId = $byProcess[$processId] ?? ''; if ($businessId === '') { continue; } $value = $row['value'] ?? null; if (is_string($value)) { $decoded = json_decode($value, true); $value = is_array($decoded) ? $decoded : []; } foreach ($this->extractFiles($value, trim((string) ($row['name'] ?? ''))) as $file) { $key = $file['file_id'] !== '' ? $file['file_id'] : hash('sha256', (string) $file['download_url']); $result[$businessId][$key] = $file; } } return array_map('array_values', $result); } /** * Some invoices are only present in approval comments. Use the official * process snapshot API only for flows that have no form attachment, and cap * the number of calls so the daily DingTalk quota remains usable. * * @param list $businessIds * @param array> $workflows * @param array>> $attachments * @return array>> */ private function addCommentAttachmentFallback( array $businessIds, array $workflows, array $attachments, ): array { $limit = max(0, (int) config('ding_invoice_data.comment_fallback_limit', 20)); if ($limit === 0) { return $attachments; } $candidates = []; foreach ($businessIds as $businessId) { if (($attachments[$businessId] ?? []) !== []) { continue; } $processId = trim((string) ($workflows[$businessId]['processInstanceId'] ?? '')); if ($processId !== '') { $candidates[$processId] = $businessId; } } if ($candidates === []) { return $attachments; } try { $result = $this->approvalClient->processSnapshots( array_slice(array_keys($candidates), 0, $limit), ); } catch (Throwable) { return $attachments; } foreach ((array) ($result['snapshots'] ?? []) as $processId => $snapshot) { $businessId = $candidates[(string) $processId] ?? ''; if ($businessId === '') { continue; } $files = []; foreach ((array) ($snapshot['form_values'] ?? []) as $field => $value) { foreach ($this->extractFiles($value, (string) $field) as $file) { $key = $file['file_id'] !== '' ? $file['file_id'] : hash('sha256', (string) $file['download_url']); $files[$key] = $file; } } foreach ($this->extractFiles($snapshot['operation_records'] ?? [], '评论附件') as $file) { $key = $file['file_id'] !== '' ? $file['file_id'] : hash('sha256', (string) $file['download_url']); $files[$key] = $file; } if ($files !== []) { $attachments[$businessId] = array_values($files); } } return $attachments; } /** * @return list */ private function extractFiles(mixed $value, string $sourceField): array { $files = []; $walk = function (mixed $node) use (&$walk, &$files, $sourceField): void { if (is_string($node)) { $trimmed = trim($node); if (str_starts_with($trimmed, '{') || str_starts_with($trimmed, '[')) { $decoded = json_decode($trimmed, true); if (is_array($decoded)) { $walk($decoded); } } elseif (str_starts_with($trimmed, 'http://') || str_starts_with($trimmed, 'https://')) { $files[] = [ 'file_id' => '', 'file_name' => basename((string) parse_url($trimmed, PHP_URL_PATH)), 'file_type' => strtolower(pathinfo((string) parse_url($trimmed, PHP_URL_PATH), PATHINFO_EXTENSION)), 'space_id' => '', 'file_size' => 0, 'source_field' => $sourceField, 'download_url' => $trimmed, ]; } return; } if (! is_array($node)) { return; } $fileId = trim((string) ($node['fileId'] ?? $node['file_id'] ?? '')); if ($fileId !== '') { $files[] = [ 'file_id' => $fileId, 'file_name' => trim((string) ( $node['fileName'] ?? $node['file_name'] ?? $sourceField )), 'file_type' => strtolower(trim((string) ( $node['fileType'] ?? $node['file_type'] ?? '' ))), 'space_id' => trim((string) ($node['spaceId'] ?? $node['space_id'] ?? '')), 'file_size' => (int) ($node['fileSize'] ?? $node['file_size'] ?? 0), 'source_field' => $sourceField, 'download_url' => '', ]; } foreach ($node as $child) { $walk($child); } }; $walk($value); return $files; } /** * @param array $workflow * @param list> $files * @return array{scan_status:string,invoice_count:int,invoice_total:float,error:?string} */ private function scanFlow(object $flow, array $workflow, array $files, string $tempDir): array { if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) { throw new RuntimeException('无法创建流程发票临时目录。'); } $processInstanceId = trim((string) ( $workflow['processInstanceId'] ?? $flow->process_instance_id ?? '' )); $files = array_slice( $files, 0, max(1, (int) config('ding_invoice_data.max_files_per_flow', 30)), ); $invoices = []; $errors = []; $scannedFiles = 0; foreach ($files as $index => $file) { if ((int) ($file['file_size'] ?? 0) > (int) config('ding_invoice_data.max_file_bytes')) { $errors[] = $file['file_name'] . ':文件超过大小限制'; continue; } try { $uri = trim((string) ($file['download_url'] ?? '')); if ($uri === '') { $uri = $this->downloads->downloadUri($processInstanceId, $file['file_id']) ?? ''; } if ($uri === '') { throw new RuntimeException('无法取得下载地址'); } $extension = strtolower(pathinfo($file['file_name'], PATHINFO_EXTENSION)); if ($extension === '' && in_array( strtolower((string) ($file['file_type'] ?? '')), ['pdf', 'jpg', 'jpeg', 'png', 'webp', 'bmp', 'xlsx', 'zip'], true, )) { $extension = strtolower((string) $file['file_type']); } $path = $tempDir . '/' . $index . ($extension !== '' ? '.' . $extension : ''); $response = Http::timeout(120) ->withOptions(['sink' => $path]) ->get($uri); if (! $response->successful() || ! is_file($path)) { throw new RuntimeException('下载返回 HTTP ' . $response->status()); } if (filesize($path) > (int) config('ding_invoice_data.max_file_bytes')) { @unlink($path); throw new RuntimeException('下载文件超过大小限制'); } $scannedFiles++; $hash = hash_file('sha256', $path) ?: null; $recognized = $this->recognizer->recognize($path, $file['file_name']); foreach ($recognized['invoices'] as $invoice) { $invoice['_source'] = [ 'file_id' => $file['file_id'], 'file_name' => $file['file_name'], 'file_type' => $extension ?: $file['file_type'], 'source_field' => $file['source_field'], 'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'], 'source_hash' => $hash, 'ocr_provider' => $recognized['provider'], ]; $invoices[] = $invoice; } array_push($errors, ...array_map( static fn (string $error): string => $file['file_name'] . ':' . $error, $recognized['errors'], )); } catch (Throwable $exception) { $errors[] = $file['file_name'] . ':' . $exception->getMessage(); } } $invoices = $this->deduplicate($invoices); $invoiceTotal = round(array_sum(array_map( static fn (array $invoice): float => (float) $invoice['invoice_total'], $invoices, )), 2); $scanStatus = match (true) { $errors !== [] && $invoices !== [] => 'partial', $errors !== [] && $invoices === [] => 'failed', $invoices !== [] => 'recognized', default => 'no_invoice', }; $error = $errors === [] ? null : mb_substr(implode("\n", array_slice($errors, 0, 8)), 0, 4000); $this->connection->transaction(function () use ( $flow, $invoices, $invoiceTotal, $scanStatus, $error, $files, $scannedFiles, $workflow, ): void { $scope = $this->scope(); $businessId = (string) $flow->business_id; $this->connection->table('ding_invoice_record_mirror') ->where('source_scope', $scope) ->where('business_id', $businessId) ->delete(); $now = now(); $records = []; foreach ($invoices as $invoice) { $source = $invoice['_source']; $records[] = [ 'source_scope' => $scope, 'business_id' => $businessId, 'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''), 'paid_month' => (string) $flow->paid_month, 'invoice_key' => $this->invoiceKey($invoice), 'invoice_type' => mb_substr((string) $invoice['invoice_type'], 0, 100), 'seller_name' => mb_substr((string) $invoice['seller_name'], 0, 255), 'seller_tax_no' => mb_substr((string) $invoice['seller_tax_no'], 0, 64), 'buyer_name' => mb_substr((string) $invoice['buyer_name'], 0, 255), 'buyer_tax_no' => mb_substr((string) $invoice['buyer_tax_no'], 0, 64), 'invoice_total' => round((float) $invoice['invoice_total'], 2), 'invoice_number' => mb_substr((string) $invoice['invoice_number'], 0, 32), 'invoice_date' => $invoice['invoice_date'], 'item_name' => (string) $invoice['item_name'], 'amount_without_tax' => $invoice['amount_without_tax'], 'tax_rate' => mb_substr((string) $invoice['tax_rate'], 0, 32), 'tax_amount' => $invoice['tax_amount'], 'source_file_id' => $source['file_id'], 'source_file_name' => mb_substr((string) $source['file_name'], 0, 255), 'source_file_type' => mb_substr((string) $source['file_type'], 0, 32), 'source_field' => mb_substr((string) $source['source_field'], 0, 255), 'source_path' => mb_substr((string) $source['source_path'], 0, 1024), 'source_hash' => $source['source_hash'], 'ocr_provider' => mb_substr((string) $source['ocr_provider'], 0, 32), 'recognition_payload' => json_encode( array_diff_key($invoice, ['_source' => true]), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, ), 'created_at' => $now, 'updated_at' => $now, ]; } if ($records !== []) { $this->connection->table('ding_invoice_record_mirror')->insert($records); } $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('business_id', $businessId) ->update([ 'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''), 'title' => $flow->title ?: ($workflow['title'] ?? null), 'invoice_count' => count($records), 'invoice_total' => $invoiceTotal, 'scan_status' => $scanStatus, 'attachment_count' => count($files), 'scanned_file_count' => $scannedFiles, 'last_error' => $error, 'scanned_at' => $now, 'updated_at' => $now, ]); }); return [ 'scan_status' => $scanStatus, 'invoice_count' => count($invoices), 'invoice_total' => $invoiceTotal, 'error' => $error, ]; } /** @param list> $invoices @return list> */ private function deduplicate(array $invoices): array { $unique = []; foreach ($invoices as $invoice) { $number = preg_replace( '/[^0-9A-Za-z]/', '', (string) ($invoice['invoice_number'] ?? ''), ) ?? ''; $seller = trim((string) ($invoice['seller_name'] ?? '')); $amount = number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''); $key = $number !== '' ? 'number:' . $number : 'near:' . mb_strtolower($seller) . '|' . $amount; foreach ($unique as $existingKey => $existing) { $existingSeller = trim((string) ($existing['seller_name'] ?? '')); $existingAmount = number_format((float) ($existing['invoice_total'] ?? 0), 2, '.', ''); if ($seller !== '' && $existingSeller !== '' && mb_strtolower($seller) === mb_strtolower($existingSeller) && $amount === $existingAmount) { $key = $existingKey; break; } } if (! isset($unique[$key])) { $unique[$key] = $invoice; } else { $unique[$key] = $this->mergeInvoice($unique[$key], $invoice); } } return array_values($unique); } /** @param array $left @param array $right */ private function mergeInvoice(array $left, array $right): array { foreach ($right as $key => $value) { if (($left[$key] ?? null) === null || (is_string($left[$key]) && trim($left[$key]) === '') || (is_array($left[$key]) && $left[$key] === [])) { $left[$key] = $value; } } return $left; } /** @param array $invoice */ private function invoiceKey(array $invoice): string { $number = preg_replace('/[^0-9A-Za-z]/', '', (string) ($invoice['invoice_number'] ?? '')) ?? ''; return hash('sha256', $number !== '' ? 'number:' . $number : implode('|', [ 'near', (string) ($invoice['seller_name'] ?? ''), number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''), (string) ($invoice['invoice_date'] ?? ''), (string) ($invoice['item_name'] ?? ''), ])); } private function recognizerOcrConfigured(): bool { return trim((string) config('ding_invoice_data.ocr.api_key', '')) !== ''; } /** @param array $metrics */ private function updateState(array $metrics): void { if (! Schema::connection($this->connection->getName())->hasTable('business_mirror_table_states')) { return; } $now = now(); $state = $this->connection->table('business_mirror_table_states') ->where('dataset_key', DingInvoiceWorkbookImporter::DATASET_KEY) ->first(); $this->connection->table('business_mirror_table_states')->updateOrInsert( ['dataset_key' => DingInvoiceWorkbookImporter::DATASET_KEY], [ 'source_key' => 'operations_replica', 'source_object' => 'rpt.ding_Workflow + DingTalk attachments + invoice OCR', 'target_table' => 'ding_invoice_record_mirror', 'status' => 'succeeded', 'run_mode' => 'incremental', 'cursor' => json_encode($metrics, JSON_UNESCAPED_UNICODE), 'initial_completed_at' => $state?->initial_completed_at ?? $now, 'last_attempted_at' => $now, 'last_succeeded_at' => $now, 'last_upserted_rows' => (int) ($metrics['recognized_invoices'] ?? 0), 'mirror_row_count' => (int) $this->connection->table('ding_invoice_record_mirror') ->where('source_scope', $this->scope())->count(), 'mirror_row_count_is_exact' => true, 'last_error_code' => null, 'created_at' => $state?->created_at ?? $now, 'updated_at' => $now, ], ); } private function removeDirectory(string $directory): void { if (! is_dir($directory)) { return; } $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST, ); foreach ($iterator as $item) { if ($item->isDir()) { @rmdir($item->getPathname()); } else { @unlink($item->getPathname()); } } @rmdir($directory); } }