feat: 动账明细支持手工导入并拆分行操作列 (#1226)
Co-authored-by: 92451 <924518135@qq.com> Co-committed-by: 92451 <924518135@qq.com>
This commit is contained in:
parent
bd3532e140
commit
ceac04e1e0
@ -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,
|
||||
|
||||
@ -0,0 +1,964 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use App\Utilities\FinanceLedgerIndependentAccounts;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
|
||||
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Alignment;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Border;
|
||||
use PhpOffice\PhpSpreadsheet\Style\Fill;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
class FinanceLedgerManualTransactionImporter
|
||||
{
|
||||
private const MAX_ROWS = 2000;
|
||||
|
||||
private const PREVIEW_ROWS = 200;
|
||||
|
||||
private const HEADERS = [
|
||||
'txn_date' => '日期',
|
||||
'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<array<string,mixed>>,
|
||||
* plan:list<array<string,mixed>>,
|
||||
* 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<array<string,mixed>> $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<string>,1:list<array{row:int,cells:list<mixed>}>}
|
||||
*/
|
||||
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<string>,1:list<array{row:int,cells:list<mixed>}>}
|
||||
*/
|
||||
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<string>,1:list<array{row:int,cells:list<mixed>}>}
|
||||
*/
|
||||
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<mixed> $header
|
||||
* @return array<string,int>
|
||||
*/
|
||||
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<mixed>} $rawRow
|
||||
* @param array<string,int> $columns
|
||||
* @param array<string,true> $accountLookup
|
||||
* @return array<string,mixed>|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<string> $dates
|
||||
* @return array<string,true>
|
||||
*/
|
||||
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<mixed> $cells */
|
||||
private function rowIsEmpty(array $cells): bool
|
||||
{
|
||||
foreach ($cells as $cell) {
|
||||
if (trim((string) (is_scalar($cell) ? $cell : '')) !== '') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $cells
|
||||
*/
|
||||
private function headerScore(array $cells, string $fixedAccountShort): int
|
||||
{
|
||||
try {
|
||||
return count($this->mapHeaders($cells, $fixedAccountShort));
|
||||
} catch (ValidationException) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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 @@
|
||||
</section>
|
||||
|
||||
{{-- 动账明细 --}}
|
||||
<section class="ledger-panel" id="ledger-panel-transactions" role="tabpanel" data-ledger-panel="transactions" data-transaction-view="{{ $transactionView }}" data-transaction-view-account="{{ $transactionViewAccount }}" data-transaction-view-independent="{{ $transactionViewIsIndependent ? '1' : '0' }}" data-transaction-account-url-template="{{ route('business.financial-ledger.transactions.account.update', ['id' => '__TRANSACTION__']) }}" data-transaction-statement-update-url-template="{{ route('business.financial-ledger.transactions.statement.update', ['id' => '__TRANSACTION__']) }}" data-transaction-statement-delete-url-template="{{ route('business.financial-ledger.transactions.statement.delete', ['id' => '__TRANSACTION__']) }}" data-transaction-statement-insert-url-template="{{ route('business.financial-ledger.transactions.insert', ['id' => '__TRANSACTION__']) }}" data-transaction-column-storage-key="caiwu.financial-ledger.transactions.widths.v1.{{ auth()->id() }}.{{ company_id() }}" @if ($activeTab !== 'transactions') hidden @endif>
|
||||
<section class="ledger-panel" id="ledger-panel-transactions" role="tabpanel" data-ledger-panel="transactions" data-transaction-view="{{ $transactionView }}" data-transaction-view-account="{{ $transactionViewAccount }}" data-transaction-view-independent="{{ $transactionViewIsIndependent ? '1' : '0' }}" data-transaction-account-url-template="{{ route('business.financial-ledger.transactions.account.update', ['id' => '__TRANSACTION__']) }}" data-transaction-manual-update-url-template="{{ route('business.financial-ledger.transactions.manual.update', ['id' => '__TRANSACTION__']) }}" data-transaction-manual-delete-url-template="{{ route('business.financial-ledger.transactions.manual.delete', ['id' => '__TRANSACTION__']) }}" data-transaction-statement-update-url-template="{{ route('business.financial-ledger.transactions.statement.update', ['id' => '__TRANSACTION__']) }}" data-transaction-statement-delete-url-template="{{ route('business.financial-ledger.transactions.statement.delete', ['id' => '__TRANSACTION__']) }}" data-transaction-statement-insert-url-template="{{ route('business.financial-ledger.transactions.insert', ['id' => '__TRANSACTION__']) }}" data-transaction-column-storage-key="caiwu.financial-ledger.transactions.widths.v1.{{ auth()->id() }}.{{ company_id() }}" @if ($activeTab !== 'transactions') hidden @endif>
|
||||
<nav class="ledger-subtabbar" role="tablist" aria-label="动账明细分页">
|
||||
@foreach ($transactionViews as $viewKey => $view)
|
||||
@continue($viewKey !== 'all')
|
||||
@ -1996,6 +2021,9 @@
|
||||
'preserve' => $ledgerHeaderPreserve['transactions'],
|
||||
])
|
||||
@endforeach
|
||||
@if ($canEditTransactions)
|
||||
<th scope="col" class="ledger-action-column" data-ledger-action-column>操作</th>
|
||||
@endif
|
||||
@foreach ($transactionCustomFields as $customField)
|
||||
<th scope="col" class="ledger-custom-column" data-ledger-header-field="custom-{{ $customField['field_key'] }}" data-custom-field-key="{{ $customField['field_key'] }}">
|
||||
<div class="ledger-custom-column-head">
|
||||
@ -2028,6 +2056,10 @@
|
||||
<span class="material-icons-outlined" aria-hidden="true">view_column</span>
|
||||
新增自定义列
|
||||
</button>
|
||||
<button class="ledger-manual-trigger" type="button" data-ledger-transaction-import-trigger>
|
||||
<span class="material-icons-outlined" aria-hidden="true">upload_file</span>
|
||||
导入
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="ledger-manual-draft" data-ledger-manual-draft hidden>
|
||||
@ -2099,20 +2131,22 @@
|
||||
<td class="wrap">{{ $row->payment_remark }}</td>
|
||||
<td class="wrap">{{ $row->detail }}</td>
|
||||
<td><span class="ledger-source-tag">{{ $sourceLabels[$row->source] ?? $row->source }}</span></td>
|
||||
<td>
|
||||
<div class="ledger-transaction-approval-actions">
|
||||
<span title="{{ $row->approval_no }}">{{ $row->approval_no }}</span>
|
||||
@if ($canEditTransactions && $row->source === 'internal_transfer')
|
||||
<button class="ledger-row-edit is-delete" type="button" title="删除整笔内部转账" aria-label="删除内部转账 {{ $row->approval_no }}" data-ledger-internal-transfer-delete data-url="{{ route('business.financial-ledger.transfers.internal.delete', ['id' => $row->id]) }}"><span class="material-icons-outlined" aria-hidden="true">delete</span></button>
|
||||
@elseif ($canEditTransactions && ($row->source === 'manual' || $transactionViewIsIndependent))
|
||||
@if ($transactionViewIsIndependent)
|
||||
<button class="ledger-row-edit ledger-row-insert" type="button" title="在此行附近插入明细" aria-label="在此行附近插入明细 {{ $row->approval_no }}" data-ledger-excel-row-trigger><span class="material-icons-outlined" aria-hidden="true">playlist_add</span></button>
|
||||
<td><span class="ledger-transaction-approval-text" title="{{ $row->approval_no }}">{{ $row->approval_no }}</span></td>
|
||||
@if ($canEditTransactions)
|
||||
<td>
|
||||
<div class="ledger-transaction-actions">
|
||||
@if ($row->source === 'internal_transfer')
|
||||
<button class="ledger-row-edit is-delete" type="button" title="删除整笔内部转账" aria-label="删除内部转账 {{ $row->approval_no }}" data-ledger-internal-transfer-delete data-url="{{ route('business.financial-ledger.transfers.internal.delete', ['id' => $row->id]) }}"><span class="material-icons-outlined" aria-hidden="true">delete</span></button>
|
||||
@elseif ($row->source === 'manual' || $transactionViewIsIndependent)
|
||||
@if ($transactionViewIsIndependent)
|
||||
<button class="ledger-row-edit ledger-row-insert" type="button" title="在此行附近插入明细" aria-label="在此行附近插入明细 {{ $row->approval_no }}" data-ledger-excel-row-trigger><span class="material-icons-outlined" aria-hidden="true">playlist_add</span></button>
|
||||
@endif
|
||||
<button class="ledger-row-edit" type="button" title="编辑明细" aria-label="编辑明细 {{ $row->approval_no }}" data-ledger-manual-edit><span class="material-icons-outlined" aria-hidden="true">edit</span></button>
|
||||
<button class="ledger-row-edit is-delete" type="button" title="删除明细" aria-label="删除明细 {{ $row->approval_no }}" data-ledger-manual-delete><span class="material-icons-outlined" aria-hidden="true">delete</span></button>
|
||||
@endif
|
||||
<button class="ledger-row-edit" type="button" title="编辑明细" aria-label="编辑明细 {{ $row->approval_no }}" data-ledger-manual-edit><span class="material-icons-outlined" aria-hidden="true">edit</span></button>
|
||||
<button class="ledger-row-edit is-delete" type="button" title="删除明细" aria-label="删除明细 {{ $row->approval_no }}" data-ledger-manual-delete><span class="material-icons-outlined" aria-hidden="true">delete</span></button>
|
||||
@endif
|
||||
</div>
|
||||
</td>
|
||||
</div>
|
||||
</td>
|
||||
@endif
|
||||
@foreach ($transactionCustomFields as $customField)
|
||||
<td class="wrap" data-custom-field-key="{{ $customField['field_key'] }}">{{ $row->custom_values[$customField['field_key']] ?? '' }}</td>
|
||||
@endforeach
|
||||
@ -2400,6 +2434,66 @@
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
<dialog class="ledger-company-dialog ledger-import-dialog" data-ledger-transaction-import-dialog aria-labelledby="ledger-transaction-import-title">
|
||||
<div class="ledger-company-form"
|
||||
data-ledger-transaction-import-preview-url="{{ route('business.financial-ledger.transactions.import.preview') }}"
|
||||
data-ledger-transaction-import-commit-url="{{ route('business.financial-ledger.transactions.import.commit') }}"
|
||||
data-ledger-transaction-import-template-url="{{ route('business.financial-ledger.transactions.import.template') }}">
|
||||
<header class="ledger-company-form__header">
|
||||
<div>
|
||||
<h3 class="ledger-company-form__title" id="ledger-transaction-import-title">导入手工动账明细</h3>
|
||||
<p class="ledger-company-form__help">按模板补充动账数据。系统会先逐行校验并显示重复与错误,确认前不会写入任何数据。</p>
|
||||
</div>
|
||||
<button class="ledger-company-form__close" type="button" aria-label="关闭导入手工动账明细" data-ledger-transaction-import-close><span class="material-icons-outlined" aria-hidden="true">close</span></button>
|
||||
</header>
|
||||
<div class="ledger-company-form__body">
|
||||
<p class="ledger-import-dialog__lead">只支持 xlsx、xls、csv,单文件不超过 10MB、最多 2,000 条。账户简称必须与账户总表一致;每行只能填写收入或支出其中一项。</p>
|
||||
<div class="ledger-import-dialog__upload">
|
||||
<div class="ledger-import-dialog__field">
|
||||
<label for="ledger-transaction-import-file">选择导入文件</label>
|
||||
<input id="ledger-transaction-import-file" type="file" accept=".xlsx,.xls,.csv" data-ledger-transaction-import-file>
|
||||
</div>
|
||||
<div class="ledger-import-dialog__upload-actions">
|
||||
<a class="ledger-btn" href="#" data-ledger-transaction-import-template><span class="material-icons-outlined" aria-hidden="true">download</span>下载模板</a>
|
||||
<button class="ledger-btn primary" type="button" data-ledger-transaction-import-preview><span class="material-icons-outlined" aria-hidden="true">preview</span>上传并预览</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="ledger-import-dialog__hint" data-ledger-transaction-import-file-name hidden></p>
|
||||
<div class="ledger-import-dialog__stats" data-ledger-transaction-import-stats hidden>
|
||||
<div class="ledger-import-dialog__stat"><span>文件数据</span><strong data-ledger-transaction-import-total>0</strong></div>
|
||||
<div class="ledger-import-dialog__stat"><span>可导入</span><strong data-ledger-transaction-import-valid>0</strong></div>
|
||||
<div class="ledger-import-dialog__stat"><span>重复跳过</span><strong data-ledger-transaction-import-duplicate>0</strong></div>
|
||||
<div class="ledger-import-dialog__stat"><span>需修正</span><strong data-ledger-transaction-import-invalid>0</strong></div>
|
||||
</div>
|
||||
<div class="ledger-import-dialog__preview" data-ledger-transaction-import-preview-wrap hidden>
|
||||
<table class="ledger-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>行号</th>
|
||||
<th>日期</th>
|
||||
<th>账户简称</th>
|
||||
<th>对方信息</th>
|
||||
<th class="num">收入</th>
|
||||
<th class="num">支出</th>
|
||||
<th class="num">余额</th>
|
||||
<th>付款备注</th>
|
||||
<th>明细</th>
|
||||
<th>审批编号/业务单号</th>
|
||||
<th>校验结果</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-ledger-transaction-import-preview-body></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="ledger-import-dialog__hint" data-ledger-transaction-import-truncated hidden></p>
|
||||
<p class="ledger-import-dialog__error" role="alert" data-ledger-transaction-import-error hidden></p>
|
||||
</div>
|
||||
<footer class="ledger-company-form__footer">
|
||||
<button class="ledger-btn" type="button" data-ledger-transaction-import-cancel>取消</button>
|
||||
<button class="ledger-btn primary" type="button" data-ledger-transaction-import-commit disabled><span class="material-icons-outlined" aria-hidden="true">save</span>确认导入</button>
|
||||
</footer>
|
||||
</div>
|
||||
</dialog>
|
||||
@endif
|
||||
|
||||
<div class="ledger-excel-insert-menu" data-ledger-excel-insert-menu role="dialog" aria-modal="false" aria-label="插入" hidden>
|
||||
@ -3058,6 +3152,8 @@
|
||||
const manualTransactionDraft = page.querySelector('[data-ledger-manual-draft]');
|
||||
const manualTransactionForm = page.querySelector('[data-ledger-manual-form]');
|
||||
const transactionAccountUrlTemplate = page.querySelector('#ledger-panel-transactions')?.dataset.transactionAccountUrlTemplate || '';
|
||||
const transactionManualUpdateUrlTemplate = page.querySelector('#ledger-panel-transactions')?.dataset.transactionManualUpdateUrlTemplate || '';
|
||||
const transactionManualDeleteUrlTemplate = page.querySelector('#ledger-panel-transactions')?.dataset.transactionManualDeleteUrlTemplate || '';
|
||||
const transactionStatementUpdateUrlTemplate = page.querySelector('#ledger-panel-transactions')?.dataset.transactionStatementUpdateUrlTemplate || '';
|
||||
const transactionStatementDeleteUrlTemplate = page.querySelector('#ledger-panel-transactions')?.dataset.transactionStatementDeleteUrlTemplate || '';
|
||||
const transactionStatementInsertUrlTemplate = page.querySelector('#ledger-panel-transactions')?.dataset.transactionStatementInsertUrlTemplate || '';
|
||||
@ -3260,12 +3356,19 @@
|
||||
tableRow.dataset.transactionId = String(row.id);
|
||||
tableRow.dataset.source = row.source;
|
||||
tableRow.dataset.approvalNo = row.approval_no || '';
|
||||
if (independent) {
|
||||
const editableManual = independent || row.source === 'manual';
|
||||
if (editableManual) {
|
||||
tableRow.dataset.ledgerManualRow = '';
|
||||
tableRow.dataset.editableIndependent = '1';
|
||||
tableRow.dataset.updateUrl = transactionStatementUpdateUrlTemplate.replace('__TRANSACTION__', encodeURIComponent(String(row.id)));
|
||||
tableRow.dataset.deleteUrl = transactionStatementDeleteUrlTemplate.replace('__TRANSACTION__', encodeURIComponent(String(row.id)));
|
||||
tableRow.dataset.insertUrl = transactionStatementInsertUrlTemplate.replace('__TRANSACTION__', encodeURIComponent(String(row.id)));
|
||||
tableRow.dataset.editableIndependent = independent ? '1' : '0';
|
||||
tableRow.dataset.updateUrl = (
|
||||
independent ? transactionStatementUpdateUrlTemplate : transactionManualUpdateUrlTemplate
|
||||
).replace('__TRANSACTION__', encodeURIComponent(String(row.id)));
|
||||
tableRow.dataset.deleteUrl = (
|
||||
independent ? transactionStatementDeleteUrlTemplate : transactionManualDeleteUrlTemplate
|
||||
).replace('__TRANSACTION__', encodeURIComponent(String(row.id)));
|
||||
tableRow.dataset.insertUrl = independent
|
||||
? transactionStatementInsertUrlTemplate.replace('__TRANSACTION__', encodeURIComponent(String(row.id)))
|
||||
: '';
|
||||
tableRow.dataset.txnDate = row.txn_date || '';
|
||||
tableRow.dataset.accountShort = row.account_short || '';
|
||||
tableRow.dataset.counterpartyInfo = row.counterparty_info || '';
|
||||
@ -3308,13 +3411,17 @@
|
||||
sourceTag.textContent = row.source_label;
|
||||
sourceCell.appendChild(sourceTag);
|
||||
const approvalCell = addCell();
|
||||
const approvalActions = document.createElement('div');
|
||||
approvalActions.className = 'ledger-transaction-approval-actions';
|
||||
const approvalText = document.createElement('span');
|
||||
approvalText.className = 'ledger-transaction-approval-text';
|
||||
approvalText.textContent = row.approval_no || '';
|
||||
approvalText.title = row.approval_no || '';
|
||||
approvalActions.appendChild(approvalText);
|
||||
if (independent) {
|
||||
approvalCell.appendChild(approvalText);
|
||||
const actionsCell = addCell();
|
||||
const rowActions = document.createElement('div');
|
||||
rowActions.className = 'ledger-transaction-actions';
|
||||
actionsCell.appendChild(rowActions);
|
||||
if (editableManual) {
|
||||
if (independent) {
|
||||
const insertButton = document.createElement('button');
|
||||
insertButton.className = 'ledger-row-edit ledger-row-insert';
|
||||
insertButton.type = 'button';
|
||||
@ -3322,7 +3429,8 @@
|
||||
insertButton.title = '在此行附近插入明细';
|
||||
insertButton.setAttribute('aria-label', '在此行附近插入明细 ' + (row.approval_no || ''));
|
||||
insertButton.innerHTML = '<span class="material-icons-outlined" aria-hidden="true">playlist_add</span>';
|
||||
approvalActions.appendChild(insertButton);
|
||||
rowActions.appendChild(insertButton);
|
||||
}
|
||||
const editButton = document.createElement('button');
|
||||
editButton.className = 'ledger-row-edit';
|
||||
editButton.type = 'button';
|
||||
@ -3330,7 +3438,7 @@
|
||||
editButton.title = '编辑明细';
|
||||
editButton.setAttribute('aria-label', '编辑明细 ' + (row.approval_no || ''));
|
||||
editButton.innerHTML = '<span class="material-icons-outlined" aria-hidden="true">edit</span>';
|
||||
approvalActions.appendChild(editButton);
|
||||
rowActions.appendChild(editButton);
|
||||
const deleteButton = document.createElement('button');
|
||||
deleteButton.className = 'ledger-row-edit is-delete';
|
||||
deleteButton.type = 'button';
|
||||
@ -3338,7 +3446,7 @@
|
||||
deleteButton.title = '删除明细';
|
||||
deleteButton.setAttribute('aria-label', '删除明细 ' + (row.approval_no || ''));
|
||||
deleteButton.innerHTML = '<span class="material-icons-outlined" aria-hidden="true">delete</span>';
|
||||
approvalActions.appendChild(deleteButton);
|
||||
rowActions.appendChild(deleteButton);
|
||||
} else if (row.source === 'internal_transfer') {
|
||||
const deleteButton = document.createElement('button');
|
||||
deleteButton.className = 'ledger-row-edit is-delete';
|
||||
@ -3348,9 +3456,8 @@
|
||||
deleteButton.title = '删除整笔内部转账';
|
||||
deleteButton.setAttribute('aria-label', '删除内部转账 ' + (row.approval_no || ''));
|
||||
deleteButton.innerHTML = '<span class="material-icons-outlined" aria-hidden="true">delete</span>';
|
||||
approvalActions.appendChild(deleteButton);
|
||||
rowActions.appendChild(deleteButton);
|
||||
}
|
||||
approvalCell.appendChild(approvalActions);
|
||||
currentTransactionCustomFields().forEach((field) => addCell('').dataset.customFieldKey = field.field_key || '');
|
||||
|
||||
manualTransactionDraft.insertAdjacentElement('afterend', tableRow);
|
||||
@ -3602,6 +3709,231 @@
|
||||
});
|
||||
}
|
||||
|
||||
const manualImportDialog = page.querySelector('[data-ledger-transaction-import-dialog]');
|
||||
const manualImportTrigger = page.querySelector('[data-ledger-transaction-import-trigger]');
|
||||
if (manualImportDialog && manualImportTrigger) {
|
||||
const importPanel = manualImportDialog.querySelector('[data-ledger-transaction-import-preview-url]');
|
||||
const fileInput = manualImportDialog.querySelector('[data-ledger-transaction-import-file]');
|
||||
const templateLink = manualImportDialog.querySelector('[data-ledger-transaction-import-template]');
|
||||
const previewButton = manualImportDialog.querySelector('[data-ledger-transaction-import-preview]');
|
||||
const commitButton = manualImportDialog.querySelector('[data-ledger-transaction-import-commit]');
|
||||
const statsWrap = manualImportDialog.querySelector('[data-ledger-transaction-import-stats]');
|
||||
const previewWrap = manualImportDialog.querySelector('[data-ledger-transaction-import-preview-wrap]');
|
||||
const previewBody = manualImportDialog.querySelector('[data-ledger-transaction-import-preview-body]');
|
||||
const fileName = manualImportDialog.querySelector('[data-ledger-transaction-import-file-name]');
|
||||
const truncated = manualImportDialog.querySelector('[data-ledger-transaction-import-truncated]');
|
||||
const errorBox = manualImportDialog.querySelector('[data-ledger-transaction-import-error]');
|
||||
let previewToken = '';
|
||||
|
||||
const importUrl = (rawUrl) => {
|
||||
const target = new URL(rawUrl, window.location.origin);
|
||||
const current = new URL(window.location.href);
|
||||
current.searchParams.forEach((value, key) => target.searchParams.set(key, value));
|
||||
return target;
|
||||
};
|
||||
const showImportError = (message) => {
|
||||
if (!errorBox) return;
|
||||
errorBox.textContent = message || '';
|
||||
errorBox.hidden = !message;
|
||||
};
|
||||
const resetImportPreview = () => {
|
||||
previewToken = '';
|
||||
if (statsWrap) statsWrap.hidden = true;
|
||||
if (previewWrap) previewWrap.hidden = true;
|
||||
if (truncated) truncated.hidden = true;
|
||||
if (fileName) fileName.hidden = true;
|
||||
if (previewBody) previewBody.replaceChildren();
|
||||
if (commitButton) {
|
||||
commitButton.disabled = true;
|
||||
commitButton.innerHTML = '<span class="material-icons-outlined" aria-hidden="true">save</span>确认导入';
|
||||
}
|
||||
showImportError('');
|
||||
};
|
||||
const closeImportDialog = () => {
|
||||
if (manualImportDialog.open) manualImportDialog.close();
|
||||
};
|
||||
const appendTextCell = (row, value, className = '') => {
|
||||
const cell = document.createElement('td');
|
||||
cell.textContent = value || '';
|
||||
if (className) cell.className = className;
|
||||
row.appendChild(cell);
|
||||
return cell;
|
||||
};
|
||||
const renderImportRows = (rows) => {
|
||||
if (!previewBody) return;
|
||||
previewBody.replaceChildren();
|
||||
rows.forEach((item) => {
|
||||
const row = document.createElement('tr');
|
||||
appendTextCell(row, item.row_number);
|
||||
const display = item.display || {};
|
||||
appendTextCell(row, display.txn_date || '');
|
||||
appendTextCell(row, display.account_short || '');
|
||||
appendTextCell(row, display.counterparty_info || '', 'wrap');
|
||||
appendTextCell(row, display.income || '', 'num');
|
||||
appendTextCell(row, display.expense || '', 'num');
|
||||
appendTextCell(row, display.balance || '', 'num');
|
||||
appendTextCell(row, display.payment_remark || '', 'wrap');
|
||||
appendTextCell(row, display.detail || '', 'wrap');
|
||||
appendTextCell(row, display.approval_no || '');
|
||||
const resultCell = document.createElement('td');
|
||||
const status = document.createElement('span');
|
||||
status.className = 'ledger-import-dialog__status'
|
||||
+ (item.status === 'duplicate' ? ' is-duplicate' : '')
|
||||
+ (item.status === 'invalid' ? ' is-invalid' : '');
|
||||
status.textContent = item.status_label || '';
|
||||
resultCell.appendChild(status);
|
||||
if (Array.isArray(item.messages) && item.messages.length > 0) {
|
||||
const messages = document.createElement('ul');
|
||||
messages.className = 'ledger-import-dialog__messages';
|
||||
item.messages.forEach((message) => {
|
||||
const entry = document.createElement('li');
|
||||
entry.textContent = message;
|
||||
messages.appendChild(entry);
|
||||
});
|
||||
resultCell.appendChild(messages);
|
||||
}
|
||||
row.appendChild(resultCell);
|
||||
previewBody.appendChild(row);
|
||||
});
|
||||
};
|
||||
|
||||
manualImportTrigger.addEventListener('click', () => {
|
||||
if (templateLink && importPanel) {
|
||||
templateLink.href = importUrl(importPanel.dataset.ledgerTransactionImportTemplateUrl || '').toString();
|
||||
}
|
||||
if (fileInput) fileInput.value = '';
|
||||
resetImportPreview();
|
||||
manualImportDialog.showModal();
|
||||
fileInput?.focus();
|
||||
});
|
||||
manualImportDialog.querySelectorAll(
|
||||
'[data-ledger-transaction-import-close], [data-ledger-transaction-import-cancel]'
|
||||
).forEach((button) => button.addEventListener('click', closeImportDialog));
|
||||
manualImportDialog.addEventListener('click', (event) => {
|
||||
if (event.target === manualImportDialog) closeImportDialog();
|
||||
});
|
||||
fileInput?.addEventListener('change', resetImportPreview);
|
||||
|
||||
previewButton?.addEventListener('click', async () => {
|
||||
const file = fileInput?.files?.[0];
|
||||
if (!file) {
|
||||
showImportError('请先选择要导入的 Excel 或 CSV 文件。');
|
||||
fileInput?.focus();
|
||||
return;
|
||||
}
|
||||
resetImportPreview();
|
||||
const previewUrl = importPanel
|
||||
? importUrl(importPanel.dataset.ledgerTransactionImportPreviewUrl || '').toString()
|
||||
: '';
|
||||
if (!previewUrl) {
|
||||
showImportError('导入预览地址不可用,请刷新页面后重试。');
|
||||
return;
|
||||
}
|
||||
|
||||
const originalLabel = previewButton.innerHTML;
|
||||
previewButton.disabled = true;
|
||||
previewButton.textContent = '正在校验…';
|
||||
manualImportDialog.setAttribute('aria-busy', 'true');
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('import', file);
|
||||
const response = await fetch(previewUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-CSRF-TOKEN': ledgerCsrfToken,
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const firstError = Object.values(payload.errors || {})[0]?.[0];
|
||||
throw new Error(firstError || payload.message || '导入文件预览失败');
|
||||
}
|
||||
|
||||
previewToken = payload.preview_token || '';
|
||||
const stats = payload.stats || {};
|
||||
manualImportDialog.querySelector('[data-ledger-transaction-import-total]').textContent =
|
||||
Number(stats.total || 0).toLocaleString('zh-CN');
|
||||
manualImportDialog.querySelector('[data-ledger-transaction-import-valid]').textContent =
|
||||
Number(stats.valid || 0).toLocaleString('zh-CN');
|
||||
manualImportDialog.querySelector('[data-ledger-transaction-import-duplicate]').textContent =
|
||||
Number(stats.duplicate || 0).toLocaleString('zh-CN');
|
||||
manualImportDialog.querySelector('[data-ledger-transaction-import-invalid]').textContent =
|
||||
Number(stats.invalid || 0).toLocaleString('zh-CN');
|
||||
if (statsWrap) statsWrap.hidden = false;
|
||||
if (fileName) {
|
||||
fileName.textContent = '已校验:' + (payload.file_name || file.name);
|
||||
fileName.hidden = false;
|
||||
}
|
||||
renderImportRows(payload.rows || []);
|
||||
if (previewWrap) previewWrap.hidden = false;
|
||||
if (truncated) {
|
||||
truncated.textContent = payload.truncated
|
||||
? '当前仅展示前 200 行,确认时会按全部已校验的有效行导入。'
|
||||
: '';
|
||||
truncated.hidden = !payload.truncated;
|
||||
}
|
||||
const validCount = Number(stats.valid || 0);
|
||||
if (commitButton) {
|
||||
commitButton.disabled = validCount === 0 || previewToken === '';
|
||||
commitButton.innerHTML = '<span class="material-icons-outlined" aria-hidden="true">save</span>'
|
||||
+ '确认导入 ' + validCount.toLocaleString('zh-CN') + ' 条';
|
||||
}
|
||||
} catch (error) {
|
||||
showImportError(error.message || '导入文件预览失败');
|
||||
} finally {
|
||||
previewButton.disabled = false;
|
||||
previewButton.innerHTML = originalLabel;
|
||||
manualImportDialog.removeAttribute('aria-busy');
|
||||
}
|
||||
});
|
||||
|
||||
commitButton?.addEventListener('click', async () => {
|
||||
if (!previewToken || !importPanel) return;
|
||||
const commitUrl = importUrl(importPanel.dataset.ledgerTransactionImportCommitUrl || '').toString();
|
||||
if (!commitUrl) {
|
||||
showImportError('导入提交地址不可用,请刷新页面后重试。');
|
||||
return;
|
||||
}
|
||||
const originalLabel = commitButton.innerHTML;
|
||||
commitButton.disabled = true;
|
||||
commitButton.textContent = '正在导入…';
|
||||
manualImportDialog.setAttribute('aria-busy', 'true');
|
||||
try {
|
||||
const response = await fetch(commitUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': ledgerCsrfToken,
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify({ preview_token: previewToken }),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const firstError = Object.values(payload.errors || {})[0]?.[0];
|
||||
throw new Error(firstError || payload.message || '动账明细导入失败');
|
||||
}
|
||||
|
||||
previewToken = '';
|
||||
closeImportDialog();
|
||||
notify(payload.message || '动账明细导入完成');
|
||||
window.setTimeout(() => window.location.reload(), 700);
|
||||
} catch (error) {
|
||||
showImportError(error.message || '动账明细导入失败');
|
||||
commitButton.disabled = false;
|
||||
commitButton.innerHTML = originalLabel;
|
||||
} finally {
|
||||
manualImportDialog.removeAttribute('aria-busy');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const manualEditDialog = page.querySelector('[data-ledger-manual-edit-dialog]');
|
||||
const manualEditForm = page.querySelector('[data-ledger-manual-edit-form]');
|
||||
if (manualEditDialog && manualEditForm) {
|
||||
|
||||
@ -896,6 +896,18 @@ Route::post('workspace/financial-ledger/transactions/manual', [\App\Http\Control
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.manual');
|
||||
|
||||
Route::get('workspace/financial-ledger/transactions/import-template', [\App\Http\Controllers\Business\FinanceLedger::class, 'downloadManualTransactionImportTemplate'])
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.import.template');
|
||||
|
||||
Route::post('workspace/financial-ledger/transactions/import-preview', [\App\Http\Controllers\Business\FinanceLedger::class, 'previewManualTransactionImport'])
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.import.preview');
|
||||
|
||||
Route::post('workspace/financial-ledger/transactions/import-commit', [\App\Http\Controllers\Business\FinanceLedger::class, 'commitManualTransactionImport'])
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.import.commit');
|
||||
|
||||
Route::post('workspace/financial-ledger/transfers/internal', [\App\Http\Controllers\Business\FinanceLedger::class, 'storeInternalTransfer'])
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transfers.internal');
|
||||
|
||||
@ -0,0 +1,315 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Models\Auth\Permission;
|
||||
use App\Models\Auth\Role;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class FinanceLedgerManualTransactionImportTest extends FeatureTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Carbon::setTestNow('2026-11-18 12:00:00');
|
||||
|
||||
$this->user->attachPermission(
|
||||
Permission::where('name', 'read-admin-panel')->firstOrFail(),
|
||||
);
|
||||
|
||||
$connection = DB::connection('business_mirror');
|
||||
$connection->table('fin_accounts')->insert([
|
||||
[
|
||||
'company_name' => '导入测试公司',
|
||||
'account_short' => '导入测试账户甲',
|
||||
'account_type' => '公户',
|
||||
'current_balance' => 100,
|
||||
],
|
||||
[
|
||||
'company_name' => '导入测试公司',
|
||||
'account_short' => '导入测试账户乙',
|
||||
'account_type' => '公户',
|
||||
'current_balance' => 0,
|
||||
],
|
||||
]);
|
||||
$connection->table('fin_account_opening')->insert([
|
||||
[
|
||||
'account_short' => '导入测试账户甲',
|
||||
'opening_date' => '2026-10-17',
|
||||
'opening_balance' => 100,
|
||||
],
|
||||
[
|
||||
'account_short' => '导入测试账户乙',
|
||||
'opening_date' => '2026-10-17',
|
||||
'opening_balance' => 0,
|
||||
],
|
||||
]);
|
||||
$connection->table('fin_transactions')->insert([
|
||||
'txn_date' => '2026-11-16',
|
||||
'account_short' => '导入测试账户甲',
|
||||
'counterparty_info' => '既有对方',
|
||||
'detail' => '既有重复流水',
|
||||
'income' => 50,
|
||||
'expense' => 0,
|
||||
'balance' => 150,
|
||||
'payment_remark' => '既有备注',
|
||||
'approval_no' => 'EXISTING-1',
|
||||
'source' => 'wangshang-bank',
|
||||
'source_value' => 'EXISTING-SOURCE-1',
|
||||
'process_type' => '入账',
|
||||
'row_key' => 'manual-import-existing-duplicate',
|
||||
]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Carbon::setTestNow();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_transaction_page_places_import_after_custom_column_and_actions_after_approval(): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('fin_transactions')->insert([
|
||||
'txn_date' => '2026-11-17',
|
||||
'account_short' => '导入测试账户甲',
|
||||
'detail' => '可编辑手工明细',
|
||||
'income' => 10,
|
||||
'expense' => 0,
|
||||
'approval_no' => 'EDITABLE-1',
|
||||
'source' => 'manual',
|
||||
'process_type' => '手工录入',
|
||||
'row_key' => 'manual-import-action-column-row',
|
||||
]);
|
||||
|
||||
$html = $this->loginAs()->get($this->pageUrl())->assertOk()->getContent();
|
||||
$addColumn = strpos($html, 'data-ledger-statement-column-add');
|
||||
$import = strpos($html, 'data-ledger-transaction-import-trigger');
|
||||
$approvalHeader = strpos($html, 'data-ledger-header-field="approval_no"');
|
||||
$actionHeader = strpos($html, 'data-ledger-action-column');
|
||||
|
||||
$this->assertNotFalse($addColumn);
|
||||
$this->assertNotFalse($import);
|
||||
$this->assertNotFalse($approvalHeader);
|
||||
$this->assertNotFalse($actionHeader);
|
||||
$this->assertLessThan($import, $addColumn);
|
||||
$this->assertLessThan($actionHeader, $approvalHeader);
|
||||
$this->assertStringContainsString('data-ledger-transaction-import-dialog', $html);
|
||||
$this->assertStringContainsString('data-ledger-manual-edit', $html);
|
||||
$this->assertStringContainsString('data-ledger-manual-delete', $html);
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/<span class="ledger-transaction-approval-text"[^>]*>EDITABLE-1<\/span>\s*<\/td>\s*<td>\s*'
|
||||
. '<div class="ledger-transaction-actions">.*?data-ledger-manual-edit.*?data-ledger-manual-delete/s',
|
||||
$html,
|
||||
);
|
||||
}
|
||||
|
||||
public function test_import_template_downloads_with_required_columns(): void
|
||||
{
|
||||
$this->loginAs()->get($this->templateUrl())
|
||||
->assertOk()
|
||||
->assertDownload();
|
||||
}
|
||||
|
||||
public function test_downloaded_xlsx_template_can_be_filled_and_previewed(): void
|
||||
{
|
||||
$download = $this->loginAs()->get($this->templateUrl())->assertOk();
|
||||
$templatePath = tempnam(sys_get_temp_dir(), 'ledger-manual-import-template-');
|
||||
$uploadPath = tempnam(sys_get_temp_dir(), 'ledger-manual-import-upload-');
|
||||
file_put_contents($templatePath, $download->streamedContent());
|
||||
|
||||
try {
|
||||
$spreadsheet = IOFactory::load($templatePath);
|
||||
$spreadsheet->getSheetByName('动账明细')->fromArray([
|
||||
'2026-11-17',
|
||||
'导入测试账户乙',
|
||||
'Excel 对方',
|
||||
'66.66',
|
||||
'',
|
||||
'66.66',
|
||||
'Excel 备注',
|
||||
'Excel 模板导入',
|
||||
'XLSX-IMPORT-1',
|
||||
], null, 'A2');
|
||||
(new Xlsx($spreadsheet))->save($uploadPath);
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
|
||||
$this->loginAs()->post(
|
||||
$this->previewUrl(),
|
||||
[
|
||||
'import' => new UploadedFile(
|
||||
$uploadPath,
|
||||
'动账明细.xlsx',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
null,
|
||||
true,
|
||||
),
|
||||
],
|
||||
['Accept' => 'application/json'],
|
||||
)->assertOk()
|
||||
->assertJsonPath('stats.valid', 1)
|
||||
->assertJsonPath('rows.0.display.account_short', '导入测试账户乙')
|
||||
->assertJsonPath('rows.0.display.income', '66.66');
|
||||
} finally {
|
||||
@unlink($templatePath);
|
||||
@unlink($uploadPath);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_preview_reports_valid_duplicate_and_invalid_rows_without_writing(): void
|
||||
{
|
||||
$file = UploadedFile::fake()->createWithContent(
|
||||
'手工动账.csv',
|
||||
"\xEF\xBB\xBF" . implode("\n", [
|
||||
'日期,账户简称,对方信息,收入(元),支出(元),余额(元),付款备注,明细,审批编号/业务单号',
|
||||
'2026-11-17,导入测试账户甲,新对方,100.00,,200.00,新备注,可导入收入,IMP-NEW-1',
|
||||
'2026-11-16,导入测试账户甲,既有对方,50.00,,150.00,既有备注,既有重复流水,EXISTING-1',
|
||||
'2026-11-17,导入测试账户甲,错误方向,10.00,20.00,210.00,,收支同时填写,INVALID-1',
|
||||
'2026-11-17,不存在账户,未知账户,30.00,,, ,未知账户流水,INVALID-2',
|
||||
]) . "\n",
|
||||
);
|
||||
|
||||
$response = $this->loginAs()->post(
|
||||
$this->previewUrl(),
|
||||
['import' => $file],
|
||||
['Accept' => 'application/json'],
|
||||
);
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('stats.total', 4)
|
||||
->assertJsonPath('stats.valid', 1)
|
||||
->assertJsonPath('stats.duplicate', 1)
|
||||
->assertJsonPath('stats.invalid', 2)
|
||||
->assertJsonPath('rows.0.status', 'ready')
|
||||
->assertJsonPath('rows.1.status', 'duplicate')
|
||||
->assertJsonPath('rows.2.status', 'invalid')
|
||||
->assertJsonPath('rows.3.status', 'invalid');
|
||||
$this->assertNotEmpty($response->json('preview_token'));
|
||||
$this->assertSame(1, DB::connection('business_mirror')->table('fin_transactions')->count());
|
||||
}
|
||||
|
||||
public function test_commit_imports_only_ready_rows_recalculates_flows_and_consumes_token(): void
|
||||
{
|
||||
$csv = implode("\n", [
|
||||
'日期,账户简称,对方信息,收入(元),支出(元),余额(元),付款备注,明细,审批编号/业务单号',
|
||||
'2026-11-17,导入测试账户甲,客户甲,100.00,,250.00,首款,导入收入一,IMP-READY-1',
|
||||
'2026-11-18,导入测试账户甲,供应商乙,,30.00,220.00,尾款,导入支出一,IMP-READY-2',
|
||||
'2026-11-18,导入测试账户甲,错误行,10.00,20.00,,,同时填写,INVALID-COMMIT',
|
||||
]) . "\n";
|
||||
$preview = $this->loginAs()->post(
|
||||
$this->previewUrl(),
|
||||
['import' => UploadedFile::fake()->createWithContent('手工动账.csv', $csv)],
|
||||
['Accept' => 'application/json'],
|
||||
)->assertOk()
|
||||
->assertJsonPath('stats.valid', 2)
|
||||
->assertJsonPath('stats.invalid', 1);
|
||||
$token = (string) $preview->json('preview_token');
|
||||
|
||||
$this->loginAs()->postJson($this->commitUrl(), ['preview_token' => $token])
|
||||
->assertOk()
|
||||
->assertJsonPath('imported', 2)
|
||||
->assertJsonPath('duplicate_skipped', 0)
|
||||
->assertJsonPath('summary.count', 3);
|
||||
|
||||
$connection = DB::connection('business_mirror');
|
||||
$this->assertSame(2, $connection->table('fin_transactions')
|
||||
->where('process_type', '手工导入')
|
||||
->where('source', 'manual')
|
||||
->count());
|
||||
$this->assertDatabaseHas('fin_transactions', [
|
||||
'account_short' => '导入测试账户甲',
|
||||
'detail' => '导入收入一',
|
||||
'income' => 100,
|
||||
'approval_no' => 'IMP-READY-1',
|
||||
'created_by' => 'Test User',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_daily_flows', [
|
||||
'flow_date' => '2026-11-17',
|
||||
'account_short' => '导入测试账户甲',
|
||||
'inflow' => 100,
|
||||
'closing_balance' => 250,
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_ledger_edit_events', [
|
||||
'entity_type' => 'manual_transaction_import',
|
||||
'user_name' => 'Test User',
|
||||
], 'business_mirror');
|
||||
|
||||
$this->withExceptionHandling()->loginAs()->postJson(
|
||||
$this->commitUrl(),
|
||||
['preview_token' => $token],
|
||||
)->assertUnprocessable()->assertJsonValidationErrors('preview_token');
|
||||
|
||||
$this->loginAs()->post(
|
||||
$this->previewUrl(),
|
||||
['import' => UploadedFile::fake()->createWithContent('手工动账.csv', $csv)],
|
||||
['Accept' => 'application/json'],
|
||||
)->assertOk()
|
||||
->assertJsonPath('stats.valid', 0)
|
||||
->assertJsonPath('stats.duplicate', 2)
|
||||
->assertJsonPath('stats.invalid', 1);
|
||||
}
|
||||
|
||||
public function test_import_endpoints_require_transaction_edit_permission(): void
|
||||
{
|
||||
$viewer = user_model_class()::create([
|
||||
'name' => '动账导入只读用户',
|
||||
'email' => 'manual-import-viewer-' . uniqid() . '@example.com',
|
||||
'password' => 'local-test-password',
|
||||
'locale' => 'zh-CN',
|
||||
'enabled' => 1,
|
||||
'landing_page' => 'dashboard',
|
||||
'created_from' => 'core::test',
|
||||
]);
|
||||
$viewer->companies()->attach($this->company->id);
|
||||
$viewer->roles()->attach(Role::where('name', 'user')->firstOrFail()->id);
|
||||
$viewer->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||||
|
||||
$this->withExceptionHandling()->loginAs($viewer)
|
||||
->get($this->templateUrl())
|
||||
->assertForbidden();
|
||||
$this->withExceptionHandling()->loginAs($viewer)
|
||||
->post(
|
||||
$this->previewUrl(),
|
||||
['import' => UploadedFile::fake()->createWithContent('手工动账.csv', "日期\n2026-11-17\n")],
|
||||
['Accept' => 'application/json'],
|
||||
)
|
||||
->assertForbidden();
|
||||
$this->withExceptionHandling()->loginAs($viewer)
|
||||
->postJson($this->commitUrl(), ['preview_token' => str_repeat('a', 48)])
|
||||
->assertForbidden();
|
||||
}
|
||||
|
||||
private function pageUrl(): string
|
||||
{
|
||||
return route('business.pages.show', [
|
||||
'company_id' => $this->company->id,
|
||||
'section' => 'financial-operations',
|
||||
'page' => 'ledger',
|
||||
]) . '?tab=transactions';
|
||||
}
|
||||
|
||||
private function templateUrl(): string
|
||||
{
|
||||
return route('business.financial-ledger.transactions.import.template', [
|
||||
'company_id' => $this->company->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function previewUrl(): string
|
||||
{
|
||||
return route('business.financial-ledger.transactions.import.preview', [
|
||||
'company_id' => $this->company->id,
|
||||
]);
|
||||
}
|
||||
|
||||
private function commitUrl(): string
|
||||
{
|
||||
return route('business.financial-ledger.transactions.import.commit', [
|
||||
'company_id' => $this->company->id,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -309,6 +309,9 @@ class FinanceLedgerNavigationTest extends FeatureTestCase
|
||||
'business.financial-ledger.accounts.type',
|
||||
'business.financial-ledger.accounts.template',
|
||||
'business.financial-ledger.transactions.account.update',
|
||||
'business.financial-ledger.transactions.import.template',
|
||||
'business.financial-ledger.transactions.import.preview',
|
||||
'business.financial-ledger.transactions.import.commit',
|
||||
'business.financial-ledger.mapping.shop.preview',
|
||||
'business.financial-ledger.mapping.shop.apply',
|
||||
'business.financial-ledger.mapping.payable.preview',
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user