diff --git a/app/Http/Controllers/Business/FinanceLedger.php b/app/Http/Controllers/Business/FinanceLedger.php index b2adb240..64e69855 100644 --- a/app/Http/Controllers/Business/FinanceLedger.php +++ b/app/Http/Controllers/Business/FinanceLedger.php @@ -14,6 +14,7 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Illuminate\Validation\Rule; @@ -30,6 +31,7 @@ use Modules\EcommerceFinance\Services\FinanceLedgerIndependentTransactionColumnE use Modules\EcommerceFinance\Services\FinanceLedgerIndependentTransactionEditor; use Modules\EcommerceFinance\Services\FinanceLedgerInternalTransferEditor; use Modules\EcommerceFinance\Services\FinanceLedgerManualTransactionEditor; +use Modules\EcommerceFinance\Services\FinanceLedgerManualTransactionImporter; use Modules\EcommerceFinance\Services\FinanceLedgerPayableMappingBulk; use Modules\EcommerceFinance\Services\FinanceLedgerShopDataSynchronizer; use Modules\EcommerceFinance\Services\FinanceLedgerShopMappingBulk; @@ -41,6 +43,8 @@ use Throwable; class FinanceLedger extends Controller { + private const MANUAL_TRANSACTION_IMPORT_CACHE_PREFIX = 'finance-ledger-manual-transaction-import:'; + private const UNRETAINED_OWNER_OPTIONS = [ '玉兔', '山时', @@ -1401,6 +1405,112 @@ class FinanceLedger extends Controller ], $inserted ? 201 : 200, ['Cache-Control' => 'private, no-store']); } + public function downloadManualTransactionImportTemplate( + Request $request, + FinanceLedgerManualTransactionImporter $importer, + ): StreamedResponse { + abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有导入手工动账明细权限。'); + + return $importer->downloadTemplate($this->manualTransactionImportAccount($request)); + } + + public function previewManualTransactionImport( + Request $request, + FinanceLedgerManualTransactionImporter $importer, + ): JsonResponse { + abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有导入手工动账明细权限。'); + + $file = $request->validate([ + 'import' => ['required', 'file', 'mimes:xlsx,xls,csv', 'max:10240'], + 'import.required' => '请选择要导入的 Excel 或 CSV 文件。', + 'import.file' => '导入文件上传失败,请重新选择。', + 'import.mimes' => '只支持 xlsx、xls、csv 三种格式。', + 'import.max' => '导入文件不能超过 10MB。', + ])['import']; + $preview = $importer->preview( + $file, + $this->manualTransactionImportAccount($request), + ); + $token = Str::random(48); + Cache::put($this->manualTransactionImportCacheKey($token), [ + 'company_id' => (int) company_id(), + 'user_id' => (int) user_id(), + 'source_hash' => (string) $preview['source_hash'], + 'file_name' => (string) $preview['file_name'], + 'plan' => $preview['plan'], + ], now()->addMinutes(30)); + + return response()->json([ + 'ok' => true, + 'preview_token' => $token, + 'file_name' => $preview['file_name'], + 'stats' => [ + 'total' => $preview['total'], + 'valid' => $preview['valid'], + 'duplicate' => $preview['duplicate'], + 'invalid' => $preview['invalid'], + ], + 'rows' => $preview['rows'], + 'truncated' => $preview['truncated'], + 'max_rows' => $preview['max_rows'], + ], 200, ['Cache-Control' => 'private, no-store']); + } + + public function commitManualTransactionImport( + Request $request, + FinanceLedgerManualTransactionImporter $importer, + FinanceLedgerPageData $pageData, + ): JsonResponse { + abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有导入手工动账明细权限。'); + + $data = $request->validate([ + 'preview_token' => ['required', 'string', 'size:48'], + ]); + $cacheKey = $this->manualTransactionImportCacheKey((string) $data['preview_token']); + $payload = Cache::get($cacheKey); + if (! is_array($payload) + || (int) ($payload['company_id'] ?? 0) !== (int) company_id() + || (int) ($payload['user_id'] ?? 0) !== (int) user_id() + || ! is_array($payload['plan'] ?? null) + || ! is_string($payload['source_hash'] ?? null) + || ! is_string($payload['file_name'] ?? null)) { + throw ValidationException::withMessages([ + 'preview_token' => '导入预览已失效或不属于当前账号,请重新上传并预览。', + ]); + } + + $result = $importer->commit( + $payload['plan'], + $payload['source_hash'], + $payload['file_name'], + ); + Cache::forget($cacheKey); + + return response()->json([ + 'ok' => true, + 'imported' => $result['imported'], + 'duplicate_skipped' => $result['duplicate_skipped'], + 'summary' => $pageData->transactionSummary(), + 'total_transactions' => $pageData->globalTransactionCount(), + 'message' => '导入完成:新增 ' . number_format($result['imported']) . ' 条,跳过 ' + . number_format($result['duplicate_skipped']) . ' 条重复明细。', + ], 200, ['Cache-Control' => 'private, no-store']); + } + + private function manualTransactionImportAccount(Request $request): ?string + { + $viewKey = trim((string) $request->query('txns_view', 'all')); + $accountShort = FinanceLedgerPageData::TRANSACTION_VIEWS[$viewKey]['account_short'] ?? null; + $accountShort = trim((string) $accountShort); + + return $accountShort !== '' ? $accountShort : null; + } + + private function manualTransactionImportCacheKey(string $token): string + { + return self::MANUAL_TRANSACTION_IMPORT_CACHE_PREFIX . hash('sha256', $token); + } + public function storeInternalTransfer( Request $request, FinanceLedgerInternalTransferEditor $editor, diff --git a/modules/EcommerceFinance/Services/FinanceLedgerManualTransactionImporter.php b/modules/EcommerceFinance/Services/FinanceLedgerManualTransactionImporter.php new file mode 100644 index 00000000..bec92520 --- /dev/null +++ b/modules/EcommerceFinance/Services/FinanceLedgerManualTransactionImporter.php @@ -0,0 +1,964 @@ + '日期', + 'account_short' => '账户简称', + 'counterparty_info' => '对方信息', + 'income' => '收入(元)', + 'expense' => '支出(元)', + 'balance' => '余额(元)', + 'payment_remark' => '付款备注', + 'detail' => '明细', + 'approval_no' => '审批编号/业务单号', + ]; + + private const ALIASES = [ + 'txn_date' => ['日期', '动账日期', '交易日期', '记账日期'], + 'account_short' => ['账户简称', '账户', '账户名称'], + 'counterparty_info' => ['对方信息', '对方账户', '对方账户/名称', '对方名称', '交易对方'], + 'income' => ['收入', '收入(元)', '收入(元)', '转入金额', '收款金额'], + 'expense' => ['支出', '支出(元)', '支出(元)', '转出金额', '付款金额'], + 'balance' => ['余额', '余额(元)', '余额(元)', '交易后余额'], + 'payment_remark' => ['付款备注', '备注'], + 'detail' => ['明细', '交易明细', '摘要', '用途'], + 'approval_no' => ['审批编号/业务单号', '审批编号', '业务单号'], + ]; + + private readonly ConnectionInterface $connection; + + public function __construct( + DatabaseManager $databases, + private readonly FinanceLedgerCalculator $calculator, + ) { + $this->connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{ + * total:int, + * valid:int, + * duplicate:int, + * invalid:int, + * rows:list>, + * plan:list>, + * source_hash:string, + * file_name:string, + * truncated:bool, + * max_rows:int + * } + */ + public function preview(UploadedFile $file, ?string $fixedAccountShort = null): array + { + $fixedAccountShort = trim((string) $fixedAccountShort); + $accountShortValues = $this->connection->table('fin_accounts') + ->whereNotNull('account_short') + ->pluck('account_short') + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter() + ->unique() + ->values() + ->all(); + $accountLookup = array_fill_keys($accountShortValues, true); + if ($fixedAccountShort !== '' && ! isset($accountLookup[$fixedAccountShort])) { + throw ValidationException::withMessages([ + 'import' => '当前页面指定的账户“' . $fixedAccountShort . '”不在账户总表中。', + ]); + } + + [$headers, $rawRows] = $this->readRows($file, $fixedAccountShort); + $columns = $this->mapHeaders($headers, $fixedAccountShort); + $sourceHash = hash_file('sha256', $file->getRealPath()); + if (! is_string($sourceHash) || $sourceHash === '') { + throw ValidationException::withMessages([ + 'import' => '无法校验导入文件,请重新导出模板后再试。', + ]); + } + + $openingDate = (string) config('finance_ledger.opening_date', '2026-10-17'); + $normalizedRows = []; + foreach ($rawRows as $rawRow) { + $normalized = $this->normalizeRow( + $rawRow, + $columns, + $fixedAccountShort, + $accountLookup, + $openingDate, + $sourceHash, + ); + if ($normalized !== null) { + $normalizedRows[] = $normalized; + } + } + + if ($normalizedRows === []) { + throw ValidationException::withMessages([ + 'import' => '文件中没有可读取的动账明细,请按模板填写后再上传。', + ]); + } + + $existingFingerprints = $this->existingFingerprints( + array_values(array_unique(array_column($normalizedRows, 'txn_date'))), + $fixedAccountShort, + ); + $seenInFile = []; + $previewRows = []; + $plan = []; + $duplicateCount = 0; + $invalidCount = 0; + $validCount = 0; + + foreach ($normalizedRows as $row) { + $messages = $row['errors']; + $status = 'ready'; + if ($messages !== []) { + $status = 'invalid'; + $invalidCount++; + } elseif (isset($existingFingerprints[$row['fingerprint']]) + || isset($seenInFile[$row['fingerprint']])) { + $status = 'duplicate'; + $messages[] = '系统中或本文件前面已有相同账户、日期、金额和明细,确认导入时将跳过。'; + $duplicateCount++; + } else { + $seenInFile[$row['fingerprint']] = true; + $validCount++; + unset($row['errors'], $row['fingerprint']); + $plan[] = $row; + } + + $previewRows[] = [ + 'row_number' => (int) $row['source_row'], + 'status' => $status, + 'status_label' => match ($status) { + 'ready' => '可导入', + 'duplicate' => '重复跳过', + default => '需修正', + }, + 'messages' => $messages, + 'display' => [ + 'txn_date' => (string) $row['txn_date'], + 'account_short' => (string) $row['account_short'], + 'counterparty_info' => (string) ($row['counterparty_info'] ?? ''), + 'income' => $row['income_cents'] > 0 ? $this->money($row['income_cents']) : '', + 'expense' => $row['expense_cents'] > 0 ? $this->money($row['expense_cents']) : '', + 'balance' => $row['balance_cents'] === null ? '' : $this->money($row['balance_cents']), + 'payment_remark' => (string) ($row['payment_remark'] ?? ''), + 'detail' => (string) ($row['detail'] ?? ''), + 'approval_no' => (string) ($row['approval_no'] ?? ''), + ], + ]; + } + + return [ + 'total' => count($normalizedRows), + 'valid' => $validCount, + 'duplicate' => $duplicateCount, + 'invalid' => $invalidCount, + 'rows' => array_slice($previewRows, 0, self::PREVIEW_ROWS), + 'plan' => $plan, + 'source_hash' => $sourceHash, + 'file_name' => (string) $file->getClientOriginalName(), + 'truncated' => count($previewRows) > self::PREVIEW_ROWS, + 'max_rows' => self::MAX_ROWS, + ]; + } + + /** + * @param list> $plan + * @return array{imported:int,duplicate_skipped:int} + */ + public function commit(array $plan, string $sourceHash, string $fileName): array + { + if ($plan === []) { + throw ValidationException::withMessages([ + 'import' => '没有可导入的有效明细。', + ]); + } + if (count($plan) > self::MAX_ROWS) { + throw ValidationException::withMessages([ + 'import' => '单次最多导入 ' . number_format(self::MAX_ROWS) . ' 条动账明细。', + ]); + } + + return $this->connection->transaction(function () use ($plan, $sourceHash, $fileName): array { + $now = now(); + $inserted = 0; + $rows = []; + foreach ($plan as $row) { + $rows[] = [ + 'txn_date' => (string) $row['txn_date'], + 'account_short' => (string) $row['account_short'], + 'counterparty_info' => ($row['counterparty_info'] ?? null) ?: null, + 'detail' => (string) $row['detail'], + 'income' => $this->amountFromCents((int) $row['income_cents']), + 'expense' => $this->amountFromCents((int) $row['expense_cents']), + 'balance' => $row['balance_cents'] === null + ? null + : $this->amountFromCents((int) $row['balance_cents']), + 'approval_no' => (string) $row['approval_no'], + 'payment_remark' => ($row['payment_remark'] ?? null) ?: null, + 'source' => FinanceLedgerTransactionWriter::MANUAL_SOURCE, + 'source_value' => null, + 'process_type' => '手工导入', + 'row_key' => (string) $row['row_key'], + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + 'created_by' => (string) (user()?->name ?? ''), + 'updated_by' => (string) (user()?->name ?? ''), + ]; + } + + foreach (array_chunk($rows, 500) as $chunk) { + $inserted += $this->connection->table('fin_transactions')->insertOrIgnore($chunk); + } + + if ($inserted > 0) { + $this->calculator->recalculate(); + $this->connection->table('fin_ledger_edit_events')->insert([ + 'entity_type' => 'manual_transaction_import', + 'entity_key' => 'import|' . $sourceHash, + 'changes' => json_encode([ + 'file_name' => $fileName, + 'planned' => count($plan), + 'imported' => $inserted, + 'duplicate_skipped' => count($plan) - $inserted, + ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'user_id' => user()?->id, + 'user_name' => (string) (user()?->name ?? ''), + 'created_at' => $now, + ]); + } + + return [ + 'imported' => $inserted, + 'duplicate_skipped' => count($plan) - $inserted, + ]; + }); + } + + public function downloadTemplate(?string $fixedAccountShort = null): StreamedResponse + { + $fixedAccountShort = trim((string) $fixedAccountShort); + + return response()->streamDownload(function () use ($fixedAccountShort): void { + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('动账明细'); + $headers = array_values(self::HEADERS); + $sheet->fromArray($headers, null, 'A1'); + $lastColumn = Coordinate::stringFromColumnIndex(count($headers)); + $headerRange = 'A1:' . $lastColumn . '1'; + $sheet->getStyle($headerRange)->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + 'alignment' => [ + 'horizontal' => Alignment::HORIZONTAL_CENTER, + 'vertical' => Alignment::VERTICAL_CENTER, + ], + 'borders' => [ + 'allBorders' => [ + 'borderStyle' => Border::BORDER_THIN, + 'color' => ['rgb' => 'D8D2C7'], + ], + ], + ]); + $sheet->getRowDimension(1)->setRowHeight(26); + $sheet->freezePane('A2'); + $sheet->setAutoFilter($headerRange); + foreach (array_keys(self::HEADERS) as $index => $field) { + $column = Coordinate::stringFromColumnIndex($index + 1); + $width = match ($field) { + 'detail' => 34, + 'counterparty_info', 'payment_remark', 'approval_no' => 26, + 'account_short' => 20, + default => 16, + }; + $sheet->getColumnDimension($column)->setWidth($width); + $sheet->getStyle($column . '2:' . $column . '2001') + ->getNumberFormat() + ->setFormatCode(in_array($field, ['income', 'expense', 'balance'], true) + ? '#,##0.00' + : '@'); + } + $sheet->getStyle($headerRange)->getAlignment()->setWrapText(true); + + $instructions = $spreadsheet->createSheet(); + $instructions->setTitle('填写说明'); + $instructions->fromArray([ + ['项目', '说明'], + ['导入范围', $fixedAccountShort !== '' + ? '当前页面固定导入账户:' . $fixedAccountShort . ';账户简称列如填写,必须与之一致。' + : '账户简称必须来自财务台账“账户总表”,请勿填写公司名称或银行账号。'], + ['日期', '填写 YYYY-MM-DD,例如 2026-11-18。非独立账单日期不得早于台账期初日期。'], + ['收入/支出', '每行只能填写收入或支出其中一项,金额最多两位小数。'], + ['重复数据', '系统按日期、账户、对方信息、收支金额、余额、付款备注和明细识别重复;重复行在预览中标记并跳过。'], + ['错误行', '预览会逐行显示错误;只有“可导入”的行会写入系统,确认前不会修改任何数据。'], + ['行数限制', '单个文件最多 ' . number_format(self::MAX_ROWS) . ' 条有效明细。'], + ['来源', '导入明细统一标记为“手工录入”,写入后可继续使用行尾的修改、删除操作。'], + ], null, 'A1'); + $instructions->getStyle('A1:B1')->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '856632']], + ]); + $instructions->getColumnDimension('A')->setWidth(18); + $instructions->getColumnDimension('B')->setWidth(72); + $instructions->getStyle('A1:B8')->getAlignment() + ->setVertical(Alignment::VERTICAL_CENTER) + ->setWrapText(true); + foreach (range(1, 8) as $row) { + $instructions->getRowDimension($row)->setRowHeight($row === 1 ? 24 : 38); + } + + $spreadsheet->setActiveSheetIndex(0); + (new Xlsx($spreadsheet))->save('php://output'); + $spreadsheet->disconnectWorksheets(); + }, '动账明细_手工导入模板_' . now()->format('Ymd') . '.xlsx', [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * @return array{0:list,1:list}>} + */ + private function readRows(UploadedFile $file, string $fixedAccountShort): array + { + $extension = mb_strtolower((string) $file->getClientOriginalExtension()); + if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) { + throw ValidationException::withMessages([ + 'import' => '只支持 xlsx、xls、csv 三种文件格式。', + ]); + } + + return $extension === 'csv' + ? $this->readCsv($file, $fixedAccountShort) + : $this->readSpreadsheet($file, $extension, $fixedAccountShort); + } + + /** + * @return array{0:list,1:list}>} + */ + private function readCsv(UploadedFile $file, string $fixedAccountShort): array + { + $handle = fopen($file->getRealPath(), 'rb'); + if ($handle === false) { + throw ValidationException::withMessages([ + 'import' => '无法读取导入文件。', + ]); + } + + try { + $firstLine = ''; + while (($line = fgets($handle)) !== false) { + $line = $this->normalizeCsvText($line); + if (trim($line) !== '') { + $firstLine = $line; + break; + } + } + if ($firstLine === '') { + throw ValidationException::withMessages([ + 'import' => '导入文件为空,请填写模板后再上传。', + ]); + } + $delimiter = $this->detectDelimiter($firstLine); + rewind($handle); + + $header = null; + $headerRow = 0; + $sourceRow = 0; + while (($cells = fgetcsv($handle, 0, $delimiter, '"', '')) !== false) { + $sourceRow++; + $cells = array_map(fn (mixed $value): string => $this->normalizeCsvText($value), $cells); + if ($this->rowIsEmpty($cells)) { + continue; + } + if ($header === null) { + if ($this->headerScore($cells, $fixedAccountShort) === 0) { + continue; + } + $header = array_map(static fn (mixed $value): string => trim((string) $value), $cells); + $headerRow = $sourceRow; + continue; + } + break; + } + + if ($header === null) { + throw ValidationException::withMessages([ + 'import' => '没有找到导入表头,请先下载并使用系统模板。', + ]); + } + + $rows = []; + if (is_array($cells)) { + $cells = array_map(fn (mixed $value): string => $this->normalizeCsvText($value), $cells); + if (! $this->rowIsEmpty($cells)) { + $rows[] = ['row' => $sourceRow, 'cells' => array_values($cells)]; + } + } + while (($cells = fgetcsv($handle, 0, $delimiter, '"', '')) !== false) { + $sourceRow++; + $cells = array_map(fn (mixed $value): string => $this->normalizeCsvText($value), $cells); + if ($this->rowIsEmpty($cells)) { + continue; + } + $rows[] = ['row' => $sourceRow, 'cells' => array_values($cells)]; + if (count($rows) > self::MAX_ROWS) { + throw ValidationException::withMessages([ + 'import' => '单个文件最多导入 ' . number_format(self::MAX_ROWS) . ' 条动账明细。', + ]); + } + } + + return [$header, $rows]; + } finally { + fclose($handle); + } + } + + /** + * @return array{0:list,1:list}>} + */ + private function readSpreadsheet(UploadedFile $file, string $extension, string $fixedAccountShort): array + { + try { + $reader = IOFactory::createReader(ucfirst($extension)); + $reader->setReadDataOnly(true); + if (method_exists($reader, 'setReadEmptyCells')) { + $reader->setReadEmptyCells(false); + } + if ($extension === 'xlsx') { + $reader->setReadFilter(new class(self::MAX_ROWS + 30) implements IReadFilter { + public function __construct(private readonly int $lastRow) + { + } + + public function readCell($columnAddress, $row, $worksheetName = ''): bool + { + return $row >= 1 && $row <= $this->lastRow; + } + }); + } + $spreadsheet = $reader->load($file->getRealPath()); + } catch (Throwable) { + throw ValidationException::withMessages([ + 'import' => '读不出这个文件,请确认是 xlsx、xls 或 csv,且没有损坏。', + ]); + } + + try { + $sheet = null; + foreach ($spreadsheet->getWorksheetIterator() as $candidate) { + $highestRow = $candidate->getHighestDataRow(); + if ($highestRow < 1) { + continue; + } + $lastColumn = $candidate->getHighestDataColumn(); + $sample = $candidate->rangeToArray( + 'A1:' . $lastColumn . min(30, $highestRow), + null, + false, + true, + false, + ); + foreach ($sample as $cells) { + $cells = array_values(array_map( + static fn (mixed $value): string => trim((string) (is_scalar($value) ? $value : '')), + $cells, + )); + if (! $this->rowIsEmpty($cells) + && $this->headerScore($cells, $fixedAccountShort) > 0) { + $sheet = $candidate; + break 2; + } + } + } + if ($sheet === null) { + throw ValidationException::withMessages([ + 'import' => '导入文件为空,请填写模板后再上传。', + ]); + } + + $highestRow = $sheet->getHighestDataRow(); + if ($highestRow > self::MAX_ROWS + 30) { + throw ValidationException::withMessages([ + 'import' => '单个文件最多导入 ' . number_format(self::MAX_ROWS) . ' 条动账明细。', + ]); + } + $grid = $sheet->toArray(null, false, true, false); + } finally { + $spreadsheet->disconnectWorksheets(); + } + + $header = null; + $headerIndex = null; + foreach ($grid as $index => $cells) { + $cells = array_values(array_map( + static fn (mixed $value): string => trim((string) (is_scalar($value) ? $value : '')), + $cells, + )); + if ($this->rowIsEmpty($cells)) { + continue; + } + if ($this->headerScore($cells, $fixedAccountShort) > 0) { + $header = $cells; + $headerIndex = $index; + break; + } + } + if ($header === null || $headerIndex === null) { + throw ValidationException::withMessages([ + 'import' => '没有找到导入表头,请先下载并使用系统模板。', + ]); + } + + $rows = []; + foreach ($grid as $index => $cells) { + if ($index <= $headerIndex) { + continue; + } + $cells = array_values(array_map( + static fn (mixed $value): string => trim((string) (is_scalar($value) ? $value : '')), + $cells, + )); + if ($this->rowIsEmpty($cells)) { + continue; + } + $rows[] = ['row' => (int) $index + 1, 'cells' => $cells]; + if (count($rows) > self::MAX_ROWS) { + throw ValidationException::withMessages([ + 'import' => '单个文件最多导入 ' . number_format(self::MAX_ROWS) . ' 条动账明细。', + ]); + } + } + + return [$header, $rows]; + } + + /** + * @param list $header + * @return array + */ + private function mapHeaders(array $header, string $fixedAccountShort): array + { + $normalizedHeaders = array_map( + fn (mixed $value): string => $this->normalizeHeader($value), + $header, + ); + $columns = []; + foreach (self::ALIASES as $field => $aliases) { + $index = false; + foreach ($aliases as $alias) { + $index = array_search($this->normalizeHeader($alias), $normalizedHeaders, true); + if ($index !== false) { + break; + } + } + if ($index !== false) { + $columns[$field] = (int) $index; + } + } + + $missing = []; + if (! array_key_exists('txn_date', $columns)) { + $missing[] = '日期'; + } + if ($fixedAccountShort === '' && ! array_key_exists('account_short', $columns)) { + $missing[] = '账户简称'; + } + if (! array_key_exists('detail', $columns)) { + $missing[] = '明细'; + } + if (! array_key_exists('income', $columns) && ! array_key_exists('expense', $columns)) { + $missing[] = '收入或支出'; + } + if ($missing !== []) { + throw ValidationException::withMessages([ + 'import' => '模板缺少必要列:' . implode('、', $missing) . '。请重新下载系统模板。', + ]); + } + + return $columns; + } + + /** + * @param array{row:int,cells:list} $rawRow + * @param array $columns + * @param array $accountLookup + * @return array|null + */ + private function normalizeRow( + array $rawRow, + array $columns, + string $fixedAccountShort, + array $accountLookup, + string $openingDate, + string $sourceHash, + ): ?array { + $cells = $rawRow['cells']; + $sourceRow = (int) $rawRow['row']; + $value = static fn (string $field): string => ( + isset($columns[$field]) && is_scalar($cells[$columns[$field]] ?? null) + ) ? trim((string) $cells[$columns[$field]]) : ''; + + if ($this->rowIsEmpty($cells)) { + return null; + } + + $rowKey = hash( + 'sha256', + FinanceLedgerTransactionWriter::MANUAL_SOURCE . ':import:' . $sourceHash . ':' . $sourceRow, + ); + $errors = []; + $date = $this->normalizeDate($value('txn_date')); + if ($date === null) { + $errors[] = '日期必须使用 YYYY-MM-DD 格式。'; + $date = ''; + } + + $rawAccount = $this->normalizeText($value('account_short')); + if ($fixedAccountShort !== '') { + if ($rawAccount !== '' && $rawAccount !== $fixedAccountShort) { + $errors[] = '当前页面只能导入账户“' . $fixedAccountShort . '”。'; + } + $accountShort = $fixedAccountShort; + } else { + $accountShort = $rawAccount; + if ($accountShort === '') { + $errors[] = '账户简称不能为空。'; + } elseif (mb_strlen($accountShort) > 100) { + $errors[] = '账户简称不能超过 100 个字符。'; + } elseif (! isset($accountLookup[$accountShort])) { + $errors[] = '账户简称“' . $accountShort . '”不在账户总表中。'; + } + } + + if ($date !== '' && $fixedAccountShort === '' + && ! FinanceLedgerIndependentAccounts::contains($accountShort) + && $date < $openingDate) { + $errors[] = '非独立账单日期不得早于台账期初日期 ' . $openingDate . '。'; + } elseif ($date !== '' && $fixedAccountShort !== '' + && ! FinanceLedgerIndependentAccounts::contains($fixedAccountShort) + && $date < $openingDate) { + $errors[] = '非独立账单日期不得早于台账期初日期 ' . $openingDate . '。'; + } + + $counterpartyInfo = $this->normalizeText($value('counterparty_info')); + if (mb_strlen($counterpartyInfo) > 255) { + $errors[] = '对方信息不能超过 255 个字符。'; + } + $detail = $this->normalizeText($value('detail')); + if ($detail === '') { + $errors[] = '明细不能为空。'; + } elseif (mb_strlen($detail) > 4000) { + $errors[] = '明细不能超过 4000 个字符。'; + } + $paymentRemark = $this->normalizeText($value('payment_remark')); + if (mb_strlen($paymentRemark) > 500) { + $errors[] = '付款备注不能超过 500 个字符。'; + } + + $incomeCents = $this->parseMoney($value('income')); + $expenseCents = $this->parseMoney($value('expense')); + if ($incomeCents === false) { + $errors[] = '收入金额格式不正确。'; + $incomeCents = 0; + } + if ($expenseCents === false) { + $errors[] = '支出金额格式不正确。'; + $expenseCents = 0; + } + $incomeCents ??= 0; + $expenseCents ??= 0; + if ($incomeCents < 0) { + $errors[] = '收入金额不能为负数。'; + } + if ($expenseCents < 0) { + $errors[] = '支出金额不能为负数。'; + } + if (($incomeCents > 0) === ($expenseCents > 0)) { + $errors[] = '每行收入和支出必须且只能填写一项。'; + } + + $balanceRaw = $value('balance'); + $balanceCents = $balanceRaw === '' ? null : $this->parseMoney($balanceRaw); + if ($balanceCents === false) { + $errors[] = '余额格式不正确。'; + $balanceCents = null; + } + foreach ([ + '收入' => $incomeCents, + '支出' => $expenseCents, + '余额' => $balanceCents, + ] as $label => $cents) { + if ($cents !== null && abs((int) $cents) > 999999999999999999) { + $errors[] = $label . '金额超出允许范围。'; + } + } + + $approvalNo = $this->normalizeText($value('approval_no')); + if (mb_strlen($approvalNo) > 100) { + $errors[] = '审批编号/业务单号不能超过 100 个字符。'; + } + if ($approvalNo === '') { + $approvalNo = 'IMP-' . str_replace('-', '', $date !== '' ? $date : now()->toDateString()) + . '-' . strtoupper(substr($rowKey, 0, 6)); + } + + $income = $incomeCents / 100; + $expense = $expenseCents / 100; + $balance = $balanceCents === null ? null : $balanceCents / 100; + $fingerprint = $this->fingerprint( + $date, + $accountShort, + $counterpartyInfo, + $incomeCents, + $expenseCents, + $balanceCents, + $paymentRemark, + $detail, + ); + + return [ + 'source_row' => $sourceRow, + 'row_key' => $rowKey, + 'txn_date' => $date, + 'account_short' => $accountShort, + 'counterparty_info' => $counterpartyInfo !== '' ? $counterpartyInfo : null, + 'detail' => $detail, + 'income_cents' => $incomeCents, + 'expense_cents' => $expenseCents, + 'income' => $income, + 'expense' => $expense, + 'balance_cents' => $balanceCents, + 'balance' => $balance, + 'approval_no' => $approvalNo, + 'payment_remark' => $paymentRemark !== '' ? $paymentRemark : null, + 'fingerprint' => $fingerprint, + 'errors' => array_values(array_unique($errors)), + ]; + } + + /** + * @param list $dates + * @return array + */ + private function existingFingerprints(array $dates, string $fixedAccountShort): array + { + $dates = array_values(array_filter($dates)); + if ($dates === []) { + return []; + } + + $query = $this->connection->table('fin_transactions') + ->whereIn('txn_date', $dates) + ->whereNull('deleted_at'); + if ($fixedAccountShort !== '') { + $query->where('account_short', $fixedAccountShort); + } + + $fingerprints = []; + foreach ($query->get([ + 'txn_date', + 'account_short', + 'counterparty_info', + 'income', + 'expense', + 'balance', + 'payment_remark', + 'detail', + ]) as $row) { + $fingerprints[$this->fingerprint( + substr((string) $row->txn_date, 0, 10), + trim((string) ($row->account_short ?? '')), + $this->normalizeText($row->counterparty_info), + (int) round((float) $row->income * 100), + (int) round((float) $row->expense * 100), + $row->balance === null ? null : (int) round((float) $row->balance * 100), + $this->normalizeText($row->payment_remark), + $this->normalizeText($row->detail), + )] = true; + } + + return $fingerprints; + } + + private function fingerprint( + string $date, + string $accountShort, + string $counterpartyInfo, + int $incomeCents, + int $expenseCents, + ?int $balanceCents, + string $paymentRemark, + string $detail, + ): string { + return hash('sha256', implode("\0", [ + $date, + $accountShort, + $counterpartyInfo, + (string) $incomeCents, + (string) $expenseCents, + $balanceCents === null ? 'null' : (string) $balanceCents, + $paymentRemark, + $detail, + ])); + } + + private function normalizeDate(mixed $value): ?string + { + $text = trim((string) $value); + if ($text === '') { + return null; + } + if (is_numeric($text) && (float) $text >= 1 && (float) $text <= 2958465) { + try { + return CarbonImmutable::instance(ExcelDate::excelToDateTimeObject((float) $text)) + ->format('Y-m-d'); + } catch (Throwable) { + return null; + } + } + if (preg_match('/^(\d{4})[年\/.-](\d{1,2})[月\/.-](\d{1,2})日?(?:\s|$)/u', $text, $matches) === 1) { + $year = (int) $matches[1]; + $month = (int) $matches[2]; + $day = (int) $matches[3]; + } elseif (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{4})(?:\s|$)/', $text, $matches) === 1) { + $month = (int) $matches[1]; + $day = (int) $matches[2]; + $year = (int) $matches[3]; + } else { + return null; + } + if (! checkdate($month, $day, $year)) { + return null; + } + + return sprintf('%04d-%02d-%02d', $year, $month, $day); + } + + /** + * @return int|false|null + */ + private function parseMoney(mixed $value): int|false|null + { + $text = trim((string) $value); + if ($text === '') { + return null; + } + $negative = str_starts_with($text, '(') && str_ends_with($text, ')'); + $text = str_replace( + [',', ',', '¥', '¥', '元', ' ', "\u{00A0}"], + '', + $negative ? substr($text, 1, -1) : $text, + ); + if (! is_numeric($text)) { + return false; + } + $amount = (float) $text; + if ($negative) { + $amount *= -1; + } + + return (int) round($amount * 100); + } + + private function amountFromCents(int $cents): float + { + return round($cents / 100, 2); + } + + private function money(int $cents): string + { + return number_format($cents / 100, 2, '.', ''); + } + + private function normalizeText(mixed $value): string + { + $text = trim((string) ($value ?? '')); + + return preg_replace('/\s+/u', ' ', $text) ?? $text; + } + + private function normalizeHeader(mixed $value): string + { + $text = $this->normalizeText($value); + $text = str_replace(['(', ')'], ['(', ')'], $text); + + return mb_strtolower((string) preg_replace('/[\s::]+/u', '', $text)); + } + + private function normalizeCsvText(mixed $value): string + { + $text = (string) ($value ?? ''); + if (str_starts_with($text, "\xEF\xBB\xBF")) { + $text = substr($text, 3); + } + if (! mb_check_encoding($text, 'UTF-8')) { + $text = mb_convert_encoding($text, 'UTF-8', 'GB18030'); + } + + return $text; + } + + private function detectDelimiter(string $line): string + { + $delimiters = [',' => substr_count($line, ','), "\t" => substr_count($line, "\t"), ';' => substr_count($line, ';')]; + arsort($delimiters); + + return (string) array_key_first($delimiters); + } + + /** @param list $cells */ + private function rowIsEmpty(array $cells): bool + { + foreach ($cells as $cell) { + if (trim((string) (is_scalar($cell) ? $cell : '')) !== '') { + return false; + } + } + + return true; + } + + /** + * @param list $cells + */ + private function headerScore(array $cells, string $fixedAccountShort): int + { + try { + return count($this->mapHeaders($cells, $fixedAccountShort)); + } catch (ValidationException) { + return 0; + } + } +} diff --git a/resources/views/business/pages/financial-ledger/ledger.blade.php b/resources/views/business/pages/financial-ledger/ledger.blade.php index cce81470..803c1a15 100644 --- a/resources/views/business/pages/financial-ledger/ledger.blade.php +++ b/resources/views/business/pages/financial-ledger/ledger.blade.php @@ -826,11 +826,36 @@ .ledger-row-edit { display:inline-grid; place-items:center; width:1.55rem; height:1.55rem; margin-left:.3rem; padding:0; border:1px solid var(--vip-border, #D8D2C7); border-radius:.3rem; background:#fff; color:var(--vip-content-accent-dark, #856632); cursor:pointer; vertical-align:middle; } .ledger-row-edit:hover, .ledger-row-edit:focus-visible { border-color:var(--vip-content-accent-dark, #856632); background:var(--vip-content-accent-soft, #F7F0DE); outline:none; } .ledger-row-edit .material-icons-outlined { font-size:.95rem; } - .ledger-transaction-approval-actions { display:flex; align-items:center; gap:.3rem; min-width:8.5rem; } - .ledger-transaction-approval-actions > span { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } + .ledger-transaction-approval-text { display:block; max-width:18rem; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } + .ledger-transaction-actions { display:flex; align-items:center; gap:.25rem; min-width:4.8rem; white-space:nowrap; } + .ledger-transaction-actions .ledger-row-edit { margin-left:0; } .ledger-row-edit.is-delete { color:var(--vip-danger, #B80000); } .ledger-row-edit.is-delete:hover, .ledger-row-edit.is-delete:focus-visible { border-color:var(--vip-danger, #B80000); background:#fff5f5; } .ledger-row-edit--text { display:inline-flex; width:auto; min-width:4.8rem; gap:.2rem; padding:0 .45rem; color:var(--vip-content-accent-dark, #856632); font-size:.68rem; font-weight:600; text-decoration:none; white-space:nowrap; } + .ledger-import-dialog { width:min(72rem, calc(100vw - 2rem)); } + .ledger-import-dialog .ledger-company-form__body { display:block; } + .ledger-import-dialog [hidden] { display:none !important; } + .ledger-import-dialog__lead { margin:0 0 .8rem; color:var(--vip-content-muted, #666); font-size:.78rem; line-height:1.65; } + .ledger-import-dialog__upload { display:flex; flex-wrap:wrap; align-items:end; gap:.7rem; padding:.8rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.5rem; background:#fbfaf7; } + .ledger-import-dialog__field { display:grid; flex:1 1 24rem; gap:.35rem; } + .ledger-import-dialog__field label { color:var(--vip-content-ink, #171717); font-size:.74rem; font-weight:700; } + .ledger-import-dialog__field input[type="file"] { min-height:2.2rem; padding:.35rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.35rem; background:#fff; font:inherit; font-size:.74rem; } + .ledger-import-dialog__upload-actions { display:flex; flex-wrap:wrap; gap:.45rem; } + .ledger-import-dialog__stats { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:.55rem; margin:.85rem 0; } + .ledger-import-dialog__stat { padding:.6rem .7rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.45rem; background:#fbfaf7; } + .ledger-import-dialog__stat span { display:block; color:var(--vip-content-muted, #666); font-size:.66rem; } + .ledger-import-dialog__stat strong { display:block; margin-top:.18rem; color:var(--vip-content-ink, #171717); font-size:1.05rem; } + .ledger-import-dialog__preview { max-height:min(45vh, 28rem); overflow:auto; border:1px solid var(--vip-border, #D8D2C7); border-radius:.45rem; } + .ledger-import-dialog__preview table { margin:0; } + .ledger-import-dialog__preview th { position:sticky; top:0; z-index:1; } + .ledger-import-dialog__status { display:inline-flex; align-items:center; min-height:1.35rem; padding:0 .4rem; border-radius:999px; background:#edf7ee; color:#247335; font-size:.66rem; font-weight:700; white-space:nowrap; } + .ledger-import-dialog__status.is-duplicate { background:#f7f0de; color:#856632; } + .ledger-import-dialog__status.is-invalid { background:#fff0f0; color:#b80000; } + .ledger-import-dialog__messages { margin:.3rem 0 0; padding-left:1rem; color:#8a3030; font-size:.65rem; line-height:1.5; } + .ledger-import-dialog__empty { padding:1rem; color:var(--vip-content-muted, #666); font-size:.76rem; text-align:center; } + .ledger-import-dialog__error { margin:.65rem 0 0; padding:.55rem .65rem; border:1px solid #e5b7b7; border-radius:.4rem; background:#fff5f5; color:#9f1717; font-size:.74rem; } + .ledger-import-dialog__hint { margin:.55rem 0 0; color:var(--vip-content-muted, #666); font-size:.68rem; } + @media (max-width:760px) { .ledger-import-dialog__stats { grid-template-columns:repeat(2,minmax(0,1fr)); } } #ledger-flow-date-edit:not([readonly]) { border-color:var(--vip-content-accent, #B9954F); background:#fffdf7; } #ledger-flow-date-edit:not([readonly]):focus { border-color:var(--vip-content-accent-dark, #856632); outline:none; box-shadow:0 0 0 3px rgba(133,102,50,.16); } .ledger-manual-badge { display:inline-flex; margin-left:.25rem; padding:.08rem .28rem; border-radius:.25rem; background:#fff8eb; color:var(--vip-warning, #935F07); font-size:.58rem; font-weight:700; vertical-align:middle; } @@ -1937,7 +1962,7 @@ {{-- 动账明细 --}} -