diff --git a/app/Http/Controllers/Business/FinanceLedger.php b/app/Http/Controllers/Business/FinanceLedger.php index 4b812992..98f2631f 100644 --- a/app/Http/Controllers/Business/FinanceLedger.php +++ b/app/Http/Controllers/Business/FinanceLedger.php @@ -1693,25 +1693,60 @@ class FinanceLedger extends Controller ], 200, ['Cache-Control' => 'private, no-store']); } + public function insertIndependentTransactions( + Request $request, + int $id, + FinanceLedgerIndependentTransactionEditor $editor, + ): JsonResponse { + abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有插入独立账单明细权限。'); + + $data = $request->validate([ + 'position' => ['required', 'string', Rule::in(['above', 'below'])], + 'count' => ['required', 'integer', 'min:1', 'max:20'], + ]); + $rows = $editor->insertAround( + $id, + (string) $data['position'], + (int) $data['count'], + ); + + return response()->json([ + 'ok' => true, + 'rows' => $rows, + 'message' => '已插入 ' . count($rows) . ' 行明细。', + ], 201, ['Cache-Control' => 'private, no-store']); + } + public function storeIndependentTransactionColumn( Request $request, FinanceLedgerIndependentTransactionColumnEditor $editor, ): JsonResponse { abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有维护独立账单列权限。'); + if (! $request->filled('field_names') && $request->filled('field_name')) { + $request->merge([ + 'field_names' => [(string) $request->input('field_name')], + ]); + } $data = $request->validate([ 'account_short' => ['required', 'string', 'max:100'], - 'field_name' => ['required', 'string', 'max:50'], + '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'])], ]); - $field = $editor->create( + $fields = $editor->createBatch( trim((string) $data['account_short']), - (string) $data['field_name'], + 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, - 'field' => $field, - 'message' => '自定义列已新增。', + 'field' => $fields[0], + 'fields' => $fields, + 'message' => '自定义列已插入。', ], 201, ['Cache-Control' => 'private, no-store']); } diff --git a/database/migrations/2026_11_10_200000_add_display_order_to_finance_ledger_transactions.php b/database/migrations/2026_11_10_200000_add_display_order_to_finance_ledger_transactions.php new file mode 100644 index 00000000..64e58895 --- /dev/null +++ b/database/migrations/2026_11_10_200000_add_display_order_to_finance_ledger_transactions.php @@ -0,0 +1,44 @@ +connection()); + if (! $schema->hasTable('fin_transactions') + || $schema->hasColumn('fin_transactions', 'display_order')) { + return; + } + + $schema->table('fin_transactions', function (Blueprint $table): void { + $table->decimal('display_order', 30, 10)->nullable()->after('row_key'); + $table->index( + ['txn_date', 'display_order'], + 'fin_transactions_date_display_order_index', + ); + }); + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('fin_transactions') + || ! $schema->hasColumn('fin_transactions', 'display_order')) { + return; + } + + $schema->table('fin_transactions', function (Blueprint $table): void { + $table->dropIndex('fin_transactions_date_display_order_index'); + $table->dropColumn('display_order'); + }); + } +}; diff --git a/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionColumnEditor.php b/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionColumnEditor.php index fbec5f2b..3d4b23d9 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionColumnEditor.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionColumnEditor.php @@ -27,57 +27,150 @@ class FinanceLedgerIndependentTransactionColumnEditor */ public function create(string $accountShort, string $fieldName): array { + $fields = $this->createBatch($accountShort, [$fieldName], null, 'end'); + + return $fields[0]; + } + + /** + * @param list $fieldNames + * @return list> + */ + public function createBatch( + string $accountShort, + array $fieldNames, + ?int $anchorFieldId = null, + string $position = 'end', + ): array { $accountShort = trim($accountShort); if (! FinanceLedgerIndependentAccounts::contains($accountShort)) { throw ValidationException::withMessages([ 'account_short' => '只有独立账单页面可以新增自定义列。', ]); } - $fieldName = preg_replace('/\s+/u', ' ', trim($fieldName)) ?? trim($fieldName); - if ($fieldName === '') { + $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_name' => '请填写列名。', + 'field_names' => '一次可新增 1 至 20 个自定义列。', ]); } - if (mb_strlen($fieldName) > 50) { + 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_name' => '列名不能超过 50 个字符。', + 'field_names' => '一次新增的列名不能重复。', ]); } - return $this->connection->transaction(function () use ($accountShort, $fieldName): array { - $fields = $this->connection->table('fin_transaction_custom_fields') - ->where('account_short', $accountShort); - if ((clone $fields)->count() >= self::MAX_COLUMNS) { + return $this->connection->transaction(function () use ( + $accountShort, + $fieldNames, + $normalizedNames, + $anchorFieldId, + $position, + ): array { + $existingFields = $this->connection->table('fin_transaction_custom_fields') + ->where('account_short', $accountShort) + ->orderBy('sort_order') + ->orderBy('id') + ->lockForUpdate() + ->get(); + if ($existingFields->count() + count($fieldNames) > self::MAX_COLUMNS) { throw ValidationException::withMessages([ - 'field_name' => '每个独立账单最多可设置 ' . self::MAX_COLUMNS . ' 个自定义列。', + 'field_names' => '每个独立账单最多可设置 ' . self::MAX_COLUMNS . ' 个自定义列。', ]); } - if ((clone $fields)->where('field_name', $fieldName)->exists()) { + $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_name' => '该页面已存在同名列。', + '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(); - $field = [ - 'account_short' => $accountShort, - 'field_key' => (string) Str::uuid(), - 'field_name' => $fieldName, - 'sort_order' => ((int) (clone $fields)->max('sort_order')) + 10, - 'created_by' => (string) (user()?->name ?? ''), - 'updated_by' => (string) (user()?->name ?? ''), - 'created_at' => $now, - 'updated_at' => $now, - ]; - $id = (int) $this->connection->table('fin_transaction_custom_fields')->insertGetId($field); + $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 = [ + 'account_short' => $accountShort, + '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_transaction_custom_fields') + ->insertGetId($values); + $created[] = ['id' => $id] + $values; + continue; + } + + if ((int) $field->sort_order !== $sortOrder) { + $this->connection->table('fin_transaction_custom_fields') + ->where('id', (int) $field->id) + ->update([ + 'sort_order' => $sortOrder, + 'updated_by' => (string) (user()?->name ?? ''), + 'updated_at' => $now, + ]); + } + } $this->audit( 'statement_col_add', - $accountShort . '|' . $field['field_key'], - ['after' => $field + ['id' => $id]], + $accountShort . '|' . (string) Str::uuid(), + [ + 'position' => $position, + 'anchor_field_id' => $anchorFieldId, + 'after' => $created, + ], ); - return ['id' => $id] + $field; + return $created; }); } diff --git a/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionEditor.php b/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionEditor.php index 66eb6f39..496c4a1f 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionEditor.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerIndependentTransactionEditor.php @@ -6,6 +6,7 @@ use App\Utilities\FinanceLedgerIndependentAccounts; use Carbon\CarbonImmutable; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; +use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -148,6 +149,115 @@ class FinanceLedgerIndependentTransactionEditor }); } + /** + * @return list + */ + public function insertAround(int $id, string $position, int $count): array + { + if (! in_array($position, ['above', 'below'], true) || $count < 1 || $count > 20) { + throw ValidationException::withMessages([ + 'position' => '请选择在上方或下方插入 1 至 20 行。', + ]); + } + + return $this->connection->transaction(function () use ($id, $position, $count): array { + $anchor = $this->activeRow($id, true); + $rows = $this->connection->table('fin_transactions') + ->where('account_short', (string) $anchor->account_short) + ->whereDate('txn_date', (string) $anchor->txn_date) + ->whereNull('deleted_at') + ->orderByRaw('COALESCE(display_order, id) DESC') + ->orderByDesc('id') + ->lockForUpdate() + ->get(['id', 'display_order']); + $anchorIndex = $rows->search( + static fn (object $row): bool => (int) $row->id === $id, + ); + if ($anchorIndex === false) { + throw new NotFoundHttpException('未找到要插入位置的独立账单明细。'); + } + $orders = $this->insertOrders($rows->values()->all(), (int) $anchorIndex, $position, $count); + $now = now(); + $created = []; + foreach ($orders as $displayOrder) { + $rowKey = hash('sha256', 'independent-insert:' . (string) Str::uuid()); + $insertedId = (int) $this->connection->table('fin_transactions')->insertGetId([ + 'txn_date' => substr((string) $anchor->txn_date, 0, 10), + 'account_short' => (string) $anchor->account_short, + 'counterparty_info' => null, + 'detail' => null, + 'income' => 0, + 'expense' => 0, + 'balance' => null, + 'approval_no' => null, + 'payment_remark' => null, + 'source' => FinanceLedgerTransactionWriter::MANUAL_SOURCE, + 'source_value' => null, + 'process_type' => '手工插入', + 'row_key' => $rowKey, + 'display_order' => $displayOrder, + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + 'created_by' => (string) (user()?->name ?? ''), + 'updated_by' => (string) (user()?->name ?? ''), + ]); + $created[] = [ + 'id' => $insertedId, + 'display_order' => $displayOrder, + ]; + } + $this->audit( + 'stmt_txn_insert', + (string) $anchor->row_key, + [ + 'anchor_id' => $id, + 'position' => $position, + 'count' => $count, + 'after' => $created, + ], + ); + + return $created; + }); + } + + /** + * @param list $rows + * @return list + */ + private function insertOrders(array $rows, int $anchorIndex, string $position, int $count): array + { + $anchorOrder = $this->displayOrder($rows[$anchorIndex]); + $orders = []; + if ($position === 'above') { + $upperOrder = $anchorIndex > 0 ? $this->displayOrder($rows[$anchorIndex - 1]) : null; + for ($index = 1; $index <= $count; $index++) { + $orders[] = $upperOrder === null || $upperOrder <= $anchorOrder + ? $anchorOrder + $index + : round($anchorOrder + (($upperOrder - $anchorOrder) * $index / ($count + 1)), 10); + } + + return $orders; + } + + $lowerOrder = $anchorIndex + 1 < count($rows) + ? $this->displayOrder($rows[$anchorIndex + 1]) + : null; + for ($index = 1; $index <= $count; $index++) { + $orders[] = $lowerOrder === null || $lowerOrder >= $anchorOrder + ? $anchorOrder - $index + : round($lowerOrder + (($anchorOrder - $lowerOrder) * $index / ($count + 1)), 10); + } + + return $orders; + } + + private function displayOrder(object $row): float + { + return $row->display_order === null ? (float) $row->id : (float) $row->display_order; + } + private function activeRow(int $id, bool $lock = false): object { $query = $this->connection->table('fin_transactions') diff --git a/modules/EcommerceFinance/View/FinanceLedgerPageData.php b/modules/EcommerceFinance/View/FinanceLedgerPageData.php index a4dca4f5..13164d4d 100644 --- a/modules/EcommerceFinance/View/FinanceLedgerPageData.php +++ b/modules/EcommerceFinance/View/FinanceLedgerPageData.php @@ -810,7 +810,10 @@ class FinanceLedgerPageData $summary = $this->transactionSummaryMetrics($query, $accountShort, $period); $sorted = $this->applyLedgerHeaderSort($query, 'transactions', $headerColumns); if (! $sorted) { - $query->orderByDesc('t.txn_date')->orderByDesc('t.id'); + $t = $this->queryAlias('t'); + $query->orderByDesc('t.txn_date') + ->orderByRaw("COALESCE({$t}.display_order, {$t}.id) DESC") + ->orderByDesc('t.id'); } $customFields = FinanceLedgerIndependentAccounts::contains($accountShort) ? $this->transactionCustomFields((string) $accountShort) @@ -1112,8 +1115,10 @@ class FinanceLedgerPageData $periodQuery = clone $historyQuery; $this->applyDateRange($periodQuery, 't.txn_date', $period); + $t = $this->queryAlias('t'); $first = $periodQuery ->orderBy('t.txn_date') + ->orderByRaw("COALESCE({$t}.display_order, {$t}.id) ASC") ->orderBy('t.id') ->first(['t.txn_date', 't.income', 't.expense', 't.balance']); if ($first !== null) { @@ -1128,9 +1133,11 @@ class FinanceLedgerPageData return null; } + $t = $this->queryAlias('t'); $prior = (clone $historyQuery) ->where('t.txn_date', '<', $from) ->orderByDesc('t.txn_date') + ->orderByRaw("COALESCE({$t}.display_order, {$t}.id) DESC") ->orderByDesc('t.id') ->value('t.balance'); @@ -1140,10 +1147,12 @@ class FinanceLedgerPageData private function independentTransactionCurrentBalance(string $accountShort): ?float { $effectiveAccount = $this->transactionHeaderColumns()['effective_account_short']['sort']; + $t = $this->queryAlias('t'); $balance = $this->transactionScopeQuery() ->whereRaw($effectiveAccount . ' = ?', [$accountShort]) ->whereNotNull('t.balance') ->orderByDesc('t.txn_date') + ->orderByRaw("COALESCE({$t}.display_order, {$t}.id) DESC") ->orderByDesc('t.id') ->value('t.balance'); @@ -1180,6 +1189,7 @@ class FinanceLedgerPageData 't.source_value', 't.process_type', 't.row_key', + 't.display_order', 't.synced_at', 't.created_at', 't.updated_at', diff --git a/resources/views/business/pages/financial-ledger/ledger.blade.php b/resources/views/business/pages/financial-ledger/ledger.blade.php index 01a95a9e..aa61bf40 100644 --- a/resources/views/business/pages/financial-ledger/ledger.blade.php +++ b/resources/views/business/pages/financial-ledger/ledger.blade.php @@ -571,9 +571,31 @@ .ledger-manual-badge { display:inline-flex; margin-left:.25rem; padding:.08rem .28rem; border-radius:.25rem; background:#fff8eb; color:var(--vip-warning, #935F07); font-size:.58rem; font-weight:700; vertical-align:middle; } .ledger-custom-column-head { display:flex; align-items:center; gap:.3rem; min-width:0; } .ledger-custom-column-head strong { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } + .ledger-custom-column-actions { display:inline-flex; flex:none; align-items:center; gap:.1rem; } + .ledger-custom-column-insert, .ledger-custom-column-delete { display:inline-grid; flex:none; place-items:center; width:1.35rem; height:1.35rem; padding:0; border:1px solid transparent; border-radius:.25rem; background:transparent; color:var(--vip-danger, #B80000); cursor:pointer; } + .ledger-custom-column-insert { color:var(--vip-content-accent-dark, #856632); } + .ledger-custom-column-insert:hover, .ledger-custom-column-insert:focus-visible { border-color:rgba(133,102,50,.35); background:var(--vip-content-accent-soft, #F7F0DE); outline:none; } .ledger-custom-column-delete:hover, .ledger-custom-column-delete:focus-visible { border-color:rgba(184,0,0,.35); background:#fff5f5; outline:none; } + .ledger-custom-column-insert .material-icons-outlined, .ledger-custom-column-delete .material-icons-outlined { font-size:.9rem; } + .ledger-row-insert { color:var(--vip-content-accent-dark, #856632); } + .ledger-excel-insert-menu { position:fixed; z-index:95; width:19rem; padding:.55rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.55rem; background:#fff; box-shadow:0 8px 22px rgba(23,23,23,.18); color:var(--vip-content-ink, #171717); } + .ledger-excel-insert-menu[hidden] { display:none !important; } + .ledger-excel-insert-menu__title { margin:0 0 .45rem; padding:0 .2rem .45rem; border-bottom:1px solid #e8e3da; font-size:.72rem; font-weight:700; } + .ledger-excel-insert-menu__options { display:grid; gap:.25rem; } + .ledger-excel-insert-menu__options button { display:flex; align-items:center; gap:.4rem; min-height:2rem; padding:0 .5rem; border:1px solid transparent; border-radius:.35rem; background:#fff; color:var(--vip-content-ink, #171717); font:inherit; font-size:.72rem; text-align:left; cursor:pointer; } + .ledger-excel-insert-menu__options button:hover, + .ledger-excel-insert-menu__options button.is-active { border-color:rgba(133,102,50,.3); background:var(--vip-content-accent-soft, #F7F0DE); color:var(--vip-content-accent-dark, #856632); } + .ledger-excel-insert-menu__options .material-icons-outlined { font-size:1rem; color:var(--vip-content-accent-dark, #856632); } + .ledger-excel-insert-menu__footer { display:flex; align-items:flex-end; gap:.45rem; margin-top:.5rem; padding-top:.5rem; border-top:1px solid #e8e3da; } + .ledger-excel-insert-menu__footer label { display:grid; flex:1; gap:.25rem; color:var(--vip-content-muted, #595959); font-size:.66rem; font-weight:600; } + .ledger-excel-insert-menu__footer input { width:100%; 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-variant-numeric:tabular-nums; } + .ledger-excel-insert-menu__apply { display:inline-grid; place-items:center; width:2rem; height:1.9rem; padding:0; border:1px solid var(--vip-content-accent-dark, #856632); border-radius:.35rem; background:var(--vip-content-accent-dark, #856632); color:#fff; cursor:pointer; } + .ledger-excel-insert-menu__apply:disabled { opacity:.58; cursor:wait; } + .ledger-statement-column-names { display:grid; gap:.55rem; } + .ledger-statement-column-name-row { display:grid; grid-template-columns:2rem minmax(0,1fr); align-items:center; gap:.5rem; } + .ledger-statement-column-name-row span { color:var(--vip-content-muted, #595959); font-size:.68rem; font-variant-numeric:tabular-nums; } .ledger-manual-custom-fields { grid-column:1 / -1; display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:.8rem; padding-top:.25rem; border-top:1px solid #e8e3da; } .ledger-manual-custom-fields[hidden] { display:none !important; } .ledger-manual-custom-fields__title { grid-column:1 / -1; margin:0; color:var(--vip-content-muted, #595959); font-size:.68rem; font-weight:700; } @@ -1118,7 +1140,7 @@ {{-- 动账明细 --}} -