feat(财务经营分析): 接入安装费月度汇总 (#1402)

This commit is contained in:
chenxi 2026-11-25 13:05:21 +08:00
parent b1b7710315
commit fa38374246
5 changed files with 245 additions and 17 deletions

View File

@ -3600,6 +3600,8 @@ class Pages extends Controller
$billNonInvoiceExpenseTotal = 0.0;
$promotionInvoiceExpenseComplete = $rows !== [];
$promotionInvoiceExpenseTotal = 0.0;
$installationExpenseComplete = $rows !== [];
$installationExpenseTotal = 0.0;
$netProfitComplete = $rows !== [];
$netProfitTotal = 0.0;
/** @var array<string,true> $platformOptions */
@ -3617,6 +3619,11 @@ class Pages extends Controller
} else {
$promotionInvoiceExpenseTotal += (float) $row['promotion_invoice_expense'];
}
if ($row['installation_fee'] === null) {
$installationExpenseComplete = false;
} else {
$installationExpenseTotal += (float) $row['installation_fee'];
}
if ($row['net_profit'] === null) {
$netProfitComplete = false;
} else {
@ -3650,6 +3657,9 @@ class Pages extends Controller
'promotion_invoice_expense_total' => $promotionInvoiceExpenseComplete
? round($promotionInvoiceExpenseTotal, 2)
: null,
'installation_expense_total' => $installationExpenseComplete
? round($installationExpenseTotal, 2)
: null,
'net_profit_total' => $netProfitComplete ? round($netProfitTotal, 2) : null,
],
'financialAnalysisMonths' => $months,
@ -3687,12 +3697,26 @@ class Pages extends Controller
$promotionExpenseAvailable = false;
}
$installationExpenseAvailable = true;
try {
$installationExpenseBucketsByMonth = $this->installationDetails
->settlementAmountBucketsForCustomerReviewMonths(array_map(
static fn (string $value): string => substr($value, 0, 7),
$sourceMonths,
));
} catch (Throwable $exception) {
report($exception);
$installationExpenseBucketsByMonth = [];
$installationExpenseAvailable = false;
}
$rows = [];
foreach ($sourceMonths as $sourceMonth) {
$reportMonth = substr($sourceMonth, 0, 7);
foreach ($this->financialAnalysisAggregates(
$sourceMonth,
$promotionExpenseAvailable ? ($promotionExpenseBucketsByMonth[$reportMonth] ?? []) : null,
$installationExpenseAvailable ? ($installationExpenseBucketsByMonth[$reportMonth] ?? []) : null,
) as $values) {
if ($filters['platform'] !== '' && $values['platform'] !== $filters['platform']) {
continue;
@ -3738,19 +3762,26 @@ class Pages extends Controller
* 两张表都是几十万行,聚合结果按月份缓存 5 分钟;筛选在内存里做,避免每次开页重跑分组。
*
* @param array<string,float>|null $promotionExpenseBuckets
* @param array<string,array{platform:string,amount:float}>|null $installationExpenseBuckets
* @return array<string,array<string,mixed>>
*/
private function financialAnalysisAggregates(
string $reportMonth,
?array $promotionExpenseBuckets = null,
?array $installationExpenseBuckets = null,
): array
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
return cache()->remember(
'financial-analysis-aggregates-v5:' . $reportMonth . ':' . $this->financialAnalysisMappingSignature(),
'financial-analysis-aggregates-v8:' . $reportMonth . ':' . $this->financialAnalysisMappingSignature(),
now()->addMinutes(5),
function () use ($connection, $reportMonth, $promotionExpenseBuckets): array {
function () use (
$connection,
$reportMonth,
$promotionExpenseBuckets,
$installationExpenseBuckets,
): array {
$rows = [];
$incomeRows = DB::connection($connection)->table('store_receipt_order_match_rows')
->where('report_month', $reportMonth)
@ -3805,6 +3836,43 @@ class Pages extends Controller
$rows[$key]['purchase_cost'] = round((float) $row->purchase_cost, 2);
}
$installationRowKeys = [];
if ($installationExpenseBuckets !== null) {
// 安装明细只有店铺,没有收款平台;同一店铺出现多个平台行时,
// 归到申报收入最高的一行,避免同一笔安装费重复计入利润。
foreach ($rows as $key => $row) {
$storeName = trim((string) $row['store_name']);
if (! array_key_exists($storeName, $installationExpenseBuckets)) {
continue;
}
$preferredKey = $installationRowKeys[$storeName] ?? null;
if ($preferredKey === null
|| [
(float) $row['declared_income'],
(string) $row['platform'],
] > [
(float) $rows[$preferredKey]['declared_income'],
(string) $rows[$preferredKey]['platform'],
]) {
$installationRowKeys[$storeName] = $key;
}
}
foreach ($rows as &$row) {
$row['installation_fee'] = 0.0;
}
unset($row);
foreach ($installationExpenseBuckets as $storeName => $amount) {
$storeName = trim((string) $storeName);
$key = $installationRowKeys[$storeName] ?? null;
if ($key === null) {
$platform = trim((string) ($amount['platform'] ?? '')) ?: '其他';
$key = $platform . "\0" . $storeName;
$rows[$key] ??= $this->financialAnalysisEmptyRow($platform, $storeName);
}
$rows[$key]['installation_fee'] = round((float) ($amount['amount'] ?? 0), 2);
}
}
$subjectMatcher = app(ProductCostSubjectMatcher::class);
$subjectMap = $subjectMatcher->map(
array_values(array_unique(array_column($rows, 'store_name'))),

View File

@ -236,6 +236,101 @@ class InstallationDetailMirrorRepository
];
}
/**
* 财务经营分析表安装费:按客服审核月份和店铺汇总已审核明细的结算金额。
*
* @param list<string> $reportMonths
* @return array<string,array<string,array{platform:string,amount:float}>>
*/
public function settlementAmountBucketsForCustomerReviewMonths(array $reportMonths): array
{
$months = array_values(array_unique(array_filter(
$reportMonths,
static fn (mixed $month): bool => is_string($month)
&& preg_match('/^\d{4}-\d{2}$/', $month) === 1,
)));
sort($months, SORT_STRING);
if ($months === []) {
return [];
}
$dataset = $this->datasets->get(self::DATASET);
$items = $this->datasets->get(self::ITEM_DATASET);
$connection = $this->mirror->connection();
if (! $this->ready($dataset, $items, $connection->getName())) {
throw new \RuntimeException('安装明细镜像尚未完成首次同步');
}
$start = $months[0] . '-01';
$endExclusive = \Illuminate\Support\Carbon::parse(end($months) . '-01')
->addMonth()
->toDateString();
$main = $this->latestFeeMainQuery($connection, $dataset, true);
$reviewMonth = $connection->getDriverName() === 'sqlite'
? "strftime('%Y-%m', i.kfshTime)"
: "DATE_FORMAT(i.kfshTime, '%Y-%m')";
$storeName = "COALESCE(NULLIF(TRIM(install_main.shop_name), ''), '未填写店铺')";
$platform = "CASE"
. " WHEN {$storeName} LIKE '%阿里巴巴%'"
. " OR {$storeName} LIKE '%天猫%'"
. " OR {$storeName} LIKE '%新佰广%'"
. " OR {$storeName} LIKE '%淘工厂%'"
. " OR {$storeName} LIKE '%淘宝%' THEN '淘系支付宝'"
. " WHEN {$storeName} LIKE '抖音-%' THEN '抖音'"
. " WHEN {$storeName} LIKE '拼多多-%' THEN '拼多多'"
. " WHEN {$storeName} LIKE '唯品会MP-%' THEN '唯品会'"
. " WHEN {$storeName} LIKE '得物-%' THEN '得物'"
. " WHEN {$storeName} LIKE '京东-%' THEN '京东账单'"
. " WHEN {$storeName} LIKE '京喜-%' THEN '京喜账单'"
. " ELSE '其他' END";
$rows = $connection->table($items->targetTable() . ' AS i')
->joinSub($main, 'install_main', static fn ($join) =>
$join->on('install_main.SourceGuid', '=', 'i.guid'))
->whereNotNull('i.kfshTime')
->where('i.kfshTime', '>=', $start)
->where('i.kfshTime', '<', $endExclusive)
->selectRaw($reviewMonth . ' AS review_month')
->selectRaw($storeName . ' AS store_name')
->selectRaw($platform . ' AS platform')
->selectRaw('ROUND(SUM(CAST(i.settleItemAmount AS DECIMAL(18,2))), 2) AS amount')
->groupByRaw($reviewMonth . ', ' . $storeName . ', ' . $platform)
->havingRaw('ABS(SUM(CAST(i.settleItemAmount AS DECIMAL(18,2)))) > 0.004')
->get();
$buckets = [];
foreach ($rows as $row) {
$month = trim((string) ($row->review_month ?? ''));
$store = trim((string) ($row->store_name ?? ''));
$platformName = trim((string) ($row->platform ?? ''));
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1 || $store === '' || $platformName === '') {
continue;
}
$buckets[$month][$store] = [
'platform' => $platformName,
'amount' => round((float) ($row->amount ?? 0), 2),
];
}
return $buckets;
}
private function latestFeeMainQuery($connection, $dataset, bool $customerReviewedOnly = false)
{
$latest = $connection->table($dataset->targetTable())
->selectRaw('MAX(Id) AS id')
->groupBy('SourceGuid');
$main = $connection->table($dataset->targetTable() . ' AS v')
->joinSub($latest, 'latest_install', static fn ($join) => $join->on('latest_install.id', '=', 'v.Id'))
->select(['v.SourceGuid', 'v.shop_name', 'v.installCompanyName', 'v.costWay']);
if ($customerReviewedOnly) {
$main->where('v.kfsh', 1);
}
$this->applyShipmentCutoff($main);
return $main;
}
private function feeDetailsQuery(
$connection,
$dataset,
@ -243,13 +338,7 @@ class InstallationDetailMirrorRepository
string $from,
string $to,
) {
$latest = $connection->table($dataset->targetTable())
->selectRaw('MAX(Id) AS id')
->groupBy('SourceGuid');
$main = $connection->table($dataset->targetTable() . ' AS v')
->joinSub($latest, 'latest_install', static fn ($join) => $join->on('latest_install.id', '=', 'v.Id'))
->select(['v.SourceGuid', 'v.shop_name', 'v.installCompanyName', 'v.costWay']);
$this->applyShipmentCutoff($main);
$main = $this->latestFeeMainQuery($connection, $dataset);
return $connection->table($items->targetTable() . ' AS i')
->joinSub($main, 'install_main', static fn ($join) =>

View File

@ -85,7 +85,9 @@
口径:一行 = 一个月的一个平台的一个店铺。申报收入 = 账单收入 + 退款 + 收入冲减项,金额按源字段记账符号展示。
采购成本取商品成本表汇总;账单费用-有票 / 无票按店铺收款账户账单和科目映射票据口径汇总。
推广费用-有票取聚水潭「平台费用(新)→ 推广费(店铺)」按店铺月度支出汇总。
快递运费、安装费、售后费用-小额打款、管理费用和人工费用尚未建立统一的店铺月汇总,显示为“—”;
安装费取安装明细中客服审核为“已审核”、按客服审核时间归属月份,并汇总结算明细金额;
同一店铺出现多个平台行时,安装费归入申报收入最高的一行,避免重复计入。
快递运费、售后费用-小额打款、管理费用和人工费用尚未建立统一的店铺月汇总,显示为“—”;
上述费用口径齐备后自动计算净利润。
</div>
@ -99,6 +101,7 @@
<div class="item"><span>账单费用-有票合计</span><b>{{ $money($summary['bill_invoice_expense_total'] ?? null) }}</b></div>
<div class="item"><span>账单费用-无票合计</span><b>{{ $money($summary['bill_non_invoice_expense_total'] ?? null) }}</b></div>
<div class="item"><span>推广费用-有票合计</span><b>{{ $money($summary['promotion_invoice_expense_total'] ?? null) }}</b></div>
<div class="item"><span>安装费合计</span><b>{{ $money($summary['installation_expense_total'] ?? null) }}</b></div>
<div class="item"><span>净利润合计</span><b>{{ $money($summary['net_profit_total'] ?? null) }}</b></div>
</div>

View File

@ -10,6 +10,8 @@ use App\Utilities\SidebarPermissions;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Mockery;
use Modules\EcommerceFinance\Repositories\InstallationDetailMirrorRepository;
use Modules\EcommerceFinance\Repositories\PromotionMarketingExpenseRepository;
use Modules\EcommerceFinance\View\BillingDetailsPageData;
use Tests\Feature\FeatureTestCase;
@ -299,6 +301,16 @@ class NavigationTest extends FeatureTestCase
'default_compensation_amount' => -5,
'refund_amount' => -40,
]);
DB::connection('business_mirror')->table('store_receipt_order_match_rows')->insert([
'report_month' => '2026-11-01',
'platform' => '淘系微信',
'store_name' => '测试店铺',
'income_amount' => 100,
'discount_amount' => 0,
'offset_amount' => 0,
'default_compensation_amount' => 0,
'refund_amount' => 0,
]);
DB::connection('business_mirror')->table('store_receipt_product_cost_rows')->insert([
'report_month' => '2026-11-01',
'platform' => '淘系支付宝',
@ -322,6 +334,14 @@ class NavigationTest extends FeatureTestCase
return ['2026-11' => ['测试店铺' => 30]];
}
});
$installation = Mockery::mock(InstallationDetailMirrorRepository::class);
$installation->shouldReceive('settlementAmountBucketsForCustomerReviewMonths')
->twice()
->andReturn(['2026-11' => [
'测试店铺' => ['platform' => '淘系支付宝', 'amount' => 50],
'仅安装店铺' => ['platform' => '其他', 'amount' => 25],
]]);
$this->app->instance(InstallationDetailMirrorRepository::class, $installation);
$this->loginAs()
->get(route('business.pages.show', [
@ -337,15 +357,37 @@ class NavigationTest extends FeatureTestCase
->assertSeeText('10.00')
->assertSeeText('20.00')
->assertSeeText('30.00')
->assertSeeText('推广费用-有票合计');
->assertSeeText('50.00')
->assertSeeText('推广费用-有票合计')
->assertSeeText('安装费合计');
$csv = $this->loginAs()
->get(route('business.financial-operations.financial-analysis.export'))
->streamedContent();
$this->assertStringContainsString(
'2026-11,,,,淘系支付宝,测试店铺,1000.00,-40.00,-80.00,880.00,300.00,,,10.00,20.00,30.00',
'2026-11,,,,淘系支付宝,测试店铺,1000.00,-40.00,-80.00,880.00,300.00,,50.00,10.00,20.00,30.00',
$csv,
);
$csvRows = array_map(
static fn (string $line): array => str_getcsv($line, ',', '"', '\\'),
preg_split('/\r\n|\n|\r/', trim($csv)) ?: [],
);
$storeRows = array_values(array_filter(
array_slice($csvRows, 1),
static fn (array $row): bool => ($row[5] ?? '') === '测试店铺',
));
$this->assertCount(2, $storeRows);
$this->assertSame(50.0, round(array_sum(array_map(
static fn (array $row): float => (float) ($row[12] ?? 0),
$storeRows,
)), 2));
$installationOnlyRows = array_values(array_filter(
array_slice($csvRows, 1),
static fn (array $row): bool => ($row[5] ?? '') === '仅安装店铺',
));
$this->assertCount(1, $installationOnlyRows);
$this->assertSame('其他', $installationOnlyRows[0][4] ?? null);
$this->assertSame('25.00', $installationOnlyRows[0][12] ?? null);
}
public function testFinancialRiskControlPageIsAvailableBetweenFinancialReports(): void

View File

@ -47,12 +47,12 @@ class InstallationDetailMirrorRepositoryTest extends TestCase
});
foreach(array_keys($definitions) as $key) DB::connection('business_mirror')->table('business_mirror_table_states')->insert(['dataset_key'=>$key,'initial_completed_at'=>'2026-08-01']);
DB::connection('business_mirror')->table('fixture_install')->insert([
['Id'=>1,'SourceGuid'=>'A','OrderNum'=>'OLD','shop_name'=>'旧店','SubmitTime'=>'2026-08-01','ShipTIme'=>'2026-08-02','installcost'=>500],
['Id'=>1,'SourceGuid'=>'A','OrderNum'=>'OLD','shop_name'=>'旧店','shopcode'=>null,'SubmitTime'=>'2026-08-01','ShipTIme'=>'2026-08-02','installcost'=>500],
['Id'=>2,'SourceGuid'=>'A','OrderNum'=>'NEW','shop_name'=>'测试店','shopcode'=>'SHOP-A','SubmitTime'=>'2026-08-20 23:59:59','ShipTIme'=>'2026-08-21','installcost'=>20],
['Id'=>3,'SourceGuid'=>'B','OrderNum'=>'OTHER','shop_name'=>'其他店','SubmitTime'=>'2026-08-20','ShipTIme'=>'2026-08-21','installcost'=>30],
['Id'=>4,'SourceGuid'=>'C','OrderNum'=>'NEXT','shop_name'=>'测试店','SubmitTime'=>'2026-08-21','ShipTIme'=>'2026-08-22','installcost'=>40],
['Id'=>5,'SourceGuid'=>'D','OrderNum'=>'PRE-2026','shop_name'=>'测试店','SubmitTime'=>'2026-08-21','ShipTIme'=>'2025-12-31 23:59:59','installcost'=>999],
['Id'=>6,'SourceGuid'=>'E','OrderNum'=>'NULL-SHIP','shop_name'=>'测试店','SubmitTime'=>'2026-08-21','ShipTIme'=>null,'installcost'=>999],
['Id'=>3,'SourceGuid'=>'B','OrderNum'=>'OTHER','shop_name'=>'其他店','shopcode'=>null,'SubmitTime'=>'2026-08-20','ShipTIme'=>'2026-08-21','installcost'=>30],
['Id'=>4,'SourceGuid'=>'C','OrderNum'=>'NEXT','shop_name'=>'测试店','shopcode'=>null,'SubmitTime'=>'2026-08-21','ShipTIme'=>'2026-08-22','installcost'=>40],
['Id'=>5,'SourceGuid'=>'D','OrderNum'=>'PRE-2026','shop_name'=>'测试店','shopcode'=>null,'SubmitTime'=>'2026-08-21','ShipTIme'=>'2025-12-31 23:59:59','installcost'=>999],
['Id'=>6,'SourceGuid'=>'E','OrderNum'=>'NULL-SHIP','shop_name'=>'测试店','shopcode'=>null,'SubmitTime'=>'2026-08-21','ShipTIme'=>null,'installcost'=>999],
]);
DB::connection('business_mirror')->table('fixture_items')->insert([
['Id'=>1,'guid'=>'A','shopproid'=>'PRODUCT-A'],['Id'=>2,'guid'=>'A','shopproid'=>'PRODUCT-A'],
@ -166,6 +166,32 @@ class InstallationDetailMirrorRepositoryTest extends TestCase
$this->assertSame(100.0,$result['change_rate']);
}
public function test_monthly_settlement_buckets_only_include_approved_customer_reviews(): void
{
DB::connection('business_mirror')->table('fixture_install')->whereIn('Id',[2,3,4])->update(['kfsh'=>'1']);
DB::connection('business_mirror')->table('fixture_install')->insert([
'Id' => 7,
'SourceGuid' => 'F',
'OrderNum' => 'UNAPPROVED',
'shop_name' => '测试店',
'ShipTIme' => '2026-08-20',
'kfsh' => '0',
]);
DB::connection('business_mirror')->table('fixture_items')->insert([
['Id'=>26,'guid'=>'A','shopproid'=>'P1','kfshTime'=>'2026-09-03 10:00:00','settleItemAmount'=>60.10],
['Id'=>27,'guid'=>'A','shopproid'=>'P2','kfshTime'=>'2026-09-30 18:00:00','settleItemAmount'=>39.90],
['Id'=>28,'guid'=>'B','shopproid'=>'P3','kfshTime'=>'2026-09-15 10:00:00','settleItemAmount'=>80.00],
['Id'=>29,'guid'=>'F','shopproid'=>'P4','kfshTime'=>'2026-09-15 10:00:00','settleItemAmount'=>999.00],
]);
$this->assertEquals([
'2026-09' => [
'测试店' => ['platform' => '其他', 'amount' => 100.0],
'其他店' => ['platform' => '其他', 'amount' => 80.0],
],
], $this->repository->settlementAmountBucketsForCustomerReviewMonths(['2026-09']));
}
public function test_fee_details_classifies_platform_by_store_name_rules(): void
{
$stores = [