1084 lines
45 KiB
PHP
1084 lines
45 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\View;
|
|
|
|
use App\Utilities\FinanceLedgerAccountShouldKeep;
|
|
use App\Utilities\FinanceLedgerAccountStatus;
|
|
use App\Utilities\FinanceLedgerAccess;
|
|
use App\Utilities\FinanceLedgerFlowSummaryDataSource;
|
|
use App\Utilities\FinanceLedgerIndependentAccounts;
|
|
use Illuminate\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
final class NonStoreAccountMonitorPageData
|
|
{
|
|
private const CATEGORY_BANK = 'bank';
|
|
|
|
private const CATEGORY_ALIPAY = 'alipay';
|
|
|
|
private const CATEGORY_WANGSHANG = 'wangshang';
|
|
|
|
private const CATEGORY_LEGACY_WALLET = 'legacy_wallet';
|
|
|
|
private const CATEGORY_OTHER = 'other';
|
|
|
|
private const CATEGORY_LABELS = [
|
|
self::CATEGORY_BANK => '银行账户',
|
|
self::CATEGORY_ALIPAY => '支付宝',
|
|
self::CATEGORY_WANGSHANG => '网商银行',
|
|
self::CATEGORY_LEGACY_WALLET => '旧网银钱包',
|
|
self::CATEGORY_OTHER => '其他账户',
|
|
];
|
|
|
|
private const UNRETAINED_CATEGORIES = [
|
|
self::CATEGORY_BANK,
|
|
self::CATEGORY_ALIPAY,
|
|
self::CATEGORY_WANGSHANG,
|
|
self::CATEGORY_LEGACY_WALLET,
|
|
];
|
|
|
|
private const DIRECT_ELIGIBLE_BANK_LABELS = [
|
|
'华夏银行',
|
|
'中国银行',
|
|
'招商银行',
|
|
];
|
|
|
|
private const VIEW_OVERVIEW = 'overview';
|
|
|
|
private const VIEW_ACCOUNTS = 'accounts';
|
|
|
|
private const VIEW_UNRETAINED_TASKS = 'unretained_tasks';
|
|
|
|
private const VIEW_DIRECT_TASKS = 'direct_tasks';
|
|
|
|
public function page(): array
|
|
{
|
|
$period = $this->period();
|
|
$accounts = $this->accountRows();
|
|
$retained = $accounts
|
|
->filter(static fn (array $row): bool => $row['is_retained'])
|
|
->values();
|
|
$unretained = $accounts
|
|
->reject(static fn (array $row): bool => $row['is_retained'])
|
|
->values();
|
|
$view = $this->view();
|
|
$overviewUrl = $this->pageUrl();
|
|
$accountsUrl = $this->pageUrl(['view' => self::VIEW_ACCOUNTS]);
|
|
$unretainedTasksUrl = $this->pageUrl(['view' => self::VIEW_UNRETAINED_TASKS]);
|
|
$directTasksUrl = $this->pageUrl(['view' => self::VIEW_DIRECT_TASKS]);
|
|
|
|
$retainedSummary = $this->summary($retained);
|
|
$unretainedSummary = $this->summary($unretained);
|
|
$unretainedProgress = $this->progressSummary($unretained);
|
|
$fundOverview = [
|
|
'total_accounts' => $retainedSummary['count'],
|
|
'current_balance' => $retainedSummary['current_balance'],
|
|
'available_balance' => $retainedSummary['available_balance'],
|
|
'blocked_balance' => $retainedSummary['blocked_balance'],
|
|
'retained_balance' => $retainedSummary['current_balance'],
|
|
'all_accounts_url' => $this->pageUrl([
|
|
'view' => self::VIEW_ACCOUNTS,
|
|
'account_category' => 'all',
|
|
'period_from' => $period['from'],
|
|
'period_to' => $period['to'],
|
|
]),
|
|
];
|
|
$retainedOtherAccounts = $retained
|
|
->where('category', self::CATEGORY_OTHER)
|
|
->values();
|
|
$fundOverview['other_accounts'] = $retainedOtherAccounts->all();
|
|
$fundOverview['alipay_accounts'] = $retained
|
|
->where('category', self::CATEGORY_ALIPAY)
|
|
->values()
|
|
->all();
|
|
$fundOverview['wangshang_accounts'] = $retained
|
|
->where('category', self::CATEGORY_WANGSHANG)
|
|
->values()
|
|
->all();
|
|
$fundOverview['legacy_wallet_accounts'] = $retained
|
|
->where('category', self::CATEGORY_LEGACY_WALLET)
|
|
->values()
|
|
->all();
|
|
$positiveBalanceTotal = (float) $retained
|
|
->sum(static fn (array $row): float => max(0.0, (float) $row['current_balance']));
|
|
$fundDistribution = collect(self::CATEGORY_LABELS)
|
|
->map(function (string $platform, string $category) use ($retained, $positiveBalanceTotal): array {
|
|
$rows = $retained->where('category', $category)->values();
|
|
$summary = $this->summary($rows);
|
|
$positiveBalance = max(0.0, (float) $summary['current_balance']);
|
|
|
|
return [
|
|
'platform' => $platform,
|
|
'category' => $category,
|
|
...$summary,
|
|
'share_percent' => $positiveBalanceTotal > 0
|
|
? round($positiveBalance / $positiveBalanceTotal * 100, 1)
|
|
: 0.0,
|
|
];
|
|
})
|
|
->values()
|
|
->all();
|
|
$fundDistribution = array_map(function (array $row): array {
|
|
$row['url'] = $row['category'] === self::CATEGORY_BANK
|
|
? ''
|
|
: $this->pageUrl([
|
|
'view' => self::VIEW_ACCOUNTS,
|
|
'keep' => 'retained',
|
|
'account_category' => $row['category'],
|
|
]);
|
|
|
|
return $row;
|
|
}, $fundDistribution);
|
|
$unretainedPositiveBalanceTotal = (float) $unretained
|
|
->sum(static fn (array $row): float => max(0.0, (float) $row['current_balance']));
|
|
$unretainedCategoryAccounts = [];
|
|
$unretainedDistribution = collect(self::UNRETAINED_CATEGORIES)
|
|
->map(function (string $category) use (
|
|
$unretained,
|
|
$unretainedPositiveBalanceTotal,
|
|
&$unretainedCategoryAccounts,
|
|
): array {
|
|
$rows = $unretained->where('category', $category)->values();
|
|
$summary = $this->summary($rows);
|
|
$positiveBalance = max(0.0, (float) $summary['current_balance']);
|
|
$unretainedCategoryAccounts[$category] = $rows->all();
|
|
|
|
return [
|
|
'platform' => self::CATEGORY_LABELS[$category],
|
|
'category' => $category,
|
|
...$summary,
|
|
'share_percent' => $unretainedPositiveBalanceTotal > 0
|
|
? round($positiveBalance / $unretainedPositiveBalanceTotal * 100, 1)
|
|
: 0.0,
|
|
];
|
|
})
|
|
->all();
|
|
$retainedBankAccountsForDistribution = $retained
|
|
->where('category', self::CATEGORY_BANK)
|
|
->values();
|
|
$retainedBankPositiveBalance = (float) $retainedBankAccountsForDistribution
|
|
->sum(static fn (array $row): float => max(0.0, (float) $row['current_balance']));
|
|
$bankDistribution = $retainedBankAccountsForDistribution
|
|
->groupBy('platform_label')
|
|
->map(function (Collection $rows, string $bank) use ($retainedBankPositiveBalance): array {
|
|
$summary = $this->summary($rows);
|
|
$positiveBalance = max(0.0, (float) $summary['current_balance']);
|
|
|
|
return [
|
|
'bank' => $bank !== '' ? $bank : '未填写',
|
|
...$summary,
|
|
'share_percent' => $retainedBankPositiveBalance > 0
|
|
? round($positiveBalance / $retainedBankPositiveBalance * 100, 1)
|
|
: 0.0,
|
|
'url' => $this->pageUrl([
|
|
'view' => self::VIEW_ACCOUNTS,
|
|
'keep' => 'retained',
|
|
'account_category' => self::CATEGORY_BANK,
|
|
'bank_group' => $bank,
|
|
]),
|
|
];
|
|
})
|
|
->sortByDesc('current_balance')
|
|
->values()
|
|
->all();
|
|
$fundOverview['distribution'] = $fundDistribution;
|
|
$fundOverview['bank_distribution'] = $bankDistribution;
|
|
$retainedBreakdown = $this->retainedBreakdown($retained, $accountsUrl, $directTasksUrl);
|
|
$retainedDirectEligibleBankAccounts = $retained
|
|
->filter(static fn (array $row): bool => $row['category'] === self::CATEGORY_BANK
|
|
&& in_array($row['platform_label'], self::DIRECT_ELIGIBLE_BANK_LABELS, true))
|
|
->values();
|
|
$directBankAccounts = $retainedDirectEligibleBankAccounts->where('is_direct', true)->values();
|
|
$nonDirectBankAccounts = $retainedDirectEligibleBankAccounts->where('is_direct', false)->values();
|
|
$retainedBreakdown['direct']['waiting_count'] = $nonDirectBankAccounts->count();
|
|
$retainedBreakdown['direct']['waiting_url'] = $directTasksUrl . '&direct_task_state=non_direct';
|
|
foreach ($retainedBreakdown['direct']['rows'] as &$directRow) {
|
|
if ($directRow['category'] === self::CATEGORY_BANK) {
|
|
$directRow['waiting_count'] = $nonDirectBankAccounts->count();
|
|
$directRow['waiting_url'] = $directTasksUrl . '&direct_task_state=non_direct';
|
|
}
|
|
}
|
|
unset($directRow);
|
|
|
|
$accountPage = null;
|
|
$accountColumns = [];
|
|
$accountPlatformTabs = [];
|
|
$accountFilters = $this->accountFilters();
|
|
if ($view === self::VIEW_ACCOUNTS) {
|
|
$retainedAccounts = $accounts
|
|
->where('is_retained', true)
|
|
->values();
|
|
[$filtered, $accountFilters] = $this->filterAccounts($retainedAccounts, $accountFilters);
|
|
$pageRows = $this->paginate($filtered, 100, 'account_page')->getCollection()->all();
|
|
$this->attachFlowMetrics($pageRows, $period);
|
|
$accountPage = $this->paginatorFromRows($filtered, $pageRows, 100, 'account_page');
|
|
$accountColumns = $this->accountColumns($accountFilters['category']);
|
|
$accountPlatformTabs = $this->accountPlatformTabs($accountFilters, $period);
|
|
}
|
|
|
|
$unretainedTaskPage = null;
|
|
if ($view === self::VIEW_UNRETAINED_TASKS) {
|
|
[$filtered, $taskFilters] = $this->filterUnretainedTasks($unretained);
|
|
$unretainedTaskPage = $this->paginate($filtered, 100, 'task_page');
|
|
$accountFilters['task_search'] = $taskFilters['search'];
|
|
$accountFilters['task_category'] = $taskFilters['category'];
|
|
$accountFilters['task_progress'] = $taskFilters['progress'];
|
|
}
|
|
|
|
$directTaskPage = null;
|
|
if ($view === self::VIEW_DIRECT_TASKS) {
|
|
[$filtered, $directTaskFilters] = $this->filterDirectTasks($retainedDirectEligibleBankAccounts);
|
|
$directTaskPage = $this->paginate($filtered, 100, 'direct_task_page');
|
|
$accountFilters['direct_task_state'] = $directTaskFilters['state'];
|
|
$accountFilters['direct_task_search'] = $directTaskFilters['search'];
|
|
}
|
|
|
|
return [
|
|
'view' => 'business.pages.financial-operations.non-store-accounts',
|
|
'currentUrl' => $overviewUrl,
|
|
'monitorView' => $view,
|
|
'overviewUrl' => $overviewUrl,
|
|
'accountsUrl' => $accountsUrl,
|
|
'unretainedTasksUrl' => $unretainedTasksUrl,
|
|
'directTasksUrl' => $directTasksUrl,
|
|
'period' => $period,
|
|
'dataUpdatedAt' => now()->format('Y-m-d H:i'),
|
|
'fundOverview' => $fundOverview,
|
|
'retainedCard' => [
|
|
...$retainedSummary,
|
|
'direct_count' => $retained->where('is_direct', true)->count(),
|
|
'non_direct_count' => $retained->where('is_direct', false)->count(),
|
|
],
|
|
'unretainedCard' => [
|
|
...$unretainedSummary,
|
|
'progress' => $unretainedProgress,
|
|
'distribution' => $unretainedDistribution,
|
|
'category_accounts' => $unretainedCategoryAccounts,
|
|
],
|
|
'retainedBreakdown' => $retainedBreakdown,
|
|
'directConnectionSummary' => [
|
|
'connected' => $this->summary($directBankAccounts),
|
|
'processing' => $this->summary($nonDirectBankAccounts),
|
|
'planned_unknown' => $nonDirectBankAccounts->count(),
|
|
],
|
|
'directEligibleBankLabels' => self::DIRECT_ELIGIBLE_BANK_LABELS,
|
|
'categoryLabels' => self::CATEGORY_LABELS,
|
|
'categoryOptions' => [
|
|
'all' => '全部账户类型',
|
|
self::CATEGORY_BANK => '银行账户',
|
|
self::CATEGORY_ALIPAY => '支付宝',
|
|
self::CATEGORY_WANGSHANG => '网商银行',
|
|
self::CATEGORY_LEGACY_WALLET => '旧网银钱包',
|
|
self::CATEGORY_OTHER => '其他账户',
|
|
],
|
|
'bankOptions' => $retainedBankAccountsForDistribution
|
|
->pluck('platform_label')
|
|
->filter()
|
|
->unique()
|
|
->sort()
|
|
->values()
|
|
->all(),
|
|
'statusOptions' => FinanceLedgerAccountStatus::OPTIONS,
|
|
'accountFilters' => $accountFilters,
|
|
'accountColumns' => $accountColumns,
|
|
'accountPage' => $accountPage,
|
|
'accountColumns' => $accountColumns,
|
|
'accountPlatformTabs' => $accountPlatformTabs,
|
|
'accountEditAllowed' => FinanceLedgerAccess::canEditAccountStatus(user()),
|
|
'unretainedTaskPage' => $unretainedTaskPage,
|
|
'directTaskPage' => $directTaskPage,
|
|
'unretainedProgressLabels' => [
|
|
'completed' => '已完成',
|
|
'in_progress' => '进行中',
|
|
'not_started' => '待开始',
|
|
],
|
|
];
|
|
}
|
|
|
|
private function accountRows(): Collection
|
|
{
|
|
$connection = $this->db();
|
|
$accounts = $connection->table('fin_accounts as a')
|
|
->orderBy('a.company_name')
|
|
->orderBy('a.account_short')
|
|
->orderBy('a.id')
|
|
->get([
|
|
'a.id',
|
|
'a.company_name',
|
|
'a.account_short',
|
|
'a.legal_representative',
|
|
'a.region',
|
|
'a.account_no',
|
|
'a.alipay_merchant_no',
|
|
'a.bank_name',
|
|
'a.bound_alipay',
|
|
'a.bank_city_branch',
|
|
'a.alipay_store_name',
|
|
'a.account_type',
|
|
'a.alipay_account_kind',
|
|
'a.company_plan',
|
|
'a.account_should_keep',
|
|
'a.single_limit',
|
|
'a.daily_limit',
|
|
'a.monthly_limit',
|
|
'a.yearly_limit',
|
|
'a.current_balance',
|
|
'a.blocked_amount',
|
|
'a.daily_available',
|
|
'a.owner',
|
|
'a.remark',
|
|
'a.updated_at',
|
|
]);
|
|
|
|
$labels = $this->accountDisplayLabels($accounts);
|
|
$statuses = $this->keyedValues('fin_account_statuses', 'status');
|
|
$typeOverrides = $this->keyedValues('fin_account_type_overrides', 'account_type');
|
|
$sources = $this->keyedValues('fin_flow_summary_account_sources', 'data_source');
|
|
$tasks = $this->keepTasks();
|
|
|
|
return $accounts->map(function (object $account) use (
|
|
$labels,
|
|
$statuses,
|
|
$typeOverrides,
|
|
$sources,
|
|
$tasks,
|
|
): array {
|
|
$accountShort = trim((string) ($account->account_short ?? ''));
|
|
$accountType = trim((string) (
|
|
$typeOverrides[$accountShort]
|
|
?? $account->account_type
|
|
?? ''
|
|
));
|
|
$bankName = trim((string) ($account->bank_name ?? ''));
|
|
$category = $this->category($accountShort, $accountType, $bankName);
|
|
$platformLabel = $this->platformLabel($category, $accountShort, $accountType, $bankName);
|
|
$keep = FinanceLedgerAccountShouldKeep::display(
|
|
$account->account_should_keep ?? null,
|
|
$account->company_plan ?? null,
|
|
);
|
|
$isRetained = $keep === FinanceLedgerAccountShouldKeep::YES
|
|
&& $category !== self::CATEGORY_LEGACY_WALLET;
|
|
$dataSource = FinanceLedgerFlowSummaryDataSource::normalize(
|
|
$sources[$accountShort] ?? null,
|
|
);
|
|
$isDirect = $dataSource === FinanceLedgerFlowSummaryDataSource::DIRECT
|
|
|| $platformLabel === '招商银行';
|
|
$task = $tasks[$accountShort] ?? null;
|
|
$progress = $this->normalizeProgress($task?->current_progress ?? null);
|
|
|
|
return [
|
|
'id' => (int) $account->id,
|
|
'edit_url' => route('business.financial-ledger.accounts.edit', ['id' => $account->id]),
|
|
'save_url' => route('business.financial-ledger.accounts.update', ['id' => $account->id]),
|
|
'company_name' => trim((string) ($account->company_name ?? '')),
|
|
'account_short' => $accountShort,
|
|
'account_display_short' => $labels[(int) $account->id] ?? $accountShort,
|
|
'account_type' => $accountType,
|
|
'category' => $category,
|
|
'category_label' => self::CATEGORY_LABELS[$category],
|
|
'platform_label' => $platformLabel,
|
|
'bank_name' => $bankName,
|
|
'account_no' => trim((string) ($account->account_no ?? '')),
|
|
'bank_city_branch' => trim((string) ($account->bank_city_branch ?? '')),
|
|
'region' => trim((string) ($account->region ?? '')),
|
|
'legal_representative' => trim((string) ($account->legal_representative ?? '')),
|
|
'owner' => trim((string) ($account->owner ?? '')),
|
|
'alipay_merchant_no' => trim((string) ($account->alipay_merchant_no ?? '')),
|
|
'alipay_account_kind' => trim((string) ($account->alipay_account_kind ?? '')),
|
|
'bound_alipay' => trim((string) ($account->bound_alipay ?? '')),
|
|
'alipay_store_name' => trim((string) ($account->alipay_store_name ?? '')),
|
|
'single_limit' => $account->single_limit,
|
|
'daily_limit' => $account->daily_limit,
|
|
'monthly_limit' => $account->monthly_limit,
|
|
'yearly_limit' => $account->yearly_limit,
|
|
'current_balance' => round((float) ($account->current_balance ?? 0), 2),
|
|
'available_balance' => round((float) ($account->daily_available ?? 0), 2),
|
|
'blocked_balance' => round((float) ($account->blocked_amount ?? 0), 2),
|
|
'is_retained' => $isRetained,
|
|
'keep_label' => $isRetained ? '保留' : '不保留',
|
|
'data_source' => $isDirect ? FinanceLedgerFlowSummaryDataSource::DIRECT : ($dataSource !== '' ? $dataSource : '未填写'),
|
|
'is_direct' => $isDirect,
|
|
'account_status' => FinanceLedgerAccountStatus::normalize(
|
|
$statuses[$accountShort] ?? null,
|
|
),
|
|
'account_status_label' => FinanceLedgerAccountStatus::label(
|
|
$statuses[$accountShort] ?? null,
|
|
),
|
|
'keep_progress' => $progress,
|
|
'keep_progress_label' => $this->progressLabel($progress),
|
|
'keep_owner' => trim((string) ($task?->owner_name ?? '')),
|
|
'keep_started_at' => $this->dateValue($task?->started_at ?? null),
|
|
'keep_completed_at' => $this->dateValue($task?->completed_at ?? null),
|
|
'keep_updated_at' => $this->dateValue($task?->updated_at ?? null),
|
|
'remark' => trim((string) ($account->remark ?? '')),
|
|
'updated_at' => $this->dateValue($account->updated_at ?? null),
|
|
'opening_balance' => null,
|
|
'inflow' => 0.0,
|
|
'outflow' => 0.0,
|
|
'closing_balance' => null,
|
|
'activity_days' => 0,
|
|
];
|
|
})->values();
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int,array<string,mixed>> $accounts
|
|
* @return array<int,string>
|
|
*/
|
|
private function accountDisplayLabels(Collection $accounts): array
|
|
{
|
|
$labels = [];
|
|
foreach ($accounts->groupBy('account_short') as $accountShort => $group) {
|
|
$ordered = $group->sort(static function (object $left, object $right): int {
|
|
return strnatcasecmp(
|
|
trim((string) ($left->account_no ?? '')),
|
|
trim((string) ($right->account_no ?? '')),
|
|
) ?: ((int) $left->id <=> (int) $right->id);
|
|
})->values();
|
|
|
|
foreach ($ordered as $index => $account) {
|
|
$labels[(int) $account->id] = $ordered->count() === 1
|
|
? (string) $accountShort
|
|
: (string) $accountShort . ($index + 1);
|
|
}
|
|
}
|
|
|
|
return $labels;
|
|
}
|
|
|
|
private function keyedValues(string $table, string $valueColumn): array
|
|
{
|
|
if (! $this->db()->getSchemaBuilder()->hasTable($table)) {
|
|
return [];
|
|
}
|
|
|
|
return $this->db()->table($table)
|
|
->whereNotNull('account_short')
|
|
->where('account_short', '<>', '')
|
|
->pluck($valueColumn, 'account_short')
|
|
->map(static fn (mixed $value): string => trim((string) $value))
|
|
->all();
|
|
}
|
|
|
|
private function keepTasks(): Collection
|
|
{
|
|
if (! $this->db()->getSchemaBuilder()->hasTable('fin_account_keep_todos')) {
|
|
return collect();
|
|
}
|
|
|
|
return $this->db()->table('fin_account_keep_todos')
|
|
->whereNotNull('account_short')
|
|
->where('account_short', '<>', '')
|
|
->orderBy('updated_at')
|
|
->get()
|
|
->keyBy('account_short');
|
|
}
|
|
|
|
private function category(string $accountShort, string $accountType, string $bankName): string
|
|
{
|
|
if (FinanceLedgerIndependentAccounts::contains($accountShort)) {
|
|
return self::CATEGORY_OTHER;
|
|
}
|
|
|
|
$text = $accountShort . ' ' . $accountType . ' ' . $bankName;
|
|
if (str_contains($text, '支付宝')) {
|
|
return self::CATEGORY_ALIPAY;
|
|
}
|
|
if (str_contains($text, '网商')) {
|
|
return self::CATEGORY_WANGSHANG;
|
|
}
|
|
if (str_contains($text, '钱包')) {
|
|
return self::CATEGORY_LEGACY_WALLET;
|
|
}
|
|
if (str_contains($text, '微信')) {
|
|
return self::CATEGORY_OTHER;
|
|
}
|
|
if (in_array($accountType, ['公户', '个人卡'], true)
|
|
|| ($bankName !== '' && $bankName !== '/')) {
|
|
return self::CATEGORY_BANK;
|
|
}
|
|
|
|
return self::CATEGORY_OTHER;
|
|
}
|
|
|
|
private function platformLabel(
|
|
string $category,
|
|
string $accountShort,
|
|
string $accountType,
|
|
string $bankName,
|
|
): string {
|
|
if ($category === self::CATEGORY_ALIPAY) {
|
|
return '支付宝';
|
|
}
|
|
if ($category === self::CATEGORY_WANGSHANG) {
|
|
return '网商银行';
|
|
}
|
|
if ($category === self::CATEGORY_LEGACY_WALLET) {
|
|
return '旧网银钱包';
|
|
}
|
|
if ($category === self::CATEGORY_OTHER) {
|
|
if (str_contains($accountShort, '微信') || str_contains($accountType, '微信')) {
|
|
return '微信';
|
|
}
|
|
|
|
return $accountType !== '' ? $accountType : ($bankName !== '' && $bankName !== '/' ? $bankName : '其他');
|
|
}
|
|
|
|
$bankMap = [
|
|
'工商' => '工商银行',
|
|
'工行' => '工商银行',
|
|
'农业' => '农业银行',
|
|
'农行' => '农业银行',
|
|
'招商' => '招商银行',
|
|
'招行' => '招商银行',
|
|
'建设' => '建设银行',
|
|
'建行' => '建设银行',
|
|
'中国银行' => '中国银行',
|
|
'中行' => '中国银行',
|
|
'华夏' => '华夏银行',
|
|
'兴业' => '兴业银行',
|
|
'浦发' => '浦发银行',
|
|
'中信' => '中信银行',
|
|
'北京' => '北京银行',
|
|
'杭州' => '杭州银行',
|
|
'农商' => '江南农商行',
|
|
'平安' => '平安银行',
|
|
'交通' => '交通银行',
|
|
'交行' => '交通银行',
|
|
'光大' => '光大银行',
|
|
];
|
|
$text = $accountShort . ' ' . $bankName;
|
|
foreach ($bankMap as $needle => $label) {
|
|
if (str_contains($text, $needle)) {
|
|
return $label;
|
|
}
|
|
}
|
|
|
|
return $bankName !== '' && $bankName !== '/' ? $bankName : '银行账户';
|
|
}
|
|
|
|
private function summary(Collection $rows): array
|
|
{
|
|
return [
|
|
'count' => $rows->count(),
|
|
'current_balance' => round((float) $rows->sum('current_balance'), 2),
|
|
'available_balance' => round((float) $rows->sum('available_balance'), 2),
|
|
'blocked_balance' => round((float) $rows->sum('blocked_balance'), 2),
|
|
];
|
|
}
|
|
|
|
private function progressSummary(Collection $rows): array
|
|
{
|
|
$completed = $rows->where('keep_progress', 'completed')->count();
|
|
$inProgress = $rows->where('keep_progress', 'in_progress')->count();
|
|
$notStarted = max(0, $rows->count() - $completed - $inProgress);
|
|
$percent = $rows->isEmpty() ? 0.0 : round($completed / $rows->count() * 100, 1);
|
|
|
|
return [
|
|
'completed' => $completed,
|
|
'in_progress' => $inProgress,
|
|
'not_started' => $notStarted,
|
|
'percent' => $percent,
|
|
];
|
|
}
|
|
|
|
private function retainedBreakdown(Collection $rows, string $baseUrl, string $directTasksUrl): array
|
|
{
|
|
$sections = [
|
|
'direct' => [
|
|
'key' => 'direct',
|
|
'title' => '银企直连',
|
|
'description' => '当前仅华夏银行、中国银行、招商银行纳入银企直连范围',
|
|
'rows' => [],
|
|
'manage_url' => $directTasksUrl,
|
|
],
|
|
'non_direct' => [
|
|
'key' => 'non_direct',
|
|
'title' => '非银企直连',
|
|
'description' => '当前通过手动导入或维护数据的保留账户',
|
|
'rows' => [],
|
|
'manage_url' => '',
|
|
],
|
|
];
|
|
|
|
foreach ($sections as $sectionKey => &$section) {
|
|
$sectionRows = $rows->filter(
|
|
static fn (array $row): bool => $sectionKey === 'direct' ? $row['is_direct'] : ! $row['is_direct'],
|
|
);
|
|
$categories = $sectionKey === 'direct'
|
|
? [self::CATEGORY_BANK => self::CATEGORY_LABELS[self::CATEGORY_BANK]]
|
|
: self::CATEGORY_LABELS;
|
|
foreach ($categories as $category => $label) {
|
|
$categoryRows = $sectionRows->where('category', $category)->values();
|
|
$section['rows'][] = [
|
|
'category' => $category,
|
|
'label' => $label,
|
|
...$this->summary($categoryRows),
|
|
'url' => $baseUrl . '&' . http_build_query([
|
|
'keep' => 'retained',
|
|
'direct' => $sectionKey,
|
|
'account_category' => $category,
|
|
]),
|
|
];
|
|
}
|
|
$section['summary'] = $this->summary($sectionRows);
|
|
}
|
|
unset($section);
|
|
|
|
return $sections;
|
|
}
|
|
|
|
private function accountFilters(): array
|
|
{
|
|
$keep = trim((string) request('keep', 'all'));
|
|
$direct = trim((string) request('direct', 'all'));
|
|
$category = trim((string) request('account_category', 'all'));
|
|
$status = trim((string) request('account_status', 'all'));
|
|
|
|
return [
|
|
'keep' => in_array($keep, ['all', 'retained', 'unretained'], true) ? $keep : 'all',
|
|
'direct' => in_array($direct, ['all', 'direct', 'non_direct'], true) ? $direct : 'all',
|
|
'category' => in_array($category, ['all', ...array_keys(self::CATEGORY_LABELS)], true) ? $category : 'all',
|
|
'status' => $status === 'all' || array_key_exists($status, FinanceLedgerAccountStatus::OPTIONS)
|
|
? $status
|
|
: 'all',
|
|
'bank_group' => trim((string) request('bank_group', 'all')) ?: 'all',
|
|
'search' => trim((string) request('account_search', '')),
|
|
'task_search' => '',
|
|
'task_category' => 'all',
|
|
'task_progress' => 'all',
|
|
'direct_task_state' => 'all',
|
|
'direct_task_search' => '',
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int,array<string,mixed>> $accounts
|
|
* @return array{0:Collection<int,array<string,mixed>>,1:array<string,string>}
|
|
*/
|
|
private function filterAccounts(Collection $accounts, array $filters): array
|
|
{
|
|
$rows = $accounts->filter(function (array $row) use ($filters): bool {
|
|
if ($filters['keep'] === 'retained' && ! $row['is_retained']) {
|
|
return false;
|
|
}
|
|
if ($filters['keep'] === 'unretained' && $row['is_retained']) {
|
|
return false;
|
|
}
|
|
if ($filters['direct'] === 'direct' && ! $row['is_direct']) {
|
|
return false;
|
|
}
|
|
if ($filters['direct'] === 'non_direct' && $row['is_direct']) {
|
|
return false;
|
|
}
|
|
if ($filters['category'] !== 'all' && $row['category'] !== $filters['category']) {
|
|
return false;
|
|
}
|
|
if ($filters['category'] === self::CATEGORY_BANK
|
|
&& $filters['bank_group'] !== 'all'
|
|
&& $row['platform_label'] !== $filters['bank_group']) {
|
|
return false;
|
|
}
|
|
if ($filters['status'] !== 'all' && $row['account_status'] !== $filters['status']) {
|
|
return false;
|
|
}
|
|
if ($filters['search'] !== '') {
|
|
$search = mb_strtolower($filters['search']);
|
|
$haystack = mb_strtolower(implode(' ', [
|
|
$row['company_name'],
|
|
$row['account_short'],
|
|
$row['account_no'],
|
|
$row['bank_name'],
|
|
]));
|
|
if (! str_contains($haystack, $search)) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
})->sortBy([
|
|
['is_retained', 'desc'],
|
|
['company_name', 'asc'],
|
|
['account_display_short', 'asc'],
|
|
])->values();
|
|
|
|
return [$rows, $filters];
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int,array<string,mixed>> $accounts
|
|
* @return array{0:Collection<int,array<string,mixed>>,1:array<string,string>}
|
|
*/
|
|
private function filterUnretainedTasks(Collection $accounts): array
|
|
{
|
|
$filters = [
|
|
'search' => trim((string) request('task_search', '')),
|
|
'category' => trim((string) request('task_category', 'all')),
|
|
'progress' => trim((string) request('task_progress', 'all')),
|
|
];
|
|
if (! in_array($filters['category'], ['all', ...array_keys(self::CATEGORY_LABELS)], true)) {
|
|
$filters['category'] = 'all';
|
|
}
|
|
if (! in_array($filters['progress'], ['all', 'completed', 'in_progress', 'not_started'], true)) {
|
|
$filters['progress'] = 'all';
|
|
}
|
|
|
|
$rows = $accounts->filter(function (array $row) use ($filters): bool {
|
|
if ($filters['category'] !== 'all' && $row['category'] !== $filters['category']) {
|
|
return false;
|
|
}
|
|
if ($filters['progress'] !== 'all' && $row['keep_progress'] !== $filters['progress']) {
|
|
return false;
|
|
}
|
|
if ($filters['search'] !== '') {
|
|
$search = mb_strtolower($filters['search']);
|
|
$haystack = mb_strtolower(implode(' ', [
|
|
$row['company_name'],
|
|
$row['account_short'],
|
|
$row['account_no'],
|
|
$row['keep_owner'],
|
|
]));
|
|
if (! str_contains($haystack, $search)) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
})->sortBy([
|
|
['keep_progress', 'asc'],
|
|
['company_name', 'asc'],
|
|
['account_display_short', 'asc'],
|
|
])->values();
|
|
|
|
return [$rows, $filters];
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int,array<string,mixed>> $accounts
|
|
* @return array{0:Collection<int,array<string,mixed>>,1:array<string,string>}
|
|
*/
|
|
private function filterDirectTasks(Collection $accounts): array
|
|
{
|
|
$filters = [
|
|
'state' => trim((string) request('direct_task_state', 'all')),
|
|
'search' => trim((string) request('direct_task_search', '')),
|
|
];
|
|
if (! in_array($filters['state'], ['all', 'direct', 'non_direct'], true)) {
|
|
$filters['state'] = 'all';
|
|
}
|
|
|
|
$rows = $accounts->filter(function (array $row) use ($filters): bool {
|
|
if ($filters['state'] === 'direct' && ! $row['is_direct']) {
|
|
return false;
|
|
}
|
|
if ($filters['state'] === 'non_direct' && $row['is_direct']) {
|
|
return false;
|
|
}
|
|
if ($filters['search'] !== '') {
|
|
$search = mb_strtolower($filters['search']);
|
|
$haystack = mb_strtolower(implode(' ', [
|
|
$row['company_name'],
|
|
$row['account_short'],
|
|
$row['account_no'],
|
|
$row['bank_name'],
|
|
$row['owner'],
|
|
]));
|
|
if (! str_contains($haystack, $search)) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
})->sortBy([
|
|
['is_direct', 'desc'],
|
|
['company_name', 'asc'],
|
|
['account_display_short', 'asc'],
|
|
])->values();
|
|
|
|
return [$rows, $filters];
|
|
}
|
|
|
|
private function accountColumns(string $category): array
|
|
{
|
|
$columns = [
|
|
$this->column('account_display_short', '账户简称', 'text', '公共信息', true, true),
|
|
$this->column('company_name', '公司名称', 'text', '公共信息', false),
|
|
$this->column('platform_label', '所属银行/平台', 'text', '公共信息', true),
|
|
$this->column('account_type', '账户类型', 'text', '公共信息', $category !== 'all'),
|
|
$this->column('keep_label', '是否保留', 'enum', '业务状态', false),
|
|
$this->column('account_status_label', '账户状态', 'enum', '业务状态', false),
|
|
$this->column('data_source', '数据来源', 'enum', '业务状态', false),
|
|
$this->column('opening_balance', '期初余额', 'number', '资金信息', true),
|
|
$this->column('outflow', '当期支出', 'number', '资金信息', true),
|
|
$this->column('inflow', '当期收入', 'number', '资金信息', true),
|
|
$this->column('closing_balance', '期末余额', 'number', '资金信息', true),
|
|
$this->column('current_balance', '当前余额', 'number', '资金信息', false),
|
|
$this->column('available_balance', '可用金额', 'number', '资金信息', false),
|
|
$this->column('blocked_balance', '不可用金额', 'number', '资金信息', false),
|
|
$this->column('activity_days', '活跃天数', 'integer', '资金信息', false),
|
|
];
|
|
|
|
if ($category === self::CATEGORY_BANK) {
|
|
$columns = [...$columns,
|
|
$this->column('account_no', '账号', 'text', '银行资料', false),
|
|
$this->column('bank_name', '开户行', 'text', '银行资料', false),
|
|
$this->column('bank_city_branch', '开户城市/网点', 'text', '银行资料', false),
|
|
$this->column('region', '地区', 'text', '银行资料', false),
|
|
$this->column('legal_representative', '法人', 'text', '银行资料', false),
|
|
$this->column('owner', '责任人', 'text', '银行资料', false),
|
|
$this->column('single_limit', '单笔限额', 'limit', '银行资料', true),
|
|
$this->column('daily_limit', '日限额', 'limit', '银行资料', true),
|
|
$this->column('monthly_limit', '月限额', 'limit', '银行资料', true),
|
|
$this->column('yearly_limit', '年限额', 'limit', '银行资料', true),
|
|
];
|
|
} elseif ($category === self::CATEGORY_ALIPAY) {
|
|
$columns = [...$columns,
|
|
$this->column('account_no', '支付宝账号', 'text', '支付宝资料', true),
|
|
$this->column('alipay_account_kind', '账户性质', 'text', '支付宝资料', true),
|
|
$this->column('alipay_merchant_no', '商户号', 'text', '支付宝资料', true),
|
|
$this->column('bound_alipay', '绑定支付宝', 'text', '支付宝资料', false),
|
|
$this->column('alipay_store_name', '店铺名称', 'text', '支付宝资料', false),
|
|
$this->column('owner', '责任人', 'text', '支付宝资料', false),
|
|
];
|
|
} elseif ($category === self::CATEGORY_WANGSHANG) {
|
|
$columns = [...$columns,
|
|
$this->column('account_no', '网商账号', 'text', '网商资料', true),
|
|
$this->column('bank_name', '开户机构', 'text', '网商资料', true),
|
|
$this->column('bank_city_branch', '开户城市/网点', 'text', '网商资料', false),
|
|
$this->column('owner', '责任人', 'text', '网商资料', false),
|
|
$this->column('region', '地区', 'text', '网商资料', false),
|
|
];
|
|
} elseif ($category === self::CATEGORY_OTHER) {
|
|
$columns = [...$columns,
|
|
$this->column('account_no', '登录账号/账号', 'text', '其他资料', true),
|
|
$this->column('bank_name', '机构名称', 'text', '其他资料', true),
|
|
$this->column('owner', '责任人', 'text', '其他资料', false),
|
|
$this->column('remark', '备注', 'text', '其他资料', false),
|
|
];
|
|
}
|
|
|
|
$columns[] = $this->column('updated_at', '最近更新时间', 'date', '业务状态', false);
|
|
$columns[] = $this->column('remark', '备注', 'text', '其他资料', true);
|
|
|
|
$unique = [];
|
|
foreach ($columns as $column) {
|
|
$unique[$column['key']] ??= $column;
|
|
}
|
|
|
|
return array_values($unique);
|
|
}
|
|
|
|
private function accountPlatformTabs(array $filters, array $period): array
|
|
{
|
|
$tabs = [];
|
|
foreach ([
|
|
'all' => '展示全部',
|
|
self::CATEGORY_BANK => '银行账户',
|
|
self::CATEGORY_ALIPAY => '支付宝',
|
|
self::CATEGORY_WANGSHANG => '网商银行',
|
|
self::CATEGORY_LEGACY_WALLET => '旧网银钱包',
|
|
self::CATEGORY_OTHER => '其他账户',
|
|
] as $category => $label) {
|
|
$query = [
|
|
'view' => self::VIEW_ACCOUNTS,
|
|
'account_category' => $category,
|
|
'period_from' => $period['from'],
|
|
'period_to' => $period['to'],
|
|
];
|
|
|
|
$tabs[] = [
|
|
'category' => $category,
|
|
'label' => $label,
|
|
'url' => $this->pageUrl($query),
|
|
'active' => $filters['category'] === $category,
|
|
];
|
|
}
|
|
|
|
return $tabs;
|
|
}
|
|
|
|
private function column(
|
|
string $key,
|
|
string $label,
|
|
string $type,
|
|
string $group,
|
|
bool $default,
|
|
bool $sticky = false,
|
|
): array {
|
|
return compact('key', 'label', 'type', 'group', 'default', 'sticky');
|
|
}
|
|
|
|
private function attachFlowMetrics(array &$rows, array $period): void
|
|
{
|
|
$accountShorts = array_values(array_unique(array_filter(array_column($rows, 'account_short'))));
|
|
if ($accountShorts === []) {
|
|
return;
|
|
}
|
|
|
|
$query = $this->db()->table('fin_daily_flows')
|
|
->whereIn('account_short', $accountShorts)
|
|
->where('flow_date', '<=', $period['to'])
|
|
->orderBy('account_short')
|
|
->orderBy('flow_date')
|
|
->orderBy('id');
|
|
$metrics = [];
|
|
|
|
foreach ($query->get([
|
|
'account_short',
|
|
'flow_date',
|
|
'opening_balance',
|
|
'inflow',
|
|
'outflow',
|
|
'closing_balance',
|
|
])->groupBy('account_short') as $accountShort => $flows) {
|
|
$before = $flows->filter(
|
|
static fn (object $row): bool => substr((string) $row->flow_date, 0, 10) < $period['from'],
|
|
);
|
|
$inPeriod = $flows->filter(static function (object $row) use ($period): bool {
|
|
$date = substr((string) $row->flow_date, 0, 10);
|
|
|
|
return $date >= $period['from'] && $date <= $period['to'];
|
|
});
|
|
$latestBefore = $before->last();
|
|
$firstInPeriod = $inPeriod->first();
|
|
$openingBalance = $latestBefore !== null
|
|
? round((float) $latestBefore->closing_balance, 2)
|
|
: ($firstInPeriod === null ? null : round((float) $firstInPeriod->opening_balance, 2));
|
|
$inflow = round((float) $inPeriod->sum('inflow'), 2);
|
|
$outflow = round((float) $inPeriod->sum('outflow'), 2);
|
|
$metrics[(string) $accountShort] = [
|
|
'opening_balance' => $openingBalance,
|
|
'inflow' => $inflow,
|
|
'outflow' => $outflow,
|
|
'closing_balance' => $openingBalance === null
|
|
? null
|
|
: round($openingBalance - $outflow + $inflow, 2),
|
|
'activity_days' => $inPeriod
|
|
->pluck('flow_date')
|
|
->map(static fn (mixed $date): string => substr((string) $date, 0, 10))
|
|
->unique()
|
|
->count(),
|
|
];
|
|
}
|
|
|
|
foreach ($rows as &$row) {
|
|
$row = array_merge($row, $metrics[$row['account_short']] ?? []);
|
|
}
|
|
unset($row);
|
|
}
|
|
|
|
private function paginate(Collection $rows, int $perPage, string $pageName): LengthAwarePaginator
|
|
{
|
|
$page = min(
|
|
max(1, (int) request($pageName, 1)),
|
|
max(1, (int) ceil($rows->count() / $perPage)),
|
|
);
|
|
$items = $rows->slice(($page - 1) * $perPage, $perPage)->values()->all();
|
|
|
|
$paginator = new LengthAwarePaginator(
|
|
$items,
|
|
$rows->count(),
|
|
$perPage,
|
|
$page,
|
|
['path' => request()->url(), 'query' => request()->query()],
|
|
);
|
|
$paginator->setPageName($pageName);
|
|
|
|
return $paginator;
|
|
}
|
|
|
|
private function paginatorFromRows(
|
|
Collection $filteredRows,
|
|
array $items,
|
|
int $perPage,
|
|
string $pageName,
|
|
): LengthAwarePaginator {
|
|
$page = min(
|
|
max(1, (int) request($pageName, 1)),
|
|
max(1, (int) ceil($filteredRows->count() / $perPage)),
|
|
);
|
|
|
|
$paginator = new LengthAwarePaginator(
|
|
$items,
|
|
$filteredRows->count(),
|
|
$perPage,
|
|
$page,
|
|
['path' => request()->url(), 'query' => request()->query()],
|
|
);
|
|
$paginator->setPageName($pageName);
|
|
|
|
return $paginator;
|
|
}
|
|
|
|
private function period(): array
|
|
{
|
|
$from = trim((string) request('period_from', ''));
|
|
$to = trim((string) request('period_to', ''));
|
|
$defaultFrom = now()->startOfMonth()->toDateString();
|
|
$defaultTo = now()->endOfMonth()->toDateString();
|
|
$valid = static fn (string $date): bool => preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) === 1;
|
|
|
|
return [
|
|
'from' => $valid($from) ? $from : $defaultFrom,
|
|
'to' => $valid($to) ? $to : $defaultTo,
|
|
];
|
|
}
|
|
|
|
private function view(): string
|
|
{
|
|
$view = trim((string) request('view', self::VIEW_OVERVIEW));
|
|
|
|
return in_array($view, [
|
|
self::VIEW_OVERVIEW,
|
|
self::VIEW_ACCOUNTS,
|
|
self::VIEW_UNRETAINED_TASKS,
|
|
self::VIEW_DIRECT_TASKS,
|
|
], true) ? $view : self::VIEW_OVERVIEW;
|
|
}
|
|
|
|
private function pageUrl(array $query = []): string
|
|
{
|
|
$embeddedInLedger = request()->route('section') === 'financial-operations'
|
|
&& request()->route('page') === 'ledger'
|
|
&& request('tab') === 'overview';
|
|
$url = route('business.pages.show', [
|
|
'section' => 'financial-operations',
|
|
'page' => $embeddedInLedger ? 'ledger' : 'non-store-accounts',
|
|
]);
|
|
if ($embeddedInLedger) {
|
|
$query = ['tab' => 'overview', ...$query];
|
|
}
|
|
|
|
return $query === [] ? $url : $url . '?' . http_build_query($query);
|
|
}
|
|
|
|
private function normalizeProgress(mixed $value): string
|
|
{
|
|
$value = trim((string) $value);
|
|
|
|
return in_array($value, ['completed', 'in_progress'], true) ? $value : 'not_started';
|
|
}
|
|
|
|
private function progressLabel(string $progress): string
|
|
{
|
|
return [
|
|
'completed' => '已完成',
|
|
'in_progress' => '进行中',
|
|
'not_started' => '待开始',
|
|
][$progress] ?? '待开始';
|
|
}
|
|
|
|
private function dateValue(mixed $value): string
|
|
{
|
|
$text = trim((string) ($value ?? ''));
|
|
|
|
return $text === '' ? '' : substr($text, 0, 10);
|
|
}
|
|
|
|
private function db()
|
|
{
|
|
return DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
|
|
}
|
|
}
|