feat: 完善动账明细修改和删除操作 (#1232)
Co-authored-by: 92451 <924518135@qq.com> Co-committed-by: 92451 <924518135@qq.com>
This commit is contained in:
parent
a2fbc66fb7
commit
33aa492f7b
@ -30,6 +30,7 @@ use Modules\EcommerceFinance\Services\FinanceLedgerFlowSummaryEditor;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerIndependentTransactionColumnEditor;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerIndependentTransactionEditor;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerInternalTransferEditor;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerLocalTransactionEditor;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerManualTransactionEditor;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerManualTransactionImporter;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerPayableMappingBulk;
|
||||
@ -2096,6 +2097,54 @@ class FinanceLedger extends Controller
|
||||
], 200, ['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
|
||||
public function updateLocalTransaction(
|
||||
Request $request,
|
||||
int $id,
|
||||
FinanceLedgerLocalTransactionEditor $editor,
|
||||
FinanceLedgerPageData $pageData,
|
||||
): JsonResponse {
|
||||
abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有修改动账明细权限。');
|
||||
|
||||
$openingDate = (string) config('finance_ledger.opening_date', '2026-10-17');
|
||||
$data = $request->validate([
|
||||
'txn_date' => ['required', 'date', 'after_or_equal:' . $openingDate],
|
||||
'counterparty_info' => ['nullable', 'string', 'max:255'],
|
||||
'detail' => ['nullable', 'string', 'max:4000'],
|
||||
'income' => ['nullable', 'numeric', 'min:0', 'max:9999999999999999.99'],
|
||||
'expense' => ['nullable', 'numeric', 'min:0', 'max:9999999999999999.99'],
|
||||
'balance' => ['nullable', 'numeric', 'max:9999999999999999.99'],
|
||||
'approval_no' => ['nullable', 'string', 'max:100'],
|
||||
'payment_remark' => ['nullable', 'string', 'max:500'],
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'ok' => true,
|
||||
'transaction' => $editor->update($id, $data),
|
||||
'summary' => $pageData->transactionSummary(),
|
||||
'total_transactions' => $pageData->globalTransactionCount(),
|
||||
'message' => '动账明细已保存,资金流水和当前余额已重新计算。',
|
||||
], 200, ['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
|
||||
public function deleteLocalTransaction(
|
||||
int $id,
|
||||
FinanceLedgerLocalTransactionEditor $editor,
|
||||
FinanceLedgerPageData $pageData,
|
||||
): JsonResponse {
|
||||
abort_unless(FinanceLedgerAccess::canEditTransactions(user()), 403, '当前账号没有删除动账明细权限。');
|
||||
|
||||
$deleted = $editor->delete($id);
|
||||
|
||||
return response()->json([
|
||||
'ok' => true,
|
||||
'deleted' => true,
|
||||
'transaction' => $deleted,
|
||||
'summary' => $pageData->transactionSummary(),
|
||||
'total_transactions' => $pageData->globalTransactionCount(),
|
||||
'message' => '动账明细已删除,资金流水和当前余额已重新计算。',
|
||||
], 200, ['Cache-Control' => 'private, no-store']);
|
||||
}
|
||||
|
||||
public function insertIndependentTransactions(
|
||||
Request $request,
|
||||
int $id,
|
||||
|
||||
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private string $mirrorConnection;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->mirrorConnection = (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->mirrorConnection);
|
||||
if (! $schema->hasTable('fin_transactions')
|
||||
|| $schema->hasColumn('fin_transactions', 'local_override')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table('fin_transactions', function (Blueprint $table): void {
|
||||
$table->boolean('local_override')->default(false)->after('updated_by');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = Schema::connection($this->mirrorConnection);
|
||||
if (! $schema->hasTable('fin_transactions')
|
||||
|| ! $schema->hasColumn('fin_transactions', 'local_override')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table('fin_transactions', function (Blueprint $table): void {
|
||||
$table->dropColumn('local_override');
|
||||
});
|
||||
}
|
||||
};
|
||||
@ -19,8 +19,10 @@ class CompanyAlipayBillImporter
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
public function __construct(
|
||||
DatabaseManager $databases,
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
@ -88,12 +90,14 @@ class CompanyAlipayBillImporter
|
||||
$income,
|
||||
$expense,
|
||||
): array {
|
||||
$this->connection->table('fin_transactions')
|
||||
$delete = $this->connection->table('fin_transactions')
|
||||
->where('source', self::SOURCE)
|
||||
->where('source_value', $accountNo)
|
||||
->whereDate('txn_date', $date)
|
||||
->delete();
|
||||
foreach (array_chunk($rows, 500) as $chunk) {
|
||||
->whereDate('txn_date', $date);
|
||||
$this->localOverrides->excludeFromReplacement($delete);
|
||||
$delete->delete();
|
||||
$writtenRows = $this->localOverrides->filterRows($rows, true);
|
||||
foreach (array_chunk($writtenRows, 500) as $chunk) {
|
||||
$this->connection->table('fin_transactions')->insert($chunk);
|
||||
}
|
||||
|
||||
@ -102,14 +106,15 @@ class CompanyAlipayBillImporter
|
||||
['source' => self::SOURCE, 'source_value' => $accountNo],
|
||||
[
|
||||
'account_short' => (string) $account->account_short,
|
||||
'txn_count' => count($rows),
|
||||
'income_sum' => $income,
|
||||
'expense_sum' => $expense,
|
||||
'txn_count' => 0,
|
||||
'income_sum' => 0,
|
||||
'expense_sum' => 0,
|
||||
'updated_by' => '系统自动同步',
|
||||
'updated_at' => $now,
|
||||
'created_at' => $now,
|
||||
],
|
||||
);
|
||||
$this->localOverrides->refreshMappingFor(self::SOURCE, $accountNo);
|
||||
|
||||
return app(FinanceLedgerCalculator::class)->recalculate();
|
||||
});
|
||||
|
||||
@ -29,6 +29,7 @@ class CompanyAlipayStatementImporter
|
||||
DatabaseManager $databases,
|
||||
private readonly FinanceLedgerCalculator $calculator,
|
||||
private readonly FinanceLedgerTransactionWriter $writer,
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
@ -120,9 +121,12 @@ class CompanyAlipayStatementImporter
|
||||
$expense,
|
||||
): array {
|
||||
foreach (array_chunk($replaceIds, 500) as $ids) {
|
||||
$this->connection->table('fin_transactions')->whereIn('id', $ids)->delete();
|
||||
$delete = $this->connection->table('fin_transactions')->whereIn('id', $ids);
|
||||
$this->localOverrides->excludeFromReplacement($delete);
|
||||
$delete->delete();
|
||||
}
|
||||
foreach (array_chunk($rows, 500) as $chunk) {
|
||||
$writtenRows = $this->localOverrides->filterRows($rows, true);
|
||||
foreach (array_chunk($writtenRows, 500) as $chunk) {
|
||||
$this->connection->table('fin_transactions')->upsert(
|
||||
$chunk,
|
||||
['row_key'],
|
||||
@ -337,6 +341,9 @@ class CompanyAlipayStatementImporter
|
||||
->on('m.source_value', '=', 't.source_value');
|
||||
})
|
||||
->whereNull('t.deleted_at')
|
||||
->where(function ($query): void {
|
||||
$query->where('t.local_override', false)->orWhereNull('t.local_override');
|
||||
})
|
||||
->whereBetween('t.txn_date', [$from, $to])
|
||||
->whereIn('t.source', $sources)
|
||||
->where(function ($query) use ($account): void {
|
||||
|
||||
@ -66,6 +66,7 @@ class FinanceLedgerIndependentTransactionEditor
|
||||
'approval_no' => $this->nullableText($data['approval_no'] ?? null, 100),
|
||||
'payment_remark' => $this->nullableText($data['payment_remark'] ?? null, 500),
|
||||
'source' => trim((string) ($data['source'] ?? $before->source)),
|
||||
'local_override' => true,
|
||||
'updated_by' => (string) (user()?->name ?? ''),
|
||||
'updated_at' => $now,
|
||||
];
|
||||
@ -133,6 +134,7 @@ class FinanceLedgerIndependentTransactionEditor
|
||||
|
||||
$this->connection->table('fin_transactions')->where('id', $id)->update([
|
||||
'deleted_at' => $now,
|
||||
'local_override' => true,
|
||||
'updated_by' => (string) (user()?->name ?? ''),
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use App\Utilities\FinanceLedgerIndependentAccounts;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class FinanceLedgerLocalTransactionEditor
|
||||
{
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(
|
||||
DatabaseManager $databases,
|
||||
private readonly FinanceLedgerCalculator $calculator,
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $guard,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $data
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function update(int $id, array $data): array
|
||||
{
|
||||
$date = $this->date($data['txn_date'] ?? null);
|
||||
$incomeCents = $this->cents($data['income'] ?? 0);
|
||||
$expenseCents = $this->cents($data['expense'] ?? 0);
|
||||
if (($incomeCents > 0) === ($expenseCents > 0)) {
|
||||
throw ValidationException::withMessages([
|
||||
'income' => '收入和支出只能填写一项。',
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->connection->transaction(function () use (
|
||||
$id,
|
||||
$date,
|
||||
$incomeCents,
|
||||
$expenseCents,
|
||||
$data,
|
||||
): array {
|
||||
$before = $this->localRow($id, true);
|
||||
$now = now();
|
||||
$values = [
|
||||
'txn_date' => $date,
|
||||
'counterparty_info' => $this->nullableText($data['counterparty_info'] ?? null, 255, 'counterparty_info'),
|
||||
'detail' => $this->nullableText($data['detail'] ?? null, 4000, 'detail'),
|
||||
'income' => $incomeCents / 100,
|
||||
'expense' => $expenseCents / 100,
|
||||
'balance' => $this->nullableMoney($data['balance'] ?? null),
|
||||
'approval_no' => $this->nullableText($data['approval_no'] ?? null, 100, 'approval_no'),
|
||||
'payment_remark' => $this->nullableText($data['payment_remark'] ?? null, 500, 'payment_remark'),
|
||||
'local_override' => true,
|
||||
'updated_by' => (string) (user()?->name ?? ''),
|
||||
'updated_at' => $now,
|
||||
];
|
||||
$this->connection->table('fin_transactions')->where('id', $id)->update($values);
|
||||
$after = array_merge($this->rowSnapshot($before), $values);
|
||||
$this->audit('transaction_local_update', (string) $before->row_key, [
|
||||
'before' => $this->rowSnapshot($before),
|
||||
'after' => $after,
|
||||
]);
|
||||
$this->guard->refreshMappingFor(
|
||||
(string) $before->source,
|
||||
$before->source_value !== null ? (string) $before->source_value : null,
|
||||
);
|
||||
$this->calculator->recalculate();
|
||||
|
||||
return $after;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function delete(int $id): array
|
||||
{
|
||||
return $this->connection->transaction(function () use ($id): array {
|
||||
$before = $this->localRow($id, true);
|
||||
$now = now();
|
||||
$this->connection->table('fin_transactions')->where('id', $id)->update([
|
||||
'local_override' => true,
|
||||
'deleted_at' => $now,
|
||||
'updated_by' => (string) (user()?->name ?? ''),
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
$snapshot = $this->rowSnapshot($before);
|
||||
$this->audit('transaction_local_delete', (string) $before->row_key, [
|
||||
'before' => $snapshot,
|
||||
'after' => null,
|
||||
]);
|
||||
$this->guard->refreshMappingFor(
|
||||
(string) $before->source,
|
||||
$before->source_value !== null ? (string) $before->source_value : null,
|
||||
);
|
||||
$this->calculator->recalculate();
|
||||
|
||||
return $snapshot;
|
||||
});
|
||||
}
|
||||
|
||||
private function localRow(int $id, bool $lock = false): object
|
||||
{
|
||||
$query = $this->connection->table('fin_transactions')
|
||||
->where('id', $id)
|
||||
->whereNull('deleted_at');
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
$row = $query->first();
|
||||
if ($row === null) {
|
||||
throw new NotFoundHttpException('未找到可编辑的动账明细。');
|
||||
}
|
||||
if ((string) $row->source === FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE) {
|
||||
throw ValidationException::withMessages([
|
||||
'transaction' => '内部转账需整笔删除,不能单独修改其中一侧。',
|
||||
]);
|
||||
}
|
||||
if ((string) $row->source === FinanceLedgerTransactionWriter::MANUAL_SOURCE
|
||||
|| FinanceLedgerIndependentAccounts::contains($row->account_short)) {
|
||||
throw ValidationException::withMessages([
|
||||
'transaction' => '该明细应通过对应的手工或独立账单入口编辑。',
|
||||
]);
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function rowSnapshot(object $row): array
|
||||
{
|
||||
return [
|
||||
'id' => (int) $row->id,
|
||||
'row_key' => (string) $row->row_key,
|
||||
'txn_date' => substr((string) $row->txn_date, 0, 10),
|
||||
'account_short' => (string) ($row->account_short ?? ''),
|
||||
'counterparty_info' => $row->counterparty_info !== null ? (string) $row->counterparty_info : null,
|
||||
'detail' => $row->detail !== null ? (string) $row->detail : null,
|
||||
'income' => round((float) $row->income, 2),
|
||||
'expense' => round((float) $row->expense, 2),
|
||||
'balance' => $row->balance !== null ? round((float) $row->balance, 2) : null,
|
||||
'approval_no' => $row->approval_no !== null ? (string) $row->approval_no : null,
|
||||
'payment_remark' => $row->payment_remark !== null ? (string) $row->payment_remark : null,
|
||||
'source' => (string) $row->source,
|
||||
'source_value' => $row->source_value !== null ? (string) $row->source_value : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $changes
|
||||
*/
|
||||
private function audit(string $entityType, string $rowKey, array $changes): void
|
||||
{
|
||||
$this->connection->table('fin_ledger_edit_events')->insert([
|
||||
'entity_type' => $entityType,
|
||||
'entity_key' => 'transaction|' . $rowKey,
|
||||
'changes' => json_encode($changes, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||
'user_id' => user()?->id,
|
||||
'user_name' => (string) (user()?->name ?? ''),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function date(mixed $value): string
|
||||
{
|
||||
$text = trim((string) $value);
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $text);
|
||||
if (! $date instanceof CarbonImmutable || $date->format('Y-m-d') !== $text) {
|
||||
throw ValidationException::withMessages([
|
||||
'txn_date' => '动账日期必须使用 YYYY-MM-DD 格式。',
|
||||
]);
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
private function cents(mixed $value): int
|
||||
{
|
||||
return (int) round((float) $value * 100);
|
||||
}
|
||||
|
||||
private function nullableMoney(mixed $value): ?float
|
||||
{
|
||||
$text = trim((string) ($value ?? ''));
|
||||
|
||||
return $text === '' ? null : round((float) $text, 2);
|
||||
}
|
||||
|
||||
private function nullableText(mixed $value, int $length, string $field): ?string
|
||||
{
|
||||
$text = trim((string) ($value ?? ''));
|
||||
if ($text === '') {
|
||||
return null;
|
||||
}
|
||||
$text = preg_replace('/\s+/u', ' ', $text) ?? $text;
|
||||
if (mb_strlen($text) > $length) {
|
||||
throw ValidationException::withMessages([
|
||||
$field => '字段内容超过允许长度。',
|
||||
]);
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
}
|
||||
@ -21,6 +21,7 @@ class FinanceLedgerShopDataSynchronizer
|
||||
private readonly JushuitanShopBalanceRepository $shopBalances,
|
||||
private readonly BillingDetailsPageData $billingDetails,
|
||||
private readonly StoreReceivingBillBalanceSnapshotSynchronizer $balanceSnapshots,
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
@ -429,16 +430,22 @@ class FinanceLedgerShopDataSynchronizer
|
||||
$writtenExpense += $targetExpenseCents;
|
||||
}
|
||||
|
||||
foreach (array_chunk($rows, 400) as $chunk) {
|
||||
$this->connection->table('fin_transactions')->upsert(
|
||||
$chunk,
|
||||
['row_key'],
|
||||
[
|
||||
'txn_date', 'account_short', 'detail', 'income', 'expense', 'approval_no',
|
||||
'source', 'source_value', 'process_type', 'synced_at', 'updated_at',
|
||||
],
|
||||
);
|
||||
}
|
||||
$this->connection->transaction(function () use ($rows): void {
|
||||
foreach (array_chunk($rows, 400) as $chunk) {
|
||||
$writtenRows = $this->localOverrides->filterRows($chunk, true);
|
||||
if ($writtenRows === []) {
|
||||
continue;
|
||||
}
|
||||
$this->connection->table('fin_transactions')->upsert(
|
||||
$writtenRows,
|
||||
['row_key'],
|
||||
[
|
||||
'txn_date', 'account_short', 'detail', 'income', 'expense', 'approval_no',
|
||||
'source', 'source_value', 'process_type', 'synced_at', 'updated_at',
|
||||
],
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return [
|
||||
'from' => $from,
|
||||
|
||||
@ -27,6 +27,11 @@ class FinanceLedgerSnapshotImporter
|
||||
'店铺提现' => 'shop',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
}
|
||||
|
||||
public function import(string $path, bool $recalculate = true): array
|
||||
{
|
||||
if (! is_file($path)) {
|
||||
@ -100,21 +105,24 @@ class FinanceLedgerSnapshotImporter
|
||||
throw new RuntimeException('台账快照没有可导入的动账明细。');
|
||||
}
|
||||
|
||||
$connection->transaction(function () use ($connection, $rows, $now): void {
|
||||
$connection->table('fin_transactions')
|
||||
$writtenRows = [];
|
||||
$connection->transaction(function () use ($connection, $rows, $now, &$writtenRows): void {
|
||||
$delete = $connection->table('fin_transactions')
|
||||
->where('source', '<>', FinanceLedgerTransactionWriter::MANUAL_SOURCE)
|
||||
->whereNotIn('account_short', FinanceLedgerIndependentAccounts::names())
|
||||
->delete();
|
||||
foreach (array_chunk($rows, 500) as $chunk) {
|
||||
->whereNotIn('account_short', FinanceLedgerIndependentAccounts::names());
|
||||
$this->localOverrides->excludeFromReplacement($delete);
|
||||
$delete->delete();
|
||||
$writtenRows = $this->localOverrides->filterRows($rows, true);
|
||||
foreach (array_chunk($writtenRows, 500) as $chunk) {
|
||||
$connection->table('fin_transactions')->insert($chunk);
|
||||
}
|
||||
$this->refreshMappingStats($connection, $now);
|
||||
});
|
||||
|
||||
$result = [
|
||||
'rows' => count($rows),
|
||||
'income' => round(array_sum(array_column($rows, 'income')), 2),
|
||||
'expense' => round(array_sum(array_column($rows, 'expense')), 2),
|
||||
'rows' => count($writtenRows),
|
||||
'income' => round(array_sum(array_column($writtenRows, 'income')), 2),
|
||||
'expense' => round(array_sum(array_column($writtenRows, 'expense')), 2),
|
||||
'from' => min(array_column($rows, 'txn_date')),
|
||||
'to' => max(array_column($rows, 'txn_date')),
|
||||
];
|
||||
|
||||
@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
|
||||
class FinanceLedgerTransactionLocalOverrideGuard
|
||||
{
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function filterRows(array $rows, bool $lock = false): array
|
||||
{
|
||||
if ($rows === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rowKeys = array_values(array_unique(array_filter(
|
||||
array_map(static fn (array $row): string => trim((string) ($row['row_key'] ?? '')), $rows),
|
||||
static fn (string $rowKey): bool => $rowKey !== '',
|
||||
)));
|
||||
if ($rowKeys === []) {
|
||||
return $rows;
|
||||
}
|
||||
|
||||
$overridden = [];
|
||||
foreach (array_chunk($rowKeys, 500) as $chunk) {
|
||||
$query = $this->connection->table('fin_transactions')
|
||||
->whereIn('row_key', $chunk)
|
||||
->where('local_override', true);
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
foreach ($query->pluck('row_key') as $rowKey) {
|
||||
$overridden[(string) $rowKey] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($overridden === []) {
|
||||
return $rows;
|
||||
}
|
||||
|
||||
return array_values(array_filter(
|
||||
$rows,
|
||||
static fn (array $row): bool => ! isset($overridden[(string) ($row['row_key'] ?? '')]),
|
||||
));
|
||||
}
|
||||
|
||||
public function excludeFromReplacement(Builder $query): void
|
||||
{
|
||||
$query->where(function (Builder $builder): void {
|
||||
$builder->where('local_override', false)->orWhereNull('local_override');
|
||||
});
|
||||
}
|
||||
|
||||
public function refreshMappingFor(string $source, ?string $sourceValue): void
|
||||
{
|
||||
$source = trim($source);
|
||||
$sourceValue = trim((string) $sourceValue);
|
||||
if ($source === '' || $sourceValue === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$stats = $this->connection->table('fin_transactions')
|
||||
->whereNull('deleted_at')
|
||||
->where('source', $source)
|
||||
->where('source_value', $sourceValue)
|
||||
->selectRaw('COUNT(*) AS txn_count, COALESCE(SUM(income), 0) AS income_sum, COALESCE(SUM(expense), 0) AS expense_sum')
|
||||
->first();
|
||||
$map = $this->connection->table('fin_account_map')
|
||||
->where('source', $source)
|
||||
->where('source_value', $sourceValue);
|
||||
|
||||
if ((int) ($stats->txn_count ?? 0) === 0) {
|
||||
$map->delete();
|
||||
return;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$map->update([
|
||||
'txn_count' => (int) $stats->txn_count,
|
||||
'income_sum' => round((float) $stats->income_sum, 2),
|
||||
'expense_sum' => round((float) $stats->expense_sum, 2),
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -20,6 +20,11 @@ class FinanceLedgerTransactionWriter
|
||||
|
||||
public const INTERNAL_TRANSFER_SOURCE = 'internal_transfer';
|
||||
|
||||
public function __construct(
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
}
|
||||
|
||||
public function replace(array $transactions, bool $recalculate = true): array
|
||||
{
|
||||
return $this->persist($transactions, $recalculate, true);
|
||||
@ -100,18 +105,21 @@ class FinanceLedgerTransactionWriter
|
||||
throw new RuntimeException('动账明细没有有效日期。');
|
||||
}
|
||||
|
||||
$connection->transaction(function () use ($connection, $rows, $now, $replaceExisting): void {
|
||||
$writtenRows = [];
|
||||
$connection->transaction(function () use ($connection, $rows, $now, $replaceExisting, &$writtenRows): void {
|
||||
if ($replaceExisting) {
|
||||
$connection->table('fin_transactions')
|
||||
$delete = $connection->table('fin_transactions')
|
||||
->whereNotIn('source', [
|
||||
self::MANUAL_SOURCE,
|
||||
self::SHOP_WITHDRAWAL_SOURCE,
|
||||
self::INTERNAL_TRANSFER_SOURCE,
|
||||
])
|
||||
->whereNotIn('account_short', FinanceLedgerIndependentAccounts::names())
|
||||
->delete();
|
||||
->whereNotIn('account_short', FinanceLedgerIndependentAccounts::names());
|
||||
$this->localOverrides->excludeFromReplacement($delete);
|
||||
$delete->delete();
|
||||
}
|
||||
foreach (array_chunk($rows, 500) as $chunk) {
|
||||
$writtenRows = $this->localOverrides->filterRows($rows, true);
|
||||
foreach (array_chunk($writtenRows, 500) as $chunk) {
|
||||
if ($replaceExisting) {
|
||||
$connection->table('fin_transactions')->insert($chunk);
|
||||
} else {
|
||||
@ -127,12 +135,13 @@ class FinanceLedgerTransactionWriter
|
||||
$this->refreshMappingStatsForConnection($connection, $now, $replaceExisting);
|
||||
});
|
||||
|
||||
$resultRows = $writtenRows !== [] ? $writtenRows : $rows;
|
||||
$result = [
|
||||
'rows' => count($rows),
|
||||
'income' => round(array_sum(array_column($rows, 'income')), 2),
|
||||
'expense' => round(array_sum(array_column($rows, 'expense')), 2),
|
||||
'from' => min(array_column($rows, 'txn_date')),
|
||||
'to' => max(array_column($rows, 'txn_date')),
|
||||
'rows' => count($writtenRows),
|
||||
'income' => round(array_sum(array_column($writtenRows, 'income')), 2),
|
||||
'expense' => round(array_sum(array_column($writtenRows, 'expense')), 2),
|
||||
'from' => min(array_column($resultRows, 'txn_date')),
|
||||
'to' => max(array_column($resultRows, 'txn_date')),
|
||||
];
|
||||
|
||||
if ($recalculate) {
|
||||
|
||||
@ -20,8 +20,10 @@ class WangshangBankBillImporter
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
public function __construct(
|
||||
DatabaseManager $databases,
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
@ -397,12 +399,14 @@ class WangshangBankBillImporter
|
||||
{
|
||||
return $this->connection->transaction(function () use ($entries, $date): array {
|
||||
foreach ($entries as $entry) {
|
||||
$this->connection->table('fin_transactions')
|
||||
$delete = $this->connection->table('fin_transactions')
|
||||
->where('source', self::SOURCE)
|
||||
->where('source_value', $entry['account'])
|
||||
->whereDate('txn_date', $date)
|
||||
->delete();
|
||||
foreach (array_chunk($entry['transactions'], 500) as $chunk) {
|
||||
->whereDate('txn_date', $date);
|
||||
$this->localOverrides->excludeFromReplacement($delete);
|
||||
$delete->delete();
|
||||
$writtenRows = $this->localOverrides->filterRows($entry['transactions'], true);
|
||||
foreach (array_chunk($writtenRows, 500) as $chunk) {
|
||||
$this->connection->table('fin_transactions')->insert($chunk);
|
||||
}
|
||||
|
||||
|
||||
@ -28,6 +28,7 @@ class WechatStatementImporter
|
||||
public function __construct(
|
||||
DatabaseManager $databases,
|
||||
private readonly FinanceLedgerCalculator $calculator,
|
||||
private readonly FinanceLedgerTransactionLocalOverrideGuard $localOverrides,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
@ -115,13 +116,15 @@ class WechatStatementImporter
|
||||
$openingBalance,
|
||||
$rows,
|
||||
): array {
|
||||
$this->connection->table('fin_transactions')
|
||||
$delete = $this->connection->table('fin_transactions')
|
||||
->where('source', self::SOURCE)
|
||||
->where('source_value', $accountShort)
|
||||
->whereNull('deleted_at')
|
||||
->whereBetween('txn_date', [$from, $to])
|
||||
->delete();
|
||||
foreach (array_chunk($rows, 500) as $chunk) {
|
||||
->whereBetween('txn_date', [$from, $to]);
|
||||
$this->localOverrides->excludeFromReplacement($delete);
|
||||
$delete->delete();
|
||||
$writtenRows = $this->localOverrides->filterRows($rows, true);
|
||||
foreach (array_chunk($writtenRows, 500) as $chunk) {
|
||||
$this->connection->table('fin_transactions')->upsert(
|
||||
$chunk,
|
||||
['row_key'],
|
||||
@ -149,14 +152,15 @@ class WechatStatementImporter
|
||||
['source' => self::SOURCE, 'source_value' => $accountShort],
|
||||
[
|
||||
'account_short' => $accountShort,
|
||||
'txn_count' => count($rows),
|
||||
'income_sum' => round(array_sum(array_column($rows, 'income')), 2),
|
||||
'expense_sum' => round(array_sum(array_column($rows, 'expense')), 2),
|
||||
'txn_count' => 0,
|
||||
'income_sum' => 0,
|
||||
'expense_sum' => 0,
|
||||
'updated_by' => '系统自动同步',
|
||||
'updated_at' => $now,
|
||||
'created_at' => $now,
|
||||
],
|
||||
);
|
||||
$this->localOverrides->refreshMappingFor(self::SOURCE, $accountShort);
|
||||
|
||||
return $this->calculator->recalculate();
|
||||
});
|
||||
|
||||
@ -2129,15 +2129,25 @@
|
||||
@endif
|
||||
<tbody data-ledger-transaction-tbody>
|
||||
@forelse ($ledgerTransactions as $row)
|
||||
@php
|
||||
$rowUsesLocalEditor = $canEditTransactions
|
||||
&& !$transactionViewIsIndependent
|
||||
&& $row->source !== 'manual'
|
||||
&& $row->source !== 'internal_transfer';
|
||||
$rowAccountShort = $rowUsesLocalEditor
|
||||
? ($row->effective_account_short === '未匹配' ? '' : $row->effective_account_short)
|
||||
: ($row->account_short ?? '');
|
||||
@endphp
|
||||
<tr class="ledger-transaction-row" data-ledger-transaction-row data-transaction-id="{{ $row->id }}" data-source="{{ $row->source }}" data-approval-no="{{ $row->approval_no }}"
|
||||
@if ($canEditTransactions && ($row->source === 'manual' || $transactionViewIsIndependent))
|
||||
@if ($canEditTransactions && $row->source !== 'internal_transfer')
|
||||
data-ledger-manual-row
|
||||
data-editable-independent="{{ $transactionViewIsIndependent ? '1' : '0' }}"
|
||||
data-update-url="{{ $transactionViewIsIndependent ? route('business.financial-ledger.transactions.statement.update', ['id' => $row->id]) : route('business.financial-ledger.transactions.manual.update', ['id' => $row->id]) }}"
|
||||
data-delete-url="{{ $transactionViewIsIndependent ? route('business.financial-ledger.transactions.statement.delete', ['id' => $row->id]) : route('business.financial-ledger.transactions.manual.delete', ['id' => $row->id]) }}"
|
||||
data-editable-local="{{ $rowUsesLocalEditor ? '1' : '0' }}"
|
||||
data-update-url="{{ $transactionViewIsIndependent ? route('business.financial-ledger.transactions.statement.update', ['id' => $row->id]) : ($row->source === 'manual' ? route('business.financial-ledger.transactions.manual.update', ['id' => $row->id]) : route('business.financial-ledger.transactions.local.update', ['id' => $row->id])) }}"
|
||||
data-delete-url="{{ $transactionViewIsIndependent ? route('business.financial-ledger.transactions.statement.delete', ['id' => $row->id]) : ($row->source === 'manual' ? route('business.financial-ledger.transactions.manual.delete', ['id' => $row->id]) : route('business.financial-ledger.transactions.local.delete', ['id' => $row->id])) }}"
|
||||
data-insert-url="{{ $transactionViewIsIndependent ? route('business.financial-ledger.transactions.insert', ['id' => $row->id]) : '' }}"
|
||||
data-txn-date="{{ $date($row->txn_date) }}"
|
||||
data-account-short="{{ $row->account_short }}"
|
||||
data-edit-account-short="{{ $rowAccountShort }}"
|
||||
data-counterparty-info="{{ $row->counterparty_info }}"
|
||||
data-detail="{{ $row->detail }}"
|
||||
data-income="{{ $row->income }}"
|
||||
@ -2169,7 +2179,7 @@
|
||||
<div class="ledger-transaction-actions">
|
||||
@if ($row->source === 'internal_transfer')
|
||||
<button class="ledger-row-edit is-delete" type="button" title="删除整笔内部转账" aria-label="删除内部转账 {{ $row->approval_no }}" data-ledger-internal-transfer-delete data-url="{{ route('business.financial-ledger.transfers.internal.delete', ['id' => $row->id]) }}"><span class="material-icons-outlined" aria-hidden="true">delete</span></button>
|
||||
@elseif ($row->source === 'manual' || $transactionViewIsIndependent)
|
||||
@else
|
||||
@if ($transactionViewIsIndependent)
|
||||
<button class="ledger-row-edit ledger-row-insert" type="button" title="在此行附近插入明细" aria-label="在此行附近插入明细 {{ $row->approval_no }}" data-ledger-excel-row-trigger><span class="material-icons-outlined" aria-hidden="true">playlist_add</span></button>
|
||||
@endif
|
||||
@ -2442,8 +2452,8 @@
|
||||
@csrf
|
||||
<header class="ledger-company-form__header">
|
||||
<div>
|
||||
<h3 class="ledger-company-form__title" id="ledger-manual-edit-title">{{ $transactionViewIsIndependent ? '编辑独立账单明细' : '编辑手工动账明细' }}</h3>
|
||||
<p class="ledger-company-form__help">{{ $transactionViewIsIndependent ? '当前明细的所有内容均可修改;保存后本页月度收入、支出和余额汇总会同步更新,不影响其他页面。' : '保存后会重新计算对应账户及后续每日资金流水;上游同步的明细不能在这里修改或删除。' }}</p>
|
||||
<h3 class="ledger-company-form__title" id="ledger-manual-edit-title" data-ledger-manual-edit-title>{{ $transactionViewIsIndependent ? '编辑独立账单明细' : '编辑动账明细' }}</h3>
|
||||
<p class="ledger-company-form__help" data-ledger-manual-edit-help>{{ $transactionViewIsIndependent ? '当前明细的所有内容均可修改;保存后本页月度收入、支出和余额汇总会同步更新,不影响其他页面。' : '保存后会重新计算对应账户及后续每日资金流水;来源字段由系统维护。' }}</p>
|
||||
</div>
|
||||
<button class="ledger-company-form__close" type="button" aria-label="关闭手工明细编辑" data-ledger-manual-edit-close><span class="material-icons-outlined" aria-hidden="true">close</span></button>
|
||||
</header>
|
||||
@ -3686,7 +3696,7 @@
|
||||
? transactionStatementInsertUrlTemplate.replace('__TRANSACTION__', encodeURIComponent(String(row.id)))
|
||||
: '';
|
||||
tableRow.dataset.txnDate = row.txn_date || '';
|
||||
tableRow.dataset.accountShort = row.account_short || '';
|
||||
tableRow.dataset.editAccountShort = row.account_short || '';
|
||||
tableRow.dataset.counterpartyInfo = row.counterparty_info || '';
|
||||
tableRow.dataset.detail = row.detail || '';
|
||||
tableRow.dataset.income = String(row.income ?? 0);
|
||||
@ -4269,6 +4279,8 @@
|
||||
const manualEditCustomFields = manualEditForm.querySelector('[data-ledger-manual-edit-custom-fields]');
|
||||
const manualEditError = manualEditForm.querySelector('[data-ledger-manual-edit-error]');
|
||||
const manualEditSave = manualEditForm.querySelector('[data-ledger-manual-edit-save]');
|
||||
const manualEditTitle = manualEditDialog.querySelector('[data-ledger-manual-edit-title]');
|
||||
const manualEditHelp = manualEditDialog.querySelector('[data-ledger-manual-edit-help]');
|
||||
|
||||
const closeManualEdit = () => {
|
||||
if (!manualEditDialog.open) return;
|
||||
@ -4335,11 +4347,12 @@
|
||||
manualEditForm.action = row.dataset.updateUrl || '';
|
||||
if (manualEditError) manualEditError.hidden = true;
|
||||
const independentlyEditable = row.dataset.editableIndependent === '1';
|
||||
const locallyEditable = row.dataset.editableLocal === '1';
|
||||
if (manualEditDate) manualEditDate.value = row.dataset.txnDate || '';
|
||||
if (manualEditAccount) {
|
||||
manualEditAccount.value = row.dataset.accountShort || '';
|
||||
manualEditAccount.value = row.dataset.editAccountShort || '';
|
||||
manualEditAccount.setCustomValidity('');
|
||||
manualEditAccount.readOnly = independentlyEditable;
|
||||
manualEditAccount.readOnly = independentlyEditable || locallyEditable;
|
||||
}
|
||||
if (manualEditCounterparty) manualEditCounterparty.value = row.dataset.counterpartyInfo || '';
|
||||
if (manualEditBalance) manualEditBalance.value = row.dataset.balance || '';
|
||||
@ -4349,7 +4362,22 @@
|
||||
if (manualEditIncome) manualEditIncome.value = Number(row.dataset.income) > 0 ? row.dataset.income : '';
|
||||
if (manualEditExpense) manualEditExpense.value = Number(row.dataset.expense) > 0 ? row.dataset.expense : '';
|
||||
if (manualEditDetail) manualEditDetail.required = !independentlyEditable;
|
||||
if (manualEditSource) manualEditSource.value = row.dataset.sourceValue || 'manual';
|
||||
if (manualEditSource) {
|
||||
manualEditSource.value = row.dataset.sourceValue || 'manual';
|
||||
manualEditSource.disabled = locallyEditable;
|
||||
}
|
||||
if (manualEditTitle) {
|
||||
manualEditTitle.textContent = independentlyEditable
|
||||
? '编辑独立账单明细'
|
||||
: locallyEditable ? '编辑动账明细' : '编辑手工动账明细';
|
||||
}
|
||||
if (manualEditHelp) {
|
||||
manualEditHelp.textContent = independentlyEditable
|
||||
? '当前明细的所有内容均可修改;保存后本页月度收入、支出和余额汇总会同步更新,不影响其他页面。'
|
||||
: locallyEditable
|
||||
? '保存后仅在本地财务镜像中覆盖该行,并重新计算资金流水;不会回写上游,后续同步也会保留本次修改。'
|
||||
: '保存后会重新计算对应账户及后续每日资金流水;来源字段由系统维护。';
|
||||
}
|
||||
renderCustomEditFields(row);
|
||||
syncManualEditDirection();
|
||||
manualEditDialog.showModal();
|
||||
@ -4361,10 +4389,13 @@
|
||||
if (!button) return;
|
||||
const row = button.closest('[data-ledger-manual-row]');
|
||||
if (!row) return;
|
||||
const label = [row.dataset.txnDate, row.dataset.accountShort, row.dataset.detail].filter(Boolean).join(' · ');
|
||||
if (!window.confirm('确认删除这条明细?\n' + label + '\n' + (transactionViewIsIndependent()
|
||||
? '删除后将重新计算本页月度汇总。'
|
||||
: '删除后将重新计算资金流水。'))) return;
|
||||
const label = [row.dataset.txnDate, row.dataset.editAccountShort, row.dataset.detail].filter(Boolean).join(' · ');
|
||||
const locallyEditable = row.dataset.editableLocal === '1';
|
||||
if (!window.confirm('确认删除这条明细?\n' + label + '\n' + (locallyEditable
|
||||
? '删除后仅在本地财务镜像中隐藏该行,并重新计算资金流水;不会回写上游。'
|
||||
: transactionViewIsIndependent()
|
||||
? '删除后将重新计算本页月度汇总。'
|
||||
: '删除后将重新计算资金流水。'))) return;
|
||||
|
||||
button.disabled = true;
|
||||
try {
|
||||
@ -4379,11 +4410,12 @@
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.message || '手工明细删除失败');
|
||||
const firstError = Object.values(payload.errors || {})[0]?.[0];
|
||||
throw new Error(firstError || payload.message || '动账明细删除失败');
|
||||
}
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
notify(error.message || '手工明细删除失败', true);
|
||||
notify(error.message || '动账明细删除失败', true);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
@ -4401,8 +4433,9 @@
|
||||
manualEditForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
const independentlyEditable = manualEditForm.action.includes('/statement');
|
||||
const locallyEditable = manualEditForm.action.includes('/local');
|
||||
const accountShort = manualEditAccount?.value.trim() || '';
|
||||
if (!independentlyEditable && !ledgerAccountShortValues.has(accountShort)) {
|
||||
if (!independentlyEditable && !locallyEditable && !ledgerAccountShortValues.has(accountShort)) {
|
||||
manualEditAccount?.setCustomValidity('请选择账户总表中的账户简称');
|
||||
manualEditAccount?.reportValidity();
|
||||
return;
|
||||
@ -4433,11 +4466,11 @@
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
const firstError = Object.values(payload.errors || {})[0]?.[0];
|
||||
throw new Error(firstError || payload.message || '手工明细保存失败');
|
||||
throw new Error(firstError || payload.message || '动账明细保存失败');
|
||||
}
|
||||
window.location.reload();
|
||||
} catch (error) {
|
||||
showManualEditError(error.message || '手工明细保存失败');
|
||||
showManualEditError(error.message || '动账明细保存失败');
|
||||
} finally {
|
||||
if (manualEditSave) manualEditSave.disabled = false;
|
||||
manualEditForm.removeAttribute('aria-busy');
|
||||
|
||||
@ -936,6 +936,16 @@ Route::delete('workspace/financial-ledger/transactions/{id}/manual', [\App\Http\
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.manual.delete');
|
||||
|
||||
Route::post('workspace/financial-ledger/transactions/{id}/local', [\App\Http\Controllers\Business\FinanceLedger::class, 'updateLocalTransaction'])
|
||||
->whereNumber('id')
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.local.update');
|
||||
|
||||
Route::delete('workspace/financial-ledger/transactions/{id}/local', [\App\Http\Controllers\Business\FinanceLedger::class, 'deleteLocalTransaction'])
|
||||
->whereNumber('id')
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
->name('business.financial-ledger.transactions.local.delete');
|
||||
|
||||
Route::post('workspace/financial-ledger/transactions/{id}/statement', [\App\Http\Controllers\Business\FinanceLedger::class, 'updateIndependentTransaction'])
|
||||
->whereNumber('id')
|
||||
->middleware('business.page:financial-operations,ledger')
|
||||
|
||||
@ -0,0 +1,269 @@
|
||||
<?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 Modules\EcommerceFinance\Services\FinanceLedgerTransactionWriter;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class FinanceLedgerLocalTransactionActionsTest extends FeatureTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Carbon::setTestNow('2026-11-18 12:00:00');
|
||||
|
||||
$this->user->attachPermission(
|
||||
Permission::where('name', 'read-admin-panel')->firstOrFail(),
|
||||
);
|
||||
|
||||
$connection = DB::connection('business_mirror');
|
||||
$connection->table('fin_accounts')->insert([
|
||||
'company_name' => '本地覆盖测试公司',
|
||||
'account_short' => '本地覆盖测试账户',
|
||||
'account_type' => '公户',
|
||||
'current_balance' => 100,
|
||||
]);
|
||||
$connection->table('fin_account_opening')->insert([
|
||||
'account_short' => '本地覆盖测试账户',
|
||||
'opening_date' => '2026-10-17',
|
||||
'opening_balance' => 100,
|
||||
]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Carbon::setTestNow();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_upstream_row_actions_edit_locally_and_survive_resync(): void
|
||||
{
|
||||
$transactionId = $this->insertUpstreamRow();
|
||||
$updateUrl = $this->updateUrl($transactionId);
|
||||
|
||||
$html = $this->loginAs()->get($this->pageUrl())->assertOk()->getContent();
|
||||
$this->assertStringContainsString('data-editable-local="1"', $html);
|
||||
$this->assertStringContainsString($updateUrl, $html);
|
||||
$this->assertStringContainsString($this->deleteUrl($transactionId), $html);
|
||||
$this->assertMatchesRegularExpression(
|
||||
'/data-approval-no="LOCAL-ACTION-1".*?data-ledger-manual-edit.*?data-ledger-manual-delete/s',
|
||||
$html,
|
||||
);
|
||||
|
||||
$this->loginAs()->postJson($updateUrl, [
|
||||
'txn_date' => '2026-11-17',
|
||||
'counterparty_info' => '本地修正对方',
|
||||
'detail' => '本地修正后的明细',
|
||||
'income' => 40,
|
||||
'expense' => 0,
|
||||
'balance' => 140,
|
||||
'approval_no' => 'LOCAL-ACTION-1',
|
||||
'payment_remark' => '本地修正备注',
|
||||
])->assertOk()
|
||||
->assertJsonPath('transaction.detail', '本地修正后的明细')
|
||||
->assertJsonPath('transaction.income', 40)
|
||||
->assertJsonPath('message', '动账明细已保存,资金流水和当前余额已重新计算。');
|
||||
|
||||
$connection = DB::connection('business_mirror');
|
||||
$this->assertDatabaseHas('fin_transactions', [
|
||||
'id' => $transactionId,
|
||||
'txn_date' => '2026-11-17',
|
||||
'counterparty_info' => '本地修正对方',
|
||||
'detail' => '本地修正后的明细',
|
||||
'income' => 40,
|
||||
'balance' => 140,
|
||||
'local_override' => 1,
|
||||
'updated_by' => 'Test User',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_daily_flows', [
|
||||
'flow_date' => '2026-11-17',
|
||||
'account_short' => '本地覆盖测试账户',
|
||||
'inflow' => 40,
|
||||
'closing_balance' => 140,
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_account_map', [
|
||||
'source' => 'dingtalk',
|
||||
'source_value' => 'LOCAL-MAP-1',
|
||||
'txn_count' => 1,
|
||||
'income_sum' => 40,
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_ledger_edit_events', [
|
||||
'entity_type' => 'transaction_local_update',
|
||||
'user_name' => 'Test User',
|
||||
], 'business_mirror');
|
||||
|
||||
app(FinanceLedgerTransactionWriter::class)->replace([
|
||||
$this->upstreamPayload([
|
||||
'txn_date' => '2026-11-17',
|
||||
'income' => 20,
|
||||
'expense' => 0,
|
||||
'approval_no' => 'LOCAL-ACTION-1',
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('fin_transactions', [
|
||||
'id' => $transactionId,
|
||||
'detail' => '本地修正后的明细',
|
||||
'income' => 40,
|
||||
'local_override' => 1,
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
public function test_upstream_row_can_be_deleted_locally_and_stays_deleted_after_resync(): void
|
||||
{
|
||||
$transactionId = $this->insertUpstreamRow();
|
||||
|
||||
$this->loginAs()->deleteJson($this->deleteUrl($transactionId))
|
||||
->assertOk()
|
||||
->assertJsonPath('deleted', true)
|
||||
->assertJsonPath('message', '动账明细已删除,资金流水和当前余额已重新计算。');
|
||||
|
||||
$connection = DB::connection('business_mirror');
|
||||
$row = $connection->table('fin_transactions')->where('id', $transactionId)->first();
|
||||
$this->assertNotNull($row);
|
||||
$this->assertNotNull($row->deleted_at);
|
||||
$this->assertSame(1, (int) $row->local_override);
|
||||
$this->assertDatabaseMissing('fin_account_map', [
|
||||
'source' => 'dingtalk',
|
||||
'source_value' => 'LOCAL-MAP-1',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_ledger_edit_events', [
|
||||
'entity_type' => 'transaction_local_delete',
|
||||
'user_name' => 'Test User',
|
||||
], 'business_mirror');
|
||||
|
||||
app(FinanceLedgerTransactionWriter::class)->merge([
|
||||
$this->upstreamPayload(),
|
||||
]);
|
||||
|
||||
$this->assertSame(0, $connection->table('fin_transactions')
|
||||
->where('id', $transactionId)
|
||||
->whereNull('deleted_at')
|
||||
->count());
|
||||
$this->assertStringNotContainsString(
|
||||
'上游待修正明细',
|
||||
$this->loginAs()->get($this->pageUrl())->assertOk()->getContent(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_local_actions_require_transaction_edit_permission(): void
|
||||
{
|
||||
$transactionId = $this->insertUpstreamRow();
|
||||
$viewer = user_model_class()::create([
|
||||
'name' => '动账本地编辑只读用户',
|
||||
'email' => 'local-action-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->updateUrl($transactionId), [
|
||||
'txn_date' => '2026-11-17',
|
||||
'detail' => '无权修改',
|
||||
'income' => 10,
|
||||
'expense' => 0,
|
||||
])
|
||||
->assertForbidden();
|
||||
$this->withExceptionHandling()->loginAs($viewer)
|
||||
->deleteJson($this->deleteUrl($transactionId))
|
||||
->assertForbidden();
|
||||
}
|
||||
|
||||
private function insertUpstreamRow(): int
|
||||
{
|
||||
$payload = $this->upstreamPayload();
|
||||
DB::connection('business_mirror')->table('fin_account_map')->insert([
|
||||
'source' => $payload['source'],
|
||||
'source_value' => $payload['source_value'],
|
||||
'account_short' => $payload['account_short'],
|
||||
'txn_count' => 1,
|
||||
'income_sum' => $payload['income'],
|
||||
'expense_sum' => $payload['expense'],
|
||||
]);
|
||||
$canonical = implode("\0", [
|
||||
$payload['source'],
|
||||
$payload['process_type'],
|
||||
'',
|
||||
'',
|
||||
$payload['approval_no'],
|
||||
'',
|
||||
'',
|
||||
number_format((float) $payload['income'], 2, '.', ''),
|
||||
number_format((float) $payload['expense'], 2, '.', ''),
|
||||
$payload['detail'],
|
||||
]);
|
||||
return (int) DB::connection('business_mirror')->table('fin_transactions')->insertGetId([
|
||||
'txn_date' => $payload['txn_date'],
|
||||
'account_short' => $payload['account_short'],
|
||||
'counterparty_info' => $payload['counterparty_info'],
|
||||
'detail' => $payload['detail'],
|
||||
'income' => $payload['income'],
|
||||
'expense' => $payload['expense'],
|
||||
'balance' => $payload['balance'],
|
||||
'approval_no' => $payload['approval_no'],
|
||||
'payment_remark' => $payload['payment_remark'],
|
||||
'source' => $payload['source'],
|
||||
'source_value' => $payload['source_value'],
|
||||
'process_type' => $payload['process_type'],
|
||||
'row_key' => substr(hash('sha256', $canonical), 0, 56) . ':1',
|
||||
'local_override' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $overrides
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function upstreamPayload(array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'txn_date' => '2026-11-17',
|
||||
'account_short' => '本地覆盖测试账户',
|
||||
'counterparty_info' => '上游对方',
|
||||
'detail' => '上游待修正明细',
|
||||
'income' => 20,
|
||||
'expense' => 0,
|
||||
'balance' => 120,
|
||||
'approval_no' => 'LOCAL-ACTION-1',
|
||||
'payment_remark' => '上游备注',
|
||||
'source' => 'dingtalk',
|
||||
'source_value' => 'LOCAL-MAP-1',
|
||||
'process_type' => '报销',
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
private function pageUrl(): string
|
||||
{
|
||||
return route('business.pages.show', [
|
||||
'company_id' => $this->company->id,
|
||||
'section' => 'financial-operations',
|
||||
'page' => 'ledger',
|
||||
]) . '?tab=transactions&txns_from=2026-11-01&txns_to=2026-11-30';
|
||||
}
|
||||
|
||||
private function updateUrl(int $transactionId): string
|
||||
{
|
||||
return route('business.financial-ledger.transactions.local.update', [
|
||||
'company_id' => $this->company->id,
|
||||
'id' => $transactionId,
|
||||
]);
|
||||
}
|
||||
|
||||
private function deleteUrl(int $transactionId): string
|
||||
{
|
||||
return route('business.financial-ledger.transactions.local.delete', [
|
||||
'company_id' => $this->company->id,
|
||||
'id' => $transactionId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -1032,24 +1032,32 @@ class FinanceLedgerManualTransactionTest extends FeatureTestCase
|
||||
->assertSee('data-ledger-excel-insert-count', false);
|
||||
}
|
||||
|
||||
public function test_imported_rows_outside_independent_pages_remain_read_only(): void
|
||||
public function test_imported_rows_outside_independent_pages_use_local_override_actions(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
$transactionId = (int) $connection->table('fin_transactions')->insertGetId([
|
||||
'txn_date' => '2026-10-06',
|
||||
'account_short' => '手工账户甲',
|
||||
'detail' => '普通导入明细只读',
|
||||
'detail' => '普通导入明细可本地修正',
|
||||
'income' => 5,
|
||||
'expense' => 0,
|
||||
'approval_no' => 'NORMAL-READONLY',
|
||||
'approval_no' => 'NORMAL-LOCAL',
|
||||
'source' => 'workorder',
|
||||
'source_value' => 'NORMAL-READONLY-VALUE',
|
||||
'row_key' => 'normal-imported-readonly-row',
|
||||
'source_value' => 'NORMAL-LOCAL-VALUE',
|
||||
'row_key' => 'normal-imported-local-row',
|
||||
]);
|
||||
|
||||
$this->loginAs($this->yutuUser())->get($this->pageUrl())
|
||||
->assertOk()
|
||||
->assertSee('普通导入明细只读')
|
||||
->assertSee('普通导入明细可本地修正')
|
||||
->assertSee(route('business.financial-ledger.transactions.local.update', [
|
||||
'company_id' => $this->company->id,
|
||||
'id' => $transactionId,
|
||||
]), false)
|
||||
->assertSee(route('business.financial-ledger.transactions.local.delete', [
|
||||
'company_id' => $this->company->id,
|
||||
'id' => $transactionId,
|
||||
]), false)
|
||||
->assertDontSee($this->independentUpdateUrl($transactionId), false)
|
||||
->assertDontSee($this->independentDeleteUrl($transactionId), false);
|
||||
}
|
||||
|
||||
@ -335,6 +335,8 @@ class FinanceLedgerNavigationTest extends FeatureTestCase
|
||||
'business.financial-ledger.accounts.type',
|
||||
'business.financial-ledger.accounts.template',
|
||||
'business.financial-ledger.transactions.account.update',
|
||||
'business.financial-ledger.transactions.local.update',
|
||||
'business.financial-ledger.transactions.local.delete',
|
||||
'business.financial-ledger.transactions.import.template',
|
||||
'business.financial-ledger.transactions.import.preview',
|
||||
'business.financial-ledger.transactions.import.commit',
|
||||
|
||||
@ -144,6 +144,57 @@ class ImportWangshangBankBillsTest extends FeatureTestCase
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
public function test_reimport_preserves_a_locally_edited_wangshang_row(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
$connection->table('fin_accounts')->insert([
|
||||
'company_name' => '测试网商公司',
|
||||
'account_short' => '测试网商银行',
|
||||
'account_no' => '8888000012345678',
|
||||
'account_type' => '网商银行',
|
||||
'current_balance' => 1000,
|
||||
]);
|
||||
$bundle = $this->bundle([
|
||||
['交易时间', '账务流水号', '交易名称', '借方金额(收)', '贷方金额(支)', '交易状态'],
|
||||
['2026-11-01 09:10:00', '202611010009', '他行转入', '100.00', '-', '成功'],
|
||||
], expectedRows: 1, expectedIncome: 100, expectedExpense: 0);
|
||||
|
||||
$this->artisan('finance-ledger:import-wangshang-bank', [
|
||||
'path' => $bundle,
|
||||
'--date' => '2026-11-01',
|
||||
])->assertExitCode(0);
|
||||
|
||||
$row = $connection->table('fin_transactions')
|
||||
->where('approval_no', '202611010009')
|
||||
->first();
|
||||
$this->assertNotNull($row);
|
||||
$connection->table('fin_transactions')->where('id', $row->id)->update([
|
||||
'detail' => '本地修正后的网商流水',
|
||||
'income' => 123,
|
||||
'local_override' => true,
|
||||
'updated_by' => '本地财务',
|
||||
]);
|
||||
|
||||
$this->artisan('finance-ledger:import-wangshang-bank', [
|
||||
'path' => $bundle,
|
||||
'--date' => '2026-11-01',
|
||||
])->assertExitCode(0);
|
||||
|
||||
$this->assertDatabaseHas('fin_transactions', [
|
||||
'id' => $row->id,
|
||||
'detail' => '本地修正后的网商流水',
|
||||
'income' => 123,
|
||||
'local_override' => 1,
|
||||
'updated_by' => '本地财务',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_account_map', [
|
||||
'source' => WangshangBankBillImporter::SOURCE,
|
||||
'source_value' => '8888000012345678',
|
||||
'txn_count' => 1,
|
||||
'income_sum' => 123,
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<list<string>> $rows
|
||||
*/
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user