CaiWuXiTong/modules/EcommerceFinance/Services/FinanceLedgerLocalTransactionEditor.php
92451 33aa492f7b feat: 完善动账明细修改和删除操作 (#1232)
Co-authored-by: 92451 <924518135@qq.com>
Co-committed-by: 92451 <924518135@qq.com>
2026-11-18 15:06:46 +08:00

213 lines
7.9 KiB
PHP

<?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;
}
}