账单流水数据新增种菜明细表页面与导入

新增「账单流水数据 › 种菜明细表」页面:汇总卡(笔数/财务打款金额/财务售价/扣款/京喜差价)+ 筛选(日期区间/店铺/负责人/类型/标签/关键词)+ 分页 + 按筛选全量导出,样式沿用 upstream-data 黑金令牌。新增 planting_details 表(20 列与源表一一对应,金额保留 4 位小数)、PlantingDetail 模型、PlantingDetailImporter(xlsx/xls/csv,兼容 Excel 序列号日期与千分位金额)与 planting-details:import 命令。补 PlantingDetailsPageTest 覆盖导入、序列号日期、页面渲染、筛选与导出。
This commit is contained in:
qiuxiang 2026-09-30 09:50:50 +08:00
parent ada44a4e04
commit 28b9271b3c
9 changed files with 959 additions and 0 deletions

View File

@ -0,0 +1,298 @@
<?php
namespace App\Business;
use App\Models\Business\PlantingDetail;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use RuntimeException;
use Throwable;
/**
* 种菜明细表导入(xlsx / xls / csv)。
*
* 源表头与 planting_details 列一一对应;按表头名匹配,列顺序变化不影响。
* 日期兼容 Excel 序列号与常见字符串;金额按 4 位小数保存。
*/
class PlantingDetailImporter
{
/** 源表头 → 数据库列 */
private const COLUMNS = [
'日期' => '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<int,array<int,mixed>> */
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<int,array<int,mixed>> $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<int,mixed> $row @return array<string,int> */
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<int,mixed> $row @param array<string,int> $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;
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Console\Commands;
use App\Business\PlantingDetailImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportPlantingDetails extends Command
{
protected $signature = 'planting-details:import
{file : xlsx / xls / csv 文件路径}
{--company=1 : 公司 ID}
{--replace : 先清空该公司已有的种菜明细}';
protected $description = '导入「种菜明细表」数据(账单流水数据 › 种菜明细表)';
public function handle(PlantingDetailImporter $importer): int
{
try {
$result = $importer->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;
}
}

View File

@ -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<string,string> 种菜明细表筛选条件 */
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<string,string> $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',
]);
}
/**
* 财务规则 · 科目映射表
*

View File

@ -0,0 +1,54 @@
<?php
namespace App\Models\Business;
use App\Abstracts\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* 账单流水数据 › 种菜明细表(来源:财务「1-8月种菜」等原始表导入)。
*/
class PlantingDetail extends Model
{
use SoftDeletes;
protected $table = 'planting_details';
protected $fillable = [
'company_id',
'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',
'external_id',
'created_from',
'created_by',
];
protected $casts = [
'bill_date' => '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',
];
}

View File

@ -426,6 +426,7 @@ $navigation = [
'icon' => 'receipt_long',
'pages' => [
['slug' => 'bank-transactions', 'title' => '银行账户流水'],
['slug' => 'planting-details', 'title' => '种菜明细表'],
[
'slug' => 'store-receiving-bills',
'title' => '店铺收款账户账单',

View File

@ -0,0 +1,58 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* 账单流水数据 › 种菜明细表。
*
* 数据来自财务「1-8月种菜.xlsx」等原始表,列与源表头一一对应(不改名、不丢列)。
* 金额列保留 4 位小数:源表佣金、打款金额存在 3 位小数的行。
*/
public function up(): void
{
Schema::create('planting_details', function (Blueprint $table) {
$table->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');
}
};

View File

@ -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
<div class="upstream-data-page upstream-data-page--spaced" data-planting-details="true">
@include('business.pages.partials.upstream-data-styles')
<style>
.planting-details-table {
min-width: 150rem;
}
.planting-details-table .is-money {
text-align: right;
}
.planting-details-table .is-muted {
color: var(--vip-content-muted, #595959);
}
.planting-details-hint {
margin: 0 0 0.75rem;
color: var(--vip-content-muted, #595959);
font-size: 0.75rem;
}
</style>
<dl class="upstream-data-summary" style="--upstream-summary-columns: 5" aria-label="种菜明细汇总">
<div>
<dt>笔数合计</dt>
<dd>{{ number_format($totals['pieces']) }}</dd>
</div>
<div>
<dt>财务打款金额</dt>
<dd>{{ $money($totals['payment_amount']) }}</dd>
</div>
<div>
<dt>财务售价</dt>
<dd>{{ $money($totals['selling_price']) }}</dd>
</div>
<div>
<dt>扣款</dt>
<dd>{{ $money($totals['deduction']) }}</dd>
</div>
<div>
<dt>京喜差价</dt>
<dd>{{ $money($totals['jingxi_diff']) }}</dd>
</div>
</dl>
<form class="upstream-data-toolbar" method="get" action="{{ request()->url() }}" aria-label="种菜明细表筛选">
<div class="upstream-data-field">
<label for="planting-date-from">日期从</label>
<input id="planting-date-from" name="date_from" type="date" value="{{ $filters['date_from'] ?? '' }}">
</div>
<div class="upstream-data-field">
<label for="planting-date-to">日期至</label>
<input id="planting-date-to" name="date_to" type="date" value="{{ $filters['date_to'] ?? '' }}">
</div>
<div class="upstream-data-field">
<label for="planting-store">正确店铺</label>
<select id="planting-store" name="store">
<option value="">全部店铺</option>
@foreach ($filterOptions['stores'] as $store)
<option value="{{ $store }}" @selected(($filters['store'] ?? '') === $store)>{{ $store }}</option>
@endforeach
</select>
</div>
<div class="upstream-data-field">
<label for="planting-owner">负责人</label>
<select id="planting-owner" name="owner">
<option value="">全部负责人</option>
@foreach ($filterOptions['owners'] as $owner)
<option value="{{ $owner }}" @selected(($filters['owner'] ?? '') === $owner)>{{ $owner }}</option>
@endforeach
</select>
</div>
<div class="upstream-data-field">
<label for="planting-type">类型</label>
<select id="planting-type" name="type">
<option value="">全部类型</option>
@foreach ($filterOptions['types'] as $type)
<option value="{{ $type }}" @selected(($filters['type'] ?? '') === $type)>{{ $type }}</option>
@endforeach
</select>
</div>
<div class="upstream-data-field">
<label for="planting-tag">标签</label>
<select id="planting-tag" name="tag">
<option value="">全部标签</option>
@foreach ($filterOptions['tags'] as $tag)
<option value="{{ $tag }}" @selected(($filters['tag'] ?? '') === $tag)>{{ $tag }}</option>
@endforeach
</select>
</div>
<div class="upstream-data-field">
<label for="planting-keyword">关键词</label>
<input id="planting-keyword" name="keyword" type="text" value="{{ $filters['keyword'] ?? '' }}" placeholder="订单编号 / 账户 / ID / 备注 / 创建人">
</div>
<div class="upstream-data-actions">
<button class="upstream-data-button upstream-data-button--primary" type="submit">
<span class="material-icons-outlined" aria-hidden="true">search</span>
<span>查询</span>
</button>
<a class="upstream-data-button" href="{{ request()->url() }}" title="清除筛选条件">
<span class="material-icons-outlined" aria-hidden="true">restart_alt</span>
<span>重置</span>
</a>
<a class="upstream-data-button" href="{{ route('business.billing-transactions.planting-details.export', request()->query()) }}" title="按当前筛选导出全部明细">
<span class="material-icons-outlined" aria-hidden="true">download</span>
<span>导出</span>
</a>
</div>
</form>
<p class="planting-details-hint">数据来源:财务「1-8月种菜」原始表导入,共 {{ number_format($totals['rows']) }} 行(当前筛选)。</p>
<div class="upstream-data-table-panel">
<div class="upstream-data-table-scroll">
<table class="upstream-data-table planting-details-table" aria-label="种菜明细表">
<thead>
<tr>
<th scope="col">序号</th>
<th scope="col">日期</th>
<th scope="col">订单编号</th>
<th scope="col">财务售价</th>
<th scope="col">财务运费</th>
<th scope="col">财务佣金</th>
<th scope="col">京喜差价</th>
<th scope="col">扣款</th>
<th scope="col">财务空包费</th>
<th scope="col">财务打款金额</th>
<th scope="col">笔数</th>
<th scope="col">备注</th>
<th scope="col">正确店铺</th>
<th scope="col">负责人</th>
<th scope="col">账户</th>
<th scope="col">类型</th>
<th scope="col">创建人</th>
<th scope="col">标签</th>
<th scope="col">所属利润中心</th>
<th scope="col">负责平台</th>
<th scope="col">ID</th>
</tr>
</thead>
<tbody>
@forelse ($records as $index => $record)
<tr>
<td class="is-muted">{{ $records->firstItem() + $index }}</td>
<td>{{ $record->bill_date?->toDateString() ?? '-' }}</td>
<td>{{ $record->order_no ?: '-' }}</td>
<td class="is-money">{{ $money($record->finance_selling_price) }}</td>
<td class="is-money">{{ $money($record->finance_freight) }}</td>
<td class="is-money">{{ $money($record->finance_commission) }}</td>
<td class="is-money">{{ $money($record->jingxi_price_diff) }}</td>
<td class="is-money">{{ $money($record->deduction) }}</td>
<td class="is-money">{{ $money($record->finance_empty_package_fee) }}</td>
<td class="is-money">{{ $money($record->finance_payment_amount) }}</td>
<td class="is-money">{{ number_format((int) $record->pieces) }}</td>
<td>{{ $record->remark ?: '-' }}</td>
<td>{{ $record->store ?: '-' }}</td>
<td>{{ $record->owner ?: '-' }}</td>
<td>{{ $record->account ?: '-' }}</td>
<td>{{ $record->type ?: '-' }}</td>
<td>{{ $record->creator ?: '-' }}</td>
<td>{{ $record->tag ?: '-' }}</td>
<td>{{ $record->profit_center ?: '-' }}</td>
<td>{{ $record->responsible_platform ?: '-' }}</td>
<td>{{ $record->external_id ?: '-' }}</td>
</tr>
@empty
<tr class="is-empty">
<td colspan="21">
{{ $totals['rows'] === 0 ? '暂无种菜明细数据,请先导入「1-8月种菜」等原始表。' : '当前筛选条件下没有记录,请调整筛选条件后重试。' }}
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
<div class="upstream-data-pagination">
<span>
共 {{ number_format($records->total()) }} 条记录
· 每页 {{ $records->perPage() }} 条
· 第 {{ $records->currentPage() }} / {{ max($records->lastPage(), 1) }} 页
</span>
<div class="upstream-data-pagination__controls" aria-label="种菜明细分页">
@if ($records->onFirstPage())
<span class="upstream-data-button is-disabled" aria-disabled="true" title="上一页">
<span class="material-icons-outlined" aria-hidden="true">chevron_left</span>
</span>
@else
<a class="upstream-data-button" href="{{ $records->previousPageUrl() }}" aria-label="上一页" title="上一页">
<span class="material-icons-outlined" aria-hidden="true">chevron_left</span>
</a>
@endif
<span>第 {{ $records->currentPage() }} / {{ max($records->lastPage(), 1) }} 页</span>
@if ($records->hasMorePages())
<a class="upstream-data-button" href="{{ $records->nextPageUrl() }}" aria-label="下一页" title="下一页">
<span class="material-icons-outlined" aria-hidden="true">chevron_right</span>
</a>
@else
<span class="upstream-data-button is-disabled" aria-disabled="true" title="下一页">
<span class="material-icons-outlined" aria-hidden="true">chevron_right</span>
</span>
@endif
</div>
</div>
</div>
</div>

View File

@ -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.')

View File

@ -0,0 +1,139 @@
<?php
namespace Tests\Feature\Business;
use App\Business\PlantingDetailImporter;
use App\Models\Auth\Permission;
use App\Models\Business\PlantingDetail;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
/**
* 账单流水数据 › 种菜明细表(导入 + 页面 + 筛选 + 导出)。
*/
class PlantingDetailsPageTest extends FeatureTestCase
{
private array $files = [];
protected function tearDown(): void
{
foreach ($this->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()
);
}
}