523 lines
20 KiB
PHP
523 lines
20 KiB
PHP
<?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 $replaceImportedRecords = 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,
|
||
$replaceImportedRecords,
|
||
$flows,
|
||
$invoiceRows,
|
||
$invoiceTotal,
|
||
): void {
|
||
$businessIds = array_keys($flows);
|
||
$existingFlows = $this->connection->table('ding_invoice_flow_mirror')
|
||
->where('source_scope', $scope)
|
||
->whereIn('business_id', $businessIds)
|
||
->get()
|
||
->keyBy('business_id');
|
||
|
||
foreach ($flows as $businessId => $flow) {
|
||
$existing = $existingFlows->get($businessId);
|
||
$values = $flow;
|
||
if ($existing !== null) {
|
||
$values['process_instance_id'] = $existing->process_instance_id;
|
||
$values['attachment_count'] = (int) $existing->attachment_count;
|
||
$values['scanned_file_count'] = (int) $existing->scanned_file_count;
|
||
$values['last_error'] = $existing->last_error;
|
||
$values['source_name'] = $existing->source_name ?: $flow['source_name'];
|
||
$values['scanned_at'] = $existing->scanned_at ?: $flow['scanned_at'];
|
||
$values['created_at'] = $existing->created_at;
|
||
if (in_array((string) $existing->scan_status, ['partial', 'failed'], true)) {
|
||
$values['scan_status'] = $existing->scan_status;
|
||
}
|
||
}
|
||
$this->connection->table('ding_invoice_flow_mirror')->updateOrInsert(
|
||
[
|
||
'source_scope' => $scope,
|
||
'business_id' => $businessId,
|
||
],
|
||
$values,
|
||
);
|
||
}
|
||
|
||
if ($replaceImportedRecords) {
|
||
$this->connection->table('ding_invoice_record_mirror')
|
||
->where('source_scope', $scope)
|
||
->whereIn('business_id', $businessIds)
|
||
->where('ocr_provider', 'imported_workbook')
|
||
->delete();
|
||
// Legacy OCR could persist a "number only" row with no amount.
|
||
// Once an audited ledger covers the flow, such a row is noise.
|
||
$this->connection->table('ding_invoice_record_mirror')
|
||
->where('source_scope', $scope)
|
||
->whereIn('business_id', $businessIds)
|
||
->where('invoice_total', '<=', 0)
|
||
->delete();
|
||
}
|
||
|
||
$existingRecords = $this->connection->table('ding_invoice_record_mirror')
|
||
->where('source_scope', $scope)
|
||
->whereIn('business_id', $businessIds)
|
||
->get()
|
||
->keyBy(static fn (object $row): string =>
|
||
$row->business_id . '|' . $row->invoice_key
|
||
);
|
||
|
||
foreach ($invoiceRows as $record) {
|
||
$key = $record['business_id'] . '|' . $record['invoice_key'];
|
||
$existing = $existingRecords->get($key);
|
||
if ($existing === null) {
|
||
$this->connection->table('ding_invoice_record_mirror')->insert($record);
|
||
continue;
|
||
}
|
||
|
||
$merged = $this->mergeImportedRecord((array) $existing, $record);
|
||
unset($merged['id'], $merged['created_at']);
|
||
$this->connection->table('ding_invoice_record_mirror')
|
||
->where('id', $existing->id)
|
||
->update($merged);
|
||
}
|
||
|
||
$recordTotals = $this->connection->table('ding_invoice_record_mirror')
|
||
->where('source_scope', $scope)
|
||
->whereIn('business_id', $businessIds)
|
||
->get(['business_id', 'invoice_total'])
|
||
->groupBy('business_id');
|
||
$now = now();
|
||
foreach ($businessIds as $businessId) {
|
||
$records = $recordTotals->get($businessId, collect());
|
||
$lastError = $this->connection->table('ding_invoice_flow_mirror')
|
||
->where('source_scope', $scope)
|
||
->where('business_id', $businessId)
|
||
->value('last_error');
|
||
$count = $records->count();
|
||
$status = match (true) {
|
||
$lastError !== null && $lastError !== '' && $count > 0 => 'partial',
|
||
$lastError !== null && $lastError !== '' => 'failed',
|
||
$count > 0 => 'recognized',
|
||
default => 'no_invoice',
|
||
};
|
||
$this->connection->table('ding_invoice_flow_mirror')
|
||
->where('source_scope', $scope)
|
||
->where('business_id', $businessId)
|
||
->update([
|
||
'invoice_count' => $count,
|
||
'invoice_total' => round((float) $records->sum('invoice_total'), 2),
|
||
'scan_status' => $status,
|
||
'updated_at' => $now,
|
||
]);
|
||
}
|
||
|
||
$this->updateState(
|
||
count($invoiceRows),
|
||
count($flows),
|
||
$invoiceTotal,
|
||
$months,
|
||
$scope,
|
||
);
|
||
});
|
||
|
||
return [
|
||
'flows' => count($flows),
|
||
'invoices' => count($invoiceRows),
|
||
'months' => $months,
|
||
'payment_total' => $paymentTotal,
|
||
'invoice_total' => $invoiceTotal,
|
||
];
|
||
}
|
||
|
||
private function updateState(
|
||
int $invoiceRows,
|
||
int $flowRows,
|
||
float $invoiceTotal,
|
||
array $months,
|
||
string $scope,
|
||
): 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' => $this->connection->table('ding_invoice_record_mirror')
|
||
->where('source_scope', $scope)
|
||
->whereIn('paid_month', $months)
|
||
->count(),
|
||
'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;
|
||
}
|
||
|
||
/**
|
||
* @param array<string,mixed> $existing
|
||
* @param array<string,mixed> $record
|
||
* @return array<string,mixed>
|
||
*/
|
||
private function mergeImportedRecord(array $existing, array $record): array
|
||
{
|
||
foreach ($record as $key => $value) {
|
||
if (in_array($key, [
|
||
'source_file_id',
|
||
'source_file_name',
|
||
'source_file_type',
|
||
'source_field',
|
||
'source_path',
|
||
'source_hash',
|
||
'ocr_provider',
|
||
'recognition_payload',
|
||
'created_at',
|
||
], true)) {
|
||
continue;
|
||
}
|
||
if ($value === null || (is_string($value) && trim($value) === '')) {
|
||
continue;
|
||
}
|
||
$existing[$key] = $value;
|
||
}
|
||
|
||
return $existing;
|
||
}
|
||
|
||
}
|