352 lines
13 KiB
PHP
352 lines
13 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\View;
|
||
|
||
use Illuminate\Support\Carbon;
|
||
use Modules\EcommerceFinance\Repositories\InstallationDetailMirrorRepository;
|
||
use Throwable;
|
||
|
||
/** 安装费汇总:按客服审核月份展示安装公司使用趋势。 */
|
||
class InstallationFeeUsagePageData
|
||
{
|
||
public const RANGE_OPTIONS = [
|
||
'6' => '近 6 个月',
|
||
'12' => '近 12 个月',
|
||
'ytd' => '本年至今',
|
||
];
|
||
|
||
public function __construct(
|
||
private readonly InstallationDetailMirrorRepository $repository,
|
||
) {
|
||
}
|
||
|
||
public function page(): array
|
||
{
|
||
$range = (string) request()->query('range', '12');
|
||
if (! array_key_exists($range, self::RANGE_OPTIONS)) {
|
||
$range = '12';
|
||
}
|
||
|
||
[$fromMonth, $toMonth] = $this->monthRange($range);
|
||
$rangeLabel = $fromMonth . ' 至 ' . $toMonth;
|
||
|
||
try {
|
||
$result = $this->repository->feeUsageTrend($fromMonth, $toMonth);
|
||
} catch (Throwable $exception) {
|
||
report($exception);
|
||
|
||
return $this->payload(
|
||
$range,
|
||
$rangeLabel,
|
||
$fromMonth,
|
||
$toMonth,
|
||
$this->emptyPeriods($fromMonth, $toMonth),
|
||
[],
|
||
'安装公司趋势暂时无法读取,请稍后重试。',
|
||
);
|
||
}
|
||
|
||
if (! $result['ready']) {
|
||
return $this->payload(
|
||
$range,
|
||
$rangeLabel,
|
||
$fromMonth,
|
||
$toMonth,
|
||
$this->emptyPeriods($fromMonth, $toMonth),
|
||
[],
|
||
'安装明细共享镜像尚未完成首次同步。',
|
||
);
|
||
}
|
||
|
||
return $this->payload(
|
||
$range,
|
||
$rangeLabel,
|
||
$fromMonth,
|
||
$toMonth,
|
||
$this->buildPeriods($fromMonth, $toMonth, $result['rows']),
|
||
$result['totals'],
|
||
);
|
||
}
|
||
|
||
/** @return array{0:string,1:string} */
|
||
private function monthRange(string $range): array
|
||
{
|
||
$current = Carbon::now()->startOfMonth();
|
||
$from = match ($range) {
|
||
'6' => $current->copy()->subMonthsNoOverflow(5),
|
||
'ytd' => $current->copy()->startOfYear(),
|
||
default => $current->copy()->subMonthsNoOverflow(11),
|
||
};
|
||
|
||
return [$from->format('Y-m'), $current->format('Y-m')];
|
||
}
|
||
|
||
/**
|
||
* @param list<array{period:string,installation_company:string,orders:int,amount:float}> $rows
|
||
*/
|
||
private function buildPeriods(string $fromMonth, string $toMonth, array $rows): array
|
||
{
|
||
$periods = $this->emptyPeriods($fromMonth, $toMonth);
|
||
$periodIndex = [];
|
||
foreach ($periods as $index => $period) {
|
||
$periodIndex[$period['period']] = $index;
|
||
}
|
||
|
||
foreach ($rows as $row) {
|
||
$period = $row['period'];
|
||
if (! isset($periodIndex[$period])) {
|
||
continue;
|
||
}
|
||
|
||
$key = $this->vendorKey($row['installation_company']);
|
||
$index = $periodIndex[$period];
|
||
$periods[$index]['vendors'][$key]['orders'] += (int) $row['orders'];
|
||
$periods[$index]['vendors'][$key]['amount'] += (float) $row['amount'];
|
||
$periods[$index]['source_companies'][$row['installation_company']] = true;
|
||
}
|
||
|
||
$previousPrimaryKey = null;
|
||
$previousPrimaryLabel = null;
|
||
foreach ($periods as &$period) {
|
||
$period['total_orders'] = (int) array_sum(array_column($period['vendors'], 'orders'));
|
||
$period['total_amount'] = round(array_sum(array_column($period['vendors'], 'amount')), 2);
|
||
$period['source_companies'] = array_keys($period['source_companies']);
|
||
|
||
foreach ($period['vendors'] as &$vendor) {
|
||
$vendor['amount'] = round((float) $vendor['amount'], 2);
|
||
$vendor['order_share'] = $this->share((int) $vendor['orders'], $period['total_orders']);
|
||
$vendor['amount_share'] = $this->share((float) $vendor['amount'], $period['total_amount']);
|
||
}
|
||
unset($vendor);
|
||
|
||
$primary = $this->primaryVendor($period['vendors']);
|
||
$period['primary_key'] = $primary['key'];
|
||
$period['primary_label'] = $primary['label'];
|
||
$period['primary_orders'] = $primary['orders'];
|
||
$period['primary_share'] = $primary['share'];
|
||
$period['transition_from'] = null;
|
||
|
||
if ($period['total_orders'] > 0) {
|
||
if ($previousPrimaryKey !== null && $primary['key'] !== $previousPrimaryKey) {
|
||
$period['transition_from'] = $previousPrimaryLabel;
|
||
}
|
||
$previousPrimaryKey = $primary['key'];
|
||
$previousPrimaryLabel = $primary['label'];
|
||
}
|
||
}
|
||
unset($period);
|
||
|
||
return $periods;
|
||
}
|
||
|
||
private function emptyPeriods(string $fromMonth, string $toMonth): array
|
||
{
|
||
$periods = [];
|
||
$cursor = Carbon::parse($fromMonth . '-01')->startOfMonth();
|
||
$end = Carbon::parse($toMonth . '-01')->startOfMonth();
|
||
while ($cursor->lte($end)) {
|
||
$periods[] = [
|
||
'period' => $cursor->format('Y-m'),
|
||
'short_label' => $cursor->format('m') . '月',
|
||
'total_orders' => 0,
|
||
'total_amount' => 0.0,
|
||
'vendors' => [
|
||
'wan' => ['key' => 'wan', 'label' => '万师傅', 'orders' => 0, 'amount' => 0.0],
|
||
'luban' => ['key' => 'luban', 'label' => '鲁班到家', 'orders' => 0, 'amount' => 0.0],
|
||
'other' => ['key' => 'other', 'label' => '其他安装公司', 'orders' => 0, 'amount' => 0.0],
|
||
],
|
||
'source_companies' => [],
|
||
'primary_key' => '',
|
||
'primary_label' => '无安装单',
|
||
'primary_orders' => 0,
|
||
'primary_share' => 0.0,
|
||
'transition_from' => null,
|
||
];
|
||
$cursor->addMonthNoOverflow();
|
||
}
|
||
|
||
return $periods;
|
||
}
|
||
|
||
/** @param list<array{installation_company:string,orders:int,amount:float}> $rows */
|
||
private function buildSummary(array $rows, array $periods): array
|
||
{
|
||
$vendors = $this->vendorDefinition();
|
||
foreach ($rows as $row) {
|
||
$key = $this->vendorKey($row['installation_company']);
|
||
$vendors[$key]['orders'] += (int) $row['orders'];
|
||
$vendors[$key]['amount'] += (float) $row['amount'];
|
||
}
|
||
|
||
$totalOrders = (int) array_sum(array_column($vendors, 'orders'));
|
||
$totalAmount = round(array_sum(array_column($vendors, 'amount')), 2);
|
||
foreach ($vendors as &$vendor) {
|
||
$vendor['amount'] = round((float) $vendor['amount'], 2);
|
||
$vendor['order_share'] = $this->share((int) $vendor['orders'], $totalOrders);
|
||
$vendor['amount_share'] = $this->share((float) $vendor['amount'], $totalAmount);
|
||
}
|
||
unset($vendor);
|
||
|
||
$nonEmptyPeriods = array_values(array_filter(
|
||
$periods,
|
||
static fn (array $period): bool => $period['total_orders'] > 0,
|
||
));
|
||
$latest = $nonEmptyPeriods === [] ? null : end($nonEmptyPeriods);
|
||
$previous = count($nonEmptyPeriods) < 2
|
||
? null
|
||
: $nonEmptyPeriods[count($nonEmptyPeriods) - 2];
|
||
|
||
$transitions = [];
|
||
foreach ($periods as $period) {
|
||
if ($period['transition_from'] !== null) {
|
||
$transitions[] = [
|
||
'period' => $period['period'],
|
||
'from' => $period['transition_from'],
|
||
'to' => $period['primary_label'],
|
||
];
|
||
}
|
||
}
|
||
$lastTransition = $transitions === [] ? null : end($transitions);
|
||
|
||
$latestKey = (string) ($latest['primary_key'] ?? '');
|
||
$latestLabel = (string) ($latest['primary_label'] ?? '无安装单');
|
||
if ($latestKey === 'luban') {
|
||
$switchStatus = $lastTransition && $lastTransition['from'] === '万师傅'
|
||
? '已切换至鲁班到家'
|
||
: '鲁班到家当前主导';
|
||
} elseif ($latestKey === 'wan') {
|
||
$switchStatus = $lastTransition && $lastTransition['from'] === '鲁班到家'
|
||
? '已切回万师傅'
|
||
: '仍以万师傅为主';
|
||
} elseif ($latestKey === 'tie') {
|
||
$switchStatus = '两家当前并列';
|
||
} elseif ($latestKey === 'other') {
|
||
$switchStatus = '其他安装公司主导';
|
||
} else {
|
||
$switchStatus = '所选期间暂无安装单';
|
||
}
|
||
|
||
$latestWan = $latest['vendors']['wan'] ?? ['orders' => 0, 'order_share' => 0.0];
|
||
$latestLuban = $latest['vendors']['luban'] ?? ['orders' => 0, 'order_share' => 0.0];
|
||
$switchNote = $latest === null
|
||
? '所选期间没有已审核安装单,无法判断安装公司切换。'
|
||
: sprintf(
|
||
'%s 主安装公司为%s,单量占比 %s%%;万师傅 %s%%、鲁班到家 %s%%。',
|
||
$latest['period'],
|
||
$latestLabel,
|
||
$this->percent($latest['primary_share']),
|
||
$this->percent($latestWan['order_share']),
|
||
$this->percent($latestLuban['order_share']),
|
||
);
|
||
if ($lastTransition !== null) {
|
||
$switchNote .= sprintf(
|
||
'最近一次变化:%s 从%s切到%s。',
|
||
$lastTransition['period'],
|
||
$lastTransition['from'],
|
||
$lastTransition['to'],
|
||
);
|
||
}
|
||
|
||
return [
|
||
'total_orders' => $totalOrders,
|
||
'total_amount' => $totalAmount,
|
||
'average_fee' => $totalOrders > 0 ? round($totalAmount / $totalOrders, 2) : 0.0,
|
||
'vendors' => array_values($vendors),
|
||
'latest_period' => $latest['period'] ?? null,
|
||
'latest_primary' => $latestLabel,
|
||
'latest_primary_share' => $latest['primary_share'] ?? 0.0,
|
||
'previous_period' => $previous['period'] ?? null,
|
||
'previous_primary' => $previous['primary_label'] ?? null,
|
||
'switch_status' => $switchStatus,
|
||
'switch_note' => $switchNote,
|
||
'last_transition' => $lastTransition,
|
||
'has_negative_fee' => collect($periods)->contains(
|
||
static fn (array $period): bool => (float) $period['total_amount'] < -0.004,
|
||
),
|
||
];
|
||
}
|
||
|
||
private function payload(
|
||
string $range,
|
||
string $rangeLabel,
|
||
string $fromMonth,
|
||
string $toMonth,
|
||
array $periods,
|
||
array $totals,
|
||
?string $error = null,
|
||
): array {
|
||
return [
|
||
'view' => 'business.pages.financial-operations.installation-fee-usage',
|
||
'installationFeeUsageRange' => $range,
|
||
'installationFeeUsageRangeOptions' => self::RANGE_OPTIONS,
|
||
'installationFeeUsageRangeLabel' => $rangeLabel,
|
||
'installationFeeUsageFromMonth' => $fromMonth,
|
||
'installationFeeUsageToMonth' => $toMonth,
|
||
'installationFeeUsagePeriods' => $periods,
|
||
'installationFeeUsageSummary' => $error === null ? $this->buildSummary($totals, $periods) : [],
|
||
'installationFeeUsageError' => $error,
|
||
];
|
||
}
|
||
|
||
private function vendorKey(string $company): string
|
||
{
|
||
if (str_contains($company, '万师傅')) {
|
||
return 'wan';
|
||
}
|
||
if (str_contains($company, '鲁班')) {
|
||
return 'luban';
|
||
}
|
||
|
||
return 'other';
|
||
}
|
||
|
||
private function vendorDefinition(): array
|
||
{
|
||
return [
|
||
'wan' => ['key' => 'wan', 'label' => '万师傅', 'orders' => 0, 'amount' => 0.0],
|
||
'luban' => ['key' => 'luban', 'label' => '鲁班到家', 'orders' => 0, 'amount' => 0.0],
|
||
'other' => ['key' => 'other', 'label' => '其他安装公司', 'orders' => 0, 'amount' => 0.0],
|
||
];
|
||
}
|
||
|
||
/** @return array{key:string,label:string,orders:int,share:float} */
|
||
private function primaryVendor(array $vendors): array
|
||
{
|
||
$ordered = array_values($vendors);
|
||
usort($ordered, static fn (array $left, array $right): int =>
|
||
[$right['orders'], $right['amount']] <=> [$left['orders'], $left['amount']]);
|
||
$first = $ordered[0];
|
||
if ((int) $first['orders'] === 0) {
|
||
return ['key' => '', 'label' => '无安装单', 'orders' => 0, 'share' => 0.0];
|
||
}
|
||
|
||
$second = $ordered[1];
|
||
$firstTwoKeys = [$first['key'], $second['key']];
|
||
sort($firstTwoKeys);
|
||
if ((int) $second['orders'] === (int) $first['orders']
|
||
&& $firstTwoKeys === ['luban', 'wan']) {
|
||
return ['key' => 'tie', 'label' => '万师傅 / 鲁班到家并列', 'orders' => (int) $first['orders'], 'share' => 50.0];
|
||
}
|
||
|
||
$total = array_sum(array_column($ordered, 'orders'));
|
||
return [
|
||
'key' => (string) $first['key'],
|
||
'label' => (string) $first['label'],
|
||
'orders' => (int) $first['orders'],
|
||
'share' => $this->share((int) $first['orders'], (int) $total),
|
||
];
|
||
}
|
||
|
||
private function share(int|float $value, int|float $total): float
|
||
{
|
||
return abs((float) $total) > 0.00001
|
||
? round(((float) $value / (float) $total) * 100, 1)
|
||
: 0.0;
|
||
}
|
||
|
||
private function percent(float $value): string
|
||
{
|
||
return number_format($value, 1);
|
||
}
|
||
}
|