feat: 增加 OA 发票数据页面与抓取链路 #1469

Merged
yueyang merged 1 commits from feature/yueyang-oa-invoice-data into main 2026-11-26 16:46:28 +08:00
29 changed files with 4653 additions and 2 deletions

View File

@ -5580,6 +5580,7 @@ class Pages extends Controller
'product-costs' => $this->contentForProductCosts(),
'financial-analysis' => $this->contentForFinancialAnalysis(),
'oa-process' => $this->contentForProcessDetails(),
'invoice-data' => app(\Modules\EcommerceFinance\View\InvoiceDataPageData::class)->page(request()),
'management-expenses' => $this->contentForManagementExpenses(),
'labor-expenses' => $this->contentForLaborExpenses(),
'courier-surcharge' => $this->contentForCourierSurcharge($tab),

View File

@ -19,6 +19,7 @@ return [
'icon' => 'account_tree',
'pages' => [
['slug' => 'oa-process', 'title' => 'OA流程'],
['slug' => 'invoice-data', 'title' => '发票数据', 'icon' => 'receipt_long'],
],
],
],

View File

@ -0,0 +1,21 @@
<?php
return [
'dataset_key' => 'operations_replica.rpt.ding_invoices',
'flow_batch_size' => (int) env('DING_INVOICE_SCAN_BATCH_SIZE', 20),
'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),
'pdftotext_binary' => env('DING_INVOICE_PDFTOTEXT_BINARY', '/usr/bin/pdftotext'),
'pdftoppm_binary' => env('DING_INVOICE_PDFTOPPM_BINARY', '/usr/bin/pdftoppm'),
'ocr' => [
'api_key' => env('DING_INVOICE_OCR_API_KEY', env('DEEPSEEK_API_KEY', '')),
'base_url' => env(
'DING_INVOICE_OCR_BASE_URL',
'https://api.deepseek.com/chat/completions',
),
'model' => env('DING_INVOICE_OCR_MODEL', 'deepseek-chat'),
'timeout_seconds' => (int) env('DING_INVOICE_OCR_TIMEOUT', 90),
],
];

View File

@ -0,0 +1,125 @@
<?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')) {
$schema->create('ding_invoice_flow_mirror', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('source_scope', 40)->default('personal_permission');
$table->string('business_id', 32);
$table->string('process_instance_id', 100)->nullable();
$table->string('paid_month', 7)->default('');
$table->string('title', 255)->nullable();
$table->string('originator_name', 100)->nullable();
$table->string('document_type', 100)->nullable();
$table->string('expense_type', 255)->nullable();
$table->string('payee_name', 255)->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', 24)->default('imported')->index();
$table->unsignedInteger('attachment_count')->default(0);
$table->unsignedInteger('scanned_file_count')->default(0);
$table->text('last_error')->nullable();
$table->string('source_name', 255)->nullable();
$table->dateTime('scanned_at', 6)->nullable();
$table->timestamps();
$table->unique(
['source_scope', 'business_id'],
'ding_invoice_flow_scope_business_unique',
);
$table->index(
['source_scope', 'paid_month'],
'ding_invoice_flow_scope_month_index',
);
$table->index(
['source_scope', 'paid_month', 'scan_status'],
'ding_invoice_flow_scope_month_status_index',
);
});
}
if (! $schema->hasTable('ding_invoice_record_mirror')) {
$schema->create('ding_invoice_record_mirror', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->string('source_scope', 40)->default('personal_permission');
$table->string('business_id', 32);
$table->string('process_instance_id', 100)->nullable();
$table->string('paid_month', 7)->default('');
$table->string('invoice_key', 64);
$table->string('invoice_type', 100)->nullable();
$table->string('seller_name', 255)->nullable();
$table->string('seller_tax_no', 64)->nullable();
$table->string('buyer_name', 255)->nullable();
$table->string('buyer_tax_no', 64)->nullable();
$table->decimal('invoice_total', 18, 2)->default(0);
$table->string('invoice_number', 32)->nullable();
$table->date('invoice_date')->nullable();
$table->text('item_name')->nullable();
$table->decimal('amount_without_tax', 18, 2)->nullable();
$table->string('tax_rate', 32)->nullable();
$table->decimal('tax_amount', 18, 2)->nullable();
$table->string('source_file_id', 100)->nullable();
$table->string('source_file_name', 255)->nullable();
$table->string('source_file_type', 32)->nullable();
$table->string('source_field', 255)->nullable();
$table->string('source_path', 1024)->nullable();
$table->string('source_hash', 64)->nullable();
$table->string('ocr_provider', 32)->nullable();
$table->json('recognition_payload')->nullable();
$table->timestamps();
$table->unique(
['source_scope', 'business_id', 'invoice_key'],
'ding_invoice_record_scope_business_key_unique',
);
$table->index(
['source_scope', 'business_id'],
'ding_invoice_record_scope_business_index',
);
$table->index(
['source_scope', 'invoice_type'],
'ding_invoice_record_scope_type_index',
);
$table->index(
['source_scope', 'invoice_date'],
'ding_invoice_record_scope_date_index',
);
$table->index('invoice_number', 'ding_invoice_record_number_index');
});
}
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
$schema->dropIfExists('ding_invoice_record_mirror');
$schema->dropIfExists('ding_invoice_flow_mirror');
}
};

View File

@ -271,6 +271,7 @@ CRON_TZ=Asia/Shanghai
2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1
# 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
EOF
chmod 644 /etc/cron.d/caiwu-ding-process-details

View File

@ -275,6 +275,7 @@ CRON_TZ=Asia/Shanghai
2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1
# 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
EOF
chmod 644 /etc/cron.d/caiwu-ding-process-details

View File

@ -38,6 +38,7 @@
"business-mirror:import-jd-wallet",
"business-mirror:import-pdd-platform-balances",
"ding:import-process-details",
"ding-invoices:import",
"jst-order-labels:import-planting-rules",
"jst-order-labels:import",
"jst-order-labels:sync-daily",

View File

@ -9,7 +9,7 @@ CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
*:import|*:import-*|*:import:*|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
esac
case "${1:-}" in
@ -46,6 +46,12 @@ if [ "$1" = 'business-mirror:process-ding-refresh-requests' ]; then
pending_request="$(find "$storage_root/app/ding-process-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)"
[ -n "$pending_request" ] || exit 0
fi
if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
[ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0
pending_request="$(find "$storage_root/app/ding-invoice-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)"
[ -n "$pending_request" ] || exit 0
fi
if [ "$1" != 'account-bills:exports:run' ]; then
exec 9>"$LOCK_FILE"
if ! flock -w "${CAIWU_BATCH_LOCK_WAIT:-1800}" 9; then

View File

@ -0,0 +1,49 @@
<?php
namespace Modules\EcommerceFinance\Console;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingInvoiceWorkbookImporter;
use Throwable;
class ImportDingInvoiceWorkbook extends Command
{
protected $signature = 'ding-invoices:import
{file : 报销发票识别 Excel 文件路径}
{--scope=personal_permission : 镜像来源范围}
{--keep-existing-months : 保留同月份现有镜像后再写入}';
protected $description = '导入“报销发票识别”台账到 OA 发票数据镜像';
public function handle(DingInvoiceWorkbookImporter $importer): int
{
$startedAt = microtime(true);
try {
$result = $importer->import(
(string) $this->argument('file'),
(string) $this->option('scope'),
! $this->option('keep-existing-months'),
);
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'发票台账导入完成:%d 个流程、%d 张发票、开票金额 %.2f 元;月份 %s。',
$result['flows'],
$result['invoices'],
$result['invoice_total'],
implode(',', $result['months']),
));
$this->line(sprintf(
'耗时 %.2f 秒;PHP 峰值内存 %.1f MiB。',
microtime(true) - $startedAt,
memory_get_peak_usage(true) / 1024 / 1024,
));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace Modules\EcommerceFinance\Console;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingInvoiceRefreshQueue;
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
use Throwable;
class ProcessDingInvoiceRefreshRequests extends Command
{
protected $signature = 'ding-invoices:process-refresh-requests
{--limit=50 : 单轮最多扫描的流程数}';
protected $description = '处理发票数据页面提交的附件抓取请求';
public function handle(
DingInvoiceRefreshQueue $queue,
DingInvoiceSyncService $sync,
): int {
$queue->cleanup();
$request = $queue->claimNext();
if ($request === null) {
return self::SUCCESS;
}
try {
$result = $sync->syncMonth(
(string) ($request['month'] ?? ''),
(int) $this->option('limit'),
(bool) ($request['force'] ?? false),
);
if ((int) ($result['remaining_flows'] ?? 0) > 0) {
$queue->defer((string) $request['token'], $result, false);
$this->info('本批发票抓取完成,剩余流程等待下一批处理。');
return self::SUCCESS;
}
$queue->complete((string) $request['token'], $result);
$this->info(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);
$queue->fail((string) $request['token'], $exception->getMessage());
$this->error($exception->getMessage());
return self::FAILURE;
}
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace Modules\EcommerceFinance\Console;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\DingInvoiceSyncService;
use Throwable;
class SyncDingInvoices extends Command
{
protected $signature = 'ding-invoices:sync
{--month= : 付款月份 YYYY-MM}
{--limit=20 : 本轮最多扫描的流程数}
{--force : 已扫描流程也重新抓取附件}';
protected $description = '抓取钉钉 OA 审批附件并识别发票,写入发票数据镜像';
public function handle(DingInvoiceSyncService $service): int
{
try {
$result = $service->syncMonth(
(string) ($this->option('month') ?: now()->format('Y-m')),
(int) $this->option('limit'),
(bool) $this->option('force'),
);
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,207 @@
<?php
namespace Modules\EcommerceFinance\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\Repositories\DingInvoiceDataMirrorRepository;
use Modules\EcommerceFinance\Services\DingTalkApprovalAttachmentDownloader;
use Modules\EcommerceFinance\Services\DingInvoiceRefreshQueue;
use Symfony\Component\HttpFoundation\StreamedResponse;
class InvoiceData extends Controller
{
public function __construct(
private readonly DingInvoiceDataMirrorRepository $repository,
) {}
public function export(Request $request): StreamedResponse
{
$filters = $this->filters($request);
return response()->streamDownload(function () use ($filters): void {
$stream = fopen('php://output', 'wb');
fwrite($stream, "\xEF\xBB\xBF");
if ($filters['view'] === DingInvoiceDataMirrorRepository::VIEW_FLOWS) {
fputcsv($stream, [
'流程号',
'标题',
'提交人',
'报销类型',
'费用类型',
'收款人',
'打款时间',
'本月付款金额',
'付款合计',
'发票张数',
'发票价税合计',
'付款差额',
'扫描状态',
'扫描说明',
]);
foreach ($this->repository->exportRows($filters) as $row) {
$payment = (float) ($row['payment_amount'] ?? 0);
$invoice = (float) ($row['invoice_total'] ?? 0);
fputcsv($stream, [
(string) ($row['business_id'] ?? ''),
(string) ($row['title'] ?? ''),
(string) ($row['originator_name'] ?? ''),
(string) ($row['document_type'] ?? ''),
(string) ($row['expense_type'] ?? ''),
(string) ($row['payee_name'] ?? ''),
(string) ($row['paid_at'] ?? ''),
number_format($payment, 2, '.', ''),
number_format((float) ($row['payment_total'] ?? 0), 2, '.', ''),
(int) ($row['invoice_count'] ?? 0),
number_format($invoice, 2, '.', ''),
number_format(round($payment - $invoice, 2), 2, '.', ''),
(string) ($row['scan_status'] ?? ''),
(string) ($row['last_error'] ?? ''),
]);
}
} else {
fputcsv($stream, [
'流程号',
'标题',
'提交人',
'报销类型',
'收款人',
'打款时间',
'本月付款金额',
'发票类型',
'销售方名称',
'销售方税号',
'购买方名称',
'购买方税号',
'价税合计',
'发票号码',
'开票日期',
'项目名称',
'金额',
'税率',
'税额',
'付款差额',
'附件名称',
]);
foreach ($this->repository->exportRows($filters) as $row) {
$payment = (float) ($row['payment_amount'] ?? 0);
$invoice = (float) ($row['invoice_total'] ?? 0);
fputcsv($stream, [
(string) ($row['business_id'] ?? ''),
(string) ($row['title'] ?? ''),
(string) ($row['originator_name'] ?? ''),
(string) ($row['document_type'] ?? ''),
(string) ($row['payee_name'] ?? ''),
(string) ($row['paid_at'] ?? ''),
number_format($payment, 2, '.', ''),
(string) ($row['invoice_type'] ?? ''),
(string) ($row['seller_name'] ?? ''),
(string) ($row['seller_tax_no'] ?? ''),
(string) ($row['buyer_name'] ?? ''),
(string) ($row['buyer_tax_no'] ?? ''),
number_format($invoice, 2, '.', ''),
(string) ($row['invoice_number'] ?? ''),
(string) ($row['invoice_date'] ?? ''),
(string) ($row['item_name'] ?? ''),
$row['amount_without_tax'] === null
? ''
: number_format((float) $row['amount_without_tax'], 2, '.', ''),
(string) ($row['tax_rate'] ?? ''),
$row['tax_amount'] === null
? ''
: number_format((float) $row['tax_amount'], 2, '.', ''),
number_format(round($payment - $invoice, 2), 2, '.', ''),
(string) ($row['source_file_name'] ?? ''),
]);
}
}
fclose($stream);
}, 'OA发票数据_' . ($filters['month'] ?: 'all') . '_' . now()->format('Ymd_His') . '.csv', [
'Content-Type' => 'text/csv; charset=UTF-8',
'Cache-Control' => 'private, no-store',
]);
}
public function attachment(int $invoice): RedirectResponse
{
// The row endpoint is intentionally not used for arbitrary IDs. Query the
// exact invoice record, then let DingTalk enforce whether the current app
// can mint a temporary download URL for that process attachment.
$invoiceRow = \Illuminate\Support\Facades\DB::connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
)->table('ding_invoice_record_mirror')
->where('id', $invoice)
->where('source_scope', $this->repository->scope())
->first();
abort_if($invoiceRow === null, 404);
$processInstanceId = trim((string) ($invoiceRow->process_instance_id ?? ''));
$fileId = trim((string) ($invoiceRow->source_file_id ?? ''));
abort_if($processInstanceId === '' || $fileId === '', 404, '该发票没有可下载的原始附件。');
$uri = app(DingTalkApprovalAttachmentDownloader::class)
->downloadUri($processInstanceId, $fileId);
abort_if($uri === null, 404, '原始发票附件暂时无法下载。');
return redirect()->away($uri);
}
public function requestRefresh(Request $request): JsonResponse
{
$validated = $request->validate([
'month' => ['required', 'date_format:Y-m'],
'force' => ['nullable', 'boolean'],
]);
$state = app(DingInvoiceRefreshQueue::class)->enqueue(
$validated['month'],
(bool) ($validated['force'] ?? true),
(int) company_id(),
(int) user_id(),
);
return response()->json([
'success' => true,
...$state,
'message' => $state['queued']
? '发票抓取任务已进入队列。'
: '该月份已有发票抓取任务正在排队或处理中。',
])->header('Cache-Control', 'no-store');
}
public function refreshStatus(string $token): JsonResponse
{
$status = app(DingInvoiceRefreshQueue::class)->status(
$token,
(int) company_id(),
(int) user_id(),
);
abort_if($status === null, 404);
return response()
->json(['success' => true, 'refresh' => $status])
->header('Cache-Control', 'no-store');
}
/** @return array<string,string> */
private function filters(Request $request): array
{
$month = trim((string) $request->query('month', ''));
$view = $request->query('invoice_view') === DingInvoiceDataMirrorRepository::VIEW_FLOWS
? DingInvoiceDataMirrorRepository::VIEW_FLOWS
: DingInvoiceDataMirrorRepository::VIEW_DETAIL;
$state = (string) $request->query('invoice_state', 'all');
return [
'month' => preg_match('/^\d{4}-\d{2}$/', $month) === 1 ? $month : '',
'view' => $view,
'invoice_state' => array_key_exists($state, DingInvoiceDataMirrorRepository::INVOICE_STATES)
? $state
: 'all',
'invoice_type' => mb_substr(trim((string) $request->query('invoice_type', '')), 0, 100),
'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 100),
];
}
}

View File

@ -4,12 +4,15 @@ namespace Modules\EcommerceFinance\Providers;
use Illuminate\Support\ServiceProvider as Provider;
use Modules\EcommerceFinance\Console\ExportShengsuanAnomalyOrders;
use Modules\EcommerceFinance\Console\ImportDingInvoiceWorkbook;
use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitDetails;
use Modules\EcommerceFinance\Console\ProcessDingRefreshRequests;
use Modules\EcommerceFinance\Console\ProcessDingInvoiceRefreshRequests;
use Modules\EcommerceFinance\Console\DiagnoseJushuitanPackage;
use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitRows;
use Modules\EcommerceFinance\Console\CalcShippingFreight;
use Modules\EcommerceFinance\Console\SyncJushuitanShipping;
use Modules\EcommerceFinance\Console\SyncDingInvoices;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
use Modules\EcommerceFinance\Services\JianSunSnapshotRefresher;
use Modules\EcommerceFinance\Services\OperationsReplicaSnapshotRefresher;
@ -29,7 +32,10 @@ class Main extends Provider
$this->commands([
SyncJushuitanShipping::class,
CalcShippingFreight::class,
ImportDingInvoiceWorkbook::class,
ProcessDingRefreshRequests::class,
ProcessDingInvoiceRefreshRequests::class,
SyncDingInvoices::class,
DiagnoseJushuitanPackage::class,
ImportShengsuanOrderProfitRows::class,
ImportShengsuanOrderProfitDetails::class,

View File

@ -0,0 +1,452 @@
<?php
namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\DingInvoiceWorkbookImporter;
use RuntimeException;
class DingInvoiceDataMirrorRepository
{
public const PER_PAGE_OPTIONS = [50, 100, 200];
public const VIEW_DETAIL = 'detail';
public const VIEW_FLOWS = 'flows';
public const INVOICE_STATES = [
'all' => '全部状态',
'has_invoice' => '有发票',
'no_invoice' => '无票',
'needs_review' => '待复核',
];
private ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
public function scope(): string
{
return trim((string) config(
'upstream_mirrors.ding_process_details.scope',
'personal_permission',
)) ?: 'personal_permission';
}
public function ready(): bool
{
$schema = Schema::connection($this->connection->getName());
if (! $schema->hasTable('ding_invoice_flow_mirror')
|| ! $schema->hasTable('ding_invoice_record_mirror')) {
return false;
}
$state = $this->state();
if ($state !== null && ($state['initial_completed_at'] ?? null) !== null) {
return true;
}
return (int) $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->count() > 0;
}
/** @return array<string,mixed>|null */
public function state(): ?array
{
if (! Schema::connection($this->connection->getName())
->hasTable('business_mirror_table_states')) {
return null;
}
$row = $this->connection->table('business_mirror_table_states')
->where('dataset_key', DingInvoiceWorkbookImporter::DATASET_KEY)
->first();
return $row === null ? null : (array) $row;
}
/** @return list<string> */
public function months(): array
{
if (! $this->ready()) {
return [];
}
return $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope())
->whereNotNull('paid_month')
->where('paid_month', '!=', '')
->distinct()
->orderByDesc('paid_month')
->pluck('paid_month')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
}
/**
* @param array<string,mixed> $filters
* @return array{data:list<object>,total:int,summary:array<string,mixed>,state:?array}
*/
public function paginate(array $filters, int $page, int $perPage): array
{
if (! $this->ready()) {
throw new RuntimeException('ding_invoice_mirror_not_ready');
}
$page = max(1, $page);
$perPage = in_array($perPage, self::PER_PAGE_OPTIONS, true) ? $perPage : 50;
$query = $filters['view'] === self::VIEW_FLOWS
? $this->flowQuery($filters)
: $this->detailQuery($filters);
$total = (clone $query)->count();
$data = $query
->forPage($page, $perPage)
->get()
->all();
return [
'data' => $data,
'total' => $total,
'summary' => $this->summary($filters),
'state' => $this->state(),
];
}
/** @param array<string,mixed> $filters */
public function filterOptions(array $filters): array
{
if (! $this->ready()) {
return ['invoice_types' => []];
}
$query = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $this->scope());
if (($filters['month'] ?? '') !== '') {
$query->where('paid_month', $filters['month']);
}
return [
'invoice_types' => $query
->whereNotNull('invoice_type')
->where('invoice_type', '!=', '')
->distinct()
->orderBy('invoice_type')
->pluck('invoice_type')
->map(static fn (mixed $value): string => (string) $value)
->values()
->all(),
];
}
/** @param array<string,mixed> $filters */
public function exportRows(array $filters): iterable
{
if (! $this->ready()) {
throw new RuntimeException('ding_invoice_mirror_not_ready');
}
$query = $filters['view'] === self::VIEW_FLOWS
? $this->flowQuery($filters)
: $this->detailQuery($filters);
foreach ($query->cursor() as $row) {
yield (array) $row;
}
}
/** @param array<string,mixed> $filters */
private function flowQuery(array $filters): Builder
{
$query = $this->connection->table('ding_invoice_flow_mirror as f')
->select([
'f.id',
'f.business_id',
'f.process_instance_id',
'f.paid_month',
'f.title',
'f.originator_name',
'f.document_type',
'f.expense_type',
'f.payee_name',
'f.paid_at',
'f.payment_amount',
'f.payment_total',
'f.invoice_count',
'f.invoice_total',
'f.scan_status',
'f.attachment_count',
'f.scanned_file_count',
'f.last_error',
'f.source_name',
'f.scanned_at',
])
->where('f.source_scope', $this->scope());
$this->applyFlowFilters($query, $filters);
return $query
->orderByDesc('f.paid_at')
->orderByDesc('f.business_id');
}
/** @param array<string,mixed> $filters */
private function detailQuery(array $filters): Builder
{
$query = $this->connection->table('ding_invoice_record_mirror as r')
->join('ding_invoice_flow_mirror as f', function ($join): void {
$join->on('f.business_id', '=', 'r.business_id')
->on('f.source_scope', '=', 'r.source_scope');
})
->select([
'r.id',
'r.business_id',
'r.process_instance_id',
'r.paid_month',
'r.invoice_type',
'r.seller_name',
'r.seller_tax_no',
'r.buyer_name',
'r.buyer_tax_no',
'r.invoice_total',
'r.invoice_number',
'r.invoice_date',
'r.item_name',
'r.amount_without_tax',
'r.tax_rate',
'r.tax_amount',
'r.source_file_id',
'r.source_file_name',
'r.source_file_type',
'r.source_field',
'r.ocr_provider',
'f.title',
'f.originator_name',
'f.document_type',
'f.expense_type',
'f.payee_name',
'f.paid_at',
'f.payment_amount',
'f.payment_total',
'f.invoice_count',
'f.invoice_total as flow_invoice_total',
'f.scan_status',
'f.last_error',
])
->where('r.source_scope', $this->scope());
$this->applyFlowFilters($query, $filters, 'f');
if (($filters['invoice_type'] ?? '') !== '') {
$query->where('r.invoice_type', $filters['invoice_type']);
}
if (($filters['keyword'] ?? '') !== '') {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword, $filters): void {
foreach ([
'r.business_id',
'r.invoice_number',
'r.seller_name',
'r.seller_tax_no',
'r.buyer_name',
'r.buyer_tax_no',
'r.item_name',
'f.title',
'f.originator_name',
'f.payee_name',
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
});
}
return $query
->orderByDesc('f.paid_at')
->orderByDesc('f.business_id')
->orderBy('r.id');
}
/** @param array<string,mixed> $filters */
private function applyFlowFilters(Builder $query, array $filters, string $alias = 'f'): void
{
$query->where("{$alias}.source_scope", $this->scope());
if (($filters['month'] ?? '') !== '') {
$query->where("{$alias}.paid_month", $filters['month']);
}
match ($filters['invoice_state'] ?? 'all') {
'has_invoice' => $query->where("{$alias}.invoice_count", '>', 0),
'no_invoice' => $query
->where("{$alias}.invoice_count", '=', 0)
->where(function (Builder $nested) use ($alias): void {
$nested->whereNull("{$alias}.last_error")
->orWhere("{$alias}.last_error", '=', '');
}),
'needs_review' => $query
->where(function (Builder $nested) use ($alias): void {
$nested->whereIn("{$alias}.scan_status", ['partial', 'failed'])
->orWhere(function (Builder $failed) use ($alias): void {
$failed->whereNotNull("{$alias}.last_error")
->where("{$alias}.last_error", '!=', '');
});
}),
default => null,
};
if (($filters['invoice_type'] ?? '') !== ''
&& $filters['view'] === self::VIEW_FLOWS) {
$query->whereExists(function (Builder $exists) use ($filters): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as ri')
->whereColumn('ri.source_scope', 'f.source_scope')
->whereColumn('ri.business_id', 'f.business_id')
->where('ri.invoice_type', $filters['invoice_type']);
});
}
if (($filters['keyword'] ?? '') !== ''
&& $filters['view'] === self::VIEW_FLOWS) {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword, $alias, $filters): void {
foreach ([
"{$alias}.business_id",
"{$alias}.title",
"{$alias}.originator_name",
"{$alias}.document_type",
"{$alias}.expense_type",
"{$alias}.payee_name",
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
if ($filters['view'] === self::VIEW_FLOWS) {
$nested->orWhereExists(function (Builder $exists) use ($keyword): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as rk')
->whereColumn('rk.source_scope', 'f.source_scope')
->whereColumn('rk.business_id', 'f.business_id')
->where(function (Builder $invoiceSearch) use ($keyword): void {
foreach (['invoice_number', 'seller_name', 'buyer_name', 'item_name'] as $column) {
$invoiceSearch->orWhere("rk.{$column}", 'like', $keyword);
}
});
});
}
});
}
}
/** @param array<string,mixed> $filters */
private function summary(array $filters): array
{
$query = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $this->scope());
if (($filters['month'] ?? '') !== '') {
$query->where('paid_month', $filters['month']);
}
if (($filters['invoice_state'] ?? 'all') === 'has_invoice') {
$query->where('invoice_count', '>', 0);
} elseif (($filters['invoice_state'] ?? 'all') === 'no_invoice') {
$query->where('invoice_count', 0)
->where(function (Builder $nested): void {
$nested->whereNull('last_error')->orWhere('last_error', '');
});
} elseif (($filters['invoice_state'] ?? 'all') === 'needs_review') {
$query->where(function (Builder $nested): void {
$nested->whereIn('scan_status', ['partial', 'failed'])
->orWhere(function (Builder $failed): void {
$failed->whereNotNull('last_error')->where('last_error', '!=', '');
});
});
}
if (($filters['invoice_type'] ?? '') !== '') {
$query->whereExists(function (Builder $exists) use ($filters): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as summary_invoice')
->whereColumn('summary_invoice.source_scope', 'ding_invoice_flow_mirror.source_scope')
->whereColumn('summary_invoice.business_id', 'ding_invoice_flow_mirror.business_id')
->where('summary_invoice.invoice_type', $filters['invoice_type']);
});
}
if (($filters['keyword'] ?? '') !== '') {
$keyword = '%' . $filters['keyword'] . '%';
$query->where(function (Builder $nested) use ($keyword, $filters): void {
foreach ([
'business_id',
'title',
'originator_name',
'document_type',
'expense_type',
'payee_name',
] as $column) {
$nested->orWhere($column, 'like', $keyword);
}
if (($filters['view'] ?? self::VIEW_DETAIL) === self::VIEW_DETAIL) {
$nested->orWhereExists(function (Builder $exists) use ($keyword): void {
$exists->selectRaw('1')
->from('ding_invoice_record_mirror as summary_invoice_search')
->whereColumn(
'summary_invoice_search.source_scope',
'ding_invoice_flow_mirror.source_scope',
)
->whereColumn(
'summary_invoice_search.business_id',
'ding_invoice_flow_mirror.business_id',
)
->where(function (Builder $invoiceSearch) use ($keyword): void {
foreach ([
'invoice_number',
'seller_name',
'seller_tax_no',
'buyer_name',
'buyer_tax_no',
'item_name',
] as $column) {
$invoiceSearch->orWhere(
'summary_invoice_search.' . $column,
'like',
$keyword,
);
}
});
});
}
});
}
$rows = (clone $query)->get([
'payment_amount',
'invoice_count',
'invoice_total',
'scan_status',
'last_error',
]);
$payment = round((float) $rows->sum('payment_amount'), 2);
$invoice = round((float) $rows->sum('invoice_total'), 2);
return [
'flows' => $rows->count(),
'payment_amount' => $payment,
'invoice_count' => (int) $rows->sum('invoice_count'),
'invoice_total' => $invoice,
'no_invoice_flows' => $rows->filter(
static fn (object $row): bool => (int) $row->invoice_count === 0
&& ($row->last_error === null || $row->last_error === ''),
)->count(),
'needs_review_flows' => $rows->filter(
static fn (object $row): bool => in_array((string) $row->scan_status, ['partial', 'failed'], true)
|| ($row->last_error !== null && $row->last_error !== ''),
)->count(),
'invoice_rate' => $payment > 0 ? $invoice / $payment : 0,
];
}
}

View File

@ -1,6 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\EcommerceFinance\Http\Controllers\InvoiceData;
use Modules\EcommerceFinance\Http\Controllers\ProcessDetails;
Route::admin('ecommerce-finance', function () {
@ -41,6 +42,30 @@ Route::admin('ecommerce-finance', function (): void {
->defaults('page', 'oa-process')
->name('business.process-details.pending-payment-summary');
Route::get('workspace/process-data/invoice-data/export', [InvoiceData::class, 'export'])
->middleware('business.page:process-data,invoice-data')
->name('business.invoice-data.export');
Route::post('workspace/process-data/invoice-data/refresh', [InvoiceData::class, 'requestRefresh'])
->middleware(['business.page:process-data,invoice-data', 'throttle:10,1'])
->name('business.invoice-data.refresh');
Route::get(
'workspace/process-data/invoice-data/refresh/{token}',
[InvoiceData::class, 'refreshStatus'],
)
->where('token', '[0-9a-f-]{36}')
->middleware(['business.page:process-data,invoice-data', 'throttle:120,1'])
->name('business.invoice-data.refresh-status');
Route::get(
'workspace/process-data/invoice-data/invoices/{invoice}/attachment',
[InvoiceData::class, 'attachment'],
)
->whereNumber('invoice')
->middleware('business.page:process-data,invoice-data')
->name('business.invoice-data.attachment');
Route::get('workspace/financial-operations/process-details', function (\Illuminate\Http\Request $request) {
return redirect()->route('business.pages.show', array_merge($request->query(), [
'section' => 'process-data',

View File

@ -0,0 +1,257 @@
<?php
namespace Modules\EcommerceFinance\Services;
use RuntimeException;
use Symfony\Component\Process\Process;
use Throwable;
use ZipArchive;
class DingInvoiceFileRecognizer
{
public function __construct(
private readonly DingInvoiceTextParser $textParser,
private readonly DingInvoiceVisionClient $vision,
) {}
/**
* @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string}
*/
public function recognize(string $path, string $fileName = ''): array
{
if (! is_file($path)) {
return ['invoices' => [], 'errors' => ['文件不存在'], 'provider' => ''];
}
$extension = strtolower(pathinfo($fileName !== '' ? $fileName : $path, PATHINFO_EXTENSION));
$tempDir = storage_path('app/temp/invoice-ocr/' . bin2hex(random_bytes(8)));
if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) {
throw new RuntimeException('无法创建发票临时目录。');
}
try {
return match ($extension) {
'pdf' => $this->recognizePdf($path, $tempDir),
'jpg', 'jpeg', 'png', 'webp', 'bmp' => $this->recognizeImage($path),
'xlsx' => $this->recognizeXlsx($path, $tempDir),
'zip' => $this->recognizeZip($path, $tempDir),
default => [
'invoices' => [],
'errors' => ['暂不支持识别 .' . ($extension ?: '未知') . ' 附件'],
'provider' => '',
],
};
} finally {
$this->removeDirectory($tempDir);
}
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizePdf(string $path, string $tempDir): array
{
$errors = [];
$text = $this->pdfText($path);
if ($text !== '') {
$parsed = $this->textParser->parse($text);
if ($parsed !== null) {
return ['invoices' => [$parsed], 'errors' => [], 'provider' => 'pdf_text'];
}
}
if (! $this->vision->configured()) {
return [
'invoices' => [],
'errors' => ['PDF 未提取到结构化发票,且未配置 OCR API。'],
'provider' => 'pdf_text',
];
}
$invoices = [];
for ($page = 1; $page <= max(1, (int) config('ding_invoice_data.max_pdf_pages', 5)); $page++) {
$prefix = $tempDir . '/page-' . $page;
if (! $this->renderPdfPage($path, $prefix, $page)) {
break;
}
$imagePath = $prefix . '.png';
try {
$invoice = $this->vision->recognize(
(string) file_get_contents($imagePath),
'image/png',
);
if ($invoice !== null) {
$invoices[] = $invoice;
}
} catch (Throwable $exception) {
$errors[] = 'PDF 第 ' . $page . ' 页:' . $exception->getMessage();
}
}
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'vision'];
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeImage(string $path): array
{
if (! $this->vision->configured()) {
return [
'invoices' => [],
'errors' => ['图片发票需要配置 OCR API。'],
'provider' => 'vision',
];
}
$mime = mime_content_type($path) ?: 'image/jpeg';
$bytes = (string) file_get_contents($path);
$invoice = $this->vision->recognize($bytes, $mime);
return [
'invoices' => $invoice === null ? [] : [$invoice],
'errors' => [],
'provider' => 'vision',
];
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeXlsx(string $path, string $tempDir): array
{
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
return ['invoices' => [], 'errors' => ['无法打开 Excel 附件'], 'provider' => ''];
}
$invoices = [];
$errors = [];
try {
for ($index = 0; $index < $zip->numFiles; $index++) {
$name = (string) $zip->getNameIndex($index);
if (! str_starts_with($name, 'xl/media/')) {
continue;
}
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (! in_array($extension, ['png', 'jpg', 'jpeg', 'webp', 'bmp'], true)) {
continue;
}
$target = $tempDir . '/' . basename($name);
$stream = $zip->getStream($name);
if ($stream === false) {
continue;
}
file_put_contents($target, stream_get_contents($stream));
fclose($stream);
try {
$result = $this->recognizeImage($target);
array_push($invoices, ...$result['invoices']);
array_push($errors, ...$result['errors']);
} catch (Throwable $exception) {
$errors[] = $name . ':' . $exception->getMessage();
}
}
} finally {
$zip->close();
}
return [
'invoices' => $invoices,
'errors' => $errors,
'provider' => 'xlsx_media',
];
}
/** @return array{invoices:list<array<string,mixed>>,errors:list<string>,provider:string} */
private function recognizeZip(string $path, string $tempDir): array
{
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
return ['invoices' => [], 'errors' => ['无法打开 ZIP 附件'], 'provider' => ''];
}
$invoices = [];
$errors = [];
try {
for ($index = 0; $index < $zip->numFiles; $index++) {
$name = (string) $zip->getNameIndex($index);
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (! in_array($extension, ['pdf', 'png', 'jpg', 'jpeg', 'webp', 'bmp'], true)) {
continue;
}
$target = $tempDir . '/' . $index . '-' . basename($name);
$stream = $zip->getStream($name);
if ($stream === false) {
continue;
}
file_put_contents($target, stream_get_contents($stream));
fclose($stream);
try {
$result = $this->recognize($target, $name);
array_push($invoices, ...$result['invoices']);
array_push($errors, ...$result['errors']);
} catch (Throwable $exception) {
$errors[] = $name . ':' . $exception->getMessage();
}
}
} finally {
$zip->close();
}
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'zip'];
}
private function pdfText(string $path): string
{
$binary = (string) config('ding_invoice_data.pdftotext_binary', '/usr/bin/pdftotext');
if (! is_executable($binary)) {
return '';
}
$process = new Process([$binary, '-layout', $path, '-']);
$process->setTimeout(45);
$process->run();
return $process->isSuccessful() ? $process->getOutput() : '';
}
private function renderPdfPage(string $path, string $prefix, int $page): bool
{
$binary = (string) config('ding_invoice_data.pdftoppm_binary', '/usr/bin/pdftoppm');
if (! is_executable($binary)) {
return false;
}
$process = new Process([
$binary,
'-png',
'-r',
'150',
'-f',
(string) $page,
'-l',
(string) $page,
'-singlefile',
$path,
$prefix,
]);
$process->setTimeout(60);
$process->run();
return $process->isSuccessful() && is_file($prefix . '.png');
}
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);
}
}

View File

@ -0,0 +1,247 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
class DingInvoiceRefreshQueue
{
public const DIRECTORY = 'ding-invoice-refresh';
private const RESULT_TTL_SECONDS = 3600;
private const STALE_PROCESSING_SECONDS = 3600;
/** @return array{queued:bool,token:?string,month:string} */
public function enqueue(string $month, bool $force, int $companyId, int $userId): array
{
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
throw new RuntimeException('月份格式应为 YYYY-MM。');
}
Storage::disk('local')->makeDirectory(self::DIRECTORY);
foreach (array_merge(
Storage::disk('local')->files(self::DIRECTORY),
) as $path) {
if (! str_ends_with($path, '.pending') && ! str_ends_with($path, '.processing')) {
continue;
}
$payload = $this->readJson($path);
if ($payload !== null
&& (string) ($payload['month'] ?? '') === $month
&& (int) ($payload['company_id'] ?? 0) === $companyId) {
return [
'queued' => false,
'token' => (string) ($payload['token'] ?? pathinfo($path, PATHINFO_FILENAME)),
'month' => $month,
];
}
}
$token = (string) Str::uuid();
$now = now();
$this->writeJson($token . '.pending', [
'token' => $token,
'status' => 'pending',
'month' => $month,
'force' => $force,
'company_id' => $companyId,
'user_id' => $userId,
'created_at' => $now->toIso8601String(),
'started_at' => null,
'completed_at' => null,
'error' => null,
]);
return ['queued' => true, 'token' => $token, 'month' => $month];
}
/** @return array<string,mixed>|null */
public function claimNext(): ?array
{
$this->failStaleProcessing();
$paths = array_values(array_filter(
Storage::disk('local')->files(self::DIRECTORY),
static fn (string $path): bool => str_ends_with($path, '.pending'),
));
usort($paths, fn (string $left, string $right): int =>
Storage::disk('local')->lastModified($left)
<=> Storage::disk('local')->lastModified($right)
);
foreach ($paths as $pendingPath) {
$token = pathinfo($pendingPath, PATHINFO_FILENAME);
if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) {
continue;
}
$processingPath = self::DIRECTORY . '/' . $token . '.processing';
if (! Storage::disk('local')->move($pendingPath, $processingPath)) {
continue;
}
$payload = $this->readJson($processingPath);
if ($payload === null) {
continue;
}
$payload['status'] = 'processing';
$payload['started_at'] = now()->toIso8601String();
$this->writeJson($token . '.processing', $payload);
return $payload;
}
return null;
}
/** @param array<string,mixed> $result */
public function complete(string $token, array $result): void
{
$this->finish($token, 'completed', null, $result);
}
public function fail(string $token, string $error): void
{
$this->finish($token, 'failed', $error, null);
}
/** @param array<string,mixed> $progress */
public function defer(string $token, array $progress, ?bool $force = null): void
{
if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) {
return;
}
$processingPath = self::DIRECTORY . '/' . $token . '.processing';
$payload = $this->readJson($processingPath);
if ($payload === null) {
return;
}
$payload['status'] = 'pending';
$payload['progress'] = $progress;
if ($force !== null) {
$payload['force'] = $force;
}
$this->writeJson($token . '.pending', $payload);
Storage::disk('local')->delete($processingPath);
}
/** @return array<string,mixed>|null */
public function status(string $token, int $companyId, int $userId): ?array
{
if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) {
return null;
}
$payload = null;
foreach (['completed', 'failed', 'processing', 'pending'] as $state) {
$payload = $this->readJson(self::DIRECTORY . '/' . $token . '.' . $state);
if ($payload !== null) {
break;
}
}
if ($payload === null
|| (int) ($payload['company_id'] ?? 0) !== $companyId) {
return null;
}
return [
'status' => (string) ($payload['status'] ?? 'pending'),
'month' => (string) ($payload['month'] ?? ''),
'force' => (bool) ($payload['force'] ?? false),
'created_at' => $payload['created_at'] ?? null,
'started_at' => $payload['started_at'] ?? null,
'completed_at' => $payload['completed_at'] ?? null,
'error' => $payload['error'] ?? null,
'result' => $payload['result'] ?? null,
'progress' => $payload['progress'] ?? null,
];
}
public function pendingExists(): bool
{
$disk = Storage::disk('local');
return collect($disk->files(self::DIRECTORY))
->contains(static fn (string $path): bool => str_ends_with($path, '.pending'));
}
public function cleanup(): void
{
$disk = Storage::disk('local');
$cutoff = time() - self::RESULT_TTL_SECONDS;
foreach ($disk->files(self::DIRECTORY) as $path) {
if ((! str_ends_with($path, '.completed') && ! str_ends_with($path, '.failed'))
|| $disk->lastModified($path) >= $cutoff) {
continue;
}
$disk->delete($path);
}
}
private function failStaleProcessing(): void
{
$disk = Storage::disk('local');
$cutoff = time() - self::STALE_PROCESSING_SECONDS;
foreach ($disk->files(self::DIRECTORY) as $path) {
if (! str_ends_with($path, '.processing') || $disk->lastModified($path) >= $cutoff) {
continue;
}
$token = pathinfo($path, PATHINFO_FILENAME);
$this->fail($token, '发票抓取任务处理超时,请重新发起。');
}
}
private function finish(
string $token,
string $status,
?string $error,
?array $result,
): void {
if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) {
return;
}
$processingPath = self::DIRECTORY . '/' . $token . '.processing';
$payload = $this->readJson($processingPath);
if ($payload === null) {
return;
}
$payload['status'] = $status;
$payload['completed_at'] = now()->toIso8601String();
$payload['error'] = $error === null ? null : mb_substr($error, 0, 500);
$payload['result'] = $result;
$this->writeJson($token . '.' . $status, $payload);
Storage::disk('local')->delete($processingPath);
}
/** @param array<string,mixed> $payload */
private function writeJson(string $path, array $payload): void
{
$disk = Storage::disk('local');
$fullPath = self::DIRECTORY . '/' . ltrim($path, '/');
$tempPath = $fullPath . '.' . Str::random(8) . '.tmp';
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
if (! $disk->put($tempPath, $json) || ! $disk->move($tempPath, $fullPath)) {
throw new RuntimeException('发票抓取请求写入失败。');
}
}
/** @return array<string,mixed>|null */
private function readJson(string $path): ?array
{
$disk = Storage::disk('local');
if (! $disk->exists($path)) {
return null;
}
try {
$payload = json_decode(
(string) $disk->get($path),
true,
512,
JSON_THROW_ON_ERROR,
);
} catch (Throwable) {
return null;
}
return is_array($payload) ? $payload : null;
}
}

View File

@ -0,0 +1,725 @@
<?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 ConnectionInterface $connection;
public function __construct(
DatabaseManager $database,
private readonly UpstreamReadOnlyQueryFactory $queries,
private readonly DingTalkApprovalAttachmentDownloader $downloads,
private readonly DingInvoiceFileRecognizer $recognizer,
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', '!=', '')
->whereNull('scanned_at');
$flows = $query
->orderByDesc('paid_at')
->orderByDesc('business_id')
->limit($limit)
->get()
->all();
if ($flows === []) {
$remaining = (int) $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->whereNull('scanned_at')
->count();
return [
'status' => 'succeeded',
'month' => $month,
'processed_flows' => 0,
'recognized_invoices' => 0,
'failed_flows' => 0,
'remaining_flows' => $remaining,
'ocr_configured' => $this->recognizerOcrConfigured(),
];
}
$businessIds = array_values(array_filter(array_column($flows, 'business_id')));
[$workflows, $attachmentRows] = $this->loadUpstreamWorkflowsAndAttachments($businessIds);
$attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows);
$attachmentsByBusiness = $this->addCommentAttachmentFallback(
$businessIds,
$workflows,
$attachmentsByBusiness,
);
$metrics = [
'processed_flows' => 0,
'recognized_invoices' => 0,
'failed_flows' => 0,
'remaining_flows' => 0,
'ocr_configured' => $this->recognizerOcrConfigured(),
];
$tempRoot = storage_path('app/temp/invoice-sync/' . $month . '-' . bin2hex(random_bytes(6)));
if (! is_dir($tempRoot) && ! mkdir($tempRoot, 0755, true) && ! is_dir($tempRoot)) {
throw new RuntimeException('无法创建发票抓取临时目录。');
}
try {
foreach ($flows as $flow) {
$businessId = (string) $flow->business_id;
$workflow = $workflows[$businessId] ?? [];
$files = $attachmentsByBusiness[$businessId] ?? [];
$flowResult = $this->scanFlow(
$flow,
$workflow,
$files,
$tempRoot . '/' . preg_replace('/[^A-Za-z0-9_-]/', '_', $businessId),
);
$metrics['processed_flows']++;
$metrics['recognized_invoices'] += $flowResult['invoice_count'];
if ($flowResult['scan_status'] === 'failed') {
$metrics['failed_flows']++;
}
}
} finally {
$this->removeDirectory($tempRoot);
}
$metrics['remaining_flows'] = (int) $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->whereNotNull('process_instance_id')
->where('process_instance_id', '!=', '')
->whereNull('scanned_at')
->count();
$this->updateState($metrics);
return [
'status' => 'succeeded',
'month' => $month,
...$metrics,
];
}
private function assertReady(): void
{
if (! Schema::connection($this->connection->getName())->hasTable('ding_invoice_flow_mirror')
|| ! Schema::connection($this->connection->getName())->hasTable('ding_invoice_record_mirror')
|| ! Schema::connection($this->connection->getName())->hasTable('ding_process_payment_line_mirror')
|| ! Schema::connection($this->connection->getName())->hasTable('ding_process_detail_mirror')) {
throw new RuntimeException('OA 流程镜像或发票镜像尚未准备完成。');
}
}
private function scope(): string
{
return trim((string) config(
'upstream_mirrors.ding_process_details.scope',
'personal_permission',
)) ?: 'personal_permission';
}
private function ensureFlowsForMonth(string $month, string $scope): void
{
$payments = $this->connection->table('ding_process_payment_line_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->get();
if ($payments->isEmpty()) {
return;
}
$details = $this->connection->table('ding_process_detail_mirror')
->where('source_scope', $scope)
->whereIn('business_id', $payments->pluck('business_id')->unique()->all())
->get()
->groupBy('business_id');
$existing = $this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('paid_month', $month)
->get()
->keyBy('business_id');
$now = now();
foreach ($payments->groupBy('business_id') as $businessId => $businessPayments) {
$businessId = trim((string) $businessId);
$detail = ($details->get($businessId) ?? collect())->first();
$current = $existing->get($businessId);
$values = [
'source_scope' => $scope,
'business_id' => $businessId,
'process_instance_id' => trim((string) (
$businessPayments->firstWhere('process_instance_id', '!=', '')
?->process_instance_id
?? ''
)),
'paid_month' => $month,
'title' => mb_substr($current?->title ?: ($detail?->purpose ?: ''), 0, 255) ?: null,
'originator_name' => mb_substr($current?->originator_name ?: ($detail?->originator_name ?: ''), 0, 100) ?: null,
'document_type' => mb_substr($current?->document_type ?: ($detail?->document_type ?: ''), 0, 100) ?: null,
'expense_type' => mb_substr($current?->expense_type ?: ($detail?->account_name ?: ''), 0, 255) ?: null,
'payee_name' => mb_substr($current?->payee_name ?: ($detail?->payee_name ?: ''), 0, 255) ?: null,
'paid_at' => $current?->paid_at ?: $businessPayments->min('paid_at'),
'payment_amount' => round((float) $businessPayments->sum('amount'), 2),
'payment_total' => round((float) $businessPayments->sum('amount'), 2),
'invoice_count' => (int) ($current?->invoice_count ?? 0),
'invoice_total' => (float) ($current?->invoice_total ?? 0),
'scan_status' => $current?->scan_status ?: 'pending',
'attachment_count' => (int) ($current?->attachment_count ?? 0),
'scanned_file_count' => (int) ($current?->scanned_file_count ?? 0),
'last_error' => $current?->last_error,
'source_name' => $current?->source_name ?: 'OA attachment scan',
'scanned_at' => $current?->scanned_at,
'updated_at' => $now,
];
if ($current) {
$this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->update($values);
} else {
$this->connection->table('ding_invoice_flow_mirror')->insert([
...$values,
'created_at' => $now,
]);
}
}
}
/**
* @param list<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,invoice_total:float,error:?string}
*/
private function scanFlow(object $flow, array $workflow, array $files, string $tempDir): array
{
if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) {
throw new RuntimeException('无法创建流程发票临时目录。');
}
$processInstanceId = trim((string) (
$workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''
));
$files = array_slice(
$files,
0,
max(1, (int) config('ding_invoice_data.max_files_per_flow', 30)),
);
$invoices = [];
$errors = [];
$scannedFiles = 0;
foreach ($files as $index => $file) {
if ((int) ($file['file_size'] ?? 0) > (int) config('ding_invoice_data.max_file_bytes')) {
$errors[] = $file['file_name'] . ':文件超过大小限制';
continue;
}
try {
$uri = trim((string) ($file['download_url'] ?? ''));
if ($uri === '') {
$uri = $this->downloads->downloadUri($processInstanceId, $file['file_id']) ?? '';
}
if ($uri === '') {
throw new RuntimeException('无法取得下载地址');
}
$extension = strtolower(pathinfo($file['file_name'], PATHINFO_EXTENSION));
if ($extension === '' && in_array(
strtolower((string) ($file['file_type'] ?? '')),
['pdf', 'jpg', 'jpeg', 'png', 'webp', 'bmp', 'xlsx', 'zip'],
true,
)) {
$extension = strtolower((string) $file['file_type']);
}
$path = $tempDir . '/' . $index . ($extension !== '' ? '.' . $extension : '');
$response = Http::timeout(120)
->withOptions(['sink' => $path])
->get($uri);
if (! $response->successful() || ! is_file($path)) {
throw new RuntimeException('下载返回 HTTP ' . $response->status());
}
if (filesize($path) > (int) config('ding_invoice_data.max_file_bytes')) {
@unlink($path);
throw new RuntimeException('下载文件超过大小限制');
}
$scannedFiles++;
$hash = hash_file('sha256', $path) ?: null;
$recognized = $this->recognizer->recognize($path, $file['file_name']);
foreach ($recognized['invoices'] as $invoice) {
$invoice['_source'] = [
'file_id' => $file['file_id'],
'file_name' => $file['file_name'],
'file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
'ocr_provider' => $recognized['provider'],
];
$invoices[] = $invoice;
}
array_push($errors, ...array_map(
static fn (string $error): string => $file['file_name'] . ':' . $error,
$recognized['errors'],
));
} catch (Throwable $exception) {
$errors[] = $file['file_name'] . ':' . $exception->getMessage();
}
}
$invoices = $this->deduplicate($invoices);
$invoiceTotal = round(array_sum(array_map(
static fn (array $invoice): float => (float) $invoice['invoice_total'],
$invoices,
)), 2);
$scanStatus = match (true) {
$errors !== [] && $invoices !== [] => 'partial',
$errors !== [] && $invoices === [] => 'failed',
$invoices !== [] => 'recognized',
default => 'no_invoice',
};
$error = $errors === [] ? null : mb_substr(implode("\n", array_slice($errors, 0, 8)), 0, 4000);
$this->connection->transaction(function () use (
$flow,
$invoices,
$invoiceTotal,
$scanStatus,
$error,
$files,
$scannedFiles,
$workflow,
): void {
$scope = $this->scope();
$businessId = (string) $flow->business_id;
$this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->delete();
$now = now();
$records = [];
foreach ($invoices as $invoice) {
$source = $invoice['_source'];
$records[] = [
'source_scope' => $scope,
'business_id' => $businessId,
'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''),
'paid_month' => (string) $flow->paid_month,
'invoice_key' => $this->invoiceKey($invoice),
'invoice_type' => mb_substr((string) $invoice['invoice_type'], 0, 100),
'seller_name' => mb_substr((string) $invoice['seller_name'], 0, 255),
'seller_tax_no' => mb_substr((string) $invoice['seller_tax_no'], 0, 64),
'buyer_name' => mb_substr((string) $invoice['buyer_name'], 0, 255),
'buyer_tax_no' => mb_substr((string) $invoice['buyer_tax_no'], 0, 64),
'invoice_total' => round((float) $invoice['invoice_total'], 2),
'invoice_number' => mb_substr((string) $invoice['invoice_number'], 0, 32),
'invoice_date' => $invoice['invoice_date'],
'item_name' => (string) $invoice['item_name'],
'amount_without_tax' => $invoice['amount_without_tax'],
'tax_rate' => mb_substr((string) $invoice['tax_rate'], 0, 32),
'tax_amount' => $invoice['tax_amount'],
'source_file_id' => $source['file_id'],
'source_file_name' => mb_substr((string) $source['file_name'], 0, 255),
'source_file_type' => mb_substr((string) $source['file_type'], 0, 32),
'source_field' => mb_substr((string) $source['source_field'], 0, 255),
'source_path' => mb_substr((string) $source['source_path'], 0, 1024),
'source_hash' => $source['source_hash'],
'ocr_provider' => mb_substr((string) $source['ocr_provider'], 0, 32),
'recognition_payload' => json_encode(
array_diff_key($invoice, ['_source' => true]),
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
),
'created_at' => $now,
'updated_at' => $now,
];
}
if ($records !== []) {
$this->connection->table('ding_invoice_record_mirror')->insert($records);
}
$this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)
->update([
'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''),
'title' => $flow->title ?: ($workflow['title'] ?? null),
'invoice_count' => count($records),
'invoice_total' => $invoiceTotal,
'scan_status' => $scanStatus,
'attachment_count' => count($files),
'scanned_file_count' => $scannedFiles,
'last_error' => $error,
'scanned_at' => $now,
'updated_at' => $now,
]);
});
return [
'scan_status' => $scanStatus,
'invoice_count' => count($invoices),
'invoice_total' => $invoiceTotal,
'error' => $error,
];
}
/** @param list<array<string,mixed>> $invoices @return list<array<string,mixed>> */
private function deduplicate(array $invoices): array
{
$unique = [];
foreach ($invoices as $invoice) {
$number = preg_replace(
'/[^0-9A-Za-z]/',
'',
(string) ($invoice['invoice_number'] ?? ''),
) ?? '';
$seller = trim((string) ($invoice['seller_name'] ?? ''));
$amount = number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', '');
$key = $number !== ''
? 'number:' . $number
: 'near:' . mb_strtolower($seller) . '|' . $amount;
foreach ($unique as $existingKey => $existing) {
$existingSeller = trim((string) ($existing['seller_name'] ?? ''));
$existingAmount = number_format((float) ($existing['invoice_total'] ?? 0), 2, '.', '');
if ($seller !== ''
&& $existingSeller !== ''
&& mb_strtolower($seller) === mb_strtolower($existingSeller)
&& $amount === $existingAmount) {
$key = $existingKey;
break;
}
}
if (! isset($unique[$key])) {
$unique[$key] = $invoice;
} else {
$unique[$key] = $this->mergeInvoice($unique[$key], $invoice);
}
}
return array_values($unique);
}
/** @param array<string,mixed> $left @param array<string,mixed> $right */
private function mergeInvoice(array $left, array $right): array
{
foreach ($right as $key => $value) {
if (($left[$key] ?? null) === null
|| (is_string($left[$key]) && trim($left[$key]) === '')
|| (is_array($left[$key]) && $left[$key] === [])) {
$left[$key] = $value;
}
}
return $left;
}
/** @param array<string,mixed> $invoice */
private function invoiceKey(array $invoice): string
{
$number = preg_replace('/[^0-9A-Za-z]/', '', (string) ($invoice['invoice_number'] ?? '')) ?? '';
return hash('sha256', $number !== ''
? 'number:' . $number
: implode('|', [
'near',
(string) ($invoice['seller_name'] ?? ''),
number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''),
(string) ($invoice['invoice_date'] ?? ''),
(string) ($invoice['item_name'] ?? ''),
]));
}
private function recognizerOcrConfigured(): bool
{
return trim((string) config('ding_invoice_data.ocr.api_key', '')) !== '';
}
/** @param array<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);
}
}

View File

@ -0,0 +1,126 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
use Throwable;
class DingInvoiceTextParser
{
/** @return array<string,mixed>|null */
public function parse(string $text): ?array
{
$text = trim(str_replace(["\r\n", "\r", "\u{3000}"], ["\n", "\n", ' '], $text));
if ($text === '') {
return null;
}
$invoiceNumber = $this->invoiceNumber($text);
$invoiceTotal = $this->invoiceTotal($text);
if ($invoiceNumber === '' && $invoiceTotal <= 0) {
return null;
}
$taxNumbers = [];
if (preg_match_all(
'/(?:统一社会信用代码|纳税人识别号|税号)\s*[::]\s*([0-9A-Z]{15,20})/u',
$text,
$matches,
)) {
$taxNumbers = array_values(array_unique($matches[1]));
}
$names = [];
if (preg_match_all('/名称\s*[::]\s*([^\n]{2,120})/u', $text, $matches)) {
$names = array_values(array_unique(array_filter(array_map(
static fn (string $value): string => trim(
preg_replace('/\s{2,}.*$/u', '', $value) ?? $value,
),
$matches[1],
))));
}
$invoiceDate = null;
if (preg_match('/开票日期\s*[::]?\s*(\d{4})[年\-\/](\d{1,2})[月\-\/](\d{1,2})/u', $text, $matches)) {
try {
$invoiceDate = Carbon::createFromDate(
(int) $matches[1],
(int) $matches[2],
(int) $matches[3],
)->format('Y-m-d');
} catch (Throwable) {
$invoiceDate = null;
}
}
$items = [];
if (preg_match_all('/^\s*(\*[^\n]{2,180})$/mu', $text, $matches)) {
$items = array_values(array_unique(array_map('trim', $matches[1])));
}
$taxRate = '';
if (preg_match('/(\d{1,2}(?:\.\d+)?%|免税|不征税|\*)/u', $text, $matches)) {
$taxRate = $matches[1];
}
return [
'is_invoice' => true,
'invoice_type' => $this->invoiceType($text),
'seller_name' => $names[1] ?? ($names[0] ?? ''),
'seller_tax_no' => $taxNumbers[1] ?? ($taxNumbers[0] ?? ''),
'buyer_name' => $names[0] ?? '',
'buyer_tax_no' => $taxNumbers[0] ?? '',
'invoice_total' => $invoiceTotal,
'invoice_number' => $invoiceNumber,
'invoice_date' => $invoiceDate,
'item_name' => implode("\n", $items),
'amount_without_tax' => null,
'tax_rate' => $taxRate,
'tax_amount' => null,
'ocr_text' => $text,
];
}
private function invoiceNumber(string $text): string
{
if (preg_match('/发票号码\s*[::]?\s*([0-9A-Z]{8,32})/u', $text, $matches)) {
return strtoupper($matches[1]);
}
return '';
}
private function invoiceTotal(string $text): float
{
$values = [];
if (preg_match_all(
'/(?:价税合计(?:\s*(?:\(小写\)|(小写)))?|小写)\s*[::]?\s*[¥¥]?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/u',
$text,
$matches,
)) {
foreach ($matches[1] as $value) {
$values[] = round((float) str_replace(',', '', $value), 2);
}
}
if ($values !== []) {
return max($values);
}
return 0.0;
}
private function invoiceType(string $text): string
{
if (str_contains($text, '铁路电子客票') || str_contains($text, '铁路客票')) {
return '电子发票(铁路电子客票)';
}
if (str_contains($text, '增值税专用发票') || str_contains($text, '专用发票')) {
return '电子发票(增值税专用发票)';
}
if (str_contains($text, '普通发票')) {
return '电子发票(普通发票)';
}
return '其他';
}
}

View File

@ -0,0 +1,169 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class DingInvoiceVisionClient
{
private const PROMPT = <<<'PROMPT'
你是财务发票识别器。只识别图片中的发票,合同、付款截图、银行回单、审批截图都必须返回 is_invoice=false。
返回严格 JSON,不要 Markdown,不要解释,字段固定如下:
{
"is_invoice": true,
"invoice_type": "无票|电子发票(普通发票)|电子发票(增值税专用发票)|电子发票(铁路电子客票)|其他",
"seller_name": "",
"seller_tax_no": "",
"buyer_name": "",
"buyer_tax_no": "",
"invoice_total": 0.00,
"invoice_number": "",
"invoice_date": "YYYY-MM-DD",
"item_name": "",
"amount_without_tax": null,
"tax_rate": "",
"tax_amount": null
}
金额只返回数字。无法确认的文本字段返回空字符串,无法确认的数字字段返回 null。多行项目名用换行分隔。
PROMPT;
public function configured(): bool
{
return trim((string) config('ding_invoice_data.ocr.api_key', '')) !== '';
}
/** @return array<string,mixed>|null */
public function recognize(string $bytes, string $mimeType): ?array
{
$apiKey = trim((string) config('ding_invoice_data.ocr.api_key', ''));
if ($apiKey === '') {
throw new RuntimeException(
'发票 OCR 未配置。请在服务器设置 DING_INVOICE_OCR_API_KEY 后重试。',
);
}
if ($bytes === '') {
return null;
}
$mimeType = str_starts_with($mimeType, 'image/') ? $mimeType : 'image/jpeg';
$payload = [
'model' => (string) config('ding_invoice_data.ocr.model', 'deepseek-chat'),
'temperature' => 0,
'messages' => [[
'role' => 'user',
'content' => [
['type' => 'text', 'text' => self::PROMPT],
[
'type' => 'image_url',
'image_url' => [
'url' => 'data:' . $mimeType . ';base64,' . base64_encode($bytes),
],
],
],
]],
];
try {
$response = Http::withToken($apiKey)
->acceptJson()
->timeout(max(15, (int) config('ding_invoice_data.ocr.timeout_seconds', 90)))
->post((string) config('ding_invoice_data.ocr.base_url'), $payload);
} catch (ConnectionException|RequestException $exception) {
throw new RuntimeException('发票 OCR 请求失败:' . $exception->getMessage(), 0, $exception);
}
if (! $response->successful()) {
throw new RuntimeException('发票 OCR 返回 HTTP ' . $response->status() . '。');
}
$content = (string) $response->json('choices.0.message.content', '');
$decoded = $this->decodeJson($content);
if ($decoded === null || ($decoded['is_invoice'] ?? false) !== true) {
return null;
}
$invoiceTotal = $this->number($decoded['invoice_total'] ?? null);
$invoiceNumber = preg_replace(
'/[^0-9A-Za-z]/',
'',
trim((string) ($decoded['invoice_number'] ?? '')),
) ?? '';
if ($invoiceTotal <= 0 && $invoiceNumber === '') {
return null;
}
return [
'is_invoice' => true,
'invoice_type' => trim((string) ($decoded['invoice_type'] ?? '')) ?: '其他',
'seller_name' => trim((string) ($decoded['seller_name'] ?? '')),
'seller_tax_no' => trim((string) ($decoded['seller_tax_no'] ?? '')),
'buyer_name' => trim((string) ($decoded['buyer_name'] ?? '')),
'buyer_tax_no' => trim((string) ($decoded['buyer_tax_no'] ?? '')),
'invoice_total' => $invoiceTotal,
'invoice_number' => $invoiceNumber,
'invoice_date' => $this->date($decoded['invoice_date'] ?? null),
'item_name' => trim((string) ($decoded['item_name'] ?? '')),
'amount_without_tax' => $this->numberOrNull($decoded['amount_without_tax'] ?? null),
'tax_rate' => trim((string) ($decoded['tax_rate'] ?? '')),
'tax_amount' => $this->numberOrNull($decoded['tax_amount'] ?? null),
'ocr_text' => $content,
];
}
/** @return array<string,mixed>|null */
private function decodeJson(string $content): ?array
{
$content = trim($content);
$content = preg_replace('/^```(?:json)?\s*/i', '', $content) ?? $content;
$content = preg_replace('/\s*```$/', '', $content) ?? $content;
$decoded = json_decode($content, true);
if (is_array($decoded)) {
return $decoded;
}
$start = strpos($content, '{');
$end = strrpos($content, '}');
if ($start !== false && $end !== false && $end > $start) {
$decoded = json_decode(substr($content, $start, $end - $start + 1), true);
}
return is_array($decoded) ? $decoded : null;
}
private function number(mixed $value): float
{
return $this->numberOrNull($value) ?? 0.0;
}
private function numberOrNull(mixed $value): ?float
{
if ($value === null || trim((string) $value) === '') {
return null;
}
$normalized = str_replace([',', ',', '¥', '¥', ' '], '', (string) $value);
if (! is_numeric($normalized)) {
return null;
}
return round((float) $normalized, 2);
}
private function date(mixed $value): ?string
{
$value = trim((string) ($value ?? ''));
if (preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $value) !== 1) {
return null;
}
[$year, $month, $day] = array_map('intval', explode('-', $value));
return checkdate($month, $day, $year)
? sprintf('%04d-%02d-%02d', $year, $month, $day)
: null;
}
}

View File

@ -0,0 +1,395 @@
<?php
namespace Modules\EcommerceFinance\Services;
use DateTimeInterface;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Carbon;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
use Throwable;
class DingInvoiceWorkbookImporter
{
public const DATASET_KEY = 'operations_replica.rpt.ding_invoices';
private const SHEET_NAME = '报销发票识别';
private const HEADERS = [
'title' => '单号/标题',
'business_id' => '流程号',
'originator_name' => '提交人',
'document_type' => '报销类型',
'expense_type' => '费用类型',
'payee_name' => '收款人',
'paid_at' => '打款时间',
'payment_amount' => '10月付款金额',
'payment_total' => '付款合计',
'invoice_type' => '发票类型',
'seller_name' => '销售方名称',
'seller_tax_no' => '销售方税号',
'buyer_name' => '购买方名称',
'buyer_tax_no' => '购买方税号',
'invoice_total' => '发票价税合计',
'invoice_number' => '发票号码',
'invoice_date' => '开票日期',
'item_name' => '项目名称',
'amount_without_tax' => '金额',
'tax_rate' => '税率',
'tax_amount' => '税额',
];
private ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @return array{
* flows:int,
* invoices:int,
* months:list<string>,
* payment_total:float,
* invoice_total:float
* }
*/
public function import(
string $path,
string $scope = 'personal_permission',
bool $replaceMonths = true,
): array {
if (! is_file($path)) {
throw new RuntimeException('发票台账文件不存在。');
}
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$reader = PayablesWorkbookStreamReader::forFile($path, $extension);
$sheetIndex = array_search(self::SHEET_NAME, $reader->sheetNames(), true);
if ($sheetIndex === false) {
throw new RuntimeException('发票台账缺少“' . self::SHEET_NAME . '”工作表。');
}
$headers = [];
$rows = $reader->rows((int) $sheetIndex);
$headerSeen = false;
foreach ($rows as $rowValues) {
foreach ($rowValues as $columnIndex => $cellValue) {
$value = trim((string) $cellValue);
if ($value !== '') {
$headers[$value] = (int) $columnIndex;
}
}
$headerSeen = true;
break;
}
if (! $headerSeen) {
throw new RuntimeException('发票台账为空。');
}
foreach (self::HEADERS as $field => $label) {
if (! isset($headers[$label])) {
throw new RuntimeException('发票台账缺少列:' . $label);
}
}
$flows = [];
$invoices = [];
$current = array_fill_keys(array_keys(self::HEADERS), '');
foreach ($rows as $rowNumber => $rowValues) {
$row = [];
foreach (self::HEADERS as $field => $label) {
$row[$field] = $rowValues[$headers[$label]] ?? null;
}
if (! array_filter($row, static fn (mixed $value): bool => $value !== null && $value !== '')) {
continue;
}
if ($this->text($row['business_id']) !== '') {
$current = array_fill_keys(array_keys(self::HEADERS), '');
}
foreach ([
'title',
'business_id',
'originator_name',
'document_type',
'expense_type',
'payee_name',
'paid_at',
'payment_amount',
'payment_total',
] as $field) {
$value = $this->text($row[$field]);
if ($value !== '') {
$current[$field] = $row[$field];
}
}
$businessId = $this->text($current['business_id']);
if (preg_match('/^[A-Za-z0-9_-]{1,32}$/', $businessId) !== 1) {
continue;
}
$paidAt = $this->date($current['paid_at']);
$paidMonth = $paidAt?->format('Y-m') ?? '';
if ($paidMonth === '') {
throw new RuntimeException('第 ' . $rowNumber . ' 行打款时间无法识别。');
}
$flows[$businessId] ??= [
'source_scope' => mb_substr($scope, 0, 40),
'business_id' => $businessId,
'process_instance_id' => null,
'paid_month' => $paidMonth,
'title' => $this->limit($this->text($current['title']), 255),
'originator_name' => $this->limit($this->text($current['originator_name']), 100),
'document_type' => $this->limit($this->text($current['document_type']), 100),
'expense_type' => $this->limit($this->text($current['expense_type']), 255),
'payee_name' => $this->limit($this->text($current['payee_name']), 255),
'paid_at' => $paidAt?->format('Y-m-d H:i:s'),
'payment_amount' => $this->decimal($current['payment_amount']),
'payment_total' => $this->decimal($current['payment_total']),
'invoice_count' => 0,
'invoice_total' => 0.0,
'scan_status' => 'no_invoice',
'attachment_count' => 0,
'scanned_file_count' => 0,
'last_error' => null,
'source_name' => $this->limit(basename($path), 255),
'scanned_at' => now(),
'created_at' => now(),
'updated_at' => now(),
];
$invoiceType = $this->text($row['invoice_type']);
if ($invoiceType === '' || $invoiceType === '无票') {
continue;
}
$invoiceNumber = preg_replace('/[^0-9A-Za-z]/', '', $this->text($row['invoice_number'])) ?? '';
$sellerName = $this->text($row['seller_name']);
$invoiceTotal = $this->decimal($row['invoice_total']);
$invoiceDate = $this->date($row['invoice_date']);
$invoiceKey = $invoiceNumber !== ''
? hash('sha256', 'number:' . $invoiceNumber)
: hash('sha256', implode('|', [
'fallback',
$sellerName,
number_format($invoiceTotal, 2, '.', ''),
$invoiceDate?->format('Y-m-d') ?? '',
$this->text($row['item_name']),
]));
$record = [
'source_scope' => mb_substr($scope, 0, 40),
'business_id' => $businessId,
'process_instance_id' => null,
'paid_month' => $paidMonth,
'invoice_key' => $invoiceKey,
'invoice_type' => $this->limit($invoiceType, 100),
'seller_name' => $this->limit($sellerName, 255),
'seller_tax_no' => $this->limit($this->text($row['seller_tax_no']), 64),
'buyer_name' => $this->limit($this->text($row['buyer_name']), 255),
'buyer_tax_no' => $this->limit($this->text($row['buyer_tax_no']), 64),
'invoice_total' => $invoiceTotal,
'invoice_number' => $this->limit($invoiceNumber, 32),
'invoice_date' => $invoiceDate?->format('Y-m-d'),
'item_name' => $this->text($row['item_name']),
'amount_without_tax' => $this->decimalOrNull($row['amount_without_tax']),
'tax_rate' => $this->limit($this->text($row['tax_rate']), 32),
'tax_amount' => $this->decimalOrNull($row['tax_amount']),
'source_file_id' => null,
'source_file_name' => null,
'source_file_type' => null,
'source_field' => null,
'source_path' => null,
'source_hash' => null,
'ocr_provider' => 'imported_workbook',
'recognition_payload' => null,
'created_at' => now(),
'updated_at' => now(),
];
$existing = $invoices[$businessId][$invoiceKey] ?? null;
$invoices[$businessId][$invoiceKey] = $existing === null
? $record
: $this->mergeMissing($existing, $record);
}
foreach ($invoices as $businessId => $records) {
$flows[$businessId]['invoice_count'] = count($records);
$flows[$businessId]['invoice_total'] = round(array_sum(array_map(
static fn (array $record): float => (float) $record['invoice_total'],
$records,
)), 2);
$flows[$businessId]['scan_status'] = $records === [] ? 'no_invoice' : 'recognized';
}
if ($flows === []) {
throw new RuntimeException('发票台账没有可导入的流程记录。');
}
$months = array_values(array_unique(array_column($flows, 'paid_month')));
sort($months);
$invoiceRows = [];
foreach ($invoices as $businessInvoices) {
foreach ($businessInvoices as $invoice) {
$invoiceRows[] = $invoice;
}
}
$paymentTotal = round(array_sum(array_column($flows, 'payment_amount')), 2);
$invoiceTotal = round(array_sum(array_column($invoiceRows, 'invoice_total')), 2);
$this->connection->transaction(function () use (
$scope,
$months,
$replaceMonths,
$flows,
$invoiceRows,
$invoiceTotal,
): void {
if ($replaceMonths) {
$this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->whereIn('paid_month', $months)
->delete();
$this->connection->table('ding_invoice_flow_mirror')
->where('source_scope', $scope)
->whereIn('paid_month', $months)
->delete();
}
foreach (array_chunk(array_values($flows), 250) as $chunk) {
$this->connection->table('ding_invoice_flow_mirror')->insert($chunk);
}
foreach (array_chunk($invoiceRows, 250) as $chunk) {
$this->connection->table('ding_invoice_record_mirror')->insert($chunk);
}
$this->updateState(count($invoiceRows), count($flows), $invoiceTotal);
});
return [
'flows' => count($flows),
'invoices' => count($invoiceRows),
'months' => $months,
'payment_total' => $paymentTotal,
'invoice_total' => $invoiceTotal,
];
}
private function updateState(int $invoiceRows, int $flowRows, float $invoiceTotal): void
{
if (! $this->connection->getSchemaBuilder()->hasTable('business_mirror_table_states')) {
return;
}
$now = now();
$state = $this->connection->table('business_mirror_table_states')
->where('dataset_key', self::DATASET_KEY)
->first();
$values = [
'source_key' => 'operations_replica',
'source_object' => 'rpt.ding_Workflow + DingTalk attachments + invoice OCR',
'target_table' => 'ding_invoice_record_mirror',
'status' => 'succeeded',
'run_mode' => 'import',
'cursor' => json_encode([
'invoice_rows' => $invoiceRows,
'flow_rows' => $flowRows,
'invoice_total' => round($invoiceTotal, 2),
], JSON_UNESCAPED_UNICODE),
'initial_completed_at' => $state?->initial_completed_at ?? $now,
'last_attempted_at' => $now,
'last_succeeded_at' => $now,
'last_upserted_rows' => $invoiceRows,
'mirror_row_count' => $invoiceRows,
'mirror_row_count_is_exact' => true,
'last_error_code' => null,
'updated_at' => $now,
'created_at' => $state?->created_at ?? $now,
];
$this->connection->table('business_mirror_table_states')->updateOrInsert(
['dataset_key' => self::DATASET_KEY],
$values,
);
}
private function text(mixed $value): string
{
return trim((string) ($value ?? ''));
}
private function limit(string $value, int $length): string
{
return mb_substr($value, 0, $length);
}
private function decimal(mixed $value): float
{
return $this->decimalOrNull($value) ?? 0.0;
}
private function decimalOrNull(mixed $value): ?float
{
if ($value === null || trim((string) $value) === '') {
return null;
}
$normalized = str_replace([',', ',', '¥', '¥', ' '], '', (string) $value);
if (! is_numeric($normalized)) {
return null;
}
return round((float) $normalized, 2);
}
private function date(mixed $value): ?Carbon
{
if ($value === null || $value === '') {
return null;
}
if (is_numeric($value)) {
try {
return Carbon::instance(ExcelDate::excelToDateTimeObject((float) $value))->startOfDay();
} catch (Throwable) {
return null;
}
}
if ($value instanceof DateTimeInterface) {
return Carbon::instance($value)->startOfDay();
}
$text = trim((string) $value);
foreach (['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d', 'Y/m/d'] as $format) {
try {
return Carbon::createFromFormat($format, $text)->startOfDay();
} catch (Throwable) {
// Try the next known ledger date format.
}
}
try {
return Carbon::parse($text)->startOfDay();
} catch (Throwable) {
return null;
}
}
/** @param array<string,mixed> $existing @param array<string,mixed> $record */
private function mergeMissing(array $existing, array $record): array
{
foreach ($record as $key => $value) {
if (($existing[$key] ?? null) === null
|| (is_string($existing[$key]) && trim($existing[$key]) === '')) {
$existing[$key] = $value;
}
}
return $existing;
}
}

View File

@ -0,0 +1,173 @@
<?php
namespace Modules\EcommerceFinance\View;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Modules\EcommerceFinance\Repositories\DingInvoiceDataMirrorRepository;
use Throwable;
class InvoiceDataPageData
{
public function __construct(
private readonly DingInvoiceDataMirrorRepository $repository,
) {}
public static function normalizePerPage(mixed $value): int
{
$perPage = (int) $value;
return in_array($perPage, DingInvoiceDataMirrorRepository::PER_PAGE_OPTIONS, true)
? $perPage
: 50;
}
/** @return array<string,mixed> */
public function page(Request $request): array
{
try {
$months = $this->repository->months();
} catch (Throwable $exception) {
report($exception);
$months = [];
}
$requestedMonth = trim((string) $request->query('month', ''));
$month = preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1
? $requestedMonth
: (string) ($months[0] ?? '');
$view = $request->query('invoice_view') === DingInvoiceDataMirrorRepository::VIEW_FLOWS
? DingInvoiceDataMirrorRepository::VIEW_FLOWS
: DingInvoiceDataMirrorRepository::VIEW_DETAIL;
$invoiceState = array_key_exists(
(string) $request->query('invoice_state', 'all'),
DingInvoiceDataMirrorRepository::INVOICE_STATES,
) ? (string) $request->query('invoice_state', 'all') : 'all';
$filters = [
'month' => $month,
'invoice_state' => $invoiceState,
'invoice_type' => mb_substr(trim((string) $request->query('invoice_type', '')), 0, 100),
'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 100),
];
$detailPage = max((int) $request->query('page', 1), 1);
$flowPage = max((int) $request->query('flow_page', 1), 1);
$perPage = self::normalizePerPage($request->query('per_page'));
try {
$options = $this->repository->filterOptions($filters);
$detailFilters = [...$filters, 'view' => DingInvoiceDataMirrorRepository::VIEW_DETAIL];
$flowFilters = [...$filters, 'view' => DingInvoiceDataMirrorRepository::VIEW_FLOWS];
$detailResult = $this->repository->paginate($detailFilters, $detailPage, $perPage);
$flowResult = $this->repository->paginate($flowFilters, $flowPage, $perPage);
$detailPaginator = new LengthAwarePaginator(
$detailResult['data'],
$detailResult['total'],
$perPage,
$detailPage,
[
'path' => $request->url(),
'query' => array_filter(
[...$filters, 'invoice_view' => 'detail', 'per_page' => $perPage],
static fn (mixed $value): bool => $value !== '' && $value !== null,
),
],
);
$flowPaginator = new LengthAwarePaginator(
$flowResult['data'],
$flowResult['total'],
$perPage,
$flowPage,
[
'path' => $request->url(),
'query' => array_filter(
[...$filters, 'invoice_view' => 'flows', 'per_page' => $perPage],
static fn (mixed $value): bool => $value !== '' && $value !== null,
),
'pageName' => 'flow_page',
],
);
$state = $detailResult['state'];
$mirrorStatus = (string) (
$state['status']
?? ((int) ($detailResult['summary']['flows'] ?? 0) > 0 ? 'imported' : 'unavailable')
);
return [
'view' => 'business.pages.financial-operations.invoice-data',
'invoiceDetailRows' => $detailPaginator,
'invoiceFlowRows' => $flowPaginator,
'invoiceActiveView' => $view,
'invoiceFilters' => $filters,
'invoiceMonths' => $months,
'invoiceTypes' => $options['invoice_types'],
'invoiceStates' => DingInvoiceDataMirrorRepository::INVOICE_STATES,
'invoicePerPageOptions' => DingInvoiceDataMirrorRepository::PER_PAGE_OPTIONS,
'invoicePerPage' => $perPage,
'invoiceSummary' => $detailResult['summary'],
'invoiceMirrorStatus' => $mirrorStatus,
'invoiceMirrorSyncedAt' => $state['last_succeeded_at'] ?? null,
'invoiceMirrorError' => null,
'invoicePageUrl' => route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
]),
'invoiceExportUrl' => route('business.invoice-data.export', array_filter([
'month' => $filters['month'],
'invoice_view' => $view,
'invoice_state' => $filters['invoice_state'],
'invoice_type' => $filters['invoice_type'],
'keyword' => $filters['keyword'],
], static fn (mixed $value): bool => $value !== '' && $value !== null)),
'invoiceRefreshUrl' => route('business.invoice-data.refresh'),
'invoiceOcrConfigured' => trim((string) config(
'ding_invoice_data.ocr.api_key',
'',
)) !== '',
'invoiceScope' => $this->repository->scope(),
];
} catch (Throwable $exception) {
report($exception);
return [
'view' => 'business.pages.financial-operations.invoice-data',
'invoiceDetailRows' => new LengthAwarePaginator([], 0, $perPage, 1, [
'path' => $request->url(),
'query' => $request->query(),
]),
'invoiceFlowRows' => new LengthAwarePaginator([], 0, $perPage, 1, [
'path' => $request->url(),
'query' => $request->query(),
]),
'invoiceActiveView' => $view,
'invoiceFilters' => $filters,
'invoiceMonths' => $months,
'invoiceTypes' => [],
'invoiceStates' => DingInvoiceDataMirrorRepository::INVOICE_STATES,
'invoicePerPageOptions' => DingInvoiceDataMirrorRepository::PER_PAGE_OPTIONS,
'invoicePerPage' => $perPage,
'invoiceSummary' => [
'flows' => 0,
'payment_amount' => 0.0,
'invoice_count' => 0,
'invoice_total' => 0.0,
'no_invoice_flows' => 0,
'needs_review_flows' => 0,
'invoice_rate' => 0.0,
],
'invoiceMirrorStatus' => 'unavailable',
'invoiceMirrorSyncedAt' => null,
'invoiceMirrorError' => '发票数据镜像尚未完成导入,请稍后重试。',
'invoicePageUrl' => route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
]),
'invoiceExportUrl' => '#',
'invoiceRefreshUrl' => route('business.invoice-data.refresh'),
'invoiceOcrConfigured' => trim((string) config(
'ding_invoice_data.ocr.api_key',
'',
)) !== '',
'invoiceScope' => $this->repository->scope(),
];
}
}
}

View File

@ -0,0 +1,978 @@
@php
$money = static fn (mixed $value): string => number_format((float) $value, 2);
$wan = static fn (mixed $value): string => number_format((float) $value / 10000, 2);
$summary = $invoiceSummary ?? [];
$detailRows = $invoiceDetailRows ?? collect();
$flowRows = $invoiceFlowRows ?? collect();
$filters = $invoiceFilters ?? [];
$activeView = $invoiceActiveView ?? 'detail';
$statusLabels = [
'imported' => '已导入',
'recognized' => '已识别',
'no_invoice' => '无票',
'partial' => '部分识别',
'failed' => '识别失败',
];
$mirrorStatusLabels = [
'succeeded' => '已同步',
'failed' => '同步失败',
'pending' => '待同步',
'running' => '同步中',
'imported' => '已导入',
'unavailable' => '未导入',
];
$filterQuery = array_filter($filters, static fn (mixed $value): bool => $value !== '' && $value !== null);
$detailTabUrl = $invoicePageUrl . '?' . http_build_query(array_merge($filterQuery, [
'invoice_view' => 'detail',
'per_page' => $invoicePerPage,
]));
$flowTabUrl = $invoicePageUrl . '?' . http_build_query(array_merge($filterQuery, [
'invoice_view' => 'flows',
'per_page' => $invoicePerPage,
]));
@endphp
<div class="invoice-data-page" data-invoice-data-page>
<style>
.invoice-data-page {
--invoice-ink: var(--vip-content-ink, #171717);
--invoice-muted: var(--vip-content-muted, #595959);
--invoice-border: var(--vip-border, #d8d2c7);
--invoice-surface: var(--vip-surface, #ffffff);
--invoice-soft: var(--vip-content-accent-soft, #f7f0de);
--invoice-accent: var(--vip-content-accent, #b9954f);
--invoice-accent-dark: var(--vip-content-accent-dark, #856632);
color: var(--invoice-ink);
font-size: 0.8125rem;
}
.invoice-data-alert {
display: flex;
align-items: center;
gap: 0.55rem;
margin-bottom: 0.75rem;
padding: 0.75rem 0.9rem;
border: 1px solid #b80000;
border-radius: 0.5rem;
background: #fff5f5;
color: #b80000;
}
.invoice-data-toolbar {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
padding: 1rem;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
background: var(--invoice-surface);
}
.invoice-data-filters {
display: flex;
align-items: flex-end;
gap: 0.65rem;
flex-wrap: wrap;
}
.invoice-data-field {
display: flex;
min-width: 9rem;
flex-direction: column;
gap: 0.3rem;
}
.invoice-data-field.is-search {
min-width: 15rem;
flex: 1 1 15rem;
}
.invoice-data-field > span {
color: var(--invoice-muted);
font-size: 0.6875rem;
font-weight: 600;
}
.invoice-data-field input,
.invoice-data-field select {
height: 2.125rem;
min-width: 0;
padding: 0 0.65rem;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
outline: none;
background: var(--invoice-surface);
color: var(--invoice-ink);
font: inherit;
}
.invoice-data-field input:focus,
.invoice-data-field select:focus {
border-color: var(--invoice-accent-dark);
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.2);
}
.invoice-data-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.invoice-data-button {
display: inline-flex;
height: 2.125rem;
align-items: center;
justify-content: center;
gap: 0.35rem;
padding: 0 0.85rem;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
background: var(--invoice-surface);
color: var(--invoice-ink);
cursor: pointer;
font: inherit;
font-size: 0.75rem;
font-weight: 600;
text-decoration: none;
}
.invoice-data-button.is-primary {
border-color: var(--invoice-accent-dark);
background: var(--invoice-accent-dark);
color: #ffffff;
}
.invoice-data-button:hover {
border-color: var(--invoice-accent-dark);
background: var(--invoice-soft);
}
.invoice-data-button.is-primary:hover {
background: #6a5129;
color: #ffffff;
}
.invoice-data-button:focus-visible,
.invoice-data-tab:focus-visible {
outline: 3px solid rgba(133, 102, 50, 0.2);
outline-offset: 1px;
}
.invoice-data-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
margin-top: 0.75rem;
padding: 0.65rem 0.85rem;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
background: var(--invoice-surface);
color: var(--invoice-muted);
font-size: 0.6875rem;
}
.invoice-data-status strong {
color: var(--invoice-ink);
font-weight: 600;
}
.invoice-data-kpis {
display: grid;
margin-top: 0.75rem;
grid-template-columns: repeat(6, minmax(0, 1fr));
overflow: hidden;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
background: var(--invoice-surface);
}
.invoice-data-kpi {
min-width: 0;
padding: 0.85rem 0.9rem;
border-right: 1px solid var(--invoice-border);
}
.invoice-data-kpi:last-child {
border-right: 0;
}
.invoice-data-kpi span {
display: block;
color: var(--invoice-muted);
font-size: 0.6875rem;
line-height: 1.4;
}
.invoice-data-kpi strong {
display: block;
margin-top: 0.35rem;
overflow: hidden;
color: var(--invoice-ink);
font-size: 1.25rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
line-height: 1.25;
text-overflow: ellipsis;
white-space: nowrap;
}
.invoice-data-kpi strong.is-accent {
color: var(--invoice-accent-dark);
}
.invoice-data-tabs {
display: flex;
align-items: center;
gap: 0.35rem;
margin-top: 0.75rem;
padding: 0.35rem;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
background: var(--invoice-surface);
}
.invoice-data-tab {
display: inline-flex;
min-height: 2rem;
align-items: center;
gap: 0.35rem;
padding: 0 0.75rem;
border: 0;
border-radius: 0.35rem;
background: transparent;
color: var(--invoice-muted);
cursor: pointer;
font: inherit;
font-size: 0.75rem;
font-weight: 600;
}
.invoice-data-tab[aria-selected="true"] {
background: var(--invoice-soft);
color: var(--invoice-accent-dark);
}
.invoice-data-panel {
margin-top: 0.55rem;
overflow: hidden;
border: 1px solid var(--invoice-border);
border-radius: 0.5rem;
background: var(--invoice-surface);
}
.invoice-data-panel[hidden] {
display: none;
}
.invoice-data-table-scroll {
overflow: auto;
scrollbar-color: var(--invoice-accent) #f1ece3;
scrollbar-width: thin;
}
.invoice-data-table {
width: 100%;
min-width: 82rem;
border-collapse: collapse;
color: var(--invoice-ink);
font-size: 0.75rem;
font-variant-numeric: tabular-nums;
}
.invoice-data-table.is-flow {
min-width: 72rem;
}
.invoice-data-table th,
.invoice-data-table td {
padding: 0.7rem 0.65rem;
border-right: 1px solid #eee8dd;
border-bottom: 1px solid #eee8dd;
text-align: left;
vertical-align: top;
}
.invoice-data-table th:last-child,
.invoice-data-table td:last-child {
border-right: 0;
}
.invoice-data-table thead th {
position: sticky;
top: 0;
z-index: 2;
background: var(--invoice-soft);
color: var(--invoice-muted);
font-size: 0.6875rem;
font-weight: 700;
white-space: nowrap;
}
.invoice-data-table tbody tr:hover td {
background: #fcfaf4;
}
.invoice-data-table .is-number {
text-align: right;
white-space: nowrap;
}
.invoice-data-table .is-nowrap {
white-space: nowrap;
}
.invoice-data-primary {
display: block;
color: var(--invoice-ink);
font-weight: 600;
}
.invoice-data-secondary {
display: block;
margin-top: 0.15rem;
color: var(--invoice-muted);
font-size: 0.6875rem;
line-height: 1.45;
}
.invoice-data-code {
color: var(--invoice-accent-dark);
font-weight: 600;
}
.invoice-data-tag {
display: inline-flex;
min-height: 1.4rem;
align-items: center;
padding: 0 0.42rem;
border: 1px solid rgba(133, 102, 50, 0.32);
border-radius: 999px;
background: #fbf8f1;
color: var(--invoice-accent-dark);
font-size: 0.625rem;
font-weight: 600;
white-space: nowrap;
}
.invoice-data-tag.is-warning {
border-color: rgba(147, 95, 7, 0.35);
background: #fffaf0;
color: #935f07;
}
.invoice-data-tag.is-danger {
border-color: rgba(184, 0, 0, 0.28);
background: #fff5f5;
color: #b80000;
}
.invoice-data-difference {
color: var(--invoice-accent-dark);
font-weight: 600;
}
.invoice-data-empty {
padding: 3rem 1rem;
color: var(--invoice-muted);
text-align: center;
}
.invoice-data-pagination {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
padding: 0.8rem 0.9rem;
border-top: 1px solid var(--invoice-border);
color: var(--invoice-muted);
font-size: 0.6875rem;
}
.invoice-data-pagination__actions {
display: flex;
gap: 0.4rem;
}
.invoice-data-pagination a,
.invoice-data-pagination span {
display: inline-flex;
min-height: 2rem;
align-items: center;
justify-content: center;
padding: 0 0.7rem;
border: 1px solid var(--invoice-border);
border-radius: 0.4rem;
color: var(--invoice-ink);
text-decoration: none;
}
.invoice-data-pagination a:hover {
border-color: var(--invoice-accent-dark);
background: var(--invoice-soft);
color: var(--invoice-accent-dark);
}
.invoice-data-pagination span {
color: #9a9489;
background: #fbfaf7;
}
.invoice-data-note {
margin: 0.75rem 0 0;
color: var(--invoice-muted);
font-size: 0.6875rem;
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;
gap: 0.45rem;
color: var(--invoice-muted);
font-size: 0.6875rem;
line-height: 1.45;
}
.invoice-data-refresh-status.is-error {
color: #b80000;
}
.invoice-data-refresh-status[hidden] {
display: none;
}
@media (max-width: 1180px) {
.invoice-data-kpis {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.invoice-data-kpi:nth-child(3) {
border-right: 0;
}
.invoice-data-kpi:nth-child(n + 4) {
border-top: 1px solid var(--invoice-border);
}
}
@media (max-width: 680px) {
.invoice-data-toolbar,
.invoice-data-filters,
.invoice-data-actions {
align-items: stretch;
}
.invoice-data-filters,
.invoice-data-field,
.invoice-data-field.is-search,
.invoice-data-actions {
width: 100%;
}
.invoice-data-actions .invoice-data-button {
flex: 1 1 auto;
}
.invoice-data-kpis {
grid-template-columns: minmax(0, 1fr);
}
.invoice-data-kpi {
border-top: 1px solid var(--invoice-border);
border-right: 0;
}
.invoice-data-kpi:first-child {
border-top: 0;
}
}
</style>
@if (!empty($invoiceMirrorError))
<div class="invoice-data-alert" role="alert">
<span class="material-icons-outlined" aria-hidden="true">error_outline</span>
<span>{{ $invoiceMirrorError }}</span>
</div>
@endif
<form method="GET" action="{{ $invoicePageUrl }}" class="invoice-data-toolbar" aria-label="发票数据筛选">
<div class="invoice-data-filters">
<label class="invoice-data-field">
<span>付款月份</span>
<select name="month">
@forelse ($invoiceMonths as $monthOption)
<option value="{{ $monthOption }}" @selected(($filters['month'] ?? '') === $monthOption)>{{ $monthOption }}</option>
@empty
<option value="">暂无月份</option>
@endforelse
</select>
</label>
<label class="invoice-data-field">
<span>发票状态</span>
<select name="invoice_state">
@foreach ($invoiceStates as $value => $label)
<option value="{{ $value }}" @selected(($filters['invoice_state'] ?? 'all') === $value)>{{ $label }}</option>
@endforeach
</select>
</label>
<label class="invoice-data-field">
<span>发票类型</span>
<select name="invoice_type">
<option value="">全部类型</option>
@foreach ($invoiceTypes as $invoiceType)
<option value="{{ $invoiceType }}" @selected(($filters['invoice_type'] ?? '') === $invoiceType)>{{ $invoiceType }}</option>
@endforeach
</select>
</label>
<label class="invoice-data-field is-search">
<span>关键词</span>
<input
type="search"
name="keyword"
value="{{ $filters['keyword'] ?? '' }}"
placeholder="流程号、发票号、销售方、购买方"
>
</label>
<label class="invoice-data-field">
<span>每页</span>
<select name="per_page">
@foreach ($invoicePerPageOptions as $perPageOption)
<option value="{{ $perPageOption }}" @selected((int) $invoicePerPage === (int) $perPageOption)>{{ $perPageOption }} 条</option>
@endforeach
</select>
</label>
<input type="hidden" name="invoice_view" value="{{ $activeView }}" data-invoice-view-field>
</div>
<div class="invoice-data-actions">
<button type="submit" class="invoice-data-button is-primary">
<span class="material-icons-outlined" aria-hidden="true">search</span>
<span>查询</span>
</button>
<a href="{{ $invoicePageUrl }}" class="invoice-data-button">
<span class="material-icons-outlined" aria-hidden="true">restart_alt</span>
<span>重置</span>
</a>
<a href="{{ $invoiceExportUrl }}" class="invoice-data-button" data-invoice-export>
<span class="material-icons-outlined" aria-hidden="true">download</span>
<span>导出</span>
</a>
<button
type="button"
class="invoice-data-button"
data-invoice-refresh
data-refresh-url="{{ $invoiceRefreshUrl }}"
data-ocr-configured="{{ $invoiceOcrConfigured ? 'true' : 'false' }}"
>
<span class="material-icons-outlined" aria-hidden="true">document_scanner</span>
<span data-invoice-refresh-label>抓取发票</span>
</button>
</div>
</form>
<div class="invoice-data-refresh-status" data-invoice-refresh-status aria-live="polite" hidden>
<span class="material-icons-outlined" aria-hidden="true">sync</span>
<span data-invoice-refresh-message></span>
</div>
<div class="invoice-data-status">
<span>
数据口径:<strong>按打款时间归属月份</strong> · 一张发票一行 · 无票流程保留
</span>
<span>
镜像状态:<strong>{{ $mirrorStatusLabels[$invoiceMirrorStatus] ?? $invoiceMirrorStatus }}</strong>
@if ($invoiceMirrorSyncedAt)
· 最近成功 {{ $invoiceMirrorSyncedAt }}
@endif
· OCR {{ $invoiceOcrConfigured ? '已配置' : '未配置' }}
· {{ $invoiceScope }}
</span>
</div>
<section class="invoice-data-kpis" aria-label="发票数据汇总">
<div class="invoice-data-kpi">
<span>付款流程</span>
<strong>{{ number_format((int) ($summary['flows'] ?? 0)) }}</strong>
</div>
<div class="invoice-data-kpi">
<span>本月付款金额</span>
<strong>¥{{ $wan($summary['payment_amount'] ?? 0) }} 万</strong>
</div>
<div class="invoice-data-kpi">
<span>发票张数</span>
<strong>{{ number_format((int) ($summary['invoice_count'] ?? 0)) }}</strong>
</div>
<div class="invoice-data-kpi">
<span>发票价税合计</span>
<strong class="is-accent">¥{{ $wan($summary['invoice_total'] ?? 0) }} 万</strong>
</div>
<div class="invoice-data-kpi">
<span>无票流程</span>
<strong>{{ number_format((int) ($summary['no_invoice_flows'] ?? 0)) }}</strong>
</div>
<div class="invoice-data-kpi">
<span>开票金额覆盖率</span>
<strong>{{ number_format((float) ($summary['invoice_rate'] ?? 0) * 100, 1) }}%</strong>
</div>
</section>
<div class="invoice-data-tabs" role="tablist" aria-label="发票数据视图">
<button
type="button"
class="invoice-data-tab"
id="invoice-detail-tab"
role="tab"
aria-selected="{{ $activeView === 'detail' ? 'true' : 'false' }}"
aria-controls="invoice-detail-panel"
data-invoice-tab="detail"
>
<span class="material-icons-outlined" aria-hidden="true">receipt_long</span>
<span>发票明细</span>
</button>
<button
type="button"
class="invoice-data-tab"
id="invoice-flow-tab"
role="tab"
aria-selected="{{ $activeView === 'flows' ? 'true' : 'false' }}"
aria-controls="invoice-flow-panel"
data-invoice-tab="flows"
>
<span class="material-icons-outlined" aria-hidden="true">table_rows</span>
<span>按流程汇总</span>
</button>
</div>
<section
class="invoice-data-panel"
id="invoice-detail-panel"
role="tabpanel"
aria-labelledby="invoice-detail-tab"
@if ($activeView !== 'detail') hidden @endif
>
<div class="invoice-data-table-scroll">
<table class="invoice-data-table">
<thead>
<tr>
<th scope="col">流程号 / 标题</th>
<th scope="col">提交人 / 报销类型</th>
<th scope="col">打款时间</th>
<th scope="col" class="is-number">本月付款</th>
<th scope="col">发票类型 / 项目</th>
<th scope="col">销售方</th>
<th scope="col">购买方</th>
<th scope="col" class="is-number">价税合计</th>
<th scope="col">发票号码 / 日期</th>
<th scope="col">附件</th>
</tr>
</thead>
<tbody>
@forelse ($detailRows as $row)
<tr>
<td>
<span class="invoice-data-primary">{{ $row->title ?: '未命名审批' }}</span>
<span class="invoice-data-secondary invoice-data-code">{{ $row->business_id }}</span>
</td>
<td>
<span class="invoice-data-primary">{{ $row->originator_name ?: '-' }}</span>
<span class="invoice-data-secondary">{{ $row->document_type ?: '-' }}</span>
</td>
<td class="is-nowrap">
{{ $row->paid_at ? \Illuminate\Support\Carbon::parse($row->paid_at)->format('Y-m-d') : '-' }}
</td>
<td class="is-number">¥{{ $money($row->payment_amount) }}</td>
<td>
<span class="invoice-data-tag">{{ $row->invoice_type ?: '未分类' }}</span>
<span class="invoice-data-secondary" title="{{ $row->item_name }}">{{ \Illuminate\Support\Str::limit((string) $row->item_name, 34) }}</span>
</td>
<td>
<span class="invoice-data-primary">{{ $row->seller_name ?: '-' }}</span>
<span class="invoice-data-secondary">{{ $row->seller_tax_no ?: '' }}</span>
</td>
<td>
<span class="invoice-data-primary">{{ $row->buyer_name ?: '-' }}</span>
<span class="invoice-data-secondary">{{ $row->buyer_tax_no ?: '' }}</span>
</td>
<td class="is-number">¥{{ $money($row->invoice_total) }}</td>
<td>
<span class="invoice-data-primary invoice-data-code">{{ $row->invoice_number ?: '-' }}</span>
<span class="invoice-data-secondary">{{ $row->invoice_date ?: '无开票日期' }}</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>
</tr>
@empty
<tr>
<td colspan="10" class="invoice-data-empty">当前筛选条件下没有发票明细。</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@include('business.pages.financial-operations.partials.invoice-data-pagination', ['paginator' => $detailRows, 'label' => '发票明细'])
</section>
<section
class="invoice-data-panel"
id="invoice-flow-panel"
role="tabpanel"
aria-labelledby="invoice-flow-tab"
@if ($activeView !== 'flows') hidden @endif
>
<div class="invoice-data-table-scroll">
<table class="invoice-data-table is-flow">
<thead>
<tr>
<th scope="col">流程号 / 标题</th>
<th scope="col">提交人 / 报销类型</th>
<th scope="col">收款人</th>
<th scope="col">打款时间</th>
<th scope="col" class="is-number">本月付款</th>
<th scope="col" class="is-number">发票张数</th>
<th scope="col" class="is-number">发票合计</th>
<th scope="col" class="is-number">付款差额</th>
<th scope="col">状态</th>
</tr>
</thead>
<tbody>
@forelse ($flowRows as $row)
@php
$difference = round((float) $row->payment_amount - (float) $row->invoice_total, 2);
@endphp
<tr>
<td>
<span class="invoice-data-primary">{{ $row->title ?: '未命名审批' }}</span>
<span class="invoice-data-secondary invoice-data-code">{{ $row->business_id }}</span>
</td>
<td>
<span class="invoice-data-primary">{{ $row->originator_name ?: '-' }}</span>
<span class="invoice-data-secondary">{{ $row->document_type ?: '-' }}</span>
</td>
<td>
<span class="invoice-data-primary">{{ $row->payee_name ?: '-' }}</span>
<span class="invoice-data-secondary">{{ $row->expense_type ?: '' }}</span>
</td>
<td class="is-nowrap">
{{ $row->paid_at ? \Illuminate\Support\Carbon::parse($row->paid_at)->format('Y-m-d') : '-' }}
</td>
<td class="is-number">¥{{ $money($row->payment_amount) }}</td>
<td class="is-number">{{ number_format((int) $row->invoice_count) }}</td>
<td class="is-number">¥{{ $money($row->invoice_total) }}</td>
<td class="is-number">
<span @class(['invoice-data-difference' => abs($difference) > 0.005])>
¥{{ $money($difference) }}
</span>
</td>
<td>
@if (in_array($row->scan_status, ['partial', 'failed'], true) || $row->last_error)
<span class="invoice-data-tag is-danger">{{ $statusLabels[$row->scan_status] ?? '待复核' }}</span>
<span class="invoice-data-secondary" title="{{ $row->last_error }}">{{ \Illuminate\Support\Str::limit((string) $row->last_error, 28) }}</span>
@elseif ((int) $row->invoice_count > 0)
<span class="invoice-data-tag">{{ $statusLabels[$row->scan_status] ?? '有票' }}</span>
@else
<span class="invoice-data-tag is-warning">无票</span>
@endif
</td>
</tr>
@empty
<tr>
<td colspan="9" class="invoice-data-empty">当前筛选条件下没有流程汇总。</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@include('business.pages.financial-operations.partials.invoice-data-pagination', ['paginator' => $flowRows, 'label' => '流程汇总'])
</section>
<p class="invoice-data-note">
口径:按 OA 付款明细中的打款时间归入月份;一张发票一行,同一流程多张发票分别列示;
无票流程在“按流程汇总”中保留。发票金额覆盖可能出现超过 100%,表示开票金额高于本月付款,需按具体流程复核。
</p>
</div>
<script>
(function () {
var root = document.querySelector('[data-invoice-data-page]');
if (!root) {
return;
}
var tabs = Array.from(root.querySelectorAll('[data-invoice-tab]'));
var panels = {
detail: root.querySelector('#invoice-detail-panel'),
flows: root.querySelector('#invoice-flow-panel'),
};
var field = root.querySelector('[data-invoice-view-field]');
var refreshButton = root.querySelector('[data-invoice-refresh]');
var refreshStatus = root.querySelector('[data-invoice-refresh-status]');
var refreshStatusMessage = root.querySelector('[data-invoice-refresh-message]');
var refreshStatusIcon = refreshStatus ? refreshStatus.querySelector('.material-icons-outlined') : null;
var refreshLabel = root.querySelector('[data-invoice-refresh-label]');
var exportLink = root.querySelector('[data-invoice-export]');
var csrfToken = @json(csrf_token());
function selectTab(view, updateUrl) {
tabs.forEach(function (tab) {
tab.setAttribute('aria-selected', tab.dataset.invoiceTab === view ? 'true' : 'false');
});
Object.keys(panels).forEach(function (key) {
if (panels[key]) {
panels[key].hidden = key !== view;
}
});
if (field) {
field.value = view;
}
if (exportLink) {
var exportUrl = new URL(exportLink.href);
exportUrl.searchParams.set('invoice_view', view);
exportLink.href = exportUrl.toString();
}
if (updateUrl) {
var url = new URL(window.location.href);
url.searchParams.set('invoice_view', view);
window.history.replaceState({}, '', url.toString());
}
}
tabs.forEach(function (tab) {
tab.addEventListener('click', function () {
selectTab(tab.dataset.invoiceTab, true);
});
});
function setRefreshStatus(message, isError) {
if (!refreshStatus || !refreshStatusMessage) {
return;
}
refreshStatus.hidden = message === '';
refreshStatus.classList.toggle('is-error', Boolean(isError));
refreshStatusMessage.textContent = message;
if (refreshStatusIcon) {
refreshStatusIcon.textContent = isError ? 'error_outline' : 'sync';
}
}
function setRefreshBusy(busy, label) {
if (!refreshButton) {
return;
}
refreshButton.disabled = busy;
if (refreshLabel) {
refreshLabel.textContent = label;
}
}
async function pollRefresh(url, token) {
for (let attempt = 0; attempt < 240; attempt++) {
const response = await fetch(url.replace('__TOKEN__', encodeURIComponent(token)), {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (!response.ok) {
throw new Error('发票抓取状态读取失败');
}
const payload = await response.json();
const refresh = payload.refresh || {};
if (refresh.status === 'completed') {
setRefreshStatus('抓取完成,正在刷新页面数据。', false);
setRefreshBusy(true, '完成');
window.setTimeout(function () {
window.location.reload();
}, 900);
return;
}
if (refresh.status === 'failed') {
throw new Error(refresh.error || '发票抓取失败');
}
setRefreshStatus(
refresh.status === 'pending'
? '任务已排队,等待批处理节点执行。'
: '正在抓取 OA 附件并识别发票,请稍候。',
false,
);
await new Promise(function (resolve) {
window.setTimeout(resolve, 3000);
});
}
throw new Error('发票抓取任务等待超时,请稍后刷新页面查看。');
}
if (refreshButton) {
refreshButton.addEventListener('click', async function () {
var monthField = root.querySelector('select[name="month"]');
var month = monthField ? monthField.value : '';
if (!month) {
setRefreshStatus('请先选择付款月份。', true);
return;
}
setRefreshBusy(true, '抓取中');
setRefreshStatus('正在提交发票抓取任务。', false);
try {
const response = await fetch(refreshButton.dataset.refreshUrl, {
method: 'POST',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': csrfToken,
},
body: JSON.stringify({ month: month, force: true }),
});
if (!response.ok) {
let message = '发票抓取任务提交失败';
try {
const payload = await response.json();
message = payload.message || message;
} catch (error) {
// Keep the stable message when the response is not JSON.
}
throw new Error(message);
}
const payload = await response.json();
setRefreshStatus(payload.message || '任务已提交。', false);
if (payload.token) {
await pollRefresh(
refreshButton.dataset.refreshUrl.replace(
/\/refresh$/,
'/refresh/__TOKEN__',
),
payload.token,
);
}
} catch (error) {
setRefreshStatus(error.message || '发票抓取失败', true);
setRefreshBusy(false, '重试抓取');
}
});
}
})();
</script>

View File

@ -0,0 +1,22 @@
@if ($paginator->total() > 0)
<div class="invoice-data-pagination">
<span>
{{ $label }}共 {{ number_format($paginator->total()) }} 条
· 第 {{ $paginator->currentPage() }} / {{ max(1, $paginator->lastPage()) }} 页
</span>
@if ($paginator->hasPages())
<div class="invoice-data-pagination__actions">
@if ($paginator->onFirstPage())
<span>上一页</span>
@else
<a href="{{ $paginator->previousPageUrl() }}">上一页</a>
@endif
@if ($paginator->hasMorePages())
<a href="{{ $paginator->nextPageUrl() }}">下一页</a>
@else
<span>下一页</span>
@endif
</div>
@endif
</div>
@endif

View File

@ -0,0 +1,296 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
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 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' => null,
'source_file_name' => null,
'source_file_type' => null,
'source_field' => null,
'source_path' => null,
'source_hash' => null,
'ocr_provider' => 'test',
'recognition_payload' => null,
'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('FLOW-INVOICE-1')
->assertSee('10月办公用品报销')
->assertSee('26320000000000000001')
->assertSee('测试供应商')
->assertSee('FLOW-NO-INVOICE')
->assertSee('无票');
$this->assertContains(
'invoice-data',
array_column(
collect(\App\Utilities\BusinessNavigation::all())
->firstWhere('slug', 'process-data')['pages'] ?? [],
'slug',
),
);
}
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(1, $flowResult['summary']['no_invoice_flows']);
}
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');
}
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->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->json('recognition_payload')->nullable();
$table->timestamps();
});
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace Tests\Feature\Business;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\DingInvoiceRefreshQueue;
use Tests\TestCase;
class InvoiceDataRefreshQueueTest extends TestCase
{
public function test_month_refresh_is_claimed_and_deferred_until_complete(): void
{
Storage::fake('local');
$queue = app(DingInvoiceRefreshQueue::class);
$queued = $queue->enqueue('2026-10', true, 1, 7);
$this->assertTrue($queued['queued']);
$this->assertNotNull($queued['token']);
$duplicate = $queue->enqueue('2026-10', true, 1, 7);
$this->assertFalse($duplicate['queued']);
$this->assertSame($queued['token'], $duplicate['token']);
$claimed = $queue->claimNext();
$this->assertNotNull($claimed);
$this->assertSame('2026-10', $claimed['month']);
$this->assertTrue($claimed['force']);
$queue->defer((string) $claimed['token'], ['remaining_flows' => 20], false);
$status = $queue->status((string) $claimed['token'], 1, 7);
$this->assertSame('pending', $status['status']);
$this->assertFalse($status['force'] ?? true);
$this->assertSame(20, $status['progress']['remaining_flows']);
$claimedAgain = $queue->claimNext();
$this->assertSame($queued['token'], $claimedAgain['token']);
$queue->complete((string) $claimedAgain['token'], ['remaining_flows' => 0]);
$completed = $queue->status((string) $claimedAgain['token'], 1, 7);
$this->assertSame('completed', $completed['status']);
$this->assertSame(0, $completed['result']['remaining_flows']);
$this->assertNull($queue->status((string) $claimedAgain['token'], 2, 7));
}
}

View File

@ -25,7 +25,10 @@ class ProcessDetailsNavigationTest extends FeatureTestCase
$section = $navigation[$processDataIndex];
$this->assertSame('流程数据', $section['title']);
$this->assertSame(
[['slug' => 'oa-process', 'title' => 'OA流程']],
[
['slug' => 'oa-process', 'title' => 'OA流程'],
['slug' => 'invoice-data', 'title' => '发票数据'],
],
array_map(
static fn (array $page): array => [
'slug' => $page['slug'],

View File

@ -0,0 +1,185 @@
<?php
namespace Tests\Feature\Console;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\DingInvoiceWorkbookImporter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\TestCase;
class ImportDingInvoiceWorkbookTest extends TestCase
{
private string $file;
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',
]);
DB::purge('business_mirror');
$this->createTables();
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('报销发票识别');
$sheet->fromArray([
[
'单号/标题', '流程号', '提交人', '报销类型', '费用类型', '收款人',
'打款时间', '10月付款金额', '付款合计', '发票类型', '销售方名称',
'销售方税号', '购买方名称', '购买方税号', '发票价税合计', '发票号码',
'开票日期', '项目名称', '金额', '税率', '税额', '金额校对', '差异金额',
],
[
'10月办公用品报销', 'FLOW-INVOICE-1', '张三', '公摊日常报销', '办公用品',
'测试供应商', '2026-10-12', 1000, 1000, '电子发票(普通发票)',
'测试供应商', '913200000000000001', '测试主体', '913200000000000002',
1000, '26320000000000000001', '2026-10-10', '*办公用品*打印纸',
884.96, '13%', 115.04, '一致', 0,
],
[
null, null, null, null, null, null, null, null, null,
'电子发票(普通发票)', '测试供应商', '913200000000000001',
'测试主体', '913200000000000002', 1000, '26320000000000000001',
'2026-10-10', '*办公用品*打印纸', 884.96, '13%', 115.04, null, null,
],
[
'10月借支销账', 'FLOW-NO-INVOICE', '李四', '公摊借支-销账', '借支',
'员工', '2026-10-13', 500, 500, '无票', null, null, null, null,
0, null, null, null, null, null, null, '无票', null,
],
[
'10月软件服务费', 'FLOW-INVOICE-2', '王五', '公摊日常报销', '软件服务费',
'测试服务商', '2026-10-14', 200, 200, '电子发票(普通发票)',
'测试服务商', '913200000000000003', '测试主体', '913200000000000002',
200, '26320000000000000001', '2026-10-14', '*软件服务*服务费',
188.68, '6%', 11.32, '一致', 0,
],
]);
$this->file = tempnam(sys_get_temp_dir(), 'invoice-import-') . '.xlsx';
(new Xlsx($spreadsheet))->save($this->file);
$spreadsheet->disconnectWorksheets();
}
protected function tearDown(): void
{
if (isset($this->file) && is_file($this->file)) {
unlink($this->file);
}
parent::tearDown();
}
public function test_imports_one_invoice_row_per_invoice_and_keeps_no_invoice_flow(): void
{
$result = app(DingInvoiceWorkbookImporter::class)->import($this->file);
$this->assertSame(3, $result['flows']);
$this->assertSame(2, $result['invoices']);
$this->assertSame(['2026-10'], $result['months']);
$this->assertEqualsWithDelta(1700.0, $result['payment_total'], 0.001);
$this->assertEqualsWithDelta(1200.0, $result['invoice_total'], 0.001);
$this->assertDatabaseHas('ding_invoice_flow_mirror', [
'business_id' => 'FLOW-INVOICE-1',
'invoice_count' => 1,
'scan_status' => 'recognized',
], 'business_mirror');
$this->assertDatabaseHas('ding_invoice_flow_mirror', [
'business_id' => 'FLOW-NO-INVOICE',
'invoice_count' => 0,
'scan_status' => 'no_invoice',
], 'business_mirror');
$this->assertDatabaseCount('ding_invoice_record_mirror', 2, 'business_mirror');
}
private function createTables(): 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->string('run_mode')->nullable();
$table->uuid('generation')->nullable();
$table->json('cursor')->nullable();
$table->json('high_watermark')->nullable();
$table->dateTime('window_started_at')->nullable();
$table->dateTime('window_ends_at')->nullable();
$table->dateTime('initial_completed_at')->nullable();
$table->dateTime('last_full_succeeded_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->string('last_error_code')->nullable();
$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->dateTime('scanned_at')->nullable();
$table->timestamps();
$table->unique(['source_scope', 'business_id']);
});
$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->json('recognition_payload')->nullable();
$table->timestamps();
$table->unique(['source_scope', 'business_id', 'invoice_key']);
});
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace Tests\Unit;
use Modules\EcommerceFinance\Services\DingInvoiceTextParser;
use Tests\TestCase;
class DingInvoiceTextParserTest extends TestCase
{
public function test_parses_standard_electronic_invoice_text(): void
{
$text = <<<'TEXT'
电子发票(普通发票)
发票号码:26320000000000000001
开票日期:2026年10月10日
购买方信息
名称:常州测试家居有限公司
统一社会信用代码/纳税人识别号:91320411MA00000001
销售方信息
名称:常州测试供应商有限公司
统一社会信用代码/纳税人识别号:91320411MA00000002
*办公用品*打印纸
金额:884.96
税率/征收率:13%
税额:115.04
价税合计(小写):¥1000.00
TEXT;
$invoice = app(DingInvoiceTextParser::class)->parse($text);
$this->assertNotNull($invoice);
$this->assertSame('电子发票(普通发票)', $invoice['invoice_type']);
$this->assertSame('26320000000000000001', $invoice['invoice_number']);
$this->assertSame('2026-10-10', $invoice['invoice_date']);
$this->assertSame('常州测试家居有限公司', $invoice['buyer_name']);
$this->assertSame('常州测试供应商有限公司', $invoice['seller_name']);
$this->assertEqualsWithDelta(1000.0, $invoice['invoice_total'], 0.001);
$this->assertSame('*办公用品*打印纸', $invoice['item_name']);
}
public function test_ignores_non_invoice_attachment_text(): void
{
$this->assertNull(
app(DingInvoiceTextParser::class)->parse('银行电子回单 金额 1000.00 无发票号码'),
);
}
}