CaiWuXiTong/tests/Feature/Business/InvoiceDataPageTest.php

680 lines
28 KiB
PHP

<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use App\Models\Auth\Role;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Repositories\DingInvoiceDataMirrorRepository;
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
use Tests\Feature\FeatureTestCase;
class InvoiceDataPageTest extends FeatureTestCase
{
protected function setUp(): void
{
parent::setUp();
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
'foreign_key_constraints' => true,
],
'upstream_mirrors.connection' => 'business_mirror',
'upstream_mirrors.ding_process_details.scope' => 'personal_permission',
]);
DB::purge('business_mirror');
$this->createInvoiceMirrorTables();
$now = now();
DB::connection('business_mirror')->table('business_mirror_table_states')->insert([
'dataset_key' => 'operations_replica.rpt.ding_invoices',
'source_key' => 'operations_replica',
'source_object' => 'test',
'target_table' => 'ding_invoice_record_mirror',
'status' => 'succeeded',
'initial_completed_at' => $now,
'last_succeeded_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
[
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-INVOICE-1',
'process_instance_id' => 'PROCESS-1',
'paid_month' => '2026-10',
'title' => '10月办公用品报销',
'originator_name' => '张三',
'document_type' => '公摊日常报销',
'expense_type' => '办公用品',
'payee_name' => '测试供应商',
'paid_at' => '2026-10-12 00:00:00',
'payment_amount' => 1000.00,
'payment_total' => 1000.00,
'invoice_count' => 1,
'invoice_total' => 1000.00,
'scan_status' => 'recognized',
'attachment_count' => 1,
'scanned_file_count' => 1,
'last_error' => null,
'source_name' => 'test.xlsx',
'scanned_at' => $now,
'created_at' => $now,
'updated_at' => $now,
],
[
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-NO-INVOICE',
'process_instance_id' => 'PROCESS-2',
'paid_month' => '2026-10',
'title' => '10月借支销账',
'originator_name' => '李四',
'document_type' => '公摊借支-销账',
'expense_type' => '借支',
'payee_name' => '员工',
'paid_at' => '2026-10-13 00:00:00',
'payment_amount' => 500.00,
'payment_total' => 500.00,
'invoice_count' => 0,
'invoice_total' => 0,
'scan_status' => 'no_invoice',
'attachment_count' => 0,
'scanned_file_count' => 0,
'last_error' => null,
'source_name' => 'test.xlsx',
'scanned_at' => $now,
'created_at' => $now,
'updated_at' => $now,
],
]);
DB::connection('business_mirror')->table('ding_invoice_record_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-INVOICE-1',
'process_instance_id' => 'PROCESS-1',
'paid_month' => '2026-10',
'invoice_key' => hash('sha256', 'number:26320000000000000001'),
'invoice_type' => '电子发票(普通发票)',
'seller_name' => '测试供应商',
'seller_tax_no' => '913200000000000001',
'buyer_name' => '测试主体',
'buyer_tax_no' => '913200000000000002',
'invoice_total' => 1000.00,
'invoice_number' => '26320000000000000001',
'invoice_date' => '2026-10-10',
'item_name' => '*办公用品*打印纸',
'amount_without_tax' => 884.96,
'tax_rate' => '13%',
'tax_amount' => 115.04,
'source_file_id' => 'FILE-1',
'source_file_name' => '测试发票.pdf',
'source_file_type' => 'application/pdf',
'source_field' => null,
'source_path' => null,
'source_hash' => null,
'ocr_provider' => 'test',
'preview_path' => null,
'preview_mime' => null,
'recognition_payload' => null,
'created_at' => $now,
'updated_at' => $now,
]);
DB::connection('business_mirror')->table('ding_invoice_attachment_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-INVOICE-1',
'paid_month' => '2026-10',
'attachment_key' => hash('sha256', 'attachment-1'),
'process_instance_id' => 'PROCESS-1',
'source_file_id' => 'ATTACHMENT-1',
'source_file_name' => '付款截图.png',
'source_file_type' => 'png',
'source_field' => '收款明细附件',
'source_origin' => 'form',
'source_size' => 1024,
'preview_path' => 'invoice-previews/aa/screenshot.png',
'preview_mime' => 'image/png',
'ocr_status' => 'not_invoice',
'ocr_provider' => 'local_ocr',
'invoice_count' => 0,
'downloaded_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
}
public function test_invoice_data_page_renders_detail_and_flow_views(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$response = $this->loginAs()->get(route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
'month' => '2026-10',
'per_page' => 50,
]));
$response->assertOk()
->assertSee('发票数据')
->assertSee('付款月份')
->assertSee('发票状态')
->assertSee('发票明细')
->assertSee('按流程汇总')
->assertSee('抓取发票')
->assertSee('data-invoice-refresh', false)
->assertSee('付款流程')
->assertSee('含票流程')
->assertSee('发票价税合计')
->assertSee('开票金额覆盖率')
->assertSee('通过 OA 审批流程附件自动识别')
->assertSee('FLOW-INVOICE-1')
->assertSee('10月办公用品报销')
->assertSee('26320000000000000001')
->assertSee('测试供应商')
->assertSee('data-invoice-preview', false)
->assertSee('data-invoice-preview-modal', false)
->assertSee('原始附件 (1)')
->assertSee('*办公用品*打印纸')
->assertSee('2026-10-10')
->assertSee('FLOW-NO-INVOICE')
->assertSee('无票')
->assertDontSee('台账导入');
$html = $response->getContent();
preg_match(
'/<table class="invoice-data-table is-detail">.*?<thead>.*?<\/tr>/su',
$html,
$detailHeader,
);
$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(
'/<table class="invoice-data-table is-flow">.*?<thead>.*?<\/tr>/su',
$html,
$flowHeader,
);
$this->assertNotEmpty($flowHeader);
$this->assertMatchesRegularExpression(
'/>状态<\/th>\s*<th scope="col">打款时间<\/th>\s*<\/tr>$/su',
$flowHeader[0],
);
$this->assertContains(
'invoice-data',
array_column(
collect(\App\Utilities\BusinessNavigation::all())
->firstWhere('slug', 'process-data')['pages'] ?? [],
'slug',
),
);
}
public function test_invoice_data_page_opens_with_oa_process_permission(): void
{
$this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$subject = 'user_' . $this->user->id;
setting()->set('system.sidebar_permissions', [
'configured' => [$subject],
'subjects' => [$subject => ['process-data/oa-process']],
]);
setting()->save();
$this->loginAs()
->get(route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
'month' => '2026-10',
]))
->assertOk()
->assertSeeText('发票数据')
->assertSee('/1/workspace/process-data/invoice-data', false);
}
public function test_invoice_page_previews_office_derived_pdf_and_explains_missing_source(): void
{
$connection = DB::connection('business_mirror');
$connection->table('ding_invoice_record_mirror')->update([
'source_file_name' => '报销附件.xls',
'source_file_type' => 'xls',
'preview_path' => 'invoice-previews/aa/office.pdf',
'preview_mime' => 'application/pdf',
]);
$connection->table('ding_invoice_record_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-INVOICE-1',
'process_instance_id' => 'PROCESS-1',
'paid_month' => '2026-10',
'invoice_key' => hash('sha256', 'number:26320000000000000002'),
'invoice_type' => '电子发票(普通发票)',
'invoice_total' => 20.00,
'invoice_number' => '26320000000000000002',
'invoice_date' => '2026-10-11',
'source_file_id' => null,
'source_file_name' => null,
'source_file_type' => null,
'ocr_provider' => 'imported_workbook',
'preview_path' => null,
'preview_mime' => null,
'created_at' => now(),
'updated_at' => now(),
]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()
->get(route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
'month' => '2026-10',
]))
->assertOk()
->assertSee('data-preview-kind="pdf"', false)
->assertSee('原票未关联')
->assertDontSee('原件暂不支持预览');
}
public function test_invoice_data_page_stays_forbidden_without_oa_process_permission(): void
{
$this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$subject = 'user_' . $this->user->id;
setting()->set('system.sidebar_permissions', [
'configured' => [$subject],
'subjects' => [$subject => ['financial-operations/ledger']],
]);
setting()->save();
$this->withExceptionHandling()
->loginAs()
->get(route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
]))
->assertForbidden();
}
public function test_repository_filters_invoice_type_and_state(): void
{
$repository = app(DingInvoiceDataMirrorRepository::class);
$this->assertSame(
'电子发票(普通发票)',
DB::connection('business_mirror')->table('ding_invoice_record_mirror')->value('invoice_type'),
);
$this->assertSame(
1,
DB::connection('business_mirror')
->table('ding_invoice_record_mirror')
->where('item_name', 'like', '%打印纸%')
->count(),
);
$invoiceResult = $repository->paginate([
'month' => '2026-10',
'view' => DingInvoiceDataMirrorRepository::VIEW_DETAIL,
'invoice_state' => 'has_invoice',
'invoice_type' => '电子发票(普通发票)',
'keyword' => '打印纸',
], 1, 50);
$flowResult = $repository->paginate([
'month' => '2026-10',
'view' => DingInvoiceDataMirrorRepository::VIEW_FLOWS,
'invoice_state' => 'no_invoice',
'invoice_type' => '',
'keyword' => '',
], 1, 50);
$this->assertSame(1, $invoiceResult['total']);
$this->assertSame(1, $invoiceResult['summary']['flows']);
$this->assertSame(1, $invoiceResult['summary']['invoice_count']);
$this->assertSame(1, $flowResult['total']);
$this->assertSame('FLOW-NO-INVOICE', $flowResult['data'][0]->business_id);
$this->assertSame(1, $flowResult['summary']['flows']);
$this->assertSame(0, $flowResult['summary']['invoice_flows']);
$this->assertSame(1, $flowResult['summary']['no_invoice_flows']);
}
public function test_invoice_months_start_from_october(): void
{
$now = now();
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-SEPTEMBER',
'process_instance_id' => 'PROCESS-SEPTEMBER',
'paid_month' => '2026-09',
'title' => '9月不应展示的流程',
'payment_amount' => 10,
'payment_total' => 10,
'invoice_count' => 0,
'invoice_total' => 0,
'scan_status' => 'no_invoice',
'attachment_count' => 0,
'scanned_file_count' => 0,
'source_name' => 'OA attachment scan',
'scanned_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$this->assertNotContains(
'2026-09',
app(DingInvoiceDataMirrorRepository::class)->months(),
);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()
->get(route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
'month' => '2026-09',
]))
->assertOk()
->assertDontSee('9月不应展示的流程')
->assertSee('10月办公用品报销');
}
public function test_invoice_exports_keep_payment_time_as_last_column(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
foreach ([
DingInvoiceDataMirrorRepository::VIEW_DETAIL,
DingInvoiceDataMirrorRepository::VIEW_FLOWS,
] as $view) {
$response = $this->loginAs()->get(route('business.invoice-data.export', [
'month' => '2026-10',
'invoice_view' => $view,
'invoice_state' => 'all',
]));
$response->assertOk();
$content = ltrim($response->streamedContent(), "\xEF\xBB\xBF");
$header = str_getcsv((string) strtok($content, "\n"));
$this->assertSame('打款时间', end($header));
}
}
public function test_invoice_attachment_preview_is_served_inline(): void
{
Storage::fake('uploads');
Storage::disk('uploads')->put(
'invoice-previews/aa/preview.pdf',
"%PDF-1.4\npreview",
);
$invoiceId = (int) DB::connection('business_mirror')
->table('ding_invoice_record_mirror')
->value('id');
DB::connection('business_mirror')->table('ding_invoice_record_mirror')
->where('id', $invoiceId)
->update([
'preview_path' => 'invoice-previews/aa/preview.pdf',
'preview_mime' => 'application/pdf',
]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()
->get(route('business.invoice-data.attachment', ['invoice' => $invoiceId]))
->assertOk()
->assertHeader('Content-Type', 'application/pdf')
->assertHeader('X-Content-Type-Options', 'nosniff');
}
public function test_raw_attachment_preview_is_served_inline(): void
{
Storage::fake('uploads');
Storage::disk('uploads')->put(
'invoice-previews/aa/screenshot.png',
base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='),
);
$attachmentId = (int) DB::connection('business_mirror')
->table('ding_invoice_attachment_mirror')
->value('id');
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()
->get(route('business.invoice-data.raw-attachment', ['attachment' => $attachmentId]))
->assertOk()
->assertHeader('Content-Type', 'image/png')
->assertHeader('X-Content-Type-Options', 'nosniff');
}
public function test_refresh_endpoint_queues_selected_month(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
Storage::fake('local');
$response = $this->loginAs()->postJson(route('business.invoice-data.refresh'), [
'month' => '2026-10',
'force' => true,
]);
$response->assertOk()
->assertJsonPath('success', true)
->assertJsonPath('queued', true)
->assertJsonPath('month', '2026-10');
$token = $response->json('token');
$this->getJson(route('business.invoice-data.refresh-status', ['token' => $token]))
->assertOk()
->assertJsonPath('refresh.status', 'pending')
->assertJsonPath('refresh.month', '2026-10');
}
public function test_automatic_scan_selects_latest_unfinished_month(): void
{
$now = now();
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-PENDING-OLDER',
'process_instance_id' => 'PROCESS-PENDING-OLDER',
'paid_month' => '2026-09',
'payment_amount' => 10,
'payment_total' => 10,
'invoice_count' => 0,
'invoice_total' => 0,
'scan_status' => 'pending',
'attachment_count' => 0,
'scanned_file_count' => 0,
'source_name' => 'OA attachment scan',
'created_at' => $now,
'updated_at' => $now,
]);
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-FAILED-NEWER',
'process_instance_id' => 'PROCESS-FAILED-NEWER',
'paid_month' => '2026-11',
'payment_amount' => 10,
'payment_total' => 10,
'invoice_count' => 0,
'invoice_total' => 0,
'scan_status' => 'failed',
'attachment_count' => 0,
'scanned_file_count' => 0,
'source_name' => 'OA attachment scan',
'scanned_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-IMPORTED-NEWER',
'process_instance_id' => 'PROCESS-IMPORTED-NEWER',
'paid_month' => '2026-11',
'payment_amount' => 10,
'payment_total' => 10,
'invoice_count' => 1,
'invoice_total' => 10,
'scan_status' => 'recognized',
'attachment_count' => 1,
'scanned_file_count' => 1,
'source_name' => 'invoice_recheck.xlsx',
'scanned_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([
'source_scope' => 'personal_permission',
'business_id' => 'FLOW-RECOGNIZED-LATEST',
'process_instance_id' => 'PROCESS-RECOGNIZED-LATEST',
'paid_month' => '2026-12',
'payment_amount' => 10,
'payment_total' => 10,
'invoice_count' => 1,
'invoice_total' => 10,
'scan_status' => 'recognized',
'attachment_count' => 1,
'scanned_file_count' => 1,
'source_name' => 'OA attachment scan',
'scanned_at' => $now,
'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-12',
app(DingInvoiceSyncService::class)->latestPendingMonth(),
);
}
private function createInvoiceMirrorTables(): void
{
$schema = Schema::connection('business_mirror');
$schema->create('business_mirror_table_states', function (Blueprint $table): void {
$table->string('dataset_key')->primary();
$table->string('source_key');
$table->string('source_object');
$table->string('target_table');
$table->string('status')->default('pending');
$table->dateTime('initial_completed_at')->nullable();
$table->dateTime('last_attempted_at')->nullable();
$table->dateTime('last_succeeded_at')->nullable();
$table->unsignedBigInteger('last_upserted_rows')->default(0);
$table->unsignedBigInteger('mirror_row_count')->default(0);
$table->boolean('mirror_row_count_is_exact')->default(false);
$table->timestamps();
});
$schema->create('ding_invoice_flow_mirror', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('source_scope');
$table->string('business_id');
$table->string('process_instance_id')->nullable();
$table->string('paid_month');
$table->string('title')->nullable();
$table->string('originator_name')->nullable();
$table->string('document_type')->nullable();
$table->string('expense_type')->nullable();
$table->string('payee_name')->nullable();
$table->dateTime('paid_at')->nullable();
$table->decimal('payment_amount', 18, 2)->default(0);
$table->decimal('payment_total', 18, 2)->default(0);
$table->unsignedInteger('invoice_count')->default(0);
$table->decimal('invoice_total', 18, 2)->default(0);
$table->string('scan_status')->default('imported');
$table->unsignedInteger('attachment_count')->default(0);
$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();
});
$schema->create('ding_invoice_record_mirror', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('source_scope');
$table->string('business_id');
$table->string('process_instance_id')->nullable();
$table->string('paid_month');
$table->string('invoice_key');
$table->string('invoice_type')->nullable();
$table->string('seller_name')->nullable();
$table->string('seller_tax_no')->nullable();
$table->string('buyer_name')->nullable();
$table->string('buyer_tax_no')->nullable();
$table->decimal('invoice_total', 18, 2)->default(0);
$table->string('invoice_number')->nullable();
$table->date('invoice_date')->nullable();
$table->text('item_name')->nullable();
$table->decimal('amount_without_tax', 18, 2)->nullable();
$table->string('tax_rate')->nullable();
$table->decimal('tax_amount', 18, 2)->nullable();
$table->string('source_file_id')->nullable();
$table->string('source_file_name')->nullable();
$table->string('source_file_type')->nullable();
$table->string('source_field')->nullable();
$table->string('source_path')->nullable();
$table->string('source_hash')->nullable();
$table->string('ocr_provider')->nullable();
$table->string('preview_path', 1024)->nullable();
$table->string('preview_mime')->nullable();
$table->json('recognition_payload')->nullable();
$table->timestamps();
});
$schema->create('ding_invoice_attachment_mirror', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('source_scope');
$table->string('business_id');
$table->string('paid_month');
$table->string('attachment_key');
$table->string('process_instance_id')->nullable();
$table->string('source_file_id')->nullable();
$table->string('source_file_name');
$table->string('source_file_type')->nullable();
$table->string('source_field')->nullable();
$table->string('source_origin')->default('form');
$table->unsignedBigInteger('source_size')->default(0);
$table->string('source_hash')->nullable();
$table->string('source_path', 1024)->nullable();
$table->string('preview_path', 1024)->nullable();
$table->string('preview_mime')->nullable();
$table->string('ocr_status')->default('pending');
$table->string('ocr_provider')->nullable();
$table->unsignedInteger('invoice_count')->default(0);
$table->text('last_error')->nullable();
$table->dateTime('downloaded_at')->nullable();
$table->timestamps();
});
}
}