feat: 支持账户资金汇总新增行和列 (#1064)
账户资金汇总支持新增账户行和自定义列;自定义列可逐账户填写、自动保存、左右插入和删除,并使用独立镜像表持久化。
This commit is contained in:
parent
b959cef955
commit
78f3bbb2a1
@ -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, '当前账号没有修改动账账户关联权限。');
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->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');
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use App\Utilities\FinanceLedgerIndependentAccounts;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class FinanceLedgerFlowSummaryEditor
|
||||
{
|
||||
private const MAX_COLUMNS = 30;
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $fieldNames
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
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<string,mixed>
|
||||
*/
|
||||
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<string,mixed>
|
||||
*/
|
||||
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<string,mixed> $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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -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<array{id:int,field_key:string,field_name:string}>
|
||||
*/
|
||||
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<array<string,mixed>> $rows
|
||||
* @param list<array{id:int,field_key:string,field_name:string}> $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) {
|
||||
|
||||
@ -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
|
||||
<header class="ledger-company-form__header">
|
||||
<div>
|
||||
<h3 class="ledger-company-form__title" id="ledger-company-dialog-title">新增公司/账户</h3>
|
||||
<h3 class="ledger-company-form__title" id="ledger-company-dialog-title" data-ledger-company-title>新增公司/账户</h3>
|
||||
<p class="ledger-company-form__help">公司不存在时自动加入公司台账,也可补充已有公司的资料。账户简称必须唯一,期初余额会作为该账户的起始资金并进入每日流水。</p>
|
||||
</div>
|
||||
<button class="ledger-company-form__close" type="button" aria-label="关闭新增公司/账户" data-ledger-company-close>
|
||||
@ -1073,6 +1080,12 @@
|
||||
<nav class="ledger-subtabbar" aria-label="账户资金汇总视图">
|
||||
<a class="ledger-subtab {{ $flowView === 'summary' ? 'is-active' : '' }}" href="{{ $flowViewUrl('summary') }}" @if ($flowView === 'summary') aria-current="page" @endif>账户汇总</a>
|
||||
<a class="ledger-subtab {{ $flowView === 'daily' ? 'is-active' : '' }}" href="{{ $flowViewUrl('daily') }}" @if ($flowView === 'daily') aria-current="page" @endif>按日流水</a>
|
||||
@if ($flowView === 'summary' && $canEditAccounts)
|
||||
<span class="ledger-flow-grid-actions">
|
||||
<button class="ledger-btn" type="button" title="新增一个账户汇总行" data-ledger-flow-summary-add-row data-return-url="{{ $flowViewUrl('summary') }}"><span class="material-icons-outlined" aria-hidden="true">playlist_add</span>新增行</button>
|
||||
<button class="ledger-btn" type="button" title="在账户资金汇总末尾新增一个自定义列" data-ledger-flow-summary-add-column><span class="material-icons-outlined" aria-hidden="true">view_column</span>新增列</button>
|
||||
</span>
|
||||
@endif
|
||||
</nav>
|
||||
<div class="ledger-summary">
|
||||
<div class="ledger-summary__item"><span>{{ $flowView === 'daily' ? '流水条数' : '账户数' }}</span><b>{{ number_format((int) ($ledgerFlowSummary['count'] ?? 0)) }}</b></div>
|
||||
@ -1095,6 +1108,23 @@
|
||||
'preserve' => $ledgerHeaderPreserve['flows'],
|
||||
])
|
||||
@endforeach
|
||||
@foreach ($flowSummaryCustomFields as $customField)
|
||||
@if ($flowView === 'summary')
|
||||
<th scope="col" class="ledger-custom-column" data-ledger-header-field="summary-custom-{{ $customField['field_key'] }}">
|
||||
<div class="ledger-custom-column-head">
|
||||
<strong title="{{ $customField['field_name'] }}">{{ $customField['field_name'] }}</strong>
|
||||
@if ($canEditAccounts)
|
||||
<span class="ledger-custom-column-actions">
|
||||
@foreach (['left' => ['format_indent_increase', '左侧'], 'right' => ['format_indent_decrease', '右侧']] as $position => $action)
|
||||
<button class="ledger-custom-column-insert" type="button" title="在“{{ $customField['field_name'] }}”{{ $action[1] }}插入列" aria-label="在“{{ $customField['field_name'] }}”{{ $action[1] }}插入列" data-ledger-flow-summary-column-insert data-field-id="{{ $customField['id'] }}" data-field-name="{{ $customField['field_name'] }}" data-position="{{ $position }}"><span class="material-icons-outlined" aria-hidden="true">{{ $action[0] }}</span></button>
|
||||
@endforeach
|
||||
<button class="ledger-custom-column-delete" type="button" title="删除自定义列“{{ $customField['field_name'] }}”" aria-label="删除自定义列“{{ $customField['field_name'] }}”" data-ledger-flow-summary-column-delete data-delete-url="{{ route('business.financial-ledger.flows.summary.columns.delete', ['id' => $customField['id']]) }}" data-field-name="{{ $customField['field_name'] }}"><span class="material-icons-outlined" aria-hidden="true">delete</span></button>
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
</th>
|
||||
@endif
|
||||
@endforeach
|
||||
@if ($flowView === 'summary')
|
||||
<th scope="col">操作</th>
|
||||
@endif
|
||||
@ -1108,9 +1138,36 @@
|
||||
@endforelse
|
||||
@else
|
||||
@forelse ($ledgerFlows as $row)
|
||||
<tr data-flow-summary-account="{{ $row->account_short }}"><td>{{ $row->account_short }}</td><td>{{ $row->bank_affiliation ?: '—' }}</td><td>{{ $row->company_name }}</td><td class="num">{{ $row->opening_balance === null ? '—' : $money($row->opening_balance) }}</td><td class="num">{{ $row->inflow > 0 ? $money($row->inflow) : '' }}</td><td class="num">{{ $row->outflow > 0 ? $money($row->outflow) : '' }}</td><td class="num">{{ $row->closing_balance === null ? '—' : $money($row->closing_balance) }}</td><td class="num">{{ number_format((int) $row->activity_days) }}</td><td>{{ $row->remark }}</td><td>@if ($canEditAccounts)<button class="ledger-row-edit ledger-row-edit--text" type="button" title="编辑 {{ $row->account_short }} 每日流水,默认 {{ $flowSummaryEditDate }},可在弹窗中更改日期" aria-label="编辑 {{ $row->account_short }} 每日流水" data-ledger-flow-edit data-flow-summary-edit data-edit-url="{{ route('business.financial-ledger.flows.edit', ['flow_date' => $flowSummaryEditDate, 'account_short' => $row->account_short]) }}" data-save-url="{{ route('business.financial-ledger.flows.update') }}" data-reset-url="{{ route('business.financial-ledger.flows.reset') }}" data-flow-date="{{ $flowSummaryEditDate }}" data-flow-account-short="{{ $row->account_short }}"><span class="material-icons-outlined" aria-hidden="true">edit</span><span>编辑</span></button>@else<span class="muted">—</span>@endif</td></tr>
|
||||
<tr data-flow-summary-account="{{ $row->account_short }}">
|
||||
<td>{{ $row->account_short }}</td>
|
||||
<td>{{ $row->bank_affiliation ?: '—' }}</td>
|
||||
<td>{{ $row->company_name }}</td>
|
||||
<td class="num">{{ $row->opening_balance === null ? '—' : $money($row->opening_balance) }}</td>
|
||||
<td class="num">{{ $row->inflow > 0 ? $money($row->inflow) : '' }}</td>
|
||||
<td class="num">{{ $row->outflow > 0 ? $money($row->outflow) : '' }}</td>
|
||||
<td class="num">{{ $row->closing_balance === null ? '—' : $money($row->closing_balance) }}</td>
|
||||
<td class="num">{{ number_format((int) $row->activity_days) }}</td>
|
||||
<td>{{ $row->remark }}</td>
|
||||
@foreach ($flowSummaryCustomFields as $customField)
|
||||
@php $customValue = $row->custom_values[$customField['field_key']] ?? ''; @endphp
|
||||
<td class="wrap">
|
||||
@if ($canEditAccounts)
|
||||
<input class="ledger-summary-custom-input" type="text" maxlength="4000" value="{{ $customValue }}" placeholder="填写{{ $customField['field_name'] }}" aria-label="{{ $row->account_short }} - {{ $customField['field_name'] }}" data-ledger-flow-summary-custom-value data-field-id="{{ $customField['id'] }}" data-account-short="{{ $row->account_short }}" data-previous-value="{{ $customValue }}" data-value-url="{{ route('business.financial-ledger.flows.summary.values.update') }}">
|
||||
@else
|
||||
{{ $customValue }}
|
||||
@endif
|
||||
</td>
|
||||
@endforeach
|
||||
<td>
|
||||
@if ($canEditAccounts)
|
||||
<button class="ledger-row-edit ledger-row-edit--text" type="button" title="编辑 {{ $row->account_short }} 每日流水,默认 {{ $flowSummaryEditDate }},可在弹窗中更改日期" aria-label="编辑 {{ $row->account_short }} 每日流水" data-ledger-flow-edit data-flow-summary-edit data-edit-url="{{ route('business.financial-ledger.flows.edit', ['flow_date' => $flowSummaryEditDate, 'account_short' => $row->account_short]) }}" data-save-url="{{ route('business.financial-ledger.flows.update') }}" data-reset-url="{{ route('business.financial-ledger.flows.reset') }}" data-flow-date="{{ $flowSummaryEditDate }}" data-flow-account-short="{{ $row->account_short }}"><span class="material-icons-outlined" aria-hidden="true">edit</span><span>编辑</span></button>
|
||||
@else
|
||||
<span class="muted">—</span>
|
||||
@endif
|
||||
</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr><td colspan="10"><div class="ledger-empty">没有匹配的账户。</div></td></tr>
|
||||
<tr><td colspan="{{ 10 + count($flowSummaryCustomFields) }}"><div class="ledger-empty">没有匹配的账户。</div></td></tr>
|
||||
@endforelse
|
||||
@endif
|
||||
</tbody>
|
||||
@ -1426,6 +1483,31 @@
|
||||
</section>
|
||||
|
||||
@if ($canEditAccounts)
|
||||
<dialog class="ledger-company-dialog" data-ledger-flow-summary-column-dialog aria-labelledby="ledger-flow-summary-column-title">
|
||||
<form class="ledger-company-form" method="POST" action="{{ route('business.financial-ledger.flows.summary.columns.store') }}" data-ledger-flow-summary-column-form>
|
||||
@csrf
|
||||
<header class="ledger-company-form__header">
|
||||
<div>
|
||||
<h3 class="ledger-company-form__title" id="ledger-flow-summary-column-title" data-ledger-flow-summary-column-title>新增账户资金汇总列</h3>
|
||||
<p class="ledger-company-form__help">自定义列只属于账户资金汇总页;新增后可直接在每一行填写内容,不参与余额和流水计算。</p>
|
||||
</div>
|
||||
<button class="ledger-company-form__close" type="button" aria-label="关闭新增自定义列" data-ledger-flow-summary-column-close><span class="material-icons-outlined" aria-hidden="true">close</span></button>
|
||||
</header>
|
||||
<div class="ledger-company-form__body">
|
||||
<div class="ledger-company-field ledger-company-field--full">
|
||||
<label>列名 <span aria-hidden="true">*</span></label>
|
||||
<div class="ledger-statement-column-names" data-ledger-flow-summary-column-names></div>
|
||||
</div>
|
||||
<input type="hidden" name="anchor_field_id" value="" data-ledger-flow-summary-column-anchor>
|
||||
<input type="hidden" name="position" value="end" data-ledger-flow-summary-column-position>
|
||||
<p class="ledger-company-form__message" role="alert" data-ledger-flow-summary-column-error hidden></p>
|
||||
</div>
|
||||
<footer class="ledger-company-form__footer">
|
||||
<button class="ledger-btn" type="button" data-ledger-flow-summary-column-cancel>取消</button>
|
||||
<button class="ledger-btn primary" type="submit" data-ledger-flow-summary-column-save><span class="material-icons-outlined" aria-hidden="true">check</span>新增列</button>
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
<dialog class="ledger-company-dialog ledger-edit-dialog" data-ledger-flow-dialog aria-labelledby="ledger-flow-edit-title">
|
||||
<form class="ledger-company-form" method="POST" data-ledger-flow-form>
|
||||
@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]');
|
||||
|
||||
@ -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');
|
||||
|
||||
@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use App\Models\Auth\Permission;
|
||||
use App\Models\Auth\Role;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class FinanceLedgerFlowSummarySpreadsheetTest extends FeatureTestCase
|
||||
{
|
||||
private string $accountShort;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Carbon::setTestNow('2026-11-10 12:00:00');
|
||||
$this->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('>新增行</button>', $html);
|
||||
$this->assertStringContainsString('>新增列</button>', $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="核对状态">核对状态</strong>', $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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -438,14 +438,17 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase
|
||||
]))->assertOk()->getContent();
|
||||
|
||||
$this->assertSame(1, preg_match('/<tr data-flow-summary-account="账户甲">.*?<\/tr>/s', $summaryHtml, $accountRow));
|
||||
$this->assertStringContainsString('<td>账户甲</td><td>—</td><td>甲公司</td>', $accountRow[0]);
|
||||
$this->assertMatchesRegularExpression('/<td>账户甲<\/td>\s*<td>—<\/td>\s*<td>甲公司<\/td>/', $accountRow[0]);
|
||||
$this->assertStringContainsString('>所属银行</span>', $summaryHtml);
|
||||
$this->assertStringContainsString('<td class="num">100.00</td><td class="num">10.00</td><td class="num"></td><td class="num">110.00</td><td class="num">1</td>', $accountRow[0]);
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/<td class="num">100\.00<\/td>\s*<td class="num">10\.00<\/td>\s*<td class="num"><\/td>\s*<td class="num">110\.00<\/td>\s*<td class="num">1<\/td>/',
|
||||
$accountRow[0],
|
||||
);
|
||||
$this->assertStringContainsString('data-flow-summary-edit', $accountRow[0]);
|
||||
$this->assertStringContainsString('data-edit-url=', $accountRow[0]);
|
||||
$this->assertStringContainsString('>编辑</span>', $accountRow[0]);
|
||||
$this->assertSame(1, preg_match('/<tr data-flow-summary-account="账户丙">.*?<\/tr>/s', $summaryHtml, $emptyAccountRow));
|
||||
$this->assertStringContainsString('<td>账户丙</td><td>—</td><td>丙公司</td>', $emptyAccountRow[0]);
|
||||
$this->assertMatchesRegularExpression('/<td>账户丙<\/td>\s*<td>—<\/td>\s*<td>丙公司<\/td>/', $emptyAccountRow[0]);
|
||||
$this->assertStringContainsString('<td class="num">—</td>', $emptyAccountRow[0]);
|
||||
$this->assertStringContainsString('<td>尚未起账</td>', $emptyAccountRow[0]);
|
||||
$this->assertStringContainsString('>账户汇总</a>', $summaryHtml);
|
||||
@ -498,8 +501,10 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase
|
||||
]))->assertOk()->getContent();
|
||||
|
||||
foreach ($affiliations as $suffix => $expected) {
|
||||
$this->assertStringContainsString(
|
||||
'<td>映射账户' . $suffix . '</td><td>' . $expected . '</td><td>映射公司' . $suffix . '</td>',
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/<td>' . preg_quote('映射账户' . $suffix, '/') . '<\/td>\s*<td>'
|
||||
. preg_quote($expected, '/') . '<\/td>\s*<td>'
|
||||
. preg_quote('映射公司' . $suffix, '/') . '<\/td>/',
|
||||
$html,
|
||||
);
|
||||
}
|
||||
|
||||
@ -241,8 +241,8 @@ class FinanceLedgerManualEditTest extends FeatureTestCase
|
||||
1,
|
||||
preg_match('/<tr data-flow-summary-account="手动编辑测试账户">.*?<\/tr>/s', $summaryHtml, $accountRow),
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
'<td class="num">100.00</td><td class="num">35.00</td><td class="num">30.00</td><td class="num">105.00</td>',
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/<td class="num">100\.00<\/td>\s*<td class="num">35\.00<\/td>\s*<td class="num">30\.00<\/td>\s*<td class="num">105\.00<\/td>/',
|
||||
$accountRow[0],
|
||||
);
|
||||
$this->assertStringContainsString('data-flow-summary-edit', $accountRow[0]);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user