From b2f7a072c8cf1cd81ef2283b14780f5ab7b7c655 Mon Sep 17 00:00:00 2001 From: chenxi Date: Fri, 27 Nov 2026 01:12:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=B4=A2=E5=8A=A1=E7=BB=8F=E8=90=A5?= =?UTF-8?q?=E5=88=86=E6=9E=90):=20=E6=8E=A5=E5=85=A5=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E8=BF=90=E8=B4=B9=E6=9C=88=E5=BA=A6=E5=BA=97=E9=93=BA=E6=B1=87?= =?UTF-8?q?=E6=80=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CourierFreightFinancialSummary.php | 152 ++++++++++++++ app/Business/CourierPayableSummaryMap.php | 100 +++++++++ app/Http/Controllers/Business/Pages.php | 93 +++++++- .../financial-analysis.blade.php | 5 +- .../FinancialAnalysisCourierFreightTest.php | 198 ++++++++++++++++++ 5 files changed, 546 insertions(+), 2 deletions(-) create mode 100644 app/Business/CourierFreightFinancialSummary.php create mode 100644 tests/Feature/Business/FinancialAnalysisCourierFreightTest.php diff --git a/app/Business/CourierFreightFinancialSummary.php b/app/Business/CourierFreightFinancialSummary.php new file mode 100644 index 00000000..a83c5c91 --- /dev/null +++ b/app/Business/CourierFreightFinancialSummary.php @@ -0,0 +1,152 @@ + $reportMonths YYYY-MM + * @return array> 月份 => [店铺 => 快递运费] + */ + 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 $reportMonths + */ + private function sourceMonth(string $source, string $importedAt, array $reportMonths): ?string + { + $source = trim($source); + if ($source === '') { + return null; + } + + if (preg_match( + '/(?> 月份 => [交易单号 => 金额] + */ + 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 */ private function build(int $companyId, string $page): array { @@ -135,6 +172,69 @@ class CourierPayableSummaryMap return $map; } + /** @return array> */ + 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( + '/(? $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|null $promotionExpenseBuckets * @param array|null $installationExpenseBuckets + * @param array|null $courierFreightBuckets * @return array> */ 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> $rows + * @param array $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 { diff --git a/resources/views/business/pages/financial-operations/financial-analysis.blade.php b/resources/views/business/pages/financial-operations/financial-analysis.blade.php index 23b00677..25c71526 100644 --- a/resources/views/business/pages/financial-operations/financial-analysis.blade.php +++ b/resources/views/business/pages/financial-operations/financial-analysis.blade.php @@ -87,8 +87,10 @@ 推广费用-有票取聚水潭「平台费用(新)→ 推广费(店铺)」按店铺月度支出汇总。 安装费取安装明细中客服审核为“已审核”、按客服审核时间归属月份,并汇总结算明细金额; 同一店铺出现多个平台行时,安装费归入申报收入最高的一行,避免重复计入。 + 快递运费取快递运费明细的来源月份与店铺,结算运费 = 提供成本运费 + 运费差, + 再按交易单号加计其他附加费汇总和退件费;同一月份同一交易单号的多条汇总金额全部相加。 京东网银钱包不纳入本表。 - 快递运费、售后费用-小额打款、管理费用和人工费用尚未建立统一的店铺月汇总,显示为“—”; + 售后费用-小额打款、管理费用和人工费用尚未建立统一的店铺月汇总,显示为“—”; 上述费用口径齐备后自动计算净利润。 @@ -102,6 +104,7 @@
账单费用-有票合计{{ $money($summary['bill_invoice_expense_total'] ?? null) }}
账单费用-无票合计{{ $money($summary['bill_non_invoice_expense_total'] ?? null) }}
推广费用-有票合计{{ $money($summary['promotion_invoice_expense_total'] ?? null) }}
+
快递运费合计{{ $money($summary['courier_freight_expense_total'] ?? null) }}
安装费合计{{ $money($summary['installation_expense_total'] ?? null) }}
净利润合计{{ $money($summary['net_profit_total'] ?? null) }}
diff --git a/tests/Feature/Business/FinancialAnalysisCourierFreightTest.php b/tests/Feature/Business/FinancialAnalysisCourierFreightTest.php new file mode 100644 index 00000000..1464f227 --- /dev/null +++ b/tests/Feature/Business/FinancialAnalysisCourierFreightTest.php @@ -0,0 +1,198 @@ +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> $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)); + } +}