212 lines
8.1 KiB
PHP
212 lines
8.1 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Services;
|
|
|
|
use Carbon\CarbonImmutable;
|
|
use Illuminate\Database\ConnectionInterface;
|
|
use Illuminate\Database\DatabaseManager;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
|
|
class FinanceLedgerInternalTransferEditor
|
|
{
|
|
private readonly ConnectionInterface $connection;
|
|
|
|
public function __construct(
|
|
DatabaseManager $databases,
|
|
private readonly FinanceLedgerCalculator $calculator,
|
|
) {
|
|
$this->connection = $databases->connection(
|
|
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @param array{
|
|
* idempotency_key:string,
|
|
* txn_date:string,
|
|
* from_account_short:string,
|
|
* to_account_short:string,
|
|
* amount:numeric
|
|
* } $data
|
|
* @return array{created:bool,approval_no:string,rows:list<object>}
|
|
*/
|
|
public function create(array $data): array
|
|
{
|
|
$date = $this->date($data['txn_date'] ?? null);
|
|
$from = trim((string) ($data['from_account_short'] ?? ''));
|
|
$to = trim((string) ($data['to_account_short'] ?? ''));
|
|
$amountCents = $this->cents($data['amount'] ?? 0);
|
|
if ($from === '' || $to === '') {
|
|
throw ValidationException::withMessages([
|
|
'from_account_short' => '请选择转出账户和转入账户。',
|
|
]);
|
|
}
|
|
if ($from === $to) {
|
|
throw ValidationException::withMessages([
|
|
'to_account_short' => '转入账户不能与转出账户相同。',
|
|
]);
|
|
}
|
|
if ($amountCents <= 0) {
|
|
throw ValidationException::withMessages([
|
|
'amount' => '动账金额必须大于 0。',
|
|
]);
|
|
}
|
|
|
|
return $this->connection->transaction(function () use ($data, $date, $from, $to, $amountCents): array {
|
|
$accounts = $this->connection->table('fin_accounts')
|
|
->whereIn('account_short', [$from, $to])
|
|
->orderBy('id')
|
|
->lockForUpdate()
|
|
->get(['account_short', 'company_name'])
|
|
->keyBy('account_short');
|
|
if (! $accounts->has($from) || ! $accounts->has($to)) {
|
|
throw ValidationException::withMessages([
|
|
'from_account_short' => '转出或转入账户不存在,请从账户总表中选择。',
|
|
]);
|
|
}
|
|
|
|
$idempotencyKey = trim((string) $data['idempotency_key']);
|
|
$approvalNo = 'IT-' . str_replace('-', '', $date) . '-'
|
|
. strtoupper(substr(hash('sha256', $idempotencyKey), 0, 8));
|
|
$prefix = FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE . ':' . $approvalNo;
|
|
$outgoingKey = hash('sha256', $prefix . ':out');
|
|
$incomingKey = hash('sha256', $prefix . ':in');
|
|
$amount = $amountCents / 100;
|
|
$now = now();
|
|
$userName = (string) (user()?->name ?? '');
|
|
$created = 0;
|
|
foreach ([
|
|
[
|
|
'account_short' => $from,
|
|
'counterparty_info' => $to,
|
|
'detail' => '内部转账 · 转出至 ' . $to,
|
|
'income' => 0,
|
|
'expense' => $amount,
|
|
'row_key' => $outgoingKey,
|
|
],
|
|
[
|
|
'account_short' => $to,
|
|
'counterparty_info' => $from,
|
|
'detail' => '内部转账 · 转入自 ' . $from,
|
|
'income' => $amount,
|
|
'expense' => 0,
|
|
'row_key' => $incomingKey,
|
|
],
|
|
] as $row) {
|
|
$created += $this->connection->table('fin_transactions')->insertOrIgnore([
|
|
...$row,
|
|
'txn_date' => $date,
|
|
'balance' => null,
|
|
'approval_no' => $approvalNo,
|
|
'payment_remark' => null,
|
|
'source' => FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE,
|
|
'source_value' => null,
|
|
'process_type' => '内部转账',
|
|
'synced_at' => $now,
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
'created_by' => $userName,
|
|
'updated_by' => $userName,
|
|
]);
|
|
}
|
|
|
|
if ($created > 0) {
|
|
$this->audit('internal_transfer_create', $approvalNo, [
|
|
'txn_date' => $date,
|
|
'from_account_short' => $from,
|
|
'to_account_short' => $to,
|
|
'amount' => $amount,
|
|
]);
|
|
$this->calculator->recalculate();
|
|
}
|
|
|
|
$rows = $this->connection->table('fin_transactions')
|
|
->where('source', FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE)
|
|
->where('approval_no', $approvalNo)
|
|
->orderByDesc('expense')
|
|
->orderBy('id')
|
|
->get();
|
|
if ($rows->count() !== 2) {
|
|
throw new \RuntimeException('内部转账保存不完整,请刷新后重试。');
|
|
}
|
|
|
|
return [
|
|
'created' => $created > 0,
|
|
'approval_no' => $approvalNo,
|
|
'rows' => $rows->all(),
|
|
];
|
|
});
|
|
}
|
|
|
|
/** @return array{approval_no:string,rows:list<object>} */
|
|
public function delete(int $id): array
|
|
{
|
|
return $this->connection->transaction(function () use ($id): array {
|
|
$row = $this->connection->table('fin_transactions')
|
|
->where('id', $id)
|
|
->where('source', FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE)
|
|
->lockForUpdate()
|
|
->first();
|
|
if ($row === null) {
|
|
throw new NotFoundHttpException('内部转账记录不存在。');
|
|
}
|
|
|
|
$approvalNo = (string) $row->approval_no;
|
|
$rows = $this->connection->table('fin_transactions')
|
|
->where('source', FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE)
|
|
->where('approval_no', $approvalNo)
|
|
->lockForUpdate()
|
|
->get();
|
|
$this->connection->table('fin_transactions')
|
|
->where('source', FinanceLedgerTransactionWriter::INTERNAL_TRANSFER_SOURCE)
|
|
->where('approval_no', $approvalNo)
|
|
->delete();
|
|
$this->audit('internal_transfer_delete', $approvalNo, [
|
|
'rows' => $rows->map(static fn (object $item): array => [
|
|
'account_short' => (string) $item->account_short,
|
|
'income' => round((float) $item->income, 2),
|
|
'expense' => round((float) $item->expense, 2),
|
|
])->all(),
|
|
]);
|
|
$this->calculator->recalculate();
|
|
|
|
return [
|
|
'approval_no' => $approvalNo,
|
|
'rows' => $rows->all(),
|
|
];
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $changes */
|
|
private function audit(string $entityType, string $approvalNo, array $changes): void
|
|
{
|
|
$this->connection->table('fin_ledger_edit_events')->insert([
|
|
'entity_type' => $entityType,
|
|
'entity_key' => 'internal_transfer|' . $approvalNo,
|
|
'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);
|
|
}
|
|
}
|