diff --git a/app/Business/PlantingDetailImporter.php b/app/Business/PlantingDetailImporter.php new file mode 100644 index 00000000..fd7d9b13 --- /dev/null +++ b/app/Business/PlantingDetailImporter.php @@ -0,0 +1,298 @@ + 'bill_date', + '订单编号' => 'order_no', + '财务售价' => 'finance_selling_price', + '财务运费' => 'finance_freight', + '财务佣金' => 'finance_commission', + '京喜差价' => 'jingxi_price_diff', + '扣款' => 'deduction', + '财务空包费' => 'finance_empty_package_fee', + '财务打款金额' => 'finance_payment_amount', + '笔数' => 'pieces', + '备注' => 'remark', + '正确店铺' => 'store', + '负责人' => 'owner', + '账户' => 'account', + '类型' => 'type', + '创建人' => 'creator', + '标签' => 'tag', + '所属利润中心' => 'profit_center', + '负责平台' => 'responsible_platform', + 'ID' => 'external_id', + ]; + + private const MONEY_COLUMNS = [ + 'finance_selling_price', 'finance_freight', 'finance_commission', + 'jingxi_price_diff', 'deduction', 'finance_empty_package_fee', 'finance_payment_amount', + ]; + + private const CHUNK = 1000; + + /** + * @return array{rows:int,inserted:int,skipped:int,selling_price:string,payment_amount:string,date_min:?string,date_max:?string} + */ + public function import(string $path, int $companyId = 1, bool $replace = false, ?int $userId = null, string $source = 'planting-detail-import'): array + { + if (! is_file($path)) { + throw new InvalidArgumentException('找不到要导入的文件:' . $path); + } + + $grid = $this->read($path); + if ($grid === []) { + throw new InvalidArgumentException('文件里没有可读的数据行。'); + } + + $headerIndex = $this->locateHeader($grid); + if ($headerIndex === null) { + throw new InvalidArgumentException('没找到表头:至少要有「日期」「订单编号」「财务打款金额」。'); + } + + $map = $this->mapHeader($grid[$headerIndex]); + if (! isset($map['bill_date'], $map['order_no'], $map['finance_payment_amount'])) { + throw new InvalidArgumentException('表头缺少「日期」或「订单编号」或「财务打款金额」。'); + } + + $now = now(); + $rows = []; + $skipped = 0; + $sellingPrice = 0.0; + $paymentAmount = 0.0; + $dateMin = null; + $dateMax = null; + $inserted = 0; + + $connection = DB::connection(); + if ($replace) { + PlantingDetail::query()->where('company_id', $companyId)->forceDelete(); + } + + $flush = function () use (&$rows, &$inserted, $connection): void { + if ($rows !== []) { + foreach (array_chunk($rows, self::CHUNK) as $chunk) { + $connection->table('planting_details')->insert($chunk); + $inserted += count($chunk); + } + $rows = []; + } + }; + + foreach (array_slice($grid, $headerIndex + 1) as $gridRow) { + if (! $this->hasContent($gridRow)) { + continue; + } + + $date = $this->toDate($this->cell($gridRow, $map, 'bill_date')); + $orderNo = $this->toText($this->cell($gridRow, $map, 'order_no')); + if ($date === null || $orderNo === null) { + $skipped++; + + continue; + } + + $record = [ + 'company_id' => $companyId, + 'bill_date' => $date, + 'order_no' => mb_substr($orderNo, 0, 100), + 'pieces' => (int) ($this->toNumber($this->cell($gridRow, $map, 'pieces')) ?? 0), + 'remark' => $this->toText($this->cell($gridRow, $map, 'remark')), + 'store' => $this->toText($this->cell($gridRow, $map, 'store')), + 'owner' => $this->toText($this->cell($gridRow, $map, 'owner')), + 'account' => $this->toText($this->cell($gridRow, $map, 'account')), + 'type' => $this->toText($this->cell($gridRow, $map, 'type')), + 'creator' => $this->toText($this->cell($gridRow, $map, 'creator')), + 'tag' => $this->toText($this->cell($gridRow, $map, 'tag')), + 'profit_center' => $this->toText($this->cell($gridRow, $map, 'profit_center')), + 'responsible_platform' => $this->toText($this->cell($gridRow, $map, 'responsible_platform')), + 'external_id' => $this->toText($this->cell($gridRow, $map, 'external_id')), + 'created_from' => $source, + 'created_by' => $userId, + 'created_at' => $now, + 'updated_at' => $now, + ]; + + foreach (self::MONEY_COLUMNS as $column) { + $value = $this->toNumber($this->cell($gridRow, $map, $column)) ?? 0.0; + $record[$column] = number_format($value, 4, '.', ''); + } + $sellingPrice += (float) $record['finance_selling_price']; + $paymentAmount += (float) $record['finance_payment_amount']; + + $dateMin = $dateMin === null || $date < $dateMin ? $date : $dateMin; + $dateMax = $dateMax === null || $date > $dateMax ? $date : $dateMax; + + $rows[] = $record; + if (count($rows) >= self::CHUNK * 4) { + $flush(); + } + } + + $flush(); + + return [ + 'rows' => $inserted + $skipped, + 'inserted' => $inserted, + 'skipped' => $skipped, + 'selling_price' => number_format($sellingPrice, 4, '.', ''), + 'payment_amount' => number_format($paymentAmount, 4, '.', ''), + 'date_min' => $dateMin, + 'date_max' => $dateMax, + ]; + } + + /** @return array> */ + private function read(string $path): array + { + $extension = mb_strtolower(pathinfo($path, PATHINFO_EXTENSION)); + + if ($extension === 'csv') { + $handle = fopen($path, 'rb'); + if ($handle === false) { + throw new RuntimeException('无法读取文件。'); + } + $grid = []; + $first = true; + while (($cells = fgetcsv($handle)) !== false) { + if ($first && isset($cells[0])) { + $cells[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $cells[0]); + $first = false; + } + $grid[] = $cells; + } + fclose($handle); + + return $grid; + } + + if (! in_array($extension, ['xlsx', 'xls'], true)) { + throw new InvalidArgumentException('只支持 xlsx、xls、csv。'); + } + + try { + $reader = IOFactory::createReader($extension === 'xlsx' ? 'Xlsx' : 'Xls'); + $reader->setReadDataOnly(true); + $spreadsheet = $reader->load($path); + } catch (Throwable $exception) { + throw new InvalidArgumentException('读不出这个表格:' . $exception->getMessage()); + } + + try { + return $spreadsheet->getSheet(0)->toArray(null, true, false, false); + } finally { + $spreadsheet->disconnectWorksheets(); + } + } + + /** @param array> $grid */ + private function locateHeader(array $grid): ?int + { + foreach ($grid as $index => $row) { + $map = $this->mapHeader($row); + if (isset($map['bill_date'], $map['order_no'], $map['finance_payment_amount'])) { + return $index; + } + } + + return null; + } + + /** @param array $row @return array */ + private function mapHeader(array $row): array + { + $map = []; + foreach ($row as $index => $value) { + $label = trim((string) (is_scalar($value) ? $value : '')); + if ($label === '') { + continue; + } + $column = self::COLUMNS[$label] ?? null; + if ($column !== null && ! isset($map[$column])) { + $map[$column] = (int) $index; + } + } + + return $map; + } + + /** @param array $row @param array $map */ + private function cell(array $row, array $map, string $column): mixed + { + return isset($map[$column]) ? ($row[$map[$column]] ?? null) : null; + } + + private function hasContent(array $row): bool + { + foreach ($row as $value) { + if ($value !== null && trim((string) (is_scalar($value) ? $value : '')) !== '') { + return true; + } + } + + return false; + } + + private function toDate(mixed $value): ?string + { + if ($value === null || $value === '') { + return null; + } + + if (is_numeric($value) && (float) $value > 20000 && (float) $value < 60000) { + try { + return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d'); + } catch (Throwable) { + return null; + } + } + + $text = trim((string) $value); + $timestamp = strtotime($text); + + return $timestamp === false ? null : date('Y-m-d', $timestamp); + } + + private function toText(mixed $value): ?string + { + if ($value === null) { + return null; + } + + $text = trim((string) (is_scalar($value) ? $value : '')); + + return $text === '' ? null : mb_substr($text, 0, 191); + } + + private function toNumber(mixed $value): ?float + { + if ($value === null || $value === '') { + return null; + } + if (is_numeric($value)) { + return (float) $value; + } + + $text = str_replace([',', ' ', '¥', '¥'], '', (string) $value); + + return is_numeric($text) ? (float) $text : null; + } +} diff --git a/app/Console/Commands/ImportPlantingDetails.php b/app/Console/Commands/ImportPlantingDetails.php new file mode 100644 index 00000000..00a283ef --- /dev/null +++ b/app/Console/Commands/ImportPlantingDetails.php @@ -0,0 +1,38 @@ +import( + (string) $this->argument('file'), + (int) $this->option('company'), + (bool) $this->option('replace'), + null, + 'planting-detail-import', + ); + } catch (Throwable $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(json_encode($result, JSON_UNESCAPED_UNICODE)); + + return self::SUCCESS; + } +} diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 870714ce..68c72085 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -1244,10 +1244,154 @@ class Pages extends Controller 'withdrawal-management' => $this->contentForWithdrawalManagement(), 'bill-offset' => app(\Modules\EcommerceFinance\View\BillOffsetPageData::class)->page(), 'account-mapping' => $this->contentForAccountMapping(), + 'planting-details' => $this->contentForPlantingDetails(), default => null, }; } + /** + * 账单流水数据 › 种菜明细表。 + */ + protected function contentForPlantingDetails(): array + { + $request = request(); + $filters = $this->plantingDetailFilters($request); + $query = $this->plantingDetailQuery($filters); + + $summaryRow = (clone $query)->selectRaw( + 'COUNT(*) AS rows_count, COALESCE(SUM(pieces), 0) AS pieces_total, ' + . 'COALESCE(SUM(finance_selling_price), 0) AS selling_price_total, ' + . 'COALESCE(SUM(finance_payment_amount), 0) AS payment_amount_total, ' + . 'COALESCE(SUM(deduction), 0) AS deduction_total, ' + . 'COALESCE(SUM(jingxi_price_diff), 0) AS jingxi_diff_total' + )->first(); + + $limit = min(max((int) setting('default.list_limit', 25), 10), 100); + $records = (clone $query) + ->orderByDesc('bill_date') + ->orderByDesc('id') + ->paginate($limit) + ->withQueryString(); + + return [ + 'view' => 'business.pages.billing-transactions.planting-details', + 'records' => $records, + 'filters' => $filters, + 'summary' => [ + 'rows' => (int) ($summaryRow->rows_count ?? 0), + 'pieces' => (int) ($summaryRow->pieces_total ?? 0), + 'selling_price' => (float) ($summaryRow->selling_price_total ?? 0), + 'payment_amount' => (float) ($summaryRow->payment_amount_total ?? 0), + 'deduction' => (float) ($summaryRow->deduction_total ?? 0), + 'jingxi_diff' => (float) ($summaryRow->jingxi_diff_total ?? 0), + ], + 'filterOptions' => [ + 'stores' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('store')->distinct()->orderBy('store')->limit(500)->pluck('store')->all(), + 'owners' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('owner')->distinct()->orderBy('owner')->limit(500)->pluck('owner')->all(), + 'types' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('type')->distinct()->orderBy('type')->limit(200)->pluck('type')->all(), + 'tags' => \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()) + ->whereNotNull('tag')->distinct()->orderBy('tag')->limit(200)->pluck('tag')->all(), + ], + ]; + } + + /** @return array 种菜明细表筛选条件 */ + private function plantingDetailFilters(Request $request): array + { + return [ + 'date_from' => $this->dateFilter($request->query('date_from')), + 'date_to' => $this->dateFilter($request->query('date_to')), + 'store' => mb_substr(trim((string) $request->query('store')), 0, 191), + 'owner' => mb_substr(trim((string) $request->query('owner')), 0, 191), + 'type' => mb_substr(trim((string) $request->query('type')), 0, 191), + 'tag' => mb_substr(trim((string) $request->query('tag')), 0, 191), + 'keyword' => mb_substr(trim((string) $request->query('keyword')), 0, 191), + ]; + } + + /** @param array $filters */ + private function plantingDetailQuery(array $filters): \Illuminate\Database\Eloquent\Builder + { + $query = \App\Models\Business\PlantingDetail::query()->where('company_id', company_id()); + + if ($filters['date_from'] !== '') { + $query->where('bill_date', '>=', $filters['date_from']); + } + if ($filters['date_to'] !== '') { + $query->where('bill_date', '<=', $filters['date_to']); + } + foreach (['store', 'owner', 'type', 'tag'] as $field) { + if ($filters[$field] !== '') { + $query->where($field, $filters[$field]); + } + } + if ($filters['keyword'] !== '') { + $like = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['keyword']) . '%'; + $query->where(function ($sub) use ($like): void { + $sub->where('order_no', 'like', $like) + ->orWhere('remark', 'like', $like) + ->orWhere('account', 'like', $like) + ->orWhere('external_id', 'like', $like) + ->orWhere('creator', 'like', $like); + }); + } + + return $query; + } + + /** 账单流水数据 › 种菜明细表导出(按当前筛选,全量) */ + public function exportPlantingDetails(Request $request): StreamedResponse + { + $query = $this->plantingDetailQuery($this->plantingDetailFilters($request)); + + return response()->streamDownload(function () use ($query): void { + $csv = fopen('php://output', 'w'); + if ($csv === false) { + throw new \RuntimeException('无法创建种菜明细导出流。'); + } + fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); + fputcsv($csv, [ + '日期', '订单编号', '财务售价', '财务运费', '财务佣金', '京喜差价', '扣款', + '财务空包费', '财务打款金额', '笔数', '备注', '正确店铺', '负责人', '账户', + '类型', '创建人', '标签', '所属利润中心', '负责平台', 'ID', + ]); + + $query->orderBy('id')->chunkById(2000, function ($rows) use ($csv): void { + foreach ($rows as $row) { + fputcsv($csv, [ + $row->bill_date?->toDateString(), + $row->order_no, + $row->finance_selling_price, + $row->finance_freight, + $row->finance_commission, + $row->jingxi_price_diff, + $row->deduction, + $row->finance_empty_package_fee, + $row->finance_payment_amount, + $row->pieces, + $row->remark, + $row->store, + $row->owner, + $row->account, + $row->type, + $row->creator, + $row->tag, + $row->profit_center, + $row->responsible_platform, + $row->external_id, + ]); + } + }); + fclose($csv); + }, '种菜明细表_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + /** * 财务规则 · 科目映射表 * diff --git a/app/Models/Business/PlantingDetail.php b/app/Models/Business/PlantingDetail.php new file mode 100644 index 00000000..8be6d95e --- /dev/null +++ b/app/Models/Business/PlantingDetail.php @@ -0,0 +1,54 @@ + 'date', + 'finance_selling_price' => 'decimal:4', + 'finance_freight' => 'decimal:4', + 'finance_commission' => 'decimal:4', + 'jingxi_price_diff' => 'decimal:4', + 'deduction' => 'decimal:4', + 'finance_empty_package_fee' => 'decimal:4', + 'finance_payment_amount' => 'decimal:4', + 'pieces' => 'integer', + ]; +} diff --git a/config/business_navigation.php b/config/business_navigation.php index 7e298106..f7de56b7 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -426,6 +426,7 @@ $navigation = [ 'icon' => 'receipt_long', 'pages' => [ ['slug' => 'bank-transactions', 'title' => '银行账户流水'], + ['slug' => 'planting-details', 'title' => '种菜明细表'], [ 'slug' => 'store-receiving-bills', 'title' => '店铺收款账户账单', diff --git a/database/migrations/2026_09_30_120000_create_planting_details_table.php b/database/migrations/2026_09_30_120000_create_planting_details_table.php new file mode 100644 index 00000000..9131d90e --- /dev/null +++ b/database/migrations/2026_09_30_120000_create_planting_details_table.php @@ -0,0 +1,58 @@ +increments('id'); + $table->unsignedInteger('company_id'); + $table->date('bill_date')->comment('日期'); + $table->string('order_no', 100)->nullable()->comment('订单编号'); + $table->decimal('finance_selling_price', 18, 4)->default(0)->comment('财务售价'); + $table->decimal('finance_freight', 18, 4)->default(0)->comment('财务运费'); + $table->decimal('finance_commission', 18, 4)->default(0)->comment('财务佣金'); + $table->decimal('jingxi_price_diff', 18, 4)->default(0)->comment('京喜差价'); + $table->decimal('deduction', 18, 4)->default(0)->comment('扣款'); + $table->decimal('finance_empty_package_fee', 18, 4)->default(0)->comment('财务空包费'); + $table->decimal('finance_payment_amount', 18, 4)->default(0)->comment('财务打款金额'); + $table->integer('pieces')->default(0)->comment('笔数'); + $table->text('remark')->nullable()->comment('备注'); + $table->string('store', 191)->nullable()->comment('正确店铺'); + $table->string('owner', 191)->nullable()->comment('负责人'); + $table->string('account', 191)->nullable()->comment('账户'); + $table->string('type', 191)->nullable()->comment('类型'); + $table->string('creator', 191)->nullable()->comment('创建人'); + $table->string('tag', 191)->nullable()->comment('标签'); + $table->string('profit_center', 191)->nullable()->comment('所属利润中心'); + $table->string('responsible_platform', 191)->nullable()->comment('负责平台'); + $table->string('external_id', 100)->nullable()->comment('ID'); + $table->string('created_from', 100)->nullable(); + $table->unsignedInteger('created_by')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->index(['company_id', 'bill_date']); + $table->index(['company_id', 'store']); + $table->index(['company_id', 'owner']); + $table->index(['company_id', 'type']); + $table->index(['company_id', 'tag']); + $table->index('order_no'); + }); + } + + public function down(): void + { + Schema::dropIfExists('planting_details'); + } +}; diff --git a/resources/views/business/pages/billing-transactions/planting-details.blade.php b/resources/views/business/pages/billing-transactions/planting-details.blade.php new file mode 100644 index 00000000..a12cf9fb --- /dev/null +++ b/resources/views/business/pages/billing-transactions/planting-details.blade.php @@ -0,0 +1,223 @@ +@php + $records = $records ?? null; + $filters = $filters ?? []; + $summary = $summary ?? []; + $filterOptions = $filterOptions ?? ['stores' => [], 'owners' => [], 'types' => [], 'tags' => []]; + $totals = [ + 'rows' => (int) ($summary['rows'] ?? 0), + 'pieces' => (int) ($summary['pieces'] ?? 0), + 'selling_price' => (float) ($summary['selling_price'] ?? 0), + 'payment_amount' => (float) ($summary['payment_amount'] ?? 0), + 'deduction' => (float) ($summary['deduction'] ?? 0), + 'jingxi_diff' => (float) ($summary['jingxi_diff'] ?? 0), + ]; + $money = static fn (mixed $value): string => number_format((float) $value, 2); +@endphp + +
+ @include('business.pages.partials.upstream-data-styles') + + + +
+
+
笔数合计
+
{{ number_format($totals['pieces']) }}
+
+
+
财务打款金额
+
{{ $money($totals['payment_amount']) }}
+
+
+
财务售价
+
{{ $money($totals['selling_price']) }}
+
+
+
扣款
+
{{ $money($totals['deduction']) }}
+
+
+
京喜差价
+
{{ $money($totals['jingxi_diff']) }}
+
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +

数据来源:财务「1-8月种菜」原始表导入,共 {{ number_format($totals['rows']) }} 行(当前筛选)。

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + @forelse ($records as $index => $record) + + + + + + + + + + + + + + + + + + + + + + + + @empty + + + + @endforelse + +
序号日期订单编号财务售价财务运费财务佣金京喜差价扣款财务空包费财务打款金额笔数备注正确店铺负责人账户类型创建人标签所属利润中心负责平台ID
{{ $records->firstItem() + $index }}{{ $record->bill_date?->toDateString() ?? '-' }}{{ $record->order_no ?: '-' }}{{ $money($record->finance_selling_price) }}{{ $money($record->finance_freight) }}{{ $money($record->finance_commission) }}{{ $money($record->jingxi_price_diff) }}{{ $money($record->deduction) }}{{ $money($record->finance_empty_package_fee) }}{{ $money($record->finance_payment_amount) }}{{ number_format((int) $record->pieces) }}{{ $record->remark ?: '-' }}{{ $record->store ?: '-' }}{{ $record->owner ?: '-' }}{{ $record->account ?: '-' }}{{ $record->type ?: '-' }}{{ $record->creator ?: '-' }}{{ $record->tag ?: '-' }}{{ $record->profit_center ?: '-' }}{{ $record->responsible_platform ?: '-' }}{{ $record->external_id ?: '-' }}
+ {{ $totals['rows'] === 0 ? '暂无种菜明细数据,请先导入「1-8月种菜」等原始表。' : '当前筛选条件下没有记录,请调整筛选条件后重试。' }} +
+
+ +
+ + 共 {{ number_format($records->total()) }} 条记录 + · 每页 {{ $records->perPage() }} 条 + · 第 {{ $records->currentPage() }} / {{ max($records->lastPage(), 1) }} 页 + +
+ @if ($records->onFirstPage()) + + + + @else + + + + @endif + 第 {{ $records->currentPage() }} / {{ max($records->lastPage(), 1) }} 页 + @if ($records->hasMorePages()) + + + + @else + + + + @endif +
+
+
+
diff --git a/routes/admin.php b/routes/admin.php index 8cdd1afa..147c7ee9 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -168,6 +168,10 @@ Route::get('workspace/product-inventory/monthly-weighted-average-price/export', ->middleware('business.page:product-inventory,monthly-weighted-average-price') ->name('business.product-inventory.monthly-weighted-average-price.export'); +Route::get('workspace/billing-transactions/planting-details/export', 'Business\Pages@exportPlantingDetails') + ->middleware('business.page:billing-transactions,planting-details') + ->name('business.billing-transactions.planting-details.export'); + Route::prefix('workspace/product-inventory/inventory-report/warehouse-mappings') ->middleware('business.page:product-inventory,inventory-report') ->name('business.product-inventory.inventory-report.warehouse-mappings.') diff --git a/tests/Feature/Business/PlantingDetailsPageTest.php b/tests/Feature/Business/PlantingDetailsPageTest.php new file mode 100644 index 00000000..de9c4916 --- /dev/null +++ b/tests/Feature/Business/PlantingDetailsPageTest.php @@ -0,0 +1,139 @@ +files as $file) { + if (is_file($file)) { + unlink($file); + } + } + + parent::tearDown(); + } + + public function test_import_then_page_filter_and_export(): void + { + $this->allowPage(); + $result = app(PlantingDetailImporter::class)->import($this->csvFixture(), $this->company->id, true, null, 'test-import'); + + $this->assertSame(2, $result['inserted']); + $this->assertSame('2665.3600', $result['selling_price']); + $this->assertSame('2665.8600', $result['payment_amount']); + $this->assertSame('2026-06-01', $result['date_min']); + $this->assertSame('2026-07-15', $result['date_max']); + + $page = $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'billing-transactions', + 'page' => 'planting-details', + ])); + + $page->assertOk() + ->assertSee('种菜明细表') + ->assertSee('3306215028042824171') + ->assertSee('260529-659019537933390') + ->assertSee('2,665.35') + ->assertSee('阿里巴巴-常州乐畅家居有限公司'); + + // 按店铺 + 日期筛选 + $filtered = $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'billing-transactions', + 'page' => 'planting-details', + 'store' => '拼多多-亿家达实木家具官方旗舰店', + 'date_from' => '2026-07-01', + ])); + + $filtered->assertOk() + ->assertSee('260529-659019537933390') + ->assertDontSee('3306215028042824171'); + + // 导出:表头 + 行数与页面筛选一致 + $export = $this->loginAs()->get(route('business.billing-transactions.planting-details.export', [ + 'store' => '拼多多-亿家达实木家具官方旗舰店', + ])); + + $export->assertOk()->assertDownload(); + $csv = $export->streamedContent(); + $this->assertStringContainsString('日期,订单编号,财务售价', explode("\n", $csv)[0]); + $this->assertStringContainsString('260529-659019537933390', $csv); + $this->assertStringNotContainsString('3306215028042824171', $csv); + $this->assertStringContainsString('2026-07-15', $csv); + } + + public function test_importer_handles_excel_serial_dates_and_grouped_amounts(): void + { + $path = $this->writeFile('planting.xlsx'); + $book = new Spreadsheet(); + $sheet = $book->getActiveSheet(); + $sheet->fromArray([ + ['日期', '订单编号', '财务售价', '财务运费', '财务佣金', '京喜差价', '扣款', '财务空包费', '财务打款金额', '笔数', '备注', '正确店铺', '负责人', '账户', '类型', '创建人', '标签', '所属利润中心', '负责平台', 'ID'], + [46174, 'ORDER-1', '1,234.56', 0, '0.5', 0, 0, 0, '1,235.06', 2, '', '天猫-亿家达旗舰店', '仝孟欣', '', 'CCDD', '齐静春', 'CCDD', '运营中心A', '', 'ID-1'], + // 无效日期(空)+ 无效订单号 → 跳过 + ['', '', 10, 0, 0, 0, 0, 0, 10, 1, '', '天猫-亿家达旗舰店', '', '', '', '', '', '', '', ''], + ]); + (new Xlsx($book))->save($path); + $book->disconnectWorksheets(); + + $result = app(PlantingDetailImporter::class)->import($path, $this->company->id, true, null, 'test-xlsx'); + + $this->assertSame(1, $result['inserted']); + $this->assertSame(1, $result['skipped']); + $this->assertSame('2026-06-01', $result['date_min']); + + $record = PlantingDetail::query()->where('company_id', $this->company->id)->firstOrFail(); + $this->assertSame('2026-06-01', $record->bill_date->toDateString()); + $this->assertSame('1234.5600', $record->finance_selling_price); + $this->assertSame('1235.0600', $record->finance_payment_amount); + $this->assertSame(2, $record->pieces); + $this->assertSame('CCDD', $record->type); + $this->assertSame('运营中心A', $record->profit_center); + } + + private function csvFixture(): string + { + $path = $this->writeFile('planting.csv'); + $rows = [ + ['日期', '订单编号', '财务售价', '财务运费', '财务佣金', '京喜差价', '扣款', '财务空包费', '财务打款金额', '笔数', '备注', '正确店铺', '负责人', '账户', '类型', '创建人', '标签', '所属利润中心', '负责平台', 'ID'], + ['2026-06-01', '3306215028042824171', '2665.35', '0', '0', '0', '0', '0', '2665.35', '1', '', '阿里巴巴-常州乐畅家居有限公司', '叶颖龙', '6222031202029761854', '', '勇武', 'AABB', '运营中心B', '', '1056008452997'], + ['2026-07-15', '260529-659019537933390', '0.01', '0', '0.5', '0', '0', '0', '0.51', '1', '', '拼多多-亿家达实木家具官方旗舰店', '屠锦超', '6222031211003375839', 'SSDD', '玄鸟', 'SSDD', '运营中心G', '', '959767499187'], + ]; + + $handle = fopen($path, 'wb'); + foreach ($rows as $row) { + fputcsv($handle, $row); + } + fclose($handle); + + return $path; + } + + private function writeFile(string $name): string + { + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('planting-', true) . '-' . $name; + $this->files[] = $path; + + return $path; + } + + private function allowPage(): void + { + $this->user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + } +}