CaiWuXiTong/modules/EcommerceFinance/Services/DingInvoiceSyncService.php

879 lines
38 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

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

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
use Throwable;
class DingInvoiceSyncService
{
private const DIRECT_SOURCE_NAME = 'OA attachment scan';
private ConnectionInterface $connection;
public function __construct(
DatabaseManager $database,
private readonly UpstreamReadOnlyQueryFactory $queries,
private readonly DingTalkApprovalAttachmentDownloader $downloads,
private readonly DingInvoiceFileRecognizer $recognizer,
private readonly DingInvoiceRecordNormalizer $normalizer,
private readonly DingInvoicePreviewStore $previewStore,
private readonly DingTalkProcessInstanceClient $approvalClient,
) {
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @return array<string,mixed>
*/
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,
'scan_attempts' => 0,
'next_scan_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', '!=', '');
$this->applyScanCandidates($query);
$flows = $query
->orderByDesc('paid_at')
->orderByDesc('business_id')
->limit($limit)
->get()
->all();
if ($flows === []) {
$remainingQuery = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($remainingQuery);
$remaining = (int) $remainingQuery->count();
return [
'status' => 'succeeded',
'month' => $month,
'processed_flows' => 0,
'recognized_invoices' => 0,
'preserved_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->loadWorkflowAttachments($flows);
$attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows);
$attachmentsByBusiness = $this->addCommentAttachmentFallback(
$businessIds,
$workflows,
$attachmentsByBusiness,
);
$metrics = [
'processed_flows' => 0,
'recognized_invoices' => 0,
'preserved_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['recognized_invoices'];
$metrics['preserved_invoices'] += $flowResult['preserved_invoices'];
if ($flowResult['scan_status'] === 'failed') {
$metrics['failed_flows']++;
}
}
} finally {
$this->removeDirectory($tempRoot);
}
$remainingQuery = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($remainingQuery);
$metrics['remaining_flows'] = (int) $remainingQuery->count();
$this->updateState($metrics);
return [
'status' => 'succeeded',
'month' => $month,
...$metrics,
];
}
public function latestPendingMonth(): ?string
{
$monthQuery = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($monthQuery);
$month = $monthQuery->max('paid_month');
return trim((string) $month) ?: null;
}
private function applyScanCandidates(Builder $query): void
{
$now = now();
$maxAttempts = max(
1,
(int) config('ding_invoice_data.max_scan_attempts', 3),
);
$query->where(function (Builder $candidate) use ($now, $maxAttempts): void {
$candidate
->whereNull('scanned_at')
->orWhere('scan_status', 'pending')
->orWhere(function (Builder $imported) use ($now): void {
$imported->whereIn('scan_status', ['recognized', 'no_invoice'])
->where(function (Builder $source): void {
$source->whereNull('source_name')
->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME);
})
->where(function (Builder $due) use ($now): void {
$due->whereNull('next_scan_at')
->orWhere('next_scan_at', '<=', $now);
});
})
->orWhere(function (Builder $retry) use ($now, $maxAttempts): void {
$retry->whereIn('scan_status', ['failed', 'partial'])
->where('scan_attempts', '<', $maxAttempts)
->where(function (Builder $due) use ($now): void {
$due->whereNull('next_scan_at')
->orWhere('next_scan_at', '<=', $now);
});
});
});
}
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<object> $flows
* @return array{0:array<string,array<string,mixed>>,1:list<array<string,mixed>>}
*/
private function loadWorkflowAttachments(array $flows): array
{
if ($flows === []) {
return [[], []];
}
$workflows = [];
$missingProcessIds = [];
foreach ($flows as $flow) {
$businessId = trim((string) ($flow->business_id ?? ''));
if ($businessId === '') {
continue;
}
$workflows[$businessId] = [
'businessId' => $businessId,
'processInstanceId' => trim((string) ($flow->process_instance_id ?? '')),
'title' => $flow->title ?? null,
'status' => null,
'result' => null,
];
if ($workflows[$businessId]['processInstanceId'] === '') {
$missingProcessIds[] = $businessId;
}
}
if ($missingProcessIds !== []) {
$localRows = $this->connection->table('ding_process_detail_mirror')
->where('source_scope', $this->scope())
->whereIn('business_id', $missingProcessIds)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->get(['business_id', 'process_instance_id']);
foreach ($localRows as $row) {
$businessId = trim((string) ($row->business_id ?? ''));
if (isset($workflows[$businessId])) {
$workflows[$businessId]['processInstanceId'] = trim(
(string) ($row->process_instance_id ?? ''),
);
}
}
}
$processIds = array_values(array_unique(array_filter(array_map(
static fn (array $row): string => trim((string) ($row['processInstanceId'] ?? '')),
array_values($workflows),
))));
if ($processIds === []) {
return [$workflows, []];
}
$query = $this->queries->forSourceWithTimeout('operations_replica', 120);
$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<array<string,mixed>> $rows
* @param array<string,array<string,mixed>> $workflows
* @return array<string,list<array<string,mixed>>>
*/
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<string> $businessIds
* @param array<string,array<string,mixed>> $workflows
* @param array<string,list<array<string,mixed>>> $attachments
* @return array<string,list<array<string,mixed>>>
*/
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<array{file_id:string,file_name:string,file_type:string,space_id:string,file_size:int,source_field:string,download_url:string}>
*/
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<string,mixed> $workflow
* @param list<array<string,mixed>> $files
* @return array{
* scan_status:string,
* invoice_count:int,
* recognized_invoices:int,
* preserved_invoices: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;
$flowPreviewFallbacks = [];
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',
'xls',
'zip',
'rar',
'7z',
],
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;
$preview = null;
try {
$preview = $this->previewStore->persistLocalFile($path, $file, $hash);
} catch (Throwable $exception) {
report($exception);
}
$recognized = $this->recognizer->recognize($path, $file['file_name']);
if ($preview !== null && ($recognized['invoices'] ?? []) !== []) {
$flowPreviewFallbacks[$preview['path']] = [
'preview_path' => $preview['path'],
'preview_mime' => $preview['mime'],
'source_file_id' => $file['file_id'],
'source_file_name' => $file['file_name'],
'source_file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
];
}
foreach (($recognized['previews'] ?? []) as $derivedPreview) {
if (! is_array($derivedPreview) || empty($derivedPreview['path'])) {
continue;
}
$flowPreviewFallbacks[$derivedPreview['path']] = [
'preview_path' => $derivedPreview['path'],
'preview_mime' => $derivedPreview['mime'] ?? null,
'source_file_id' => $file['file_id'],
'source_file_name' => $file['file_name'],
'source_file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
];
}
foreach ($recognized['invoices'] as $invoice) {
$invoicePreview = $invoice['_preview'] ?? $preview;
unset($invoice['_preview']);
$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'],
'preview_path' => $invoicePreview['path'] ?? null,
'preview_mime' => $invoicePreview['mime'] ?? null,
];
$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->normalizer->deduplicate($invoices);
$error = $errors === [] ? null : mb_substr(implode("\n", array_slice($errors, 0, 8)), 0, 4000);
$scope = $this->scope();
$businessId = (string) $flow->business_id;
$processInstanceId = (string) (
$workflow['processInstanceId']
?? $flow->process_instance_id
?? ''
);
$existingRows = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->get()
->mapWithKeys(static fn (object $row): array => [
(string) $row->invoice_key => (array) $row,
])
->all();
$invoiceCount = count($existingRows);
$invoiceTotal = round((float) array_sum(array_map(
static fn (array $record): float => (float) ($record['invoice_total'] ?? 0),
$existingRows,
)), 2);
$preservedInvoices = 0;
$scanStatus = 'no_invoice';
$this->connection->transaction(function () use (
$flow,
$invoices,
$error,
$files,
$scannedFiles,
$workflow,
$scope,
$businessId,
$processInstanceId,
$existingRows,
$flowPreviewFallbacks,
&$invoiceCount,
&$invoiceTotal,
&$preservedInvoices,
&$scanStatus,
): void {
$now = now();
$remainingExisting = $existingRows;
$newRecords = [];
foreach ($invoices as $invoice) {
$source = $invoice['_source'];
$record = [
'source_scope' => $scope,
'business_id' => $businessId,
'process_instance_id' => $processInstanceId,
'paid_month' => (string) $flow->paid_month,
'invoice_key' => $this->normalizer->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),
'preview_path' => $source['preview_path'] ?? null,
'preview_mime' => $source['preview_mime'] ?? null,
'recognition_payload' => json_encode(
array_diff_key($invoice, ['_source' => true]),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
),
'created_at' => $now,
'updated_at' => $now,
];
$key = (string) $record['invoice_key'];
if (isset($remainingExisting[$key])) {
$merged = $this->normalizer->mergeScanned(
$remainingExisting[$key],
$record,
);
$id = (int) $merged['id'];
unset($merged['id'], $merged['created_at']);
$this->connection->table('ding_invoice_record_mirror')
->where('id', $id)
->update($merged);
unset($remainingExisting[$key]);
continue;
}
$newRecords[] = $record;
}
if ($newRecords !== []) {
$this->connection->table('ding_invoice_record_mirror')->insert($newRecords);
}
if (count($flowPreviewFallbacks) === 1) {
$fallback = reset($flowPreviewFallbacks);
foreach ($remainingExisting as $existing) {
if (! str_starts_with((string) ($existing['ocr_provider'] ?? ''), 'imported_workbook')
|| ! empty($existing['preview_path'])) {
continue;
}
$this->connection->table('ding_invoice_record_mirror')
->where('id', (int) $existing['id'])
->update([
'source_file_id' => $fallback['source_file_id'],
'source_file_name' => $fallback['source_file_name'],
'source_file_type' => $fallback['source_file_type'],
'source_field' => $fallback['source_field'],
'source_path' => mb_substr((string) $fallback['source_path'], 0, 1024),
'source_hash' => $fallback['source_hash'],
'preview_path' => $fallback['preview_path'],
'preview_mime' => $fallback['preview_mime'],
'updated_at' => $now,
]);
}
}
$persistedRows = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->get(['invoice_total']);
$invoiceCount = $persistedRows->count();
$invoiceTotal = round((float) $persistedRows->sum('invoice_total'), 2);
$preservedInvoices = count($remainingExisting);
$scanStatus = match (true) {
$error !== null && $invoiceCount > 0 => 'partial',
$error !== null && $invoiceCount === 0 => 'failed',
$invoiceCount > 0 => 'recognized',
default => 'no_invoice',
};
$scanAttempts = (int) ($flow->scan_attempts ?? 0) + 1;
$maxAttempts = max(
1,
(int) config('ding_invoice_data.max_scan_attempts', 3),
);
$nextScanAt = match (true) {
$scanStatus === 'failed' && $scanAttempts < $maxAttempts => $now->copy()->addMinutes(
max(1, (int) config('ding_invoice_data.failed_retry_minutes', 60)),
),
$scanStatus === 'partial' && $scanAttempts < $maxAttempts => $now->copy()->addMinutes(
max(1, (int) config('ding_invoice_data.partial_retry_minutes', 360)),
),
default => null,
};
$this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->update([
'process_instance_id' => $processInstanceId,
'title' => $flow->title ?: ($workflow['title'] ?? null),
'invoice_count' => $invoiceCount,
'invoice_total' => $invoiceTotal,
'scan_status' => $scanStatus,
'attachment_count' => count($files),
'scanned_file_count' => $scannedFiles,
'last_error' => $error,
'source_name' => self::DIRECT_SOURCE_NAME,
'scan_attempts' => $scanAttempts,
'next_scan_at' => $nextScanAt,
'scanned_at' => $now,
'updated_at' => $now,
]);
});
return [
'scan_status' => $scanStatus,
'invoice_count' => $invoiceCount,
'recognized_invoices' => count($invoices),
'preserved_invoices' => $preservedInvoices,
'invoice_total' => $invoiceTotal,
'error' => $error,
];
}
private function recognizerOcrConfigured(): bool
{
return $this->recognizer->ocrConfigured();
}
/** @param array<string,mixed> $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);
}
}