feat(财务经营分析): 接入快递运费月度店铺汇总

This commit is contained in:
chenxi 2026-11-27 01:12:19 +08:00
parent 50f5c7bc64
commit b2f7a072c8
5 changed files with 546 additions and 2 deletions

View File

@ -0,0 +1,152 @@
<?php
namespace App\Business;
use Illuminate\Database\DatabaseManager;
/**
* 财务经营分析表 › 快递运费按月、按店铺汇总。
*
* 每一行快递运费由「结算运费 + 其他附加费汇总 + 退件费」组成:
* 结算运费 = 提供成本运费 + 运费差;三份快递应付快照都按交易单号匹配。
* 同一交易单号的多条快照金额全部相加;基础运费多行也全部相加,
* 但同一月份、同一交易单号的附加费用只挂一次,避免一条订单拆成多行后重复计入。
*/
class CourierFreightFinancialSummary
{
public function __construct(
private readonly DatabaseManager $databases,
private readonly CourierPayableSummaryMap $summaries,
) {}
/**
* 返回仅包含有快递运费来源的月份。调用方据此区分「本月无数据」和「金额为 0」。
*
* @param list<string> $reportMonths YYYY-MM
* @return array<string,array<string,float>> 月份 => [店铺 => 快递运费]
*/
public function monthlyStoreTotals(array $reportMonths, int $companyId): array
{
$wantedMonths = array_fill_keys(array_values(array_unique(array_filter(
$reportMonths,
static fn (string $month): bool => preg_match('/^\d{4}-\d{2}$/', $month) === 1,
))), true);
if ($wantedMonths === []) {
return [];
}
$differences = $this->summaries->mapByMonth(
$companyId,
CourierPayableSummaryMap::PAGE_FREIGHT_DIFFERENCE,
);
$surcharges = $this->summaries->mapByMonth(
$companyId,
CourierPayableSummaryMap::PAGE_OTHER_SURCHARGE,
);
$returnFees = $this->summaries->mapByMonth(
$companyId,
CourierPayableSummaryMap::PAGE_RETURN_FEE,
);
$totals = [];
$feeApplied = [];
$rows = $this->databases->connection()->table('courier_freight_rows')
->where('company_id', $companyId)
->whereNull('deleted_at')
->select(['source', 'shop_name', 'transaction_no'])
->selectRaw('SUM(COALESCE(freight_amount, 0)) AS freight_amount')
->selectRaw('MAX(created_at) AS imported_at')
->groupBy('source', 'shop_name', 'transaction_no')
->orderBy('source')
->orderBy('shop_name')
->orderBy('transaction_no')
->cursor();
foreach ($rows as $row) {
$month = $this->sourceMonth(
(string) $row->source,
(string) ($row->imported_at ?? ''),
array_keys($wantedMonths),
);
if ($month === null || ! isset($wantedMonths[$month])) {
continue;
}
// 即使店铺为空也保留月份,表示该月已有快递成本来源。
$totals[$month] ??= [];
$storeName = trim((string) $row->shop_name);
if ($storeName === '') {
continue;
}
$transactionNo = trim((string) $row->transaction_no);
$amount = (float) $row->freight_amount;
$feeKey = $month . "\0" . $transactionNo;
if ($transactionNo !== '' && ! isset($feeApplied[$feeKey])) {
$amount += $this->numeric($differences[$month][$transactionNo] ?? null);
$amount += $this->numeric($surcharges[$month][$transactionNo] ?? null);
$amount += $this->numeric($returnFees[$month][$transactionNo] ?? null);
$feeApplied[$feeKey] = true;
}
$totals[$month][$storeName] = round(
($totals[$month][$storeName] ?? 0.0) + $amount,
2,
);
}
return $totals;
}
/**
* 来源通常为「提供成本9月汇总」。优先取来源里的年份;没有年份时,
* 用导入时间年份补齐。若来源是「5-7月」范围,取最后月份作为该汇总的账期。
*
* @param list<string> $reportMonths
*/
private function sourceMonth(string $source, string $importedAt, array $reportMonths): ?string
{
$source = trim($source);
if ($source === '') {
return null;
}
if (preg_match(
'/(?<!\d)((?:19|20)\d{2})\D{0,4}(1[0-2]|0?[1-9])(?!\d)/u',
$source,
$matches,
) === 1) {
return $matches[1] . '-' . str_pad((string) (int) $matches[2], 2, '0', STR_PAD_LEFT);
}
if (preg_match(
'/(?:1[0-2]|0?[1-9])\s*[-~至]\s*(1[0-2]|0?[1-9])\s*月/u',
$source,
$range,
) === 1) {
$month = (int) $range[1];
} elseif (preg_match('/(1[0-2]|0?[1-9])\s*月/u', $source, $single) === 1) {
$month = (int) $single[1];
} else {
return null;
}
$year = preg_match('/^((?:19|20)\d{2})-/u', $importedAt, $date) === 1 ? $date[1] : null;
if ($year === null) {
$year = $reportMonths !== [] ? substr($reportMonths[0], 0, 4) : null;
}
return $year === null
? null
: $year . '-' . str_pad((string) $month, 2, '0', STR_PAD_LEFT);
}
private function numeric(mixed $value): float
{
if ($value === null || $value === '') {
return 0.0;
}
return is_numeric($value) ? (float) $value : 0.0;
}
}

View File

@ -71,6 +71,43 @@ class CourierPayableSummaryMap
});
}
/**
* 汇总快照按原始日期拆成月份,供财务经营分析表按月匹配。
*
* 同一交易单号在同一月份可以出现多行,所有金额都累加,不做去重。
*
* @return array<string,array<string,string>> 月份 => [交易单号 => 金额]
*/
public function mapByMonth(int $companyId, string $page): array
{
if (! isset(self::PAGES[$page])) {
return [];
}
$disk = Storage::disk('uploads');
$path = $this->store->path($companyId, $page);
if (! $disk->exists($path)) {
return [];
}
$key = sprintf(
'courier-payable-summary-month-map:v1:%s:%d:%d',
$page,
$companyId,
(int) $disk->lastModified($path),
);
return Cache::remember($key, now()->addMinutes(self::CACHE_MINUTES), function () use ($companyId, $page): array {
try {
return $this->buildByMonth($companyId, $page);
} catch (Throwable $exception) {
report($exception);
return [];
}
});
}
/** @return array<string,string> */
private function build(int $companyId, string $page): array
{
@ -135,6 +172,69 @@ class CourierPayableSummaryMap
return $map;
}
/** @return array<string,array<string,string>> */
private function buildByMonth(int $companyId, string $page): array
{
$snapshot = $this->store->snapshot($companyId, $page);
if ($snapshot === null) {
return [];
}
[$orderHeaders, $valueHeaders] = self::PAGES[$page];
$headers = array_map(static fn ($value): string => trim((string) $value), (array) $snapshot['headers']);
$orderColumn = $this->columnIndex($headers, $orderHeaders);
$valueColumn = $this->columnIndex($headers, $valueHeaders);
$dateColumn = $this->columnIndex($headers, ['日期', '结算月份', '结算月', '月份']);
if ($orderColumn === null || $valueColumn === null || $dateColumn === null) {
return [];
}
$totals = [];
foreach ((array) $snapshot['rows'] as $row) {
$month = $this->month((string) ($row[$dateColumn] ?? ''));
$orderNos = trim((string) ($row[$orderColumn] ?? ''));
$value = trim((string) ($row[$valueColumn] ?? ''));
$numericValue = $this->numericDecimal($value);
if ($month === null || $orderNos === '' || $numericValue === null) {
continue;
}
$totals[$month] ??= [];
foreach (preg_split('/[,,]/u', $orderNos) ?: [] as $orderNo) {
$orderNo = trim($orderNo);
if ($orderNo === '') {
continue;
}
$totals[$month][$orderNo] = function_exists('bcadd')
? bcadd($totals[$month][$orderNo] ?? '0', $numericValue, self::AMOUNT_SCALE)
: (string) ((float) ($totals[$month][$orderNo] ?? 0) + (float) $numericValue);
}
}
$map = [];
foreach ($totals as $month => $orders) {
foreach ($orders as $orderNo => $total) {
$map[$month][$orderNo] = $this->decimalString($total);
}
}
return $map;
}
private function month(string $value): ?string
{
if (preg_match(
'/(?<!\d)((?:19|20)\d{2})\D{0,4}(1[0-2]|0?[1-9])(?!\d)/u',
trim($value),
$matches,
) !== 1) {
return null;
}
return $matches[1] . '-' . str_pad((string) (int) $matches[2], 2, '0', STR_PAD_LEFT);
}
private function numericDecimal(string $value): ?string
{
if (! is_numeric($value)) {

View File

@ -16,6 +16,7 @@ use App\Business\KukaPostingQuotation\KukaPostingQuotationPageData;
use App\Business\KukaPostingReconciliation\KukaReconciliationPageData;
use App\Business\LaborExpenseWorkbookImporter;
use App\Business\LaborExpenseDataStore;
use App\Business\CourierFreightFinancialSummary;
use App\Business\CourierPayableSummaryFilter;
use App\Business\CourierPayableSummaryStore;
use App\Business\FundForecastTemplate;
@ -3607,6 +3608,8 @@ class Pages extends Controller
$billNonInvoiceExpenseTotal = 0.0;
$promotionInvoiceExpenseComplete = $rows !== [];
$promotionInvoiceExpenseTotal = 0.0;
$courierFreightExpenseComplete = $rows !== [];
$courierFreightExpenseTotal = 0.0;
$installationExpenseComplete = $rows !== [];
$installationExpenseTotal = 0.0;
$netProfitComplete = $rows !== [];
@ -3626,6 +3629,11 @@ class Pages extends Controller
} else {
$promotionInvoiceExpenseTotal += (float) $row['promotion_invoice_expense'];
}
if ($row['freight'] === null) {
$courierFreightExpenseComplete = false;
} else {
$courierFreightExpenseTotal += (float) $row['freight'];
}
if ($row['installation_fee'] === null) {
$installationExpenseComplete = false;
} else {
@ -3664,6 +3672,9 @@ class Pages extends Controller
'promotion_invoice_expense_total' => $promotionInvoiceExpenseComplete
? round($promotionInvoiceExpenseTotal, 2)
: null,
'courier_freight_expense_total' => $courierFreightExpenseComplete
? round($courierFreightExpenseTotal, 2)
: null,
'installation_expense_total' => $installationExpenseComplete
? round($installationExpenseTotal, 2)
: null,
@ -3717,13 +3728,32 @@ class Pages extends Controller
$installationExpenseAvailable = false;
}
$courierFreightAvailable = true;
try {
$courierFreightBucketsByMonth = app(CourierFreightFinancialSummary::class)
->monthlyStoreTotals(
array_map(static fn (string $value): string => substr($value, 0, 7), $sourceMonths),
(int) company_id(),
);
} catch (Throwable $exception) {
report($exception);
$courierFreightBucketsByMonth = [];
$courierFreightAvailable = false;
}
$rows = [];
foreach ($sourceMonths as $sourceMonth) {
$reportMonth = substr($sourceMonth, 0, 7);
$courierFreightBuckets = ! $courierFreightAvailable
? null
: (array_key_exists($reportMonth, $courierFreightBucketsByMonth)
? $courierFreightBucketsByMonth[$reportMonth]
: null);
foreach ($this->financialAnalysisAggregates(
$sourceMonth,
$promotionExpenseAvailable ? ($promotionExpenseBucketsByMonth[$reportMonth] ?? []) : null,
$installationExpenseAvailable ? ($installationExpenseBucketsByMonth[$reportMonth] ?? []) : null,
$courierFreightBuckets,
) as $values) {
if (in_array((string) $values['platform'], self::RECEIPT_MATCH_EXCLUDED_PLATFORMS, true)) {
continue;
@ -3773,24 +3803,27 @@ class Pages extends Controller
*
* @param array<string,float>|null $promotionExpenseBuckets
* @param array<string,array{platform:string,amount:float}>|null $installationExpenseBuckets
* @param array<string,float>|null $courierFreightBuckets
* @return array<string,array<string,mixed>>
*/
private function financialAnalysisAggregates(
string $reportMonth,
?array $promotionExpenseBuckets = null,
?array $installationExpenseBuckets = null,
?array $courierFreightBuckets = null,
): array
{
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
return cache()->remember(
'financial-analysis-aggregates-v8:' . $reportMonth . ':' . $this->financialAnalysisMappingSignature(),
'financial-analysis-aggregates-v9:' . $reportMonth . ':' . $this->financialAnalysisMappingSignature(),
now()->addMinutes(5),
function () use (
$connection,
$reportMonth,
$promotionExpenseBuckets,
$installationExpenseBuckets,
$courierFreightBuckets,
): array {
$rows = [];
$incomeRows = DB::connection($connection)->table('store_receipt_order_match_rows')
@ -3883,6 +3916,15 @@ class Pages extends Controller
}
}
if ($courierFreightBuckets !== null) {
$this->applyStoreOnlyExpense(
$rows,
$courierFreightBuckets,
'freight',
'其他',
);
}
$subjectMatcher = app(ProductCostSubjectMatcher::class);
$subjectMap = $subjectMatcher->map(
array_values(array_unique(array_column($rows, 'store_name'))),
@ -3963,6 +4005,55 @@ class Pages extends Controller
];
}
/**
* 店铺级费用归入同店铺申报收入最高的一行;店铺不存在时补一行“其他”平台,
* 保证费用总额不因缺少业绩行而丢失。
*
* @param array<string,array<string,mixed>> $rows
* @param array<string,float> $amounts
*/
private function applyStoreOnlyExpense(
array &$rows,
array $amounts,
string $field,
string $fallbackPlatform,
): void {
$preferredKeys = [];
foreach ($rows as $key => $row) {
$storeName = trim((string) $row['store_name']);
if (! array_key_exists($storeName, $amounts)) {
continue;
}
$preferredKey = $preferredKeys[$storeName] ?? null;
if ($preferredKey === null
|| [
(float) $row['declared_income'],
(string) $row['platform'],
] > [
(float) $rows[$preferredKey]['declared_income'],
(string) $rows[$preferredKey]['platform'],
]) {
$preferredKeys[$storeName] = $key;
}
}
foreach ($rows as &$row) {
$row[$field] = 0.0;
}
unset($row);
foreach ($amounts as $storeName => $amount) {
$storeName = trim((string) $storeName);
$key = $preferredKeys[$storeName] ?? null;
if ($key === null) {
$platform = $fallbackPlatform;
$key = $platform . "\0" . $storeName;
$rows[$key] ??= $this->financialAnalysisEmptyRow($platform, $storeName);
}
$rows[$key][$field] = round((float) $amount, 2);
}
}
/** 科目映射变化时自动换缓存键,避免费用拆票结果在 5 分钟缓存内继续使用旧口径。 */
private function financialAnalysisMappingSignature(): string
{

View File

@ -87,8 +87,10 @@
推广费用-有票取聚水潭「平台费用(新)→ 推广费(店铺)」按店铺月度支出汇总。
安装费取安装明细中客服审核为“已审核”、按客服审核时间归属月份,并汇总结算明细金额;
同一店铺出现多个平台行时,安装费归入申报收入最高的一行,避免重复计入。
快递运费取快递运费明细的来源月份与店铺,结算运费 = 提供成本运费 + 运费差,
再按交易单号加计其他附加费汇总和退件费;同一月份同一交易单号的多条汇总金额全部相加。
京东网银钱包不纳入本表。
快递运费、售后费用-小额打款、管理费用和人工费用尚未建立统一的店铺月汇总,显示为“—”;
售后费用-小额打款、管理费用和人工费用尚未建立统一的店铺月汇总,显示为“—”;
上述费用口径齐备后自动计算净利润。
</div>
@ -102,6 +104,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['courier_freight_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

@ -0,0 +1,198 @@
<?php
namespace Tests\Feature\Business;
use App\Business\CourierPayableSummaryStore;
use App\Models\Auth\Permission;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Mockery;
use Modules\EcommerceFinance\Repositories\InstallationDetailMirrorRepository;
use Modules\EcommerceFinance\Repositories\PromotionMarketingExpenseRepository;
use Modules\EcommerceFinance\View\BillingDetailsPageData;
use Tests\Feature\FeatureTestCase;
class FinancialAnalysisCourierFreightTest extends FeatureTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->user->attachPermission(
Permission::where('name', 'read-admin-panel')->firstOrFail()
);
}
public function test_financial_analysis_sums_courier_fees_by_month_and_store_without_deduplication(): void
{
Storage::fake('uploads');
Cache::flush();
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
Schema::connection('business_mirror')->create('store_receipt_order_match_rows', function (Blueprint $table): void {
$table->date('report_month');
$table->string('platform');
$table->string('store_name');
$table->decimal('income_amount', 20, 4)->default(0);
$table->decimal('discount_amount', 20, 4)->nullable();
$table->decimal('offset_amount', 20, 4)->nullable();
$table->decimal('default_compensation_amount', 20, 4)->nullable();
$table->decimal('refund_amount', 20, 4)->nullable();
});
Schema::connection('business_mirror')->create('store_receipt_product_cost_rows', function (Blueprint $table): void {
$table->date('report_month');
$table->string('platform');
$table->string('store_name');
$table->decimal('product_cost', 20, 4)->nullable();
});
foreach ([
['platform' => '淘系支付宝', 'income_amount' => 1000],
['platform' => '淘系微信', 'income_amount' => 100],
] as $income) {
DB::connection('business_mirror')->table('store_receipt_order_match_rows')->insert([
'report_month' => '2026-11-01',
'platform' => $income['platform'],
'store_name' => '测试店铺',
'income_amount' => $income['income_amount'],
'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' => '淘系支付宝',
'store_name' => '测试店铺',
'product_cost' => 300,
]);
foreach ([
['part' => '成品运费', 'freight_amount' => 10],
['part' => '配件运费', 'freight_amount' => 5],
] as $base) {
DB::table('courier_freight_rows')->insert([
'company_id' => $this->company->id,
'source' => '提供成本11月汇总',
'part' => $base['part'],
'transaction_no' => 'T-COURIER',
'shop_name' => '测试店铺',
'freight_amount' => $base['freight_amount'],
'created_at' => '2026-11-20 10:00:00',
'updated_at' => '2026-11-20 10:00:00',
]);
}
$store = app(CourierPayableSummaryStore::class);
$this->putSummarySnapshot($store, 'freight-difference', [
['日期', '交易单号', '差异(结算运费-提供成本运费)'],
['2026-11-02', 'T-COURIER', '0.5'],
['2026-11-03', 'T-COURIER', '0.25'],
['2026-10-15', 'T-COURIER', '1000'],
]);
$this->putSummarySnapshot($store, 'other-surcharge-summary', [
['日期', '交易单号', '金额'],
['2026-11-04', 'T-COURIER', '1.5'],
['2026-11-05', 'T-COURIER', '3'],
['2026-10-15', 'T-COURIER', '1000'],
]);
$this->putSummarySnapshot($store, 'return-fee', [
['日期', '交易订单', '结算金额'],
['2026-11-06', 'T-COURIER', '2.25'],
['2026-11-07', 'T-COURIER', '0.25'],
['2026-10-15', 'T-COURIER', '1000'],
]);
$this->app->instance(BillingDetailsPageData::class, new class {
public function expenseBucketsForMonth(string $reportMonth): array
{
return [];
}
});
$this->app->instance(PromotionMarketingExpenseRepository::class, new class {
public function promotionStoreExpenseBucketsForMonths(array $reportMonths): array
{
return [];
}
});
$installation = Mockery::mock(InstallationDetailMirrorRepository::class);
$installation->shouldReceive('settlementAmountBucketsForCustomerReviewMonths')
->andReturn([]);
$this->app->instance(InstallationDetailMirrorRepository::class, $installation);
$this->loginAs()->get(route('business.pages.show', [
'section' => 'financial-operations',
'page' => 'financial-analysis',
'month' => '2026-11',
]))
->assertOk()
->assertViewHas('content', function (array $content): bool {
$storeRows = collect($content['financialAnalysisRows']->items())
->where('store_name', '测试店铺');
$freight = $storeRows->sum(static fn (array $row): float => (float) $row['freight']);
return $storeRows->count() === 2
&& round($freight, 2) === 22.75
&& round(max($storeRows->pluck('freight')->map(static fn ($value): float => (float) $value)->all()), 2) === 22.75;
})
->assertViewHas('content', static function (array $content): bool {
return round((float) $content['financialAnalysisSummary']['courier_freight_expense_total'], 2) === 22.75;
})
->assertSeeText('快递运费合计')
->assertSeeText('22.75');
$csv = $this->loginAs()
->get(route('business.financial-operations.financial-analysis.export', [
'month' => '2026-11',
]))
->streamedContent();
$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(
22.75,
round(array_sum(array_map(
static fn (array $row): float => (float) ($row[11] ?? 0),
$storeRows,
)), 2),
);
}
/** @param list<list<string>> $rows */
private function putSummarySnapshot(
CourierPayableSummaryStore $store,
string $page,
array $rows,
): void {
$headers = array_shift($rows);
Storage::disk('uploads')->put($store->path((int) $this->company->id, $page), json_encode([
'version' => 1,
'headers' => $headers,
'rows' => $rows,
'source_name' => $page . '.csv',
'imported_at' => now()->toIso8601String(),
'imported_by' => $this->user->id,
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
}