财务台账支持新增公司账户 #590

Merged
shanshi merged 1 commits from feature/shanshi-finance-ledger-add-company into main 2026-10-26 14:08:37 +08:00
9 changed files with 569 additions and 4 deletions

View File

@ -14,6 +14,7 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\FinanceLedgerAccountCreator;
use Modules\EcommerceFinance\Services\FinanceLedgerAccountTemplate;
use Modules\EcommerceFinance\Services\FinanceLedgerCalculator;
use Modules\EcommerceFinance\Services\FinanceLedgerPayableMappingBulk;
@ -36,6 +37,72 @@ class FinanceLedger extends Controller
return $template->download();
}
public function storeAccount(Request $request, FinanceLedgerAccountCreator $creator): JsonResponse
{
abort_unless(
FinanceLedgerAccess::canEditAccountStatus(user()),
403,
'只有财务台账管理员可以新增公司或账户。',
);
$openingDate = (string) config('finance_ledger.opening_date', '2026-10-17');
$data = $request->validate([
'company_name' => ['required', 'string', 'max:100'],
'account_short' => ['required', 'string', 'max:100'],
'account_type' => ['nullable', 'string', 'max:50'],
'status' => ['required', 'string', Rule::in(array_keys(FinanceLedgerAccountStatus::OPTIONS))],
'region' => ['nullable', 'string', 'max:50'],
'account_no' => ['nullable', 'string', 'max:50'],
'bank_name' => ['nullable', 'string', 'max:200'],
'bank_city_branch' => ['nullable', 'string', 'max:100'],
'company_plan' => ['nullable', 'string', 'max:50'],
'account_should_keep' => [
'nullable',
'string',
Rule::in(FinanceLedgerAccountShouldKeep::OPTIONS),
],
'opening_date' => [
'required',
'date_format:Y-m-d',
'after_or_equal:' . $openingDate,
'before_or_equal:' . now()->toDateString(),
],
'opening_balance' => ['nullable', 'numeric'],
]);
$accountType = trim((string) ($data['account_type'] ?? ''));
if ($accountType !== '') {
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$allowedTypes = FinanceLedgerAccountType::options(
$connection->table('fin_accounts')
->whereNotNull('account_type')->where('account_type', '<>', '')
->distinct()->pluck('account_type')->all(),
$connection->table('fin_account_type_overrides')
->whereNotNull('account_type')->where('account_type', '<>', '')
->distinct()->pluck('account_type')->all(),
);
if (! in_array($accountType, $allowedTypes, true)) {
throw ValidationException::withMessages([
'account_type' => '请选择现有账户类型。',
]);
}
}
$result = $creator->create($data);
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$message = $result['company_created']
? '已新增公司并建立首个账户。'
: '已新增账户并关联现有公司。';
return response()->json([
'ok' => true,
'message' => $message,
'account' => $result,
'total_accounts' => $connection->table('fin_accounts')->count(),
'total_companies' => $connection->table('fin_companies')->count(),
], 201, ['Cache-Control' => 'private, no-store']);
}
public function syncShopData(FinanceLedgerShopDataSynchronizer $synchronizer)
{
abort_unless(FinanceLedgerAccess::canEditAccountStatus(user()), 403, '只有财务台账管理员可以同步店铺余额和提现。');

View File

@ -64,6 +64,7 @@ docker compose -f docker-compose.local.yml exec -u www-data app \
- 路由:`/workspace/financial-operations/ledger`(旧地址会自动跳转)
- 页面:账户总表、店铺台账、每日资金流水、动账明细、账户映射、数据来源
- 账户总表支持导出空白 Excel 录入模板,包含页面列、状态和账户类型选项及填写说明
- 账户总表编辑模式支持直接新增公司和首个账户:公司不存在时同步写入公司台账,账户简称必须唯一,可同时登记期初日期与期初余额
- 写权限:账户映射、账户状态和账户类型修改仅系统管理员及配置的财务台账管理员角色;其他账号只读
- 调度:`finance-ledger:sync-rpt --days=7 --merge` 每天 02:30(Asia/Shanghai)

View File

@ -0,0 +1,139 @@
<?php
namespace Modules\EcommerceFinance\Services;
use App\Utilities\FinanceLedgerAccountStatus;
use App\Utilities\FinanceLedgerAccountShouldKeep;
use App\Utilities\FinanceLedgerAccountType;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
/**
* 在账户总表中新增一个财务台账账户,并在公司不存在时同步建立公司台账。
*/
class FinanceLedgerAccountCreator
{
public function create(array $data): array
{
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$companyName = $this->text($data['company_name'] ?? '');
$accountShort = $this->text($data['account_short'] ?? '');
$accountNo = $this->text($data['account_no'] ?? '');
$accountType = $this->text($data['account_type'] ?? '');
$companyPlan = $this->text($data['company_plan'] ?? '');
$openingDate = (string) ($data['opening_date'] ?? now()->toDateString());
$openingBalance = round((float) ($data['opening_balance'] ?? 0), 2);
$status = FinanceLedgerAccountStatus::normalize((string) ($data['status'] ?? ''));
$accountShouldKeep = FinanceLedgerAccountShouldKeep::normalize(
(string) ($data['account_should_keep'] ?? ''),
);
$accountLast4 = FinanceLedgerAccountType::last4($accountType, $accountNo);
$normal = $status === FinanceLedgerAccountStatus::NORMAL;
$now = now();
return $connection->transaction(function () use (
$connection,
$companyName,
$accountShort,
$accountNo,
$accountType,
$companyPlan,
$openingDate,
$openingBalance,
$status,
$accountShouldKeep,
$accountLast4,
$normal,
$data,
$now,
): array {
if ($connection->table('fin_accounts')->where('account_short', $accountShort)->exists()) {
throw ValidationException::withMessages([
'account_short' => '账户简称已存在,请改用其他简称或直接编辑现有账户。',
]);
}
$company = $connection->table('fin_companies')->where('name', $companyName)->first(['id']);
$companyCreated = $company === null;
if ($companyCreated) {
$connection->table('fin_companies')->insert([
'name' => $companyName,
'created_at' => $now,
'updated_at' => $now,
]);
}
$accountId = $connection->table('fin_accounts')->insertGetId([
'company_name' => $companyName,
'account_short' => $accountShort,
'region' => $this->nullableText($data['region'] ?? null),
'account_no' => $accountNo !== '' ? $accountNo : null,
'bank_name' => $this->nullableText($data['bank_name'] ?? null),
'bank_city_branch' => $this->nullableText($data['bank_city_branch'] ?? null),
'account_type' => $accountType !== '' ? $accountType : null,
'company_plan' => $companyPlan !== '' ? $companyPlan : null,
'account_should_keep' => $accountShouldKeep !== '' ? $accountShouldKeep : null,
'account_last4' => $accountLast4,
'current_balance' => $openingBalance,
'blocked_amount' => $normal ? 0 : $openingBalance,
'daily_available' => $normal ? $openingBalance : 0,
'created_at' => $now,
'updated_at' => $now,
]);
$connection->table('fin_account_opening')->insert([
'account_short' => $accountShort,
'opening_date' => $openingDate,
'opening_balance' => $openingBalance,
'remark' => '新增账户期初',
'created_at' => $now,
'updated_at' => $now,
]);
$connection->table('fin_daily_flows')->insert([
'flow_date' => $openingDate,
'company_name' => $companyName,
'account_short' => $accountShort,
'opening_balance' => $openingBalance,
'inflow' => 0,
'outflow' => 0,
'closing_balance' => $openingBalance,
'remark' => '新增账户期初',
'created_at' => $now,
'updated_at' => $now,
]);
if (! $normal) {
$connection->table('fin_account_statuses')->insert([
'account_short' => $accountShort,
'status' => $status,
'updated_by' => (string) user()->name,
'created_at' => $now,
'updated_at' => $now,
]);
}
return [
'id' => (int) $accountId,
'company_name' => $companyName,
'account_short' => $accountShort,
'company_created' => $companyCreated,
'status' => $status,
'opening_date' => $openingDate,
'opening_balance' => $openingBalance,
];
});
}
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;
}
}

View File

@ -24,8 +24,8 @@ class FinanceLedgerCalculator
$now = now();
$opening = $connection->table('fin_account_opening')
->where('opening_date', '<=', $openingDate)
->orderBy('opening_date')
->orderBy('id')
->get()
->groupBy('account_short')
->map(static fn ($rows) => $rows->last());

View File

@ -64,6 +64,7 @@ class FinanceLedgerPageData
'ledgerTransactionAccountHeaderOptions' => $this->transactionAccountHeaderOptions(),
'ledgerTransactionDateHeaderOptions' => $this->transactionDateHeaderOptions(),
'ledgerAccountFilterOptions' => $this->accountFilterOptions(),
'ledgerCompanyOptions' => $this->companyOptions(),
'ledgerAccountStatusOptions' => FinanceLedgerAccountStatus::OPTIONS,
'ledgerAccountPlanOptions' => $this->accountPlanOptions(),
'ledgerAccountKeepOptions' => FinanceLedgerAccountShouldKeep::OPTIONS,
@ -562,6 +563,25 @@ class FinanceLedgerPageData
->all();
}
private function companyOptions(): array
{
return $this->db()->table('fin_companies')
->whereNotNull('name')
->pluck('name')
->merge(
$this->db()->table('fin_accounts')
->whereNotNull('company_name')
->distinct()
->pluck('company_name'),
)
->map(static fn (mixed $value): string => trim((string) $value))
->filter()
->unique()
->sortBy(static fn (string $value): string => mb_strtolower($value))
->values()
->all();
}
private function applyLedgerHeaderFilter(Builder $query, string $tab, array $columns): void
{
$column = trim((string) request($tab . '_filter_column', ''));

View File

@ -10,6 +10,7 @@
$accountFilterOptions = $ledgerAccountFilterOptions ?? ['regions' => [], 'types' => []];
$accountTypeOptions = $accountFilterOptions['types'] ?? [];
$accountPlanOptions = $ledgerAccountPlanOptions ?? [];
$companyOptions = $ledgerCompanyOptions ?? [];
$accountKeepOptions = $ledgerAccountKeepOptions ?? \App\Utilities\FinanceLedgerAccountShouldKeep::OPTIONS;
$activeAccountFilterCount = count(array_filter([
request('accounts_q'),
@ -200,6 +201,28 @@
.ledger-edit-switch input:focus-visible + .ledger-edit-switch__track { outline:2px solid var(--vip-content-accent-dark, #856632); outline-offset:2px; }
.ledger-edit-switch:has(input:checked) { border-color:var(--vip-content-accent-dark, #856632); background:var(--vip-content-accent-soft, #F7F0DE); color:var(--vip-content-accent-dark, #856632); }
.ledger-edit-switch.is-disabled { cursor:not-allowed; opacity:.55; }
.ledger-add-company[hidden] { display:none !important; }
.ledger-company-dialog { width:min(54rem, calc(100vw - 2rem)); max-height:calc(100vh - 2rem); padding:0; overflow:auto; border:1px solid var(--vip-border, #D8D2C7); border-radius:.75rem; background:#fff; color:var(--vip-content-ink, #171717); box-shadow:0 8px 24px rgba(23,23,23,.18); }
.ledger-company-dialog::backdrop { background:rgba(5,5,6,.46); }
.ledger-company-form { margin:0; }
.ledger-company-form__header { display:flex; align-items:flex-start; justify-content:space-between; gap:1rem; padding:1rem 1.1rem .85rem; border-bottom:1px solid #e8e3da; }
.ledger-company-form__title { margin:0 0 .22rem; font-size:.92rem; line-height:1.35; }
.ledger-company-form__help { margin:0; color:var(--vip-content-muted, #595959); font-size:.7rem; line-height:1.55; }
.ledger-company-form__close { display:inline-grid; flex:0 0 auto; place-items:center; width:1.8rem; height:1.8rem; padding:0; border:1px solid transparent; border-radius:.35rem; background:transparent; color:var(--vip-content-muted, #595959); cursor:pointer; }
.ledger-company-form__close:hover { border-color:var(--vip-border, #D8D2C7); color:var(--vip-content-accent-dark, #856632); }
.ledger-company-form__body { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:.8rem; padding:1rem 1.1rem; }
.ledger-company-field { display:grid; min-width:0; gap:.3rem; }
.ledger-company-field--wide { grid-column:span 2; }
.ledger-company-field label { color:var(--vip-content-muted, #595959); font-size:.7rem; font-weight:600; }
.ledger-company-field input,
.ledger-company-field select { width:100%; min-width:0; height:2.15rem; padding:0 .58rem; border:1px solid var(--vip-border, #D8D2C7); border-radius:.45rem; background:#fff; color:var(--vip-content-ink, #171717); font:inherit; }
.ledger-company-field input:focus,
.ledger-company-field select:focus { border-color:var(--vip-content-accent-dark, #856632); outline:none; box-shadow:0 0 0 3px rgba(133,102,50,.16); }
.ledger-company-field__hint { color:var(--vip-content-muted, #595959); font-size:.65rem; line-height:1.45; }
.ledger-company-form__message { grid-column:1 / -1; margin:0; padding:.55rem .65rem; border:1px solid rgba(184,0,0,.28); border-radius:.4rem; background:#fff5f5; color:var(--vip-danger, #B80000); font-size:.7rem; line-height:1.5; }
.ledger-company-form__message[hidden] { display:none !important; }
.ledger-company-form__footer { display:flex; align-items:center; justify-content:flex-end; gap:.5rem; padding:.8rem 1.1rem 1rem; border-top:1px solid #e8e3da; }
.ledger-company-form__footer .ledger-btn:disabled { opacity:.58; cursor:wait; }
#ledger-panel-accounts .ledger-account-editor { display:none; }
#ledger-panel-accounts.is-account-edit-mode .ledger-account-readonly { display:none; }
#ledger-panel-accounts.is-account-edit-mode .ledger-account-editor { display:block; }
@ -384,6 +407,8 @@
.ledger-source-tag { display:inline-flex; align-items:center; padding:.1rem .4rem; border-radius:.25rem; background:#f4f1eb; color:var(--vip-content-muted, #595959); font-size:.68rem; }
.ledger-mono { font-variant-numeric:tabular-nums; }
@media (max-width: 900px) { .ledger-hero { align-items:flex-start; flex-direction:column; } .ledger-field { min-width:calc(50% - .5rem); } }
@media (max-width: 760px) { .ledger-company-form__body { grid-template-columns:repeat(2, minmax(0, 1fr)); } .ledger-company-field--wide { grid-column:span 2; } }
@media (max-width: 520px) { .ledger-company-form__body { grid-template-columns:minmax(0, 1fr); } .ledger-company-field--wide { grid-column:auto; } }
</style>
<div class="ledger-hero">
@ -425,11 +450,17 @@
@if ($activeAccountFilterCount > 0)
<span class="ledger-filter-state" data-account-filter-state role="status" aria-live="polite" title="当前有 {{ $activeAccountFilterCount }} 个筛选条件生效"><span class="material-icons-outlined" aria-hidden="true">filter_alt</span><span>筛选中</span><b>{{ $activeAccountFilterCount }}</b></span>
@endif
<label class="ledger-edit-switch {{ $canEditAccounts ? '' : 'is-disabled' }}" title="{{ $canEditAccounts ? '开启后可修改账户类型和账户状态' : '当前账号没有财务台账编辑权限' }}">
<label class="ledger-edit-switch {{ $canEditAccounts ? '' : 'is-disabled' }}" title="{{ $canEditAccounts ? '开启后可修改账户信息并新增公司/账户' : '当前账号没有财务台账编辑权限' }}">
<span>编辑模式</span>
<input type="checkbox" role="switch" aria-label="编辑模式" aria-checked="false" data-ledger-edit-mode-toggle @disabled(! $canEditAccounts)>
<span class="ledger-edit-switch__track" aria-hidden="true"><span class="ledger-edit-switch__thumb"></span></span>
</label>
@if ($canEditAccounts)
<button class="ledger-btn ledger-add-company" type="button" data-ledger-add-company hidden>
<span class="material-icons-outlined" aria-hidden="true">domain_add</span>
新增公司/账户
</button>
@endif
<div class="ledger-column-picker" data-ledger-column-picker data-column-storage-key="caiwu.financial-ledger.accounts.preferences.v2.{{ auth()->id() }}.{{ company_id() }}">
<button class="ledger-btn" type="button" data-ledger-column-toggle aria-expanded="false"><span class="material-icons-outlined" aria-hidden="true">view_column</span>列设置</button>
<div class="ledger-column-panel" data-ledger-column-panel role="group" aria-label="选择账户总表展示列" hidden>
@ -441,6 +472,105 @@
<div class="ledger-actions"><button class="ledger-btn primary" type="submit"><span class="material-icons-outlined">search</span>查询</button><a class="ledger-btn" href="{{ $tabUrl('accounts') }}"><span class="material-icons-outlined">refresh</span>重置</a><a class="ledger-btn" href="{{ route('business.financial-ledger.accounts.template') }}" download data-account-template-download><span class="material-icons-outlined">download</span>导出录入模板</a></div>
<div class="ledger-download-status" data-account-template-download-status role="status" aria-live="polite" hidden>下载已开始,请查看浏览器下载目录。</div>
</form>
@if ($canEditAccounts)
<dialog class="ledger-company-dialog" data-ledger-company-dialog data-ledger-accounts-url="{{ $tabUrl('accounts') }}" aria-labelledby="ledger-company-dialog-title">
<form class="ledger-company-form" method="POST" action="{{ route('business.financial-ledger.accounts.store') }}" data-ledger-company-form>
@csrf
<header class="ledger-company-form__header">
<div>
<h3 class="ledger-company-form__title" id="ledger-company-dialog-title">新增公司/账户</h3>
<p class="ledger-company-form__help">公司不存在时自动加入公司台账;账户简称必须唯一。期初余额会作为该账户的起始资金并进入每日流水。</p>
</div>
<button class="ledger-company-form__close" type="button" aria-label="关闭新增公司/账户" data-ledger-company-close>
<span class="material-icons-outlined" aria-hidden="true">close</span>
</button>
</header>
<div class="ledger-company-form__body">
<div class="ledger-company-field">
<label for="ledger-company-name">公司名称 <span aria-hidden="true">*</span></label>
<input id="ledger-company-name" name="company_name" type="text" list="ledger-company-options" maxlength="100" required autocomplete="off" placeholder="选择或输入公司名称" data-ledger-company-first-field>
<span class="ledger-company-field__hint">输入公司台账中不存在的名称时会自动新增公司。</span>
</div>
<div class="ledger-company-field">
<label for="ledger-company-account-short">账户简称 <span aria-hidden="true">*</span></label>
<input id="ledger-company-account-short" name="account_short" type="text" maxlength="100" required autocomplete="off" placeholder="如 上海甲公司农行">
</div>
<div class="ledger-company-field">
<label for="ledger-company-account-type">账户类型</label>
<select id="ledger-company-account-type" name="account_type">
<option value="">未填写</option>
@foreach ($accountTypeOptions as $accountType)
<option value="{{ $accountType }}">{{ $accountType }}</option>
@endforeach
</select>
</div>
<div class="ledger-company-field">
<label for="ledger-company-status">账户状态</label>
<select id="ledger-company-status" name="status" required>
@foreach ($accountStatusOptions as $statusCode => $statusLabel)
<option value="{{ $statusCode }}" @selected($statusCode === \App\Utilities\FinanceLedgerAccountStatus::NORMAL)>{{ $statusLabel }}</option>
@endforeach
</select>
</div>
<div class="ledger-company-field">
<label for="ledger-company-region">地区</label>
<input id="ledger-company-region" name="region" type="text" maxlength="50" autocomplete="off" placeholder="如 上海">
</div>
<div class="ledger-company-field">
<label for="ledger-company-account-no">账号</label>
<input id="ledger-company-account-no" name="account_no" type="text" maxlength="50" autocomplete="off" placeholder="银行账号或支付宝账号">
</div>
<div class="ledger-company-field">
<label for="ledger-company-bank-name">开户行</label>
<input id="ledger-company-bank-name" name="bank_name" type="text" maxlength="200" autocomplete="off" placeholder="开户银行">
</div>
<div class="ledger-company-field">
<label for="ledger-company-bank-branch">开户城市/网点</label>
<input id="ledger-company-bank-branch" name="bank_city_branch" type="text" maxlength="100" autocomplete="off" placeholder="城市及网点">
</div>
<div class="ledger-company-field">
<label for="ledger-company-plan">公司规划</label>
<input id="ledger-company-plan" name="company_plan" type="text" list="ledger-company-plan-options" maxlength="50" autocomplete="off" placeholder="如 保留、待注销">
</div>
<div class="ledger-company-field">
<label for="ledger-company-keep">账户是否保留</label>
<select id="ledger-company-keep" name="account_should_keep">
<option value="">未填写</option>
@foreach ($accountKeepOptions as $keepOption)
<option value="{{ $keepOption }}">{{ $keepOption }}</option>
@endforeach
</select>
</div>
<div class="ledger-company-field">
<label for="ledger-company-opening-date">期初日期</label>
<input id="ledger-company-opening-date" name="opening_date" type="date" min="{{ $ledgerOpeningDate }}" max="{{ now()->format('Y-m-d') }}" value="{{ now()->format('Y-m-d') }}" required>
</div>
<div class="ledger-company-field">
<label for="ledger-company-opening-balance">期初余额(元)</label>
<input id="ledger-company-opening-balance" name="opening_balance" type="number" inputmode="decimal" step="0.01" value="0" placeholder="0.00">
</div>
<p class="ledger-company-form__message" role="alert" data-ledger-company-error hidden></p>
</div>
<footer class="ledger-company-form__footer">
<button class="ledger-btn" type="button" data-ledger-company-cancel>取消</button>
<button class="ledger-btn primary" type="submit" data-ledger-company-save>
<span class="material-icons-outlined" aria-hidden="true">check</span>
保存公司/账户
</button>
</footer>
</form>
<datalist id="ledger-company-options">
@foreach ($companyOptions as $companyOption)
<option value="{{ $companyOption }}"></option>
@endforeach
</datalist>
<datalist id="ledger-company-plan-options">
@foreach ($accountPlanOptions as $planOption)
<option value="{{ $planOption }}"></option>
@endforeach
</datalist>
</dialog>
@endif
<div class="ledger-summary">
<div class="ledger-summary__item"><span>账户数</span><b>{{ number_format((int) ($ledgerAccountSummary['count'] ?? 0)) }}</b></div>
<a class="ledger-summary__item ledger-summary__item--link" href="{{ route('business.financial-ledger.unretained-accounts') }}" aria-label="查看不保留账户处理待办"><span>不保留账户数</span><b>{{ number_format((int) ($ledgerAccountSummary['unretained'] ?? 0)) }}</b></a>
@ -1322,6 +1452,11 @@
const accountPanel = page.querySelector('#ledger-panel-accounts');
const accountEditToggle = page.querySelector('[data-ledger-edit-mode-toggle]');
const accountAddCompanyButton = page.querySelector('[data-ledger-add-company]');
const accountCompanyDialog = page.querySelector('[data-ledger-company-dialog]');
const accountCompanyForm = page.querySelector('[data-ledger-company-form]');
const accountCompanyError = page.querySelector('[data-ledger-company-error]');
const accountCompanySave = page.querySelector('[data-ledger-company-save]');
const applyAccountEditMode = (enabled) => {
const active = Boolean(enabled && accountEditToggle && !accountEditToggle.disabled);
accountPanel?.classList.toggle('is-account-edit-mode', active);
@ -1329,10 +1464,78 @@
editor.disabled = !active;
});
accountEditToggle?.setAttribute('aria-checked', active ? 'true' : 'false');
if (accountAddCompanyButton) {
accountAddCompanyButton.hidden = !active;
}
};
accountEditToggle?.addEventListener('change', () => {
applyAccountEditMode(accountEditToggle.checked);
notify(accountEditToggle.checked ? '编辑模式已开启' : '编辑模式已关闭');
notify(accountEditToggle.checked ? '编辑模式已开启,可修改账户并新增公司/账户' : '编辑模式已关闭');
});
const closeAccountCompanyDialog = () => {
if (!accountCompanyDialog?.open) return;
accountCompanyDialog.close();
};
accountAddCompanyButton?.addEventListener('click', () => {
if (!accountCompanyDialog) return;
accountCompanyForm?.reset();
if (accountCompanyError) {
accountCompanyError.hidden = true;
accountCompanyError.textContent = '';
}
if (typeof accountCompanyDialog.showModal === 'function') {
accountCompanyDialog.showModal();
} else {
accountCompanyDialog.setAttribute('open', '');
}
page.querySelector('[data-ledger-company-first-field]')?.focus();
});
page.querySelector('[data-ledger-company-close]')?.addEventListener('click', closeAccountCompanyDialog);
page.querySelector('[data-ledger-company-cancel]')?.addEventListener('click', closeAccountCompanyDialog);
accountCompanyForm?.addEventListener('submit', async (event) => {
event.preventDefault();
if (!accountCompanyForm.reportValidity()) return;
if (accountCompanySave) accountCompanySave.disabled = true;
accountCompanyForm.setAttribute('aria-busy', 'true');
if (accountCompanyError) {
accountCompanyError.hidden = true;
accountCompanyError.textContent = '';
}
try {
const response = await fetch(accountCompanyForm.action, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: new FormData(accountCompanyForm),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const firstError = Object.values(payload.errors || {})[0]?.[0];
throw new Error(firstError || payload.message || '公司/账户保存失败');
}
notify(payload.message || '公司/账户已新增');
closeAccountCompanyDialog();
const target = new URL(
accountCompanyDialog?.dataset.ledgerAccountsUrl || window.location.href,
window.location.origin,
);
target.searchParams.set('accounts_short', payload.account?.account_short || '');
window.location.assign(target.toString());
} catch (error) {
if (accountCompanyError) {
accountCompanyError.textContent = error.message || '公司/账户保存失败';
accountCompanyError.hidden = false;
}
notify(error.message || '公司/账户保存失败', true);
} finally {
if (accountCompanySave) accountCompanySave.disabled = false;
accountCompanyForm.removeAttribute('aria-busy');
}
});
const accountColumnPicker = page.querySelector('[data-ledger-column-picker]');
const accountColumnPanel = accountColumnPicker?.querySelector('[data-ledger-column-panel]');

View File

@ -717,6 +717,10 @@ Route::post('workspace/financial-ledger/accounts/status', [\App\Http\Controllers
->middleware('business.page:financial-operations,ledger')
->name('business.financial-ledger.accounts.status');
Route::post('workspace/financial-ledger/accounts', [\App\Http\Controllers\Business\FinanceLedger::class, 'storeAccount'])
->middleware('business.page:financial-operations,ledger')
->name('business.financial-ledger.accounts.store');
Route::post('workspace/financial-ledger/accounts/type', [\App\Http\Controllers\Business\FinanceLedger::class, 'updateAccountType'])
->middleware('business.page:financial-operations,ledger')
->name('business.financial-ledger.accounts.type');

View File

@ -80,6 +80,13 @@ class FinanceLedgerAccountStatusTest extends FeatureTestCase
]);
}
private function createAccountUrl(): string
{
return route('business.financial-ledger.accounts.store', [
'company_id' => $this->company->id,
]);
}
public function test_account_table_renders_status_selector_with_four_options(): void
{
$this->loginAs()->get($this->pageUrl())
@ -130,6 +137,12 @@ class FinanceLedgerAccountStatusTest extends FeatureTestCase
->assertSee('data-ledger-column-picker', false)
->assertSee('data-ledger-column-panel', false)
->assertSee('data-ledger-edit-mode-toggle', false)
->assertSee('data-ledger-add-company', false)
->assertSee('data-ledger-company-dialog', false)
->assertSee('新增公司/账户')
->assertSee('name="company_name"', false)
->assertSee('name="opening_balance"', false)
->assertSee('id="ledger-company-options"', false)
->assertSee('aria-checked="false"', false)
->assertSee('ledger-account-editor', false)
->assertSee('data-account-edit-display', false)
@ -736,6 +749,80 @@ class FinanceLedgerAccountStatusTest extends FeatureTestCase
])->assertUnprocessable()->assertJsonValidationErrors('account_should_keep');
}
public function test_editor_can_create_new_company_and_account_with_opening_balance(): void
{
$this->loginAs()->postJson($this->createAccountUrl(), [
'company_name' => '新设财务公司',
'account_short' => '新设财务公司农行',
'account_type' => '公户',
'status' => 'limited',
'region' => '上海',
'account_no' => '6222000000001234',
'bank_name' => '中国农业银行',
'bank_city_branch' => '上海浦东支行',
'company_plan' => '待注销',
'account_should_keep' => '否',
'opening_date' => '2026-10-20',
'opening_balance' => '12345.67',
])
->assertCreated()
->assertJsonPath('account.company_name', '新设财务公司')
->assertJsonPath('account.account_short', '新设财务公司农行')
->assertJsonPath('account.company_created', true)
->assertJsonPath('account.status', 'limited')
->assertJsonPath('message', '已新增公司并建立首个账户。');
$this->assertDatabaseHas('fin_companies', [
'name' => '新设财务公司',
], 'business_mirror');
$this->assertDatabaseHas('fin_accounts', [
'company_name' => '新设财务公司',
'account_short' => '新设财务公司农行',
'account_type' => '公户',
'region' => '上海',
'account_no' => '6222000000001234',
'account_last4' => '1234',
'company_plan' => '待注销',
'account_should_keep' => '否',
'current_balance' => 12345.67,
'daily_available' => 0,
'blocked_amount' => 12345.67,
], 'business_mirror');
$this->assertDatabaseHas('fin_account_statuses', [
'account_short' => '新设财务公司农行',
'status' => 'limited',
'updated_by' => 'Test User',
], 'business_mirror');
$this->assertDatabaseHas('fin_account_opening', [
'account_short' => '新设财务公司农行',
'opening_date' => '2026-10-20',
'opening_balance' => 12345.67,
], 'business_mirror');
$this->assertDatabaseHas('fin_daily_flows', [
'company_name' => '新设财务公司',
'account_short' => '新设财务公司农行',
'flow_date' => '2026-10-20',
'opening_balance' => 12345.67,
'closing_balance' => 12345.67,
], 'business_mirror');
$this->loginAs()->get($this->pageUrl() . '?accounts_short=' . urlencode('新设财务公司农行'))
->assertOk()
->assertSee('新设财务公司')
->assertSee('新设财务公司农行')
->assertSee('>1.23</td>', false);
$this->withExceptionHandling()->loginAs()->postJson($this->createAccountUrl(), [
'company_name' => '另一个公司',
'account_short' => '新设财务公司农行',
'status' => 'normal',
'opening_date' => '2026-10-20',
'opening_balance' => 0,
])->assertUnprocessable()->assertJsonValidationErrors('account_short');
$this->assertDatabaseCount('fin_companies', 1, 'business_mirror');
}
public function test_invalid_status_or_account_is_rejected(): void
{
$this->withExceptionHandling()->loginAs()->postJson($this->statusUrl(), [
@ -771,7 +858,8 @@ class FinanceLedgerAccountStatusTest extends FeatureTestCase
->assertSee('data-ledger-edit-mode-toggle', false)
->assertSee('当前账号没有财务台账编辑权限')
->assertDontSee('data-account-status data-account-short', false)
->assertDontSee('data-account-type data-account-short', false);
->assertDontSee('data-account-type data-account-short', false)
->assertDontSee('class="ledger-btn ledger-add-company"', false);
$this->withExceptionHandling()->loginAs($viewer)->postJson($this->statusUrl(), [
'account_short' => '测试账户',
@ -785,6 +873,13 @@ class FinanceLedgerAccountStatusTest extends FeatureTestCase
'account_short' => '测试账户',
'account_should_keep' => '否',
])->assertForbidden();
$this->withExceptionHandling()->loginAs($viewer)->postJson($this->createAccountUrl(), [
'company_name' => '无权限公司',
'account_short' => '无权限账户',
'status' => 'normal',
'opening_date' => '2026-10-20',
'opening_balance' => 0,
])->assertForbidden();
$this->withExceptionHandling()->loginAs($viewer)->post($this->accountTodoUrl(), [
'account_short' => '测试账户',
'current_progress' => '处理中',

View File

@ -155,4 +155,40 @@ class FinanceLedgerCalculatorTest extends TestCase
$this->assertEqualsWithDelta(500.00, (float) $account->daily_available, 0.001);
$this->assertEqualsWithDelta(0.00, (float) $account->blocked_amount, 0.001);
}
public function test_new_account_uses_its_later_opening_date_and_ignores_earlier_transactions(): void
{
$db = DB::connection('business_mirror');
$db->table('fin_accounts')->insert([
'company_name' => '新设公司',
'account_short' => '新设账户',
'blocked_amount' => 0,
]);
$db->table('fin_account_opening')->insert([
'account_short' => '新设账户',
'opening_date' => '2026-10-20',
'opening_balance' => 700,
]);
$db->table('fin_transactions')->insert([
['txn_date' => '2026-10-18', 'account_short' => '新设账户', 'source' => 'manual', 'source_value' => null, 'income' => 999, 'expense' => 0],
['txn_date' => '2026-10-20', 'account_short' => '新设账户', 'source' => 'manual', 'source_value' => null, 'income' => 200, 'expense' => 0],
]);
app(FinanceLedgerCalculator::class)->recalculate();
$flows = $db->table('fin_daily_flows')
->where('account_short', '新设账户')
->orderBy('flow_date')
->get();
$this->assertCount(1, $flows);
$this->assertSame('2026-10-20', (string) $flows[0]->flow_date);
$this->assertEqualsWithDelta(700.00, (float) $flows[0]->opening_balance, 0.001);
$this->assertEqualsWithDelta(200.00, (float) $flows[0]->inflow, 0.001);
$this->assertEqualsWithDelta(900.00, (float) $flows[0]->closing_balance, 0.001);
$this->assertEqualsWithDelta(
900.00,
(float) $db->table('fin_accounts')->where('account_short', '新设账户')->value('current_balance'),
0.001,
);
}
}