feat(发票数据): 合并OA同步并精简发票明细 (#1508)

发票识别并入 OA 流程同步,加入重试退避;发票页移除前置业务列和附件,流程号直达 OA 详情。
This commit is contained in:
yueyang 2026-11-27 15:19:07 +08:00
parent dcd12eca7b
commit bec7cbdabb
10 changed files with 368 additions and 103 deletions

View File

@ -3,6 +3,7 @@
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
use Throwable;
@ -12,12 +13,15 @@ class SyncDingProcessDetailMirror extends Command
{--full : 从配置起始日期完整重建明细和付款事实}
{--business-id= : 只同步指定审批编号,多个用逗号分隔(最多 50 个)}
{--skip-approval-api : 定向同步时不调用钉钉官方审批接口}
{--skip-invoices : 不执行同轮发票增量识别}
{--dry-run : 只读取上游并校验,不写入镜像}';
protected $description = '从结构化审批镜像同步流程明细,并用钉钉官方接口补取缺失付款';
protected $description = '同步 OA 流程结构化明细,并在同一批处理中增量识别发票';
public function handle(DingProcessDetailMirrorSynchronizer $synchronizer): int
{
public function handle(
DingProcessDetailMirrorSynchronizer $synchronizer,
DingInvoiceSyncService $invoiceSync,
): int {
$businessIds = array_values(array_filter(array_map(
'trim',
explode(',', (string) $this->option('business-id')),
@ -61,6 +65,32 @@ class SyncDingProcessDetailMirror extends Command
$result['bank_amount_total'],
));
if ($businessIds === []
&& ! (bool) $this->option('dry-run')
&& ! (bool) $this->option('skip-invoices')
&& $result['workflows'] > 0
&& (bool) config('ding_invoice_data.sync_with_oa_process', true)) {
try {
$month = $invoiceSync->latestPendingMonth();
if ($month !== null) {
$invoiceResult = $invoiceSync->syncMonth(
$month,
(int) config('ding_invoice_data.auto_scan_limit', 5),
);
$this->info(sprintf(
'发票增量识别完成:%d 个流程,新识别 %d 张,保留 %d 张,剩余 %d 个流程。',
$invoiceResult['processed_flows'],
$invoiceResult['recognized_invoices'],
$invoiceResult['preserved_invoices'],
$invoiceResult['remaining_flows'],
));
}
} catch (Throwable $exception) {
report($exception);
$this->warn('发票增量识别失败,OA 流程镜像已正常更新:' . $exception->getMessage());
}
}
return self::SUCCESS;
}
}

View File

@ -6,7 +6,15 @@ return [
'max_files_per_flow' => (int) env('DING_INVOICE_MAX_FILES_PER_FLOW', 30),
'max_file_bytes' => (int) env('DING_INVOICE_MAX_FILE_BYTES', 60 * 1024 * 1024),
'max_pdf_pages' => (int) env('DING_INVOICE_MAX_PDF_PAGES', 5),
'comment_fallback_limit' => (int) env('DING_INVOICE_COMMENT_FALLBACK_LIMIT', 20),
'comment_fallback_limit' => (int) env('DING_INVOICE_COMMENT_FALLBACK_LIMIT', 5),
'auto_scan_limit' => (int) env('DING_INVOICE_AUTO_SCAN_LIMIT', 5),
'failed_retry_minutes' => (int) env('DING_INVOICE_FAILED_RETRY_MINUTES', 60),
'partial_retry_minutes' => (int) env('DING_INVOICE_PARTIAL_RETRY_MINUTES', 360),
'max_scan_attempts' => (int) env('DING_INVOICE_MAX_SCAN_ATTEMPTS', 3),
'sync_with_oa_process' => filter_var(
env('DING_INVOICE_SYNC_WITH_OA_PROCESS', true),
FILTER_VALIDATE_BOOL,
),
'pdftotext_binary' => env('DING_INVOICE_PDFTOTEXT_BINARY', '/usr/bin/pdftotext'),
'pdftoppm_binary' => env('DING_INVOICE_PDFTOPPM_BINARY', '/usr/bin/pdftoppm'),
'tesseract_binary' => env('DING_INVOICE_TESSERACT_BINARY', '/usr/bin/tesseract'),

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_flow_mirror')) {
return;
}
$schema->table('ding_invoice_flow_mirror', function (Blueprint $table) use ($schema): void {
if (! $schema->hasColumn('ding_invoice_flow_mirror', 'scan_attempts')) {
$table->unsignedInteger('scan_attempts')->default(0);
}
if (! $schema->hasColumn('ding_invoice_flow_mirror', 'next_scan_at')) {
$table->dateTime('next_scan_at', 6)->nullable();
}
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('ding_invoice_flow_mirror')) {
return;
}
$columns = [];
foreach (['scan_attempts', 'next_scan_at'] as $column) {
if ($schema->hasColumn('ding_invoice_flow_mirror', $column)) {
$columns[] = $column;
}
}
if ($columns !== []) {
$schema->table('ding_invoice_flow_mirror', function (Blueprint $table) use ($columns): void {
$table->dropColumn($columns);
});
}
}
};

View File

@ -266,8 +266,8 @@ CRON_TZ=Asia/Shanghai
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转,
# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。
# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票;
# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。
cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'
CRON_TZ=Asia/Shanghai
@ -275,7 +275,6 @@ CRON_TZ=Asia/Shanghai
# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。
* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1
* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:process-refresh-requests --quiet >/dev/null 2>&1
7,22,37,52 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:sync --auto --limit=20 --quiet >/dev/null 2>&1
EOF
chmod 644 /etc/cron.d/caiwu-ding-process-details

View File

@ -270,8 +270,8 @@ CRON_TZ=Asia/Shanghai
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转,
# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。
# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票;
# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。
cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'
CRON_TZ=Asia/Shanghai
@ -279,7 +279,6 @@ CRON_TZ=Asia/Shanghai
# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。
* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1
* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:process-refresh-requests --quiet >/dev/null 2>&1
7,22,37,52 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:sync --auto --limit=20 --quiet >/dev/null 2>&1
EOF
chmod 644 /etc/cron.d/caiwu-ding-process-details

View File

@ -4,6 +4,7 @@ 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;
@ -47,6 +48,8 @@ class DingInvoiceSyncService
->update([
'scan_status' => 'pending',
'scanned_at' => null,
'scan_attempts' => 0,
'next_scan_at' => null,
'updated_at' => now(),
]);
}
@ -55,13 +58,8 @@ class DingInvoiceSyncService
->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);
});
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($query);
$flows = $query
->orderByDesc('paid_at')
->orderByDesc('business_id')
@ -70,18 +68,13 @@ class DingInvoiceSyncService
->all();
if ($flows === []) {
$remaining = (int) $this->connection->table('ding_invoice_flow_mirror')
$remainingQuery = $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();
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($remainingQuery);
$remaining = (int) $remainingQuery->count();
return [
'status' => 'succeeded',
@ -96,7 +89,7 @@ class DingInvoiceSyncService
}
$businessIds = array_values(array_filter(array_column($flows, 'business_id')));
[$workflows, $attachmentRows] = $this->loadUpstreamWorkflowsAndAttachments($businessIds);
[$workflows, $attachmentRows] = $this->loadWorkflowAttachments($flows);
$attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows);
$attachmentsByBusiness = $this->addCommentAttachmentFallback(
$businessIds,
@ -139,18 +132,13 @@ class DingInvoiceSyncService
$this->removeDirectory($tempRoot);
}
$metrics['remaining_flows'] = (int) $this->connection->table('ding_invoice_flow_mirror')
$remainingQuery = $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();
->where('process_instance_id', '!=', '');
$this->applyScanCandidates($remainingQuery);
$metrics['remaining_flows'] = (int) $remainingQuery->count();
$this->updateState($metrics);
return [
@ -162,21 +150,50 @@ class DingInvoiceSyncService
public function latestPendingMonth(): ?string
{
$month = $this->connection->table('ding_invoice_flow_mirror')
$monthQuery = $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');
->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')
@ -264,37 +281,58 @@ class DingInvoiceSyncService
}
/**
* @param list<string> $businessIds
* @param list<object> $flows
* @return array{0:array<string,array<string,mixed>>,1:list<array<string,mixed>>}
*/
private function loadUpstreamWorkflowsAndAttachments(array $businessIds): array
private function loadWorkflowAttachments(array $flows): array
{
if ($businessIds === []) {
if ($flows === []) {
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;
$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'] ?? '')),
$workflowRows,
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 '
@ -673,6 +711,20 @@ class DingInvoiceSyncService
$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)
@ -686,6 +738,8 @@ class DingInvoiceSyncService
'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,
]);

View File

@ -278,7 +278,7 @@
.invoice-data-table {
width: 100%;
min-width: 178rem;
min-width: 148rem;
border-collapse: collapse;
color: var(--invoice-ink);
font-size: 0.75rem;
@ -375,6 +375,24 @@
font-weight: 600;
}
.invoice-data-process-link {
display: inline-flex;
align-items: center;
gap: 0.25rem;
color: var(--invoice-accent-dark);
font-weight: 600;
text-decoration: none;
}
.invoice-data-process-link:hover,
.invoice-data-process-link:focus-visible {
text-decoration: underline;
}
.invoice-data-process-link .material-icons-outlined {
font-size: 0.875rem;
}
.invoice-data-tag {
display: inline-flex;
min-height: 1.4rem;
@ -460,16 +478,6 @@
line-height: 1.65;
}
.invoice-data-attachment {
color: var(--invoice-accent-dark);
font-weight: 600;
text-decoration: none;
}
.invoice-data-attachment:hover {
text-decoration: underline;
}
.invoice-data-refresh-status {
display: flex;
align-items: center;
@ -709,11 +717,6 @@
<thead>
<tr>
<th scope="col">流程号</th>
<th scope="col">流程标题</th>
<th scope="col">提交人</th>
<th scope="col">报销类型</th>
<th scope="col">费用类型</th>
<th scope="col">收款人</th>
<th scope="col">发票类型</th>
<th scope="col">发票号码</th>
<th scope="col">开票日期</th>
@ -731,7 +734,6 @@
<th scope="col" class="is-number">发票张数</th>
<th scope="col">金额校对</th>
<th scope="col" class="is-number">差异金额</th>
<th scope="col">附件</th>
<th scope="col">打款时间</th>
</tr>
</thead>
@ -744,12 +746,20 @@
);
@endphp
<tr>
<td class="is-nowrap invoice-data-code">{{ $row->business_id }}</td>
<td>{{ $row->title ?: '未命名审批' }}</td>
<td class="is-nowrap">{{ $row->originator_name ?: '-' }}</td>
<td>{{ $row->document_type ?: '-' }}</td>
<td>{{ $row->expense_type ?: '-' }}</td>
<td>{{ $row->payee_name ?: '-' }}</td>
<td class="is-nowrap">
<a
class="invoice-data-process-link invoice-data-code"
href="{{ route('business.pages.show', [
'section' => 'process-data',
'page' => 'oa-process',
'business_id' => $row->business_id,
]) }}"
title="查看 OA 流程详情"
>
{{ $row->business_id }}
<span class="material-icons-outlined" aria-hidden="true">open_in_new</span>
</a>
</td>
<td>
<span class="invoice-data-tag">{{ $row->invoice_type ?: '未分类' }}</span>
</td>
@ -777,26 +787,13 @@
¥{{ $money($flowDifference) }}
</span>
</td>
<td>
@if ($row->source_file_id)
<a
class="invoice-data-attachment"
href="{{ route('business.invoice-data.attachment', ['invoice' => $row->id]) }}"
title="{{ $row->source_file_name ?: '查看原始附件' }}"
target="_blank"
rel="noopener"
>查看附件</a>
@else
<span class="invoice-data-secondary">待关联原件</span>
@endif
</td>
<td class="is-nowrap">
{{ $row->paid_at ? \Illuminate\Support\Carbon::parse($row->paid_at)->format('Y-m-d') : '-' }}
</td>
</tr>
@empty
<tr>
<td colspan="25" class="invoice-data-empty">当前筛选条件下没有发票明细。</td>
<td colspan="19" class="invoice-data-empty">当前筛选条件下没有发票明细。</td>
</tr>
@endforelse
</tbody>
@ -836,7 +833,20 @@
$difference = round((float) $row->payment_amount - (float) $row->invoice_total, 2);
@endphp
<tr>
<td class="is-nowrap invoice-data-code">{{ $row->business_id }}</td>
<td class="is-nowrap">
<a
class="invoice-data-process-link invoice-data-code"
href="{{ route('business.pages.show', [
'section' => 'process-data',
'page' => 'oa-process',
'business_id' => $row->business_id,
]) }}"
title="查看 OA 流程详情"
>
{{ $row->business_id }}
<span class="material-icons-outlined" aria-hidden="true">open_in_new</span>
</a>
</td>
<td>{{ $row->title ?: '未命名审批' }}</td>
<td class="is-nowrap">{{ $row->originator_name ?: '-' }}</td>
<td>{{ $row->document_type ?: '-' }}</td>
@ -876,10 +886,10 @@
</section>
<p class="invoice-data-note">
口径:统计从 {{ $startMonth }} 开始。发票通过 OA 审批流程附件自动识别,按打款时间归入月份;
一张发票一行,同一流程多张发票分别列示,并保留对应流程号。无票流程在“按流程汇总”中保留。
尚未关联原件的历史记录会标记为“待关联原件”。开票金额覆盖率可能超过 100%,
表示开票金额高于本月付款,需要按具体流程复核。
口径:统计从 {{ $startMonth }} 开始。发票附件只由服务端临时下载并识别,页面直接展示识别结果,
不提供附件下载。发票按打款时间归入月份,一张发票一行,同一流程多张发票分别列示。
无票流程在“按流程汇总”中保留。开票金额覆盖率可能超过 100%,表示开票金额高于本月付款,
需要按具体流程复核。
</p>
</div>

View File

@ -168,10 +168,21 @@ class InvoiceDataPageTest extends FeatureTestCase
);
$this->assertNotEmpty($detailHeader);
$this->assertStringContainsString('>项目名称</th>', $detailHeader[0]);
foreach (['流程标题', '提交人', '报销类型', '费用类型', '收款人', '附件'] as $removedHeader) {
$this->assertStringNotContainsString(">{$removedHeader}</th>", $detailHeader[0]);
}
$this->assertMatchesRegularExpression(
'/>项目名称<\/th>.*>打款时间<\/th>\s*<\/tr>$/su',
$detailHeader[0],
);
$response->assertSee(
route('business.pages.show', [
'section' => 'process-data',
'page' => 'oa-process',
'business_id' => 'FLOW-INVOICE-1',
]),
false,
);
$flowHeader = null;
preg_match(
@ -426,6 +437,25 @@ class InvoiceDataPageTest extends FeatureTestCase
'created_at' => $now,
'updated_at' => $now,
]);
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-FAILED-BACKOFF',
'process_instance_id' => 'PROCESS-FAILED-BACKOFF',
'paid_month' => '2026-12',
'payment_amount' => 10,
'payment_total' => 10,
'invoice_count' => 0,
'invoice_total' => 0,
'scan_status' => 'failed',
'attachment_count' => 1,
'scanned_file_count' => 1,
'source_name' => 'OA attachment scan',
'scan_attempts' => 1,
'next_scan_at' => $now->copy()->addHour(),
'scanned_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$this->assertSame(
'2026-11',
@ -471,6 +501,8 @@ class InvoiceDataPageTest extends FeatureTestCase
$table->unsignedInteger('scanned_file_count')->default(0);
$table->text('last_error')->nullable();
$table->string('source_name')->nullable();
$table->unsignedInteger('scan_attempts')->default(0);
$table->dateTime('next_scan_at')->nullable();
$table->dateTime('scanned_at')->nullable();
$table->timestamps();
});

View File

@ -3,6 +3,7 @@
namespace Tests\Feature\Console;
use Mockery;
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer;
use Tests\Feature\FeatureTestCase;
@ -72,4 +73,69 @@ class SyncDingProcessDetailMirrorTest extends FeatureTestCase
'--business-id' => '202610151743000310225',
])->assertFailed();
}
public function test_incremental_oa_sync_runs_bounded_invoice_scan(): void
{
config([
'ding_invoice_data.sync_with_oa_process' => true,
'ding_invoice_data.auto_scan_limit' => 5,
]);
$synchronizer = Mockery::mock(DingProcessDetailMirrorSynchronizer::class);
$synchronizer->shouldReceive('sync')
->once()
->with(false, false)
->andReturn([
'status' => 'succeeded',
'run_mode' => 'incremental',
'workflows' => 2,
'details' => 3,
'payments' => 2,
'amount_total' => 100.0,
'bank_amount_total' => 100.0,
]);
$this->app->instance(DingProcessDetailMirrorSynchronizer::class, $synchronizer);
$invoices = Mockery::mock(DingInvoiceSyncService::class);
$invoices->shouldReceive('latestPendingMonth')->once()->andReturn('2026-10');
$invoices->shouldReceive('syncMonth')
->once()
->with('2026-10', 5)
->andReturn([
'processed_flows' => 5,
'recognized_invoices' => 2,
'preserved_invoices' => 3,
'remaining_flows' => 9,
]);
$this->app->instance(DingInvoiceSyncService::class, $invoices);
$this->artisan('business-mirror:sync-ding-process-details')
->expectsOutputToContain('发票增量识别完成')
->assertSuccessful();
}
public function test_oa_sync_skips_invoices_when_no_workflow_changed(): void
{
$synchronizer = Mockery::mock(DingProcessDetailMirrorSynchronizer::class);
$synchronizer->shouldReceive('sync')
->once()
->with(false, false)
->andReturn([
'status' => 'succeeded',
'run_mode' => 'incremental',
'workflows' => 0,
'details' => 0,
'payments' => 0,
'amount_total' => 0.0,
'bank_amount_total' => 0.0,
]);
$this->app->instance(DingProcessDetailMirrorSynchronizer::class, $synchronizer);
$invoices = Mockery::mock(DingInvoiceSyncService::class);
$invoices->shouldNotReceive('latestPendingMonth');
$invoices->shouldNotReceive('syncMonth');
$this->app->instance(DingInvoiceSyncService::class, $invoices);
$this->artisan('business-mirror:sync-ding-process-details')->assertSuccessful();
}
}

View File

@ -159,6 +159,11 @@ class BusinessMirrorScheduleTest extends TestCase
$contents,
$script,
);
$this->assertStringNotContainsString(
'ding-invoices:sync --auto',
$contents,
$script,
);
$this->assertSame(1, substr_count($contents, 'business-mirror:sync-ding-worklogs --quiet'), $script);
$this->assertStringContainsString(
"cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'\n"
@ -168,6 +173,8 @@ class BusinessMirrorScheduleTest extends TestCase
. "# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。\n"
. '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock '
. "/bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1\n"
. '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock '
. "/bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:process-refresh-requests --quiet >/dev/null 2>&1\n"
. 'EOF',
$contents,
$script,