diff --git a/app/Business/ThirdPartyWarehouseQuoteRepository.php b/app/Business/ThirdPartyWarehouseQuoteRepository.php index ca8d3e33b..dfd953bdd 100644 --- a/app/Business/ThirdPartyWarehouseQuoteRepository.php +++ b/app/Business/ThirdPartyWarehouseQuoteRepository.php @@ -3,6 +3,7 @@ namespace App\Business; use App\Models\Business\ThirdPartyWarehouseQuote; +use Carbon\CarbonInterface; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Schema; @@ -52,6 +53,42 @@ class ThirdPartyWarehouseQuoteRepository ]; } + /** + * Return active quote versions that may apply on or before the settlement end date. + * + * @return Collection> + */ + public function settlementQuotes(string $warehouseName, CarbonInterface|string $throughDate): Collection + { + if (! $this->ready()) { + return collect(); + } + + $normalizedName = preg_replace('/^\s*三方-/u', '', trim($warehouseName)) ?: trim($warehouseName); + $aliases = array_values(array_unique(array_filter([ + trim($warehouseName), + $normalizedName, + '三方-' . $normalizedName, + ]))); + $date = $throughDate instanceof CarbonInterface + ? $throughDate->toDateString() + : trim($throughDate); + + try { + return ThirdPartyWarehouseQuote::query() + ->whereIn('warehouse_name', $aliases) + ->where('status', ThirdPartyWarehouseQuote::STATUS_ACTIVE) + ->whereDate('effective_at', '<=', $date) + ->orderBy('effective_at') + ->orderBy('id') + ->get() + ->map(fn (ThirdPartyWarehouseQuote $quote): array => $this->present($quote)) + ->values(); + } catch (QueryException) { + return collect(); + } + } + /** @param array $data */ public function create(array $data, int $userId): ThirdPartyWarehouseQuote { diff --git a/modules/EcommerceFinance/Http/Controllers/ThirdPartyWarehouseStorageSettlementExportController.php b/modules/EcommerceFinance/Http/Controllers/ThirdPartyWarehouseStorageSettlementExportController.php new file mode 100644 index 000000000..9727e01c3 --- /dev/null +++ b/modules/EcommerceFinance/Http/Controllers/ThirdPartyWarehouseStorageSettlementExportController.php @@ -0,0 +1,41 @@ +__invoke($request, $settlement); + } + + public function __invoke(Request $request, ThirdPartyWarehouseStorageSettlementService $settlement): StreamedResponse + { + $filters = $request->only(['dimension', 'period', 'sku_code', 'product_name', 'supplier', 'category']); + $result = $settlement->settle($filters); + abort_unless($result['ready'] && $result['complete'], 422, $result['message'] ?? '核算资料尚未准备完成。'); + + $filename = '三方仓进销存仓储费核算-' . ($result['filters']['period'] ?? '2026-08') . '.csv'; + return response()->streamDownload(function () use ($result): void { + $out = fopen('php://output', 'wb'); + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, ['日期', '商品编码', '商品名称', '重量(kg)', '采购进仓', '销售出仓', '其它出库', '期末库存', '入库管理费', '出库费用', '仓储费', '合计', '报价生效日期']); + foreach ($result['rows'] as $row) { + fputcsv($out, [ + $row['date'] ?? '', $row['sku_code'] ?? '', $row['product_name'] ?? '', + $row['weight_kg'], $row['purchase_in'] ?? 0, $row['sales_out'] ?? 0, + $row['other_out'] ?? 0, $row['closing_qty'] ?? 0, + number_format((float) ($row['inbound_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['outbound_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['storage_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['total_fee'] ?? 0), 2, '.', ''), $row['quote_effective_at'] ?? '', + ]); + } + fclose($out); + }, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']); + } +} diff --git a/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSettlementService.php b/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSettlementService.php new file mode 100644 index 000000000..2f997db98 --- /dev/null +++ b/modules/EcommerceFinance/Services/ThirdPartyWarehouseStorageSettlementService.php @@ -0,0 +1,160 @@ + $filters @return array */ + public function settle(array $filters): array + { + $filters = $this->normaliseFilters($filters); + if (! $this->mirror->ready()) { + return $this->emptyResult('进销存镜像尚未完成首次同步。', false); + } + + $rawRows = iterator_to_array($this->mirror->exportRows($filters), false); + if ($rawRows === []) { + return $this->emptyResult('当前期间及筛选条件下没有进销存明细。', true); + } + + $weights = $this->weights($rawRows); + $daysInMonth = $this->daysInMonth((string) $filters['period'], (string) $filters['dimension']); + $quoteCache = []; + $rows = []; + $missingWeight = []; + $missingQuote = []; + $inbound = $outbound = $storage = 0.0; + + foreach ($rawRows as $row) { + $date = (string) ($row['date'] ?? ''); + $quote = $quoteCache[$date] ??= $this->quoteForDate($date); + if ($quote === null) { + $missingQuote[$date] = true; + } + + $sku = (string) ($row['sku_code'] ?? ''); + $weight = $weights[$sku] ?? null; + if ($weight === null && (float) ($row['purchase_in'] ?? 0) != 0.0) { + $missingWeight[$sku] = true; + } + + $purchaseIn = max(0.0, (float) ($row['purchase_in'] ?? 0)); + $salesOut = abs(min(0.0, (float) ($row['sales_out'] ?? 0))); + $otherOut = abs(min(0.0, (float) ($row['other_out'] ?? 0))); + $closing = max(0.0, (float) ($row['closing_qty'] ?? 0)); + // A zero inbound quantity does not require a product weight. Only a + // positive inbound quantity is blocked by a missing weight. + $inFee = $purchaseIn <= 0.0 + ? 0.0 + : ($quote !== null && $weight !== null + ? $purchaseIn * $weight / 1000 * (float) $quote['inbound_rate_per_ton'] + : null); + $outFee = $quote !== null + ? ($salesOut + $otherOut) * (float) $quote['outbound_rate_per_order'] + : null; + $storageFee = $quote !== null + ? $closing / max((float) $quote['pieces_per_pallet'], 0.0001) + * (float) $quote['pallet_area_sqm'] + * (float) $quote['storage_rate_per_sqm_month'] / $daysInMonth + : null; + $total = $inFee === null || $outFee === null || $storageFee === null + ? null + : $inFee + $outFee + $storageFee; + + if ($inFee !== null) $inbound += $inFee; + if ($outFee !== null) $outbound += $outFee; + if ($storageFee !== null) $storage += $storageFee; + $rows[] = $row + [ + 'weight_kg' => $weight, + 'inbound_fee' => $inFee, + 'outbound_fee' => $outFee, + 'storage_fee' => $storageFee, + 'total_fee' => $total, + 'quote_effective_at' => $quote['effective_at'] ?? null, + ]; + } + + $complete = $missingWeight === [] && $missingQuote === []; + return [ + 'ready' => true, + 'complete' => $complete, + 'message' => $complete ? null : '报价或商品重量资料不完整,金额仅供核对,不能作为最终结算。', + 'rows' => $rows, + 'inbound_fee' => $complete ? $inbound : null, + 'outbound_fee' => $complete ? $outbound : null, + 'storage_fee' => $complete ? $storage : null, + 'total_fee' => $complete ? $inbound + $outbound + $storage : null, + 'missing_weight_skus' => array_keys($missingWeight), + 'missing_quote_dates' => array_keys($missingQuote), + 'days_in_month' => $daysInMonth, + 'filters' => $filters, + ]; + } + + /** @param list> $rows @return array */ + private function weights(array $rows): array + { + $codes = collect($rows)->pluck('sku_code')->filter()->unique()->values(); + if ($codes->isEmpty()) return []; + $connection = $this->databases->connection((string) config('upstream_mirrors.connection', 'business_mirror')); + $result = []; + foreach ($codes->chunk(1000) as $chunk) { + try { + $connection->table('ops_jst_sku')->where('sku_type', 'normal')->whereIn('sku_id', $chunk->all()) + ->orderByDesc('autoid')->get(['sku_id', 'weight'])->each(function (object $item) use (&$result): void { + if (! array_key_exists((string) $item->sku_id, $result) && is_numeric($item->weight)) { + $result[(string) $item->sku_id] = (float) $item->weight; + } + }); + } catch (\Throwable) { + return []; + } + } + return $result; + } + + /** @return array|null */ + private function quoteForDate(string $date): ?array + { + $quotes = $this->quotes->settlementQuotes('三方-南昌樵舍仓', $date); + return $quotes->last() ?: null; + } + + private function daysInMonth(string $period, string $dimension): int + { + try { + return $dimension === 'day' ? (int) date('t', strtotime($period)) : (int) date('t', strtotime($period . '-01')); + } catch (\Throwable) { + return 31; + } + } + + /** @param array $filters @return array */ + private function normaliseFilters(array $filters): array + { + $dimension = in_array(($filters['dimension'] ?? 'month'), ['month', 'day'], true) ? $filters['dimension'] : 'month'; + $period = trim((string) ($filters['period'] ?? '2026-08')); + if ($dimension === 'month' && preg_match('/^\d{4}-\d{2}$/', $period) !== 1) $period = '2026-08'; + if ($dimension === 'day' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $period) !== 1) $period = '2026-08-01'; + return ['dimension' => $dimension, 'period' => $period] + $filters; + } + + /** @return array */ + private function emptyResult(string $message, bool $ready): array + { + return ['ready' => $ready, 'complete' => false, 'message' => $message, 'rows' => [], 'inbound_fee' => null, 'outbound_fee' => null, 'storage_fee' => null, 'total_fee' => null, 'missing_weight_skus' => [], 'missing_quote_dates' => [], 'days_in_month' => 31, 'filters' => []]; + } +} diff --git a/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php b/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php index de7a19480..d192f2f3c 100644 --- a/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php +++ b/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php @@ -87,6 +87,19 @@ : (is_countable($rows) ? count($rows) : 0); $summaryReady = ! $pending && collect(['count', 'opening_qty', 'closing_qty']) ->every(static fn (string $key): bool => array_key_exists($key, $summary)); + $settlement = [ + 'ready' => false, 'complete' => false, + 'inbound_fee' => 0, 'outbound_fee' => 0, 'storage_fee' => 0, 'total_fee' => 0, + 'message' => null, + ]; + if ($summaryReady) { + try { + $settlement = app(\Modules\EcommerceFinance\Services\ThirdPartyWarehouseStorageSettlementService::class)->settle($filters); + } catch (\Throwable) { + $settlement['message'] = '仓储费暂时无法核算,请稍后重试。'; + } + } + $settlementComplete = ($settlement['ready'] ?? false) && ($settlement['complete'] ?? false); $showingLastVersion = $rowTotal > 0 && ($error !== '' || in_array($statusCode, [ 'syncing', 'reconciling', 'stale', 'delayed', 'failed', ], true)); @@ -95,6 +108,7 @@ $filters, static fn (mixed $value): bool => $value !== null && $value !== '' ); + $settlementExportUrl = route('business.courier-payables.third-party-warehouse-storage.settlement-export', $activeFilters); if (is_object($rows) && method_exists($rows, 'appends')) { $rows->appends($activeFilters); } @@ -219,7 +233,7 @@ .third-party-warehouse-actions [data-finance-server-export] { display:none; } .third-party-warehouse-page[data-finance-enhanced] .third-party-warehouse-actions [data-finance-server-export] { display:inline-flex; } .third-party-warehouse-page .finance-table-field-picker__panel { right:0; left:auto; } - .third-party-warehouse-summary { display:grid; grid-template-columns:repeat(5,minmax(8rem,1fr)); overflow:hidden; border:1px solid var(--warehouse-border); border-radius:.5rem; background:#fff; } + .third-party-warehouse-summary { display:grid; grid-template-columns:repeat(7,minmax(8rem,1fr)); overflow:hidden; border:1px solid var(--warehouse-border); border-radius:.5rem; background:#fff; } .third-party-warehouse-summary__item { min-width:0; padding:.625rem .75rem; border-right:1px solid var(--warehouse-border); } .third-party-warehouse-summary__item:last-child { border-right:0; } .third-party-warehouse-summary__label { display:block; color:var(--warehouse-muted); font-size:.7rem; } @@ -363,6 +377,13 @@ + $settlementComplete, 'is-disabled' => ! $settlementComplete]) + href="{{ $settlementComplete ? $settlementExportUrl : '#' }}" + @if (! $settlementComplete) aria-disabled="true" @endif + > + 导出仓储费核算 +
+ @if (! empty($settlement['message'])) +
+ + {{ $settlement['message'] }} +
+ @endif +
name('business.store-account-passwords.reveal-visible-page'); @@ -146,6 +147,11 @@ Route::get('workspace/courier-payables/third-party-warehouse-storage/export', 'B ->middleware('business.page:courier-payables,third-party-warehouse-storage') ->name('business.courier-payables.third-party-warehouse-storage.export'); +Route::get('workspace/courier-payables/third-party-warehouse-storage/settlement-export', + [ThirdPartyWarehouseStorageSettlementExportController::class, 'export']) + ->middleware('business.page:courier-payables,third-party-warehouse-storage') + ->name('business.courier-payables.third-party-warehouse-storage.settlement-export'); + Route::get('workspace/{section}/{page}/{tab}/export', 'Business\Pages@export') ->name('business.pages.export'); diff --git a/tests/Feature/Business/ThirdPartyWarehouseStoragePageTest.php b/tests/Feature/Business/ThirdPartyWarehouseStoragePageTest.php index 250e50c17..01bc82ff1 100644 --- a/tests/Feature/Business/ThirdPartyWarehouseStoragePageTest.php +++ b/tests/Feature/Business/ThirdPartyWarehouseStoragePageTest.php @@ -6,10 +6,28 @@ use App\Models\Auth\Permission; use Illuminate\Support\Carbon; use Mockery; use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository; +use Modules\EcommerceFinance\Services\ThirdPartyWarehouseStorageSettlementService; use Tests\Feature\FeatureTestCase; class ThirdPartyWarehouseStoragePageTest extends FeatureTestCase { + protected function setUp(): void + { + parent::setUp(); + + $settlement = Mockery::mock(ThirdPartyWarehouseStorageSettlementService::class); + $settlement->shouldReceive('settle')->zeroOrMoreTimes()->andReturn([ + 'ready' => false, + 'complete' => false, + 'message' => null, + 'inbound_fee' => null, + 'outbound_fee' => null, + 'storage_fee' => null, + 'total_fee' => null, + ]); + $this->app->instance(ThirdPartyWarehouseStorageSettlementService::class, $settlement); + } + protected function tearDown(): void { Carbon::setTestNow(); diff --git a/tests/Unit/EcommerceFinance/ThirdPartyWarehouseStorageSettlementServiceTest.php b/tests/Unit/EcommerceFinance/ThirdPartyWarehouseStorageSettlementServiceTest.php new file mode 100644 index 000000000..2c93e9b48 --- /dev/null +++ b/tests/Unit/EcommerceFinance/ThirdPartyWarehouseStorageSettlementServiceTest.php @@ -0,0 +1,235 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('ops_jst_sku', function (Blueprint $table): void { + $table->increments('autoid'); + $table->string('sku_id'); + $table->string('sku_type')->nullable(); + $table->decimal('weight', 18, 4)->nullable(); + }); + } + + public function test_it_calculates_daily_storage_and_switches_quote_versions_by_effective_date(): void + { + DB::connection('business_mirror')->table('ops_jst_sku')->insert([ + ['autoid' => 1, 'sku_id' => 'SKU-A', 'sku_type' => 'normal', 'weight' => 500], + ]); + + $mirror = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); + $mirror->shouldReceive('ready')->once()->andReturnTrue(); + $mirror->shouldReceive('exportRows')->once()->with(Mockery::subset([ + 'dimension' => 'month', + 'period' => '2026-08', + ]))->andReturn($this->rows()); + + $quotes = Mockery::mock(ThirdPartyWarehouseQuoteRepository::class); + $quotes->shouldReceive('settlementQuotes')->twice()->andReturnUsing( + static fn (string $warehouse, string $date): Collection => $date === '2026-08-02' + ? collect([ + self::quote('2026-08-01', 20, 0.85, 23, 3, 10.5), + self::quote('2026-08-02', 30, 0.9, 23, 3, 10.5), + ]) + : collect([self::quote('2026-08-01', 20, 0.85, 23, 3, 10.5)]), + ); + + $result = $this->service($mirror, $quotes)->settle([ + 'dimension' => 'month', + 'period' => '2026-08', + ]); + + $this->assertTrue($result['complete']); + $this->assertSame(31, $result['days_in_month']); + $this->assertEqualsWithDelta(10000.0, $result['inbound_fee'], 0.000001); + $this->assertEqualsWithDelta(3.45, $result['outbound_fee'], 0.000001); + $this->assertEqualsWithDelta((23 / 23 * 3 * 10.5 / 31) + (46 / 23 * 3 * 10.5 / 31), $result['storage_fee'], 0.000001); + $this->assertEqualsWithDelta($result['inbound_fee'] + $result['outbound_fee'] + $result['storage_fee'], $result['total_fee'], 0.000001); + $this->assertSame(10000.0, $result['rows'][0]['inbound_fee']); + $this->assertSame('2026-08-02', $result['rows'][1]['quote_effective_at']); + } + + public function test_missing_weight_or_quote_does_not_produce_a_final_amount(): void + { + $mirror = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); + $mirror->shouldReceive('ready')->once()->andReturnTrue(); + $mirror->shouldReceive('exportRows')->once()->andReturn((static function (): \Generator { + yield [ + 'date' => '2026-08-01', + 'sku_code' => 'SKU-MISSING', + 'product_name' => '缺资料商品', + 'purchase_in' => 10, + 'sales_out' => 0, + 'other_out' => 0, + 'closing_qty' => 1, + ]; + })()); + + $quotes = Mockery::mock(ThirdPartyWarehouseQuoteRepository::class); + $quotes->shouldReceive('settlementQuotes')->once()->andReturn(collect()); + + $result = $this->service($mirror, $quotes)->settle([ + 'dimension' => 'month', + 'period' => '2026-08', + ]); + + $this->assertFalse($result['complete']); + $this->assertNull($result['total_fee']); + $this->assertSame(['SKU-MISSING'], $result['missing_weight_skus']); + $this->assertSame(['2026-08-01'], $result['missing_quote_dates']); + } + + public function test_zero_inbound_quantity_does_not_require_a_weight(): void + { + $mirror = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); + $mirror->shouldReceive('ready')->once()->andReturnTrue(); + $mirror->shouldReceive('exportRows')->once()->andReturn((static function (): \Generator { + yield [ + 'date' => '2026-08-01', + 'sku_code' => 'SKU-WITHOUT-WEIGHT', + 'product_name' => '无采购商品', + 'purchase_in' => 0, + 'sales_out' => -2, + 'other_out' => 0, + 'closing_qty' => 23, + ]; + })()); + + $quotes = Mockery::mock(ThirdPartyWarehouseQuoteRepository::class); + $quotes->shouldReceive('settlementQuotes')->once()->andReturn(collect([ + self::quote('2026-08-01', 20, 0.85, 23, 3, 10.5), + ])); + + $result = $this->service($mirror, $quotes)->settle([ + 'dimension' => 'day', + 'period' => '2026-08-01', + ]); + + $this->assertTrue($result['complete']); + $this->assertSame([], $result['missing_weight_skus']); + $this->assertSame(0.0, $result['rows'][0]['inbound_fee']); + $this->assertEqualsWithDelta(0.85 * 2, $result['total_fee'] - $result['storage_fee'], 0.000001); + } + + public function test_complete_settlement_can_be_exported_as_utf8_csv(): void + { + $settlement = Mockery::mock(ThirdPartyWarehouseStorageSettlementService::class); + $settlement->shouldReceive('settle')->once()->with([ + 'dimension' => 'month', + 'period' => '2026-08', + 'sku_code' => '', + 'product_name' => '', + 'supplier' => '', + 'category' => '', + ])->andReturn([ + 'ready' => true, + 'complete' => true, + 'message' => null, + 'filters' => ['period' => '2026-08'], + 'rows' => [[ + 'date' => '2026-08-01', + 'sku_code' => 'SKU-001', + 'product_name' => '测试商品', + 'weight_kg' => 12.5, + 'purchase_in' => 10, + 'sales_out' => -2, + 'other_out' => -1, + 'closing_qty' => 7, + 'inbound_fee' => 2.5, + 'outbound_fee' => 2.55, + 'storage_fee' => 0.31, + 'total_fee' => 5.36, + 'quote_effective_at' => '2026-08-01', + ]], + ]); + + $response = (new ThirdPartyWarehouseStorageSettlementExportController())->export( + Request::create('/settlement-export', 'GET', [ + 'dimension' => 'month', + 'period' => '2026-08', + 'sku_code' => '', + 'product_name' => '', + 'supplier' => '', + 'category' => '', + ]), + $settlement, + ); + + ob_start(); + $response->sendContent(); + $content = (string) ob_get_clean(); + $this->assertStringStartsWith(chr(0xEF) . chr(0xBB) . chr(0xBF), $content); + $this->assertStringContainsString('日期,商品编码,商品名称', $content); + $this->assertStringContainsString('2026-08-01,SKU-001,测试商品,12.5,10,-2,-1,7,2.50,2.55,0.31,5.36,2026-08-01', $content); + } + + /** @return \Generator> */ + private function rows(): \Generator + { + yield [ + 'date' => '2026-08-01', + 'sku_code' => 'SKU-A', + 'product_name' => '商品 A', + 'purchase_in' => 1000, + 'sales_out' => -2, + 'other_out' => -1, + 'closing_qty' => 23, + ]; + yield [ + 'date' => '2026-08-02', + 'sku_code' => 'SKU-A', + 'product_name' => '商品 A', + 'purchase_in' => 0, + 'sales_out' => -1, + 'other_out' => 0, + 'closing_qty' => 46, + ]; + } + + /** @return array */ + private static function quote(string $effectiveAt, float $inbound, float $outbound, float $pieces, float $area, float $storage): array + { + return [ + 'effective_at' => $effectiveAt, + 'inbound_rate_per_ton' => $inbound, + 'outbound_rate_per_order' => $outbound, + 'pieces_per_pallet' => $pieces, + 'pallet_area_sqm' => $area, + 'storage_rate_per_sqm_month' => $storage, + ]; + } + + private function service( + ThirdPartyWarehouseStorageMirrorRepository $mirror, + ThirdPartyWarehouseQuoteRepository $quotes, + ): ThirdPartyWarehouseStorageSettlementService { + return new ThirdPartyWarehouseStorageSettlementService($mirror, $quotes, app('db')); + } +}