412 lines
18 KiB
PHP
412 lines
18 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use App\Utilities\FinanceLedgerAccountStatus;
|
||
use App\Utilities\FinanceLedgerAccountType;
|
||
use App\Utilities\FinanceLedgerIndependentAccounts;
|
||
use Illuminate\Database\ConnectionInterface;
|
||
use Illuminate\Database\DatabaseManager;
|
||
use Illuminate\Support\Facades\Schema;
|
||
use Illuminate\Validation\ValidationException;
|
||
|
||
class FinanceLedgerAccountEditor
|
||
{
|
||
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<string,mixed> $data
|
||
* @return array<string,mixed>
|
||
*/
|
||
public function update(int $id, array $data): array
|
||
{
|
||
return $this->connection->transaction(function () use ($id, $data): array {
|
||
$account = $this->connection->table('fin_accounts')->where('id', $id)->lockForUpdate()->first();
|
||
if ($account === null) {
|
||
abort(404);
|
||
}
|
||
|
||
$oldShort = trim((string) $account->account_short);
|
||
$accountShort = $this->text($data['account_short'] ?? '');
|
||
$companyName = $this->text($data['company_name'] ?? '');
|
||
if ($accountShort === '' || $companyName === '') {
|
||
throw ValidationException::withMessages([
|
||
'account_short' => '账户简称和公司名称不能为空。',
|
||
]);
|
||
}
|
||
|
||
$duplicate = $this->connection->table('fin_accounts')
|
||
->where('account_short', $accountShort)
|
||
->where('id', '<>', $id)
|
||
->exists();
|
||
if ($duplicate) {
|
||
throw ValidationException::withMessages([
|
||
'account_short' => '账户简称已存在,请改用其他简称。',
|
||
]);
|
||
}
|
||
|
||
$accountType = $this->nullableText($data['account_type'] ?? null);
|
||
$accountNo = $this->nullableText($data['account_no'] ?? null);
|
||
$status = FinanceLedgerAccountStatus::normalize((string) ($data['status'] ?? ''));
|
||
$accountLast4 = FinanceLedgerAccountType::last4(
|
||
(string) $accountType,
|
||
(string) $accountNo,
|
||
(string) ($account->account_last4 ?? ''),
|
||
);
|
||
$values = [
|
||
'company_name' => $companyName,
|
||
'account_short' => $accountShort,
|
||
'legal_representative' => $this->nullableText($data['legal_representative'] ?? null),
|
||
'region' => $this->nullableText($data['region'] ?? null),
|
||
'account_no' => $accountNo,
|
||
'bank_name' => $this->nullableText($data['bank_name'] ?? null),
|
||
'bound_alipay' => $this->nullableText($data['bound_alipay'] ?? null),
|
||
'bank_city_branch' => $this->nullableText($data['bank_city_branch'] ?? null),
|
||
'account_type' => $accountType,
|
||
'company_plan' => $this->nullableText($data['company_plan'] ?? null),
|
||
'account_should_keep' => $this->nullableText($data['account_should_keep'] ?? null),
|
||
'account_last4' => $accountLast4,
|
||
'single_limit' => $this->nullableText($data['single_limit'] ?? null),
|
||
'daily_limit' => $this->nullableText($data['daily_limit'] ?? null),
|
||
'monthly_limit' => $this->nullableText($data['monthly_limit'] ?? null),
|
||
'yearly_limit' => $this->nullableText($data['yearly_limit'] ?? null),
|
||
'clearing_days' => $this->nullableNumber($data['clearing_days'] ?? null),
|
||
'raise_target' => $this->nullableText($data['raise_target'] ?? null),
|
||
'raise_status' => $this->nullableText($data['raise_status'] ?? null),
|
||
'raise_actions' => $this->nullableText($data['raise_actions'] ?? null),
|
||
'done_actions' => $this->nullableText($data['done_actions'] ?? null),
|
||
'next_action' => $this->nullableText($data['next_action'] ?? null),
|
||
'remark' => $this->nullableText($data['remark'] ?? null),
|
||
'owner' => $this->nullableText($data['owner'] ?? null),
|
||
'updated_at' => now(),
|
||
];
|
||
|
||
$before = (array) $account;
|
||
if ($oldShort !== $accountShort) {
|
||
$this->renameReferences($oldShort, $accountShort);
|
||
}
|
||
|
||
$this->connection->table('fin_accounts')->where('id', $id)->update($values);
|
||
$this->upsertStatus($accountShort, $status);
|
||
$this->connection->table('fin_account_type_overrides')
|
||
->where('account_short', $accountShort)
|
||
->delete();
|
||
$this->connection->table('fin_daily_flows')
|
||
->where('account_short', $accountShort)
|
||
->update([
|
||
'company_name' => $companyName,
|
||
'updated_at' => now(),
|
||
]);
|
||
|
||
$this->calculator->refreshAccountAmounts($accountShort);
|
||
|
||
$after = (array) $this->connection->table('fin_accounts')->where('id', $id)->first();
|
||
$this->connection->table('fin_ledger_edit_events')->insert([
|
||
'entity_type' => 'account',
|
||
'entity_key' => (string) $id,
|
||
'changes' => json_encode([
|
||
'before' => $before,
|
||
'after' => $after,
|
||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||
'user_id' => user()?->id,
|
||
'user_name' => (string) (user()?->name ?? ''),
|
||
'created_at' => now(),
|
||
]);
|
||
|
||
return $after;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* @param list<array{id:int,old_short:string,new_short:string,account_no?:string,company_name?:string}> $mappings
|
||
* @return array{requested:int,changed:int,unchanged:int,dry_run:bool}
|
||
*/
|
||
public function renameShorts(array $mappings, bool $apply = false): array
|
||
{
|
||
$normalized = [];
|
||
$seenIds = [];
|
||
$oldToNew = [];
|
||
$newToOld = [];
|
||
foreach ($mappings as $index => $mapping) {
|
||
$id = (int) ($mapping['id'] ?? 0);
|
||
$oldShort = $this->text($mapping['old_short'] ?? '');
|
||
$newShort = $this->text($mapping['new_short'] ?? '');
|
||
if ($id <= 0 || $oldShort === '' || $newShort === '') {
|
||
throw ValidationException::withMessages([
|
||
'mappings.' . $index => '账户 ID、旧简称和新简称不能为空。',
|
||
]);
|
||
}
|
||
if (mb_strlen($newShort) > 100) {
|
||
throw ValidationException::withMessages([
|
||
'mappings.' . $index . '.new_short' => '新账户简称不能超过 100 个字符。',
|
||
]);
|
||
}
|
||
if (isset($seenIds[$id])) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '同一个账户不能重复提交。',
|
||
]);
|
||
}
|
||
if (isset($oldToNew[$oldShort]) && $oldToNew[$oldShort] !== $newShort) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '同一旧账户简称不能改成多个不同新简称。',
|
||
]);
|
||
}
|
||
if (isset($newToOld[$newShort]) && $newToOld[$newShort] !== $oldShort) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '不同旧账户简称不能合并成同一个新简称。',
|
||
]);
|
||
}
|
||
if (FinanceLedgerIndependentAccounts::contains($oldShort)
|
||
|| FinanceLedgerIndependentAccounts::contains($newShort)) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '独立账单账户不允许批量修改账户简称。',
|
||
]);
|
||
}
|
||
|
||
$seenIds[$id] = true;
|
||
$oldToNew[$oldShort] = $newShort;
|
||
$newToOld[$newShort] = $oldShort;
|
||
$normalized[] = [
|
||
'id' => $id,
|
||
'old_short' => $oldShort,
|
||
'new_short' => $newShort,
|
||
'account_no' => $this->digits($mapping['account_no'] ?? ''),
|
||
'company_name' => $this->text($mapping['company_name'] ?? ''),
|
||
];
|
||
}
|
||
if ($normalized === []) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '没有可处理的账户简称。',
|
||
]);
|
||
}
|
||
if (count($normalized) > 5000) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '单次最多批量修改 5000 个账户。',
|
||
]);
|
||
}
|
||
|
||
return $this->connection->transaction(function () use ($normalized, $apply): array {
|
||
$ids = array_column($normalized, 'id');
|
||
$accounts = $this->connection->table('fin_accounts')
|
||
->whereIn('id', $ids)
|
||
->lockForUpdate()
|
||
->get(['id', 'company_name', 'account_short', 'account_no'])
|
||
->keyBy('id');
|
||
if ($accounts->count() !== count($ids)) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '部分账户已不存在,请刷新数据后重试。',
|
||
]);
|
||
}
|
||
|
||
$newShorts = array_values(array_unique(array_column($normalized, 'new_short')));
|
||
$oldOwners = $this->connection->table('fin_accounts')
|
||
->whereIn('account_short', array_column($normalized, 'old_short'))
|
||
->get(['id', 'account_short'])
|
||
->groupBy('account_short');
|
||
$newOwners = $this->connection->table('fin_accounts')
|
||
->whereIn('account_short', $newShorts)
|
||
->get(['id', 'account_short'])
|
||
->groupBy('account_short');
|
||
$groups = collect($normalized)->groupBy('old_short');
|
||
foreach ($groups as $oldShort => $group) {
|
||
$expectedIds = $group
|
||
->pluck('id')
|
||
->map(static fn (mixed $id): int => (int) $id)
|
||
->sort()
|
||
->values()
|
||
->all();
|
||
$ownerIds = $oldOwners->get($oldShort, collect())
|
||
->pluck('id')
|
||
->map(static fn (mixed $id): int => (int) $id)
|
||
->sort()
|
||
->values()
|
||
->all();
|
||
if ($ownerIds !== $expectedIds) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '旧账户简称“' . $oldShort . '”对应的账户与导入数据不一致。',
|
||
]);
|
||
}
|
||
$newShort = (string) $group->first()['new_short'];
|
||
$existingOwnerIds = $newOwners->get($newShort, collect())
|
||
->pluck('id')
|
||
->map(static fn (mixed $id): int => (int) $id)
|
||
->all();
|
||
if (array_diff($existingOwnerIds, $expectedIds) !== []) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '新账户简称“' . $newShort . '”已被其他账户使用。',
|
||
]);
|
||
}
|
||
}
|
||
|
||
$changed = 0;
|
||
foreach ($groups as $oldShort => $group) {
|
||
$newShort = (string) $group->first()['new_short'];
|
||
foreach ($group as $mapping) {
|
||
$account = $accounts->get($mapping['id']);
|
||
$currentShort = $this->text($account->account_short ?? '');
|
||
if ($currentShort !== $mapping['old_short']) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => sprintf(
|
||
'账户 ID %d 的简称已从“%s”变为“%s”,请刷新后重试。',
|
||
$mapping['id'],
|
||
$mapping['old_short'],
|
||
$currentShort,
|
||
),
|
||
]);
|
||
}
|
||
if ($mapping['account_no'] !== ''
|
||
&& $this->digits($account->account_no ?? '') !== $mapping['account_no']) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '账户 ID ' . $mapping['id'] . ' 的账号与导入数据不一致。',
|
||
]);
|
||
}
|
||
if ($mapping['company_name'] !== ''
|
||
&& $this->text($account->company_name ?? '') !== $mapping['company_name']) {
|
||
throw ValidationException::withMessages([
|
||
'mappings' => '账户 ID ' . $mapping['id'] . ' 的公司名称与导入数据不一致。',
|
||
]);
|
||
}
|
||
}
|
||
if ($oldShort === $newShort) {
|
||
continue;
|
||
}
|
||
$changed += $group->count();
|
||
if (! $apply) {
|
||
continue;
|
||
}
|
||
|
||
$this->renameReferences($oldShort, $newShort);
|
||
$groupIds = $group->pluck('id')->map(static fn (mixed $id): int => (int) $id)->all();
|
||
$this->connection->table('fin_accounts')
|
||
->whereIn('id', $groupIds)
|
||
->update([
|
||
'account_short' => $newShort,
|
||
'updated_at' => now(),
|
||
]);
|
||
foreach ($group as $mapping) {
|
||
$account = $accounts->get($mapping['id']);
|
||
$this->connection->table('fin_ledger_edit_events')->insert([
|
||
'entity_type' => 'account_short_rename',
|
||
'entity_key' => (string) $mapping['id'],
|
||
'changes' => json_encode([
|
||
'before' => $oldShort,
|
||
'after' => $newShort,
|
||
'account_no' => (string) ($account->account_no ?? ''),
|
||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||
'user_id' => user()?->id,
|
||
'user_name' => (string) (user()?->name ?? 'CLI'),
|
||
'created_at' => now(),
|
||
]);
|
||
}
|
||
}
|
||
|
||
return [
|
||
'requested' => count($normalized),
|
||
'changed' => $changed,
|
||
'unchanged' => count($normalized) - $changed,
|
||
'dry_run' => ! $apply,
|
||
];
|
||
});
|
||
}
|
||
|
||
private function upsertStatus(string $accountShort, string $status): void
|
||
{
|
||
$values = [
|
||
'status' => $status,
|
||
'updated_by' => (string) (user()?->name ?? ''),
|
||
'updated_at' => now(),
|
||
];
|
||
if ($this->connection->table('fin_account_statuses')->where('account_short', $accountShort)->exists()) {
|
||
$this->connection->table('fin_account_statuses')->where('account_short', $accountShort)->update($values);
|
||
|
||
return;
|
||
}
|
||
|
||
$this->connection->table('fin_account_statuses')->insert($values + [
|
||
'account_short' => $accountShort,
|
||
'created_at' => now(),
|
||
]);
|
||
}
|
||
|
||
private function renameReferences(string $oldShort, string $newShort): void
|
||
{
|
||
$now = now();
|
||
foreach ([
|
||
'fin_account_opening' => ['updated_at' => $now],
|
||
'fin_daily_flows' => ['updated_at' => $now],
|
||
'fin_transactions' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_account_map' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_account_statuses' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_account_type_overrides' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_account_todos' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_account_keep_todos' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_shops' => ['updated_at' => $now],
|
||
'fin_flow_summary_custom_values' => ['updated_at' => $now],
|
||
'fin_flow_summary_account_sources' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
'fin_bank_direct_bills' => ['updated_at' => $now],
|
||
'fin_bank_balance_current_adjustments' => ['updated_at' => $now],
|
||
'fin_bank_direct_balance_snapshots' => ['updated_at' => $now],
|
||
'fin_transaction_custom_fields' => ['updated_by' => (string) (user()?->name ?? ''), 'updated_at' => $now],
|
||
] as $table => $extra) {
|
||
if (! Schema::connection($this->connection->getName())->hasTable($table)
|
||
|| ! Schema::connection($this->connection->getName())->hasColumn($table, 'account_short')) {
|
||
continue;
|
||
}
|
||
$this->connection->table($table)->where('account_short', $oldShort)->update([
|
||
'account_short' => $newShort,
|
||
...$extra,
|
||
]);
|
||
}
|
||
|
||
if (Schema::connection($this->connection->getName())->hasTable('fin_daily_flow_overrides')) {
|
||
$this->connection->table('fin_daily_flow_overrides')
|
||
->where('account_short', $oldShort)
|
||
->update([
|
||
'account_short' => $newShort,
|
||
'updated_at' => $now,
|
||
]);
|
||
}
|
||
$this->connection->table('fin_account_map_events')
|
||
->where('old_account_short', $oldShort)
|
||
->update(['old_account_short' => $newShort]);
|
||
$this->connection->table('fin_account_map_events')
|
||
->where('new_account_short', $oldShort)
|
||
->update(['new_account_short' => $newShort]);
|
||
}
|
||
|
||
private function text(mixed $value): string
|
||
{
|
||
return preg_replace('/\s+/u', ' ', trim((string) $value)) ?? trim((string) $value);
|
||
}
|
||
|
||
private function nullableText(mixed $value): ?string
|
||
{
|
||
$text = $this->text($value);
|
||
|
||
return $text !== '' ? $text : null;
|
||
}
|
||
|
||
private function nullableNumber(mixed $value): ?float
|
||
{
|
||
if ($value === null || trim((string) $value) === '') {
|
||
return null;
|
||
}
|
||
|
||
return round((float) $value, 2);
|
||
}
|
||
|
||
private function digits(mixed $value): string
|
||
{
|
||
return preg_replace('/\D+/', '', (string) $value) ?? '';
|
||
}
|
||
}
|