From 78f3bbb2a1a03cb74809cafe33b5e1acfb1912b7 Mon Sep 17 00:00:00 2001 From: shanshi <3316401569@qq.com> Date: Tue, 10 Nov 2026 22:00:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E8=B4=A6=E6=88=B7?= =?UTF-8?q?=E8=B5=84=E9=87=91=E6=B1=87=E6=80=BB=E6=96=B0=E5=A2=9E=E8=A1=8C?= =?UTF-8?q?=E5=92=8C=E5=88=97=20(#1064)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 账户资金汇总支持新增账户行和自定义列;自定义列可逐账户填写、自动保存、左右插入和删除,并使用独立镜像表持久化。 --- .../Controllers/Business/FinanceLedger.php | 63 ++++ ...130000_add_flow_summary_custom_columns.php | 58 ++++ .../FinanceLedgerFlowSummaryEditor.php | 274 ++++++++++++++++ .../View/FinanceLedgerPageData.php | 75 ++++- .../pages/financial-ledger/ledger.blade.php | 304 +++++++++++++++++- routes/admin.php | 13 + ...inanceLedgerFlowSummarySpreadsheetTest.php | 151 +++++++++ .../FinanceLedgerHeaderControlsTest.php | 15 +- .../Business/FinanceLedgerManualEditTest.php | 4 +- 9 files changed, 941 insertions(+), 16 deletions(-) create mode 100644 database/migrations/2026_11_10_130000_add_flow_summary_custom_columns.php create mode 100644 modules/EcommerceFinance/Services/FinanceLedgerFlowSummaryEditor.php create mode 100644 tests/Feature/Business/FinanceLedgerFlowSummarySpreadsheetTest.php diff --git a/app/Http/Controllers/Business/FinanceLedger.php b/app/Http/Controllers/Business/FinanceLedger.php index c4b2c8d6..05236791 100644 --- a/app/Http/Controllers/Business/FinanceLedger.php +++ b/app/Http/Controllers/Business/FinanceLedger.php @@ -21,6 +21,7 @@ use Modules\EcommerceFinance\Services\FinanceLedgerAccountEditor; use Modules\EcommerceFinance\Services\FinanceLedgerAccountTemplate; use Modules\EcommerceFinance\Services\FinanceLedgerCalculator; use Modules\EcommerceFinance\Services\FinanceLedgerFlowEditor; +use Modules\EcommerceFinance\Services\FinanceLedgerFlowSummaryEditor; use Modules\EcommerceFinance\Services\FinanceLedgerIndependentTransactionColumnEditor; use Modules\EcommerceFinance\Services\FinanceLedgerIndependentTransactionEditor; use Modules\EcommerceFinance\Services\FinanceLedgerManualTransactionEditor; @@ -1443,6 +1444,68 @@ class FinanceLedger extends Controller ], 200, ['Cache-Control' => 'private, no-store']); } + public function storeFlowSummaryColumn( + Request $request, + FinanceLedgerFlowSummaryEditor $editor, + ): JsonResponse { + abort_unless(FinanceLedgerAccess::canEditAccountStatus(user()), 403, '只有财务台账管理员可以维护账户资金汇总列。'); + + $data = $request->validate([ + 'field_names' => ['required', 'array', 'min:1', 'max:20'], + 'field_names.*' => ['required', 'string', 'max:50'], + 'anchor_field_id' => ['nullable', 'integer', 'min:1'], + 'position' => ['nullable', 'string', Rule::in(['left', 'right', 'end'])], + ]); + $fields = $editor->createColumns( + array_values($data['field_names']), + isset($data['anchor_field_id']) ? (int) $data['anchor_field_id'] : null, + (string) ($data['position'] ?? 'end'), + ); + + return response()->json([ + 'ok' => true, + 'fields' => $fields, + 'message' => '账户资金汇总自定义列已新增。', + ], 201, ['Cache-Control' => 'private, no-store']); + } + + public function deleteFlowSummaryColumn( + int $id, + FinanceLedgerFlowSummaryEditor $editor, + ): JsonResponse { + abort_unless(FinanceLedgerAccess::canEditAccountStatus(user()), 403, '只有财务台账管理员可以维护账户资金汇总列。'); + + return response()->json([ + 'ok' => true, + 'deleted' => true, + 'field' => $editor->deleteColumn($id), + 'message' => '自定义列及其账户数据已删除。', + ], 200, ['Cache-Control' => 'private, no-store']); + } + + public function updateFlowSummaryValue( + Request $request, + FinanceLedgerFlowSummaryEditor $editor, + ): JsonResponse { + abort_unless(FinanceLedgerAccess::canEditAccountStatus(user()), 403, '只有财务台账管理员可以编辑账户资金汇总自定义列。'); + + $data = $request->validate([ + 'field_id' => ['required', 'integer', 'min:1'], + 'account_short' => ['required', 'string', 'max:100'], + 'value' => ['nullable', 'string', 'max:4000'], + ]); + + return response()->json([ + 'ok' => true, + 'value' => $editor->updateValue( + (int) $data['field_id'], + trim((string) $data['account_short']), + $data['value'] ?? null, + ), + 'message' => '自定义列数据已保存。', + ], 200, ['Cache-Control' => 'private, no-store']); + } + public function updateTransactionAccount(Request $request, int $id, FinanceLedgerCalculator $calculator): JsonResponse { abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有修改动账账户关联权限。'); diff --git a/database/migrations/2026_11_10_130000_add_flow_summary_custom_columns.php b/database/migrations/2026_11_10_130000_add_flow_summary_custom_columns.php new file mode 100644 index 00000000..f1e49ead --- /dev/null +++ b/database/migrations/2026_11_10_130000_add_flow_summary_custom_columns.php @@ -0,0 +1,58 @@ +connection()); + + if (! $schema->hasTable('fin_flow_summary_custom_fields')) { + $schema->create('fin_flow_summary_custom_fields', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->uuid('field_key')->unique('fin_flow_summary_custom_field_key_unique'); + $table->string('field_name', 50)->unique('fin_flow_summary_custom_field_name_unique'); + $table->unsignedInteger('sort_order')->default(0); + $table->string('created_by', 100)->nullable(); + $table->string('updated_by', 100)->nullable(); + $table->timestamps(); + + $table->index( + ['sort_order', 'id'], + 'fin_flow_summary_custom_field_sort_index', + ); + }); + } + + if (! $schema->hasTable('fin_flow_summary_custom_values')) { + $schema->create('fin_flow_summary_custom_values', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedBigInteger('custom_field_id'); + $table->string('account_short', 100); + $table->text('value')->nullable(); + $table->timestamps(); + + $table->unique( + ['custom_field_id', 'account_short'], + 'fin_flow_summary_custom_value_field_account_unique', + ); + $table->index('account_short', 'fin_flow_summary_custom_value_account_index'); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('fin_flow_summary_custom_values'); + $schema->dropIfExists('fin_flow_summary_custom_fields'); + } +}; diff --git a/modules/EcommerceFinance/Services/FinanceLedgerFlowSummaryEditor.php b/modules/EcommerceFinance/Services/FinanceLedgerFlowSummaryEditor.php new file mode 100644 index 00000000..1cf8621d --- /dev/null +++ b/modules/EcommerceFinance/Services/FinanceLedgerFlowSummaryEditor.php @@ -0,0 +1,274 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @param list $fieldNames + * @return list> + */ + public function createColumns( + array $fieldNames, + ?int $anchorFieldId = null, + string $position = 'end', + ): array { + $position = in_array($position, ['left', 'right'], true) ? $position : 'end'; + $fieldNames = array_values(array_map(function (mixed $value): string { + $text = trim((string) $value); + + return preg_replace('/\s+/u', ' ', $text) ?? $text; + }, $fieldNames)); + if ($fieldNames === [] || count($fieldNames) > 20) { + throw ValidationException::withMessages([ + 'field_names' => '一次可新增 1 至 20 个自定义列。', + ]); + } + foreach ($fieldNames as $index => $fieldName) { + if ($fieldName === '') { + throw ValidationException::withMessages([ + 'field_names.' . $index => '请填写列名。', + ]); + } + if (mb_strlen($fieldName) > 50) { + throw ValidationException::withMessages([ + 'field_names.' . $index => '列名不能超过 50 个字符。', + ]); + } + } + + $normalizedNames = array_map(static fn (string $name): string => mb_strtolower($name), $fieldNames); + if (count(array_unique($normalizedNames)) !== count($normalizedNames)) { + throw ValidationException::withMessages([ + 'field_names' => '一次新增的列名不能重复。', + ]); + } + + return $this->connection->transaction(function () use ( + $fieldNames, + $normalizedNames, + $anchorFieldId, + $position, + ): array { + $existingFields = $this->connection->table('fin_flow_summary_custom_fields') + ->orderBy('sort_order') + ->orderBy('id') + ->lockForUpdate() + ->get(); + if ($existingFields->count() + count($fieldNames) > self::MAX_COLUMNS) { + throw ValidationException::withMessages([ + 'field_names' => '账户资金汇总最多可设置 ' . self::MAX_COLUMNS . ' 个自定义列。', + ]); + } + + $existingNames = $existingFields + ->pluck('field_name') + ->map(static fn (mixed $name): string => mb_strtolower(trim((string) $name))) + ->all(); + if (array_intersect($normalizedNames, $existingNames) !== []) { + throw ValidationException::withMessages([ + 'field_names' => '账户资金汇总已存在同名列。', + ]); + } + + $anchor = null; + if ($anchorFieldId !== null) { + $anchor = $existingFields->firstWhere('id', $anchorFieldId); + if ($anchor === null) { + throw ValidationException::withMessages([ + 'anchor_field_id' => '插入位置已变更,请刷新页面后重试。', + ]); + } + } + + $insertIndex = $existingFields->count(); + if ($anchor !== null) { + $anchorIndex = $existingFields->search( + static fn (object $field): bool => (int) $field->id === $anchorFieldId, + ); + $insertIndex = $position === 'left' ? (int) $anchorIndex : (int) $anchorIndex + 1; + } + + $now = now(); + $ordered = $existingFields->values()->all(); + $placeholders = array_map( + static fn (string $name): array => ['new_name' => $name], + $fieldNames, + ); + array_splice($ordered, $insertIndex, 0, $placeholders); + $created = []; + foreach ($ordered as $index => $field) { + $sortOrder = ($index + 1) * 10; + if (is_array($field) && isset($field['new_name'])) { + $values = [ + 'field_key' => (string) Str::uuid(), + 'field_name' => (string) $field['new_name'], + 'sort_order' => $sortOrder, + 'created_by' => (string) (user()?->name ?? ''), + 'updated_by' => (string) (user()?->name ?? ''), + 'created_at' => $now, + 'updated_at' => $now, + ]; + $id = (int) $this->connection->table('fin_flow_summary_custom_fields') + ->insertGetId($values); + $created[] = ['id' => $id] + $values; + continue; + } + + if ((int) $field->sort_order !== $sortOrder) { + $this->connection->table('fin_flow_summary_custom_fields') + ->where('id', (int) $field->id) + ->update([ + 'sort_order' => $sortOrder, + 'updated_by' => (string) (user()?->name ?? ''), + 'updated_at' => $now, + ]); + } + } + $this->audit( + 'flow_summary_col_add', + (string) Str::uuid(), + [ + 'position' => $position, + 'anchor_field_id' => $anchorFieldId, + 'after' => $created, + ], + ); + + return $created; + }); + } + + /** + * @return array + */ + public function deleteColumn(int $id): array + { + return $this->connection->transaction(function () use ($id): array { + $field = $this->connection->table('fin_flow_summary_custom_fields') + ->where('id', $id) + ->lockForUpdate() + ->first(); + if ($field === null) { + throw new NotFoundHttpException('未找到可删除的账户资金汇总自定义列。'); + } + + $this->connection->table('fin_flow_summary_custom_values') + ->where('custom_field_id', $id) + ->delete(); + $this->connection->table('fin_flow_summary_custom_fields')->where('id', $id)->delete(); + $this->audit( + 'flow_summary_col_del', + (string) $field->field_key, + ['before' => (array) $field, 'after' => null], + ); + + return (array) $field; + }); + } + + /** + * @return array + */ + public function updateValue(int $fieldId, string $accountShort, mixed $value): array + { + $accountShort = preg_replace('/\s+/u', ' ', trim($accountShort)) ?? trim($accountShort); + $text = trim((string) ($value ?? '')); + $text = preg_replace('/\s+/u', ' ', $text) ?? $text; + + return $this->connection->transaction(function () use ($fieldId, $accountShort, $text): array { + $field = $this->connection->table('fin_flow_summary_custom_fields') + ->where('id', $fieldId) + ->lockForUpdate() + ->first(); + if ($field === null) { + throw new NotFoundHttpException('自定义列已删除,请刷新页面后重试。'); + } + if ($accountShort === '' || FinanceLedgerIndependentAccounts::contains($accountShort)) { + throw ValidationException::withMessages([ + 'account_short' => '请选择账户资金汇总中的账户。', + ]); + } + if (! $this->connection->table('fin_accounts')->where('account_short', $accountShort)->exists()) { + throw ValidationException::withMessages([ + 'account_short' => '账户简称不存在,请刷新页面后重试。', + ]); + } + + $query = $this->connection->table('fin_flow_summary_custom_values') + ->where('custom_field_id', $fieldId) + ->where('account_short', $accountShort); + $existing = $query->first(); + $before = $existing?->value; + $nextValue = $text !== '' ? mb_substr($text, 0, 4000) : null; + if ($nextValue === null) { + if ($existing !== null) { + $query->delete(); + } + } elseif ($existing === null) { + $this->connection->table('fin_flow_summary_custom_values')->insert([ + 'custom_field_id' => $fieldId, + 'account_short' => $accountShort, + 'value' => $nextValue, + 'created_at' => now(), + 'updated_at' => now(), + ]); + } else { + $this->connection->table('fin_flow_summary_custom_values') + ->where('id', $existing->id) + ->update([ + 'value' => $nextValue, + 'updated_at' => now(), + ]); + } + $this->audit( + 'flow_summary_val_set', + (string) $field->field_key . '|' . $accountShort, + [ + 'before' => $before, + 'after' => $nextValue, + ], + ); + + return [ + 'field_id' => $fieldId, + 'field_key' => (string) $field->field_key, + 'account_short' => $accountShort, + 'value' => $nextValue, + ]; + }); + } + + /** + * @param array $changes + */ + private function audit(string $entityType, string $entityKey, array $changes): void + { + $this->connection->table('fin_ledger_edit_events')->insert([ + 'entity_type' => $entityType, + 'entity_key' => mb_substr('flow_summary|' . $entityKey, 0, 200), + 'changes' => json_encode($changes, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'user_id' => user()?->id, + 'user_name' => (string) (user()?->name ?? ''), + 'created_at' => now(), + ]); + } +} diff --git a/modules/EcommerceFinance/View/FinanceLedgerPageData.php b/modules/EcommerceFinance/View/FinanceLedgerPageData.php index 13164d4d..fc541422 100644 --- a/modules/EcommerceFinance/View/FinanceLedgerPageData.php +++ b/modules/EcommerceFinance/View/FinanceLedgerPageData.php @@ -121,6 +121,7 @@ class FinanceLedgerPageData 'ledgerFlowSummary' => $flows['summary'], 'ledgerFlowPeriod' => $flowPeriod, 'ledgerFlowView' => $flowView, + 'ledgerFlowSummaryCustomFields' => $flows['custom_fields'] ?? [], 'ledgerTransactions' => $transactions['rows'], 'ledgerTransactionSummary' => $transactions['summary'], 'ledgerTransactionPeriod' => $transactionPeriod, @@ -630,6 +631,7 @@ class FinanceLedgerPageData private function accountFlowSummary(array $period): array { + $customFields = $this->flowSummaryCustomFields(); $accountQuery = FinanceLedgerIndependentAccounts::exclude( $this->db()->table('fin_accounts as a'), 'a.account_short', @@ -715,8 +717,10 @@ class FinanceLedgerPageData $total = count($rows); $lastPage = max(1, (int) ceil($total / 100)); $page = min($lastPage, max(1, (int) request('flows_page', 1))); + $pageRows = array_slice($rows, ($page - 1) * 100, 100); + $this->attachFlowSummaryCustomValues($pageRows, $customFields); $paginator = new LengthAwarePaginator( - array_map(static fn (array $row): object => (object) $row, array_slice($rows, ($page - 1) * 100, 100)), + array_map(static fn (array $row): object => (object) $row, $pageRows), $total, 100, $page, @@ -736,9 +740,78 @@ class FinanceLedgerPageData 'outflow' => round(array_sum(array_column($rows, 'outflow')), 2), 'closing' => round(array_sum(array_map(static fn (array $row): float => (float) ($row['closing_balance'] ?? 0), $rows)), 2), ], + 'custom_fields' => $customFields, ]; } + /** + * @return list + */ + private function flowSummaryCustomFields(): array + { + $schema = $this->db()->getSchemaBuilder(); + if (! $schema->hasTable('fin_flow_summary_custom_fields')) { + return []; + } + + return $this->db()->table('fin_flow_summary_custom_fields') + ->orderBy('sort_order') + ->orderBy('id') + ->get(['id', 'field_key', 'field_name']) + ->map(static fn (object $field): array => [ + 'id' => (int) $field->id, + 'field_key' => (string) $field->field_key, + 'field_name' => (string) $field->field_name, + ]) + ->values() + ->all(); + } + + /** + * @param list> $rows + * @param list $fields + */ + private function attachFlowSummaryCustomValues(array &$rows, array $fields): void + { + if ($rows === [] || $fields === []) { + foreach ($rows as &$row) { + $row['custom_values'] = []; + } + unset($row); + + return; + } + + $accountShorts = array_values(array_unique(array_column($rows, 'account_short'))); + $fieldKeys = []; + foreach ($fields as $field) { + $fieldKeys[(int) $field['id']] = (string) $field['field_key']; + } + $values = []; + $this->db()->table('fin_flow_summary_custom_values') + ->whereIn('account_short', $accountShorts) + ->whereIn('custom_field_id', array_keys($fieldKeys)) + ->get(['account_short', 'custom_field_id', 'value']) + ->each(static function (object $value) use (&$values, $fieldKeys): void { + $accountShort = (string) $value->account_short; + $fieldKey = $fieldKeys[(int) $value->custom_field_id] ?? null; + if ($fieldKey !== null) { + $values[$accountShort][$fieldKey] = $value->value !== null + ? (string) $value->value + : null; + } + }); + foreach ($rows as &$row) { + $accountShort = (string) ($row['account_short'] ?? ''); + $rowValues = $values[$accountShort] ?? []; + $row['custom_values'] = []; + foreach ($fields as $field) { + $row['custom_values'][(string) $field['field_key']] = $rowValues[(string) $field['field_key']] ?? null; + } + } + unset($row); + } + private function bankAffiliation(string $accountShort): string { foreach (self::BANK_AFFILIATION_SUFFIXES as $suffix => $label) { diff --git a/resources/views/business/pages/financial-ledger/ledger.blade.php b/resources/views/business/pages/financial-ledger/ledger.blade.php index bc0ab671..651df5cf 100644 --- a/resources/views/business/pages/financial-ledger/ledger.blade.php +++ b/resources/views/business/pages/financial-ledger/ledger.blade.php @@ -71,6 +71,7 @@ $currentMonthEnd = now()->endOfMonth()->toDateString(); $flowPeriod = $ledgerFlowPeriod ?? ['from' => $currentMonthStart, 'to' => $currentMonthEnd]; $flowView = $ledgerFlowView ?? 'summary'; + $flowSummaryCustomFields = $ledgerFlowSummaryCustomFields ?? []; $transactionPeriod = $ledgerTransactionPeriod ?? ['from' => $currentMonthStart, 'to' => $currentMonthEnd]; $mappingPeriod = $ledgerMappingPeriod ?? ['from' => $currentMonthStart, 'to' => $currentMonthEnd]; $sourcePeriod = $ledgerSourcePeriod ?? ['from' => $currentMonthStart, 'to' => $currentMonthEnd]; @@ -243,6 +244,12 @@ .ledger-subtab.is-active { color:var(--vip-content-accent-dark, #856632); } .ledger-subtab.is-active::after { background:var(--vip-content-accent, #B9954F); } .ledger-subtab:focus-visible { outline:2px solid var(--vip-content-accent-dark, #856632); outline-offset:-2px; } + .ledger-flow-grid-actions { display:flex; align-items:center; gap:.4rem; margin-left:auto; padding:0 .1rem 0 1rem; } + .ledger-flow-grid-actions .ledger-btn { min-height:2rem; height:2rem; padding:0 .6rem; font-size:.68rem; } + .ledger-summary-custom-input { width:100%; min-width:8rem; height:1.9rem; padding:0 .45rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.35rem; background:#fff; color:var(--vip-content-ink, #171717); font:inherit; font-size:.7rem; } + .ledger-summary-custom-input:focus { border-color:var(--vip-content-accent-dark, #856632); outline:none; box-shadow:0 0 0 3px rgba(133,102,50,.14); } + .ledger-summary-custom-input.is-saving { opacity:.62; } + .ledger-summary-custom-input.is-error { border-color:var(--vip-danger, #B80000); background:#fff5f5; } .ledger-transaction-view-note { margin:0 0 .75rem; padding:.55rem .65rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.45rem; background:#fff; color:var(--vip-content-muted, #595959); font-size:.7rem; line-height:1.6; } .ledger-transaction-view-note.is-warning { border-color:#E2C88E; background:#fff8eb; color:var(--vip-warning, #935F07); } @media (prefers-reduced-motion: reduce) { .ledger-subtab { transition:none; } } @@ -689,7 +696,7 @@ @csrf
-

新增公司/账户

+

新增公司/账户

公司不存在时自动加入公司台账,也可补充已有公司的资料。账户简称必须唯一,期初余额会作为该账户的起始资金并进入每日流水。

+ + + @endif
{{ $flowView === 'daily' ? '流水条数' : '账户数' }}{{ number_format((int) ($ledgerFlowSummary['count'] ?? 0)) }}
@@ -1095,6 +1108,23 @@ 'preserve' => $ledgerHeaderPreserve['flows'], ]) @endforeach + @foreach ($flowSummaryCustomFields as $customField) + @if ($flowView === 'summary') + +
+ {{ $customField['field_name'] }} + @if ($canEditAccounts) + + @foreach (['left' => ['format_indent_increase', '左侧'], 'right' => ['format_indent_decrease', '右侧']] as $position => $action) + + @endforeach + + + @endif +
+ + @endif + @endforeach @if ($flowView === 'summary') 操作 @endif @@ -1108,9 +1138,36 @@ @endforelse @else @forelse ($ledgerFlows as $row) - {{ $row->account_short }}{{ $row->bank_affiliation ?: '—' }}{{ $row->company_name }}{{ $row->opening_balance === null ? '—' : $money($row->opening_balance) }}{{ $row->inflow > 0 ? $money($row->inflow) : '' }}{{ $row->outflow > 0 ? $money($row->outflow) : '' }}{{ $row->closing_balance === null ? '—' : $money($row->closing_balance) }}{{ number_format((int) $row->activity_days) }}{{ $row->remark }}@if ($canEditAccounts)@else—@endif + + {{ $row->account_short }} + {{ $row->bank_affiliation ?: '—' }} + {{ $row->company_name }} + {{ $row->opening_balance === null ? '—' : $money($row->opening_balance) }} + {{ $row->inflow > 0 ? $money($row->inflow) : '' }} + {{ $row->outflow > 0 ? $money($row->outflow) : '' }} + {{ $row->closing_balance === null ? '—' : $money($row->closing_balance) }} + {{ number_format((int) $row->activity_days) }} + {{ $row->remark }} + @foreach ($flowSummaryCustomFields as $customField) + @php $customValue = $row->custom_values[$customField['field_key']] ?? ''; @endphp + + @if ($canEditAccounts) + + @else + {{ $customValue }} + @endif + + @endforeach + + @if ($canEditAccounts) + + @else + — + @endif + + @empty -
没有匹配的账户。
+
没有匹配的账户。
@endforelse @endif @@ -1426,6 +1483,31 @@ @if ($canEditAccounts) + +
+ @csrf +
+
+

新增账户资金汇总列

+

自定义列只属于账户资金汇总页;新增后可直接在每一行填写内容,不参与余额和流水计算。

+
+ +
+
+
+ +
+
+ + + +
+
+ + +
+
+
@csrf @@ -1567,6 +1649,7 @@ })); if (window.location.hash === '#mapping') showTab('mapping', false); + const flowsPanel = page.querySelector('#ledger-panel-flows'); const transactionPanel = page.querySelector('#ledger-panel-transactions'); const transactionViewTabs = Array.from(page.querySelectorAll('[data-ledger-transaction-view]')); let transactionViewRequest = null; @@ -3104,6 +3187,8 @@ const accountCompanyForm = page.querySelector('[data-ledger-company-form]'); const accountCompanyError = page.querySelector('[data-ledger-company-error]'); const accountCompanySave = page.querySelector('[data-ledger-company-save]'); + const accountCompanyTitle = page.querySelector('[data-ledger-company-title]'); + const accountCompanyFirstField = page.querySelector('[data-ledger-company-first-field]'); const applyAccountEditMode = (enabled) => { const active = Boolean(enabled && accountEditToggle && !accountEditToggle.disabled); accountPanel?.classList.toggle('is-account-edit-mode', active); @@ -3123,9 +3208,18 @@ if (!accountCompanyDialog?.open) return; accountCompanyDialog.close(); }; - accountAddCompanyButton?.addEventListener('click', () => { + const openAccountCompanyDialog = (trigger = null) => { if (!accountCompanyDialog) return; + if (accountCompanyDialog.parentElement !== document.body) { + document.body.appendChild(accountCompanyDialog); + } accountCompanyForm?.reset(); + accountCompanyDialog.dataset.activeReturnUrl = trigger?.dataset.returnUrl || ''; + if (accountCompanyTitle) { + accountCompanyTitle.textContent = trigger?.hasAttribute('data-ledger-flow-summary-add-row') + ? '新增账户汇总行' + : '新增公司/账户'; + } if (accountCompanyError) { accountCompanyError.hidden = true; accountCompanyError.textContent = ''; @@ -3135,8 +3229,11 @@ } else { accountCompanyDialog.setAttribute('open', ''); } - page.querySelector('[data-ledger-company-first-field]')?.focus(); - }); + accountCompanyFirstField?.focus(); + }; + accountAddCompanyButton?.addEventListener('click', () => openAccountCompanyDialog(accountAddCompanyButton)); + flowsPanel?.querySelectorAll('[data-ledger-flow-summary-add-row]') + .forEach((button) => button.addEventListener('click', () => openAccountCompanyDialog(button))); page.querySelector('[data-ledger-company-close]')?.addEventListener('click', closeAccountCompanyDialog); page.querySelector('[data-ledger-company-cancel]')?.addEventListener('click', closeAccountCompanyDialog); accountCompanyForm?.addEventListener('submit', async (event) => { @@ -3165,13 +3262,15 @@ throw new Error(firstError || payload.message || '公司/账户保存失败'); } + const returnUrl = accountCompanyDialog?.dataset.activeReturnUrl || ''; + const accountShort = payload.account?.account_short || ''; notify(payload.message || '公司/账户已新增'); closeAccountCompanyDialog(); const target = new URL( - accountCompanyDialog?.dataset.ledgerAccountsUrl || window.location.href, + returnUrl || accountCompanyDialog?.dataset.ledgerAccountsUrl || window.location.href, window.location.origin, ); - target.searchParams.set('accounts_short', payload.account?.account_short || ''); + target.searchParams.set(returnUrl ? 'flows_account' : 'accounts_short', accountShort); window.location.assign(target.toString()); } catch (error) { if (accountCompanyError) { @@ -3516,6 +3615,195 @@ } }); + const flowSummaryColumnDialog = page.querySelector('[data-ledger-flow-summary-column-dialog]'); + const flowSummaryColumnForm = page.querySelector('[data-ledger-flow-summary-column-form]'); + let openFlowSummaryColumnDialog = null; + if (flowSummaryColumnDialog && flowSummaryColumnForm) { + const columnNames = flowSummaryColumnForm.querySelector('[data-ledger-flow-summary-column-names]'); + const columnAnchor = flowSummaryColumnForm.querySelector('[data-ledger-flow-summary-column-anchor]'); + const columnPosition = flowSummaryColumnForm.querySelector('[data-ledger-flow-summary-column-position]'); + const columnTitle = flowSummaryColumnDialog.querySelector('[data-ledger-flow-summary-column-title]'); + const columnError = flowSummaryColumnForm.querySelector('[data-ledger-flow-summary-column-error]'); + const columnSave = flowSummaryColumnForm.querySelector('[data-ledger-flow-summary-column-save]'); + const renderColumnNames = () => { + if (!columnNames) return; + columnNames.replaceChildren(); + const row = document.createElement('label'); + row.className = 'ledger-statement-column-name-row'; + const number = document.createElement('span'); + number.textContent = '01'; + const input = document.createElement('input'); + input.type = 'text'; + input.name = 'field_names[]'; + input.maxLength = 50; + input.required = true; + input.placeholder = '例如:责任人、核对状态、票据编号'; + input.dataset.ledgerFlowSummaryColumnName = ''; + row.append(number, input); + columnNames.appendChild(row); + }; + const closeFlowSummaryColumnDialog = () => { + if (flowSummaryColumnDialog.open) flowSummaryColumnDialog.close(); + }; + openFlowSummaryColumnDialog = ({ + anchorFieldId = null, + position = 'end', + title = '新增账户资金汇总列', + } = {}) => { + flowSummaryColumnForm.reset(); + renderColumnNames(); + if (columnAnchor) columnAnchor.value = anchorFieldId || ''; + if (columnPosition) columnPosition.value = position; + if (columnTitle) columnTitle.textContent = title; + if (columnError) { + columnError.hidden = true; + columnError.textContent = ''; + } + flowSummaryColumnDialog.showModal(); + columnNames?.querySelector('input')?.focus(); + }; + + flowsPanel?.addEventListener('click', async (event) => { + const addButton = event.target.closest('[data-ledger-flow-summary-add-column]'); + if (addButton) { + openFlowSummaryColumnDialog({ position: 'end', title: '新增账户资金汇总列' }); + return; + } + const insertButton = event.target.closest('[data-ledger-flow-summary-column-insert]'); + if (insertButton) { + const position = insertButton.dataset.position === 'left' ? 'left' : 'right'; + const fieldName = insertButton.dataset.fieldName || '自定义列'; + openFlowSummaryColumnDialog({ + anchorFieldId: Number(insertButton.dataset.fieldId || 0), + position, + title: '在“' + fieldName + '”' + (position === 'left' ? '左侧' : '右侧') + '插入列', + }); + return; + } + const deleteButton = event.target.closest('[data-ledger-flow-summary-column-delete]'); + if (!deleteButton) return; + const fieldName = deleteButton.dataset.fieldName || '该自定义列'; + if (!window.confirm('确认删除“' + fieldName + '”列?\n该列在全部账户行中的数据也会一并删除。')) return; + + deleteButton.disabled = true; + try { + const response = await fetch(deleteButton.dataset.deleteUrl, { + method: 'DELETE', + credentials: 'same-origin', + headers: { + 'Accept': 'application/json', + 'X-CSRF-TOKEN': ledgerCsrfToken, + 'X-Requested-With': 'XMLHttpRequest', + }, + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(payload.message || '自定义列删除失败'); + notify(payload.message || '自定义列已删除'); + window.setTimeout(() => window.location.reload(), 450); + } catch (error) { + deleteButton.disabled = false; + notify(error.message || '自定义列删除失败', true); + } + }); + + page.querySelectorAll('[data-ledger-flow-summary-column-close], [data-ledger-flow-summary-column-cancel]') + .forEach((button) => button.addEventListener('click', closeFlowSummaryColumnDialog)); + flowSummaryColumnDialog.addEventListener('click', (event) => { + if (event.target === flowSummaryColumnDialog) closeFlowSummaryColumnDialog(); + }); + flowSummaryColumnForm.addEventListener('submit', async (event) => { + event.preventDefault(); + if (!flowSummaryColumnForm.reportValidity()) return; + if (columnError) columnError.hidden = true; + if (columnSave) columnSave.disabled = true; + try { + const response = await fetch(flowSummaryColumnForm.action, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest', + }, + body: new FormData(flowSummaryColumnForm), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + const firstError = Object.values(payload.errors || {})[0]?.[0]; + throw new Error(firstError || payload.message || '自定义列新增失败'); + } + closeFlowSummaryColumnDialog(); + notify(payload.message || '自定义列已新增'); + window.setTimeout(() => window.location.reload(), 450); + } catch (error) { + if (columnError) { + columnError.textContent = error.message || '自定义列新增失败'; + columnError.hidden = false; + } + } finally { + if (columnSave) columnSave.disabled = false; + } + }); + } + + flowsPanel?.querySelectorAll('[data-ledger-flow-summary-custom-value]').forEach((input) => { + const saveValue = async () => { + if (input.dataset.saving === '1') return; + const previousValue = input.dataset.previousValue || ''; + const nextValue = input.value.trim(); + if (nextValue === previousValue) return; + input.dataset.saving = '1'; + input.disabled = true; + input.classList.remove('is-error'); + input.classList.add('is-saving'); + try { + const response = await fetch(input.dataset.valueUrl, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'X-CSRF-TOKEN': ledgerCsrfToken, + 'X-Requested-With': 'XMLHttpRequest', + }, + body: JSON.stringify({ + field_id: Number(input.dataset.fieldId || 0), + account_short: input.dataset.accountShort || '', + value: nextValue, + }), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + const firstError = Object.values(payload.errors || {})[0]?.[0]; + throw new Error(firstError || payload.message || '自定义列数据保存失败'); + } + const savedValue = payload.value?.value || ''; + input.value = savedValue; + input.dataset.previousValue = savedValue; + notify(payload.message || '自定义列数据已保存'); + } catch (error) { + input.value = previousValue; + input.classList.add('is-error'); + notify(error.message || '自定义列数据保存失败', true); + } finally { + input.disabled = false; + input.classList.remove('is-saving'); + delete input.dataset.saving; + } + }; + input.addEventListener('change', saveValue); + input.addEventListener('blur', saveValue); + input.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + input.blur(); + } else if (event.key === 'Escape') { + event.preventDefault(); + input.value = input.dataset.previousValue || ''; + input.blur(); + } + }); + }); + const accountColumnPicker = page.querySelector('[data-ledger-column-picker]'); const accountColumnPanel = accountColumnPicker?.querySelector('[data-ledger-column-panel]'); const accountColumnOptions = accountColumnPicker?.querySelector('[data-ledger-column-options]'); diff --git a/routes/admin.php b/routes/admin.php index 4fe435c7..c8f1d776 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -856,6 +856,19 @@ Route::post('workspace/financial-ledger/flows/reset', [\App\Http\Controllers\Bus ->middleware('business.page:financial-operations,ledger') ->name('business.financial-ledger.flows.reset'); +Route::post('workspace/financial-ledger/flows/summary/columns', [\App\Http\Controllers\Business\FinanceLedger::class, 'storeFlowSummaryColumn']) + ->middleware('business.page:financial-operations,ledger') + ->name('business.financial-ledger.flows.summary.columns.store'); + +Route::delete('workspace/financial-ledger/flows/summary/columns/{id}', [\App\Http\Controllers\Business\FinanceLedger::class, 'deleteFlowSummaryColumn']) + ->whereNumber('id') + ->middleware('business.page:financial-operations,ledger') + ->name('business.financial-ledger.flows.summary.columns.delete'); + +Route::post('workspace/financial-ledger/flows/summary/values', [\App\Http\Controllers\Business\FinanceLedger::class, 'updateFlowSummaryValue']) + ->middleware('business.page:financial-operations,ledger') + ->name('business.financial-ledger.flows.summary.values.update'); + Route::post('workspace/financial-ledger/accounts/status', [\App\Http\Controllers\Business\FinanceLedger::class, 'updateAccountStatus']) ->middleware('business.page:financial-operations,ledger') ->name('business.financial-ledger.accounts.status'); diff --git a/tests/Feature/Business/FinanceLedgerFlowSummarySpreadsheetTest.php b/tests/Feature/Business/FinanceLedgerFlowSummarySpreadsheetTest.php new file mode 100644 index 00000000..080cf354 --- /dev/null +++ b/tests/Feature/Business/FinanceLedgerFlowSummarySpreadsheetTest.php @@ -0,0 +1,151 @@ +user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail(), + ); + + $this->accountShort = '汇总表格测试账户-' . strtoupper(substr(md5(uniqid('', true)), 0, 8)); + $connection = DB::connection('business_mirror'); + $connection->table('fin_accounts')->insert([ + 'company_name' => '汇总表格测试公司', + 'account_short' => $this->accountShort, + 'account_type' => '公户', + 'current_balance' => 100, + 'daily_available' => 100, + 'blocked_amount' => 0, + ]); + $connection->table('fin_account_opening')->insert([ + 'account_short' => $this->accountShort, + 'opening_date' => '2026-11-01', + 'opening_balance' => 100, + ]); + } + + protected function tearDown(): void + { + Carbon::setTestNow(); + parent::tearDown(); + } + + public function test_summary_exposes_excel_style_add_row_and_add_column_controls(): void + { + $html = $this->loginAs()->get($this->pageUrl())->assertOk()->getContent(); + + $this->assertStringContainsString('data-ledger-flow-summary-add-row', $html); + $this->assertStringContainsString('data-ledger-flow-summary-add-column', $html); + $this->assertStringContainsString('data-ledger-flow-summary-column-dialog', $html); + $this->assertStringContainsString('>新增行', $html); + $this->assertStringContainsString('>新增列', $html); + } + + public function test_summary_custom_column_values_can_be_saved_and_column_can_be_deleted(): void + { + $create = $this->loginAs()->postJson($this->columnStoreUrl(), [ + 'field_names' => ['核对状态'], + 'position' => 'end', + ])->assertCreated() + ->assertJsonPath('fields.0.field_name', '核对状态'); + $fieldId = (int) $create->json('fields.0.id'); + + $this->assertDatabaseHas('fin_flow_summary_custom_fields', [ + 'id' => $fieldId, + 'field_name' => '核对状态', + ], 'business_mirror'); + + $this->loginAs()->postJson($this->valueUrl(), [ + 'field_id' => $fieldId, + 'account_short' => $this->accountShort, + 'value' => '已核对', + ])->assertOk() + ->assertJsonPath('value.value', '已核对'); + + $html = $this->loginAs()->get($this->pageUrl())->assertOk()->getContent(); + $this->assertStringContainsString('title="核对状态">核对状态', $html); + $this->assertStringContainsString('data-ledger-flow-summary-custom-value', $html); + $this->assertStringContainsString('data-account-short="' . $this->accountShort . '"', $html); + $this->assertStringContainsString('value="已核对"', $html); + + $this->loginAs()->deleteJson($this->columnDeleteUrl($fieldId)) + ->assertOk() + ->assertJsonPath('deleted', true); + $this->assertDatabaseMissing('fin_flow_summary_custom_fields', [ + 'id' => $fieldId, + ], 'business_mirror'); + $this->assertDatabaseMissing('fin_flow_summary_custom_values', [ + 'custom_field_id' => $fieldId, + ], 'business_mirror'); + } + + public function test_summary_spreadsheet_endpoints_reject_account_viewers(): void + { + $viewer = user_model_class()::create([ + 'name' => '汇总只读用户', + 'email' => 'flow-summary-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)->postJson($this->columnStoreUrl(), [ + 'field_names' => ['无权限列'], + ])->assertForbidden(); + } + + private function pageUrl(): string + { + return route('business.pages.show', [ + 'company_id' => $this->company->id, + 'section' => 'financial-operations', + 'page' => 'ledger', + ]) . '?' . http_build_query([ + 'tab' => 'flows', + 'flows_view' => 'summary', + 'flows_from' => '2026-11-01', + 'flows_to' => '2026-11-30', + 'flows_account' => $this->accountShort, + ]); + } + + private function columnStoreUrl(): string + { + return route('business.financial-ledger.flows.summary.columns.store', [ + 'company_id' => $this->company->id, + ]); + } + + private function columnDeleteUrl(int $fieldId): string + { + return route('business.financial-ledger.flows.summary.columns.delete', [ + 'company_id' => $this->company->id, + 'id' => $fieldId, + ]); + } + + private function valueUrl(): string + { + return route('business.financial-ledger.flows.summary.values.update', [ + 'company_id' => $this->company->id, + ]); + } +} diff --git a/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php b/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php index 19e3e626..c3cbcd50 100644 --- a/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php +++ b/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php @@ -438,14 +438,17 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase ]))->assertOk()->getContent(); $this->assertSame(1, preg_match('/.*?<\/tr>/s', $summaryHtml, $accountRow)); - $this->assertStringContainsString('账户甲—甲公司', $accountRow[0]); + $this->assertMatchesRegularExpression('/账户甲<\/td>\s*—<\/td>\s*甲公司<\/td>/', $accountRow[0]); $this->assertStringContainsString('>所属银行', $summaryHtml); - $this->assertStringContainsString('100.0010.00110.001', $accountRow[0]); + $this->assertMatchesRegularExpression( + '/100\.00<\/td>\s*10\.00<\/td>\s*<\/td>\s*110\.00<\/td>\s*1<\/td>/', + $accountRow[0], + ); $this->assertStringContainsString('data-flow-summary-edit', $accountRow[0]); $this->assertStringContainsString('data-edit-url=', $accountRow[0]); $this->assertStringContainsString('>编辑', $accountRow[0]); $this->assertSame(1, preg_match('/.*?<\/tr>/s', $summaryHtml, $emptyAccountRow)); - $this->assertStringContainsString('账户丙—丙公司', $emptyAccountRow[0]); + $this->assertMatchesRegularExpression('/账户丙<\/td>\s*—<\/td>\s*丙公司<\/td>/', $emptyAccountRow[0]); $this->assertStringContainsString('—', $emptyAccountRow[0]); $this->assertStringContainsString('尚未起账', $emptyAccountRow[0]); $this->assertStringContainsString('>账户汇总', $summaryHtml); @@ -498,8 +501,10 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase ]))->assertOk()->getContent(); foreach ($affiliations as $suffix => $expected) { - $this->assertStringContainsString( - '映射账户' . $suffix . '' . $expected . '映射公司' . $suffix . '', + $this->assertMatchesRegularExpression( + '/' . preg_quote('映射账户' . $suffix, '/') . '<\/td>\s*' + . preg_quote($expected, '/') . '<\/td>\s*' + . preg_quote('映射公司' . $suffix, '/') . '<\/td>/', $html, ); } diff --git a/tests/Feature/Business/FinanceLedgerManualEditTest.php b/tests/Feature/Business/FinanceLedgerManualEditTest.php index 69356d44..72c71e2e 100644 --- a/tests/Feature/Business/FinanceLedgerManualEditTest.php +++ b/tests/Feature/Business/FinanceLedgerManualEditTest.php @@ -241,8 +241,8 @@ class FinanceLedgerManualEditTest extends FeatureTestCase 1, preg_match('/.*?<\/tr>/s', $summaryHtml, $accountRow), ); - $this->assertStringContainsString( - '100.0035.0030.00105.00', + $this->assertMatchesRegularExpression( + '/100\.00<\/td>\s*35\.00<\/td>\s*30\.00<\/td>\s*105\.00<\/td>/', $accountRow[0], ); $this->assertStringContainsString('data-flow-summary-edit', $accountRow[0]);