CaiWuXiTong/modules/EcommerceFinance/Services/DingInvoiceSyncService.php
yueyang b72b2e12bd feat(发票数据): 展示流程直抓完整发票字段 (#1505)
发票明细按 OA 流程附件直抓口径展示完整字段,打款时间移到最后,并从 2026-10 开始统计。
2026-11-27 14:42:41 +08:00

761 lines
32 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\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 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,
'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', '!=', '')
->where(function ($query): void {
$query->whereIn('scan_status', ['pending', 'failed', 'partial'])
->orWhereNull('scanned_at')
->orWhereNull('source_name')
->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME);
});
$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', '!=', '')
->where(function ($query): void {
$query->whereIn('scan_status', ['pending', 'failed', 'partial'])
->orWhereNull('scanned_at')
->orWhereNull('source_name')
->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME);
})
->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->loadUpstreamWorkflowsAndAttachments($businessIds);
$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);
}
$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', '!=', '')
->where(function ($query): void {
$query->whereIn('scan_status', ['pending', 'failed', 'partial'])
->orWhereNull('scanned_at')
->orWhereNull('source_name')
->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME);
})
->count();
$this->updateState($metrics);
return [
'status' => 'succeeded',
'month' => $month,
...$metrics,
];
}
public function latestPendingMonth(): ?string
{
$month = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->where(function ($query): void {
$query->whereIn('scan_status', ['pending', 'failed', 'partial'])
->orWhereNull('scanned_at')
->orWhereNull('source_name')
->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME);
})
->max('paid_month');
return trim((string) $month) ?: null;
}
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<string> $businessIds
* @return array{0:array<string,array<string,mixed>>,1:list<array<string,mixed>>}
*/
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<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;
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;
$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->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,
&$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),
'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);
}
$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',
};
$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,
'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);
}
}