进销存:入库明细支持页面导入 (#473)

This commit is contained in:
chenxi 2026-10-23 15:02:03 +08:00
parent f61fbb5028
commit c9ecf033d5
6 changed files with 444 additions and 190 deletions

View File

@ -0,0 +1,237 @@
<?php
namespace App\Business;
use App\Models\Business\InventoryWarehouseNameMapping;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
class InventoryInboundDetailImporter
{
private const TABLE = 'inventory_inbound_detail_rows';
/**
* Replace the imported inbound detail snapshot only after the workbook has
* been opened successfully. The delete and inserts share one transaction,
* so a malformed file cannot leave the page with a partially imported table.
*
* @return array{imported:int,mapped:int,skipped:int,total:int}
*/
public function import(string $file, string $forcedMonth = ''): array
{
$path = realpath($file);
if ($path === false || ! is_file($path) || ! is_readable($path)) {
throw new RuntimeException('入库明细文件不存在或不可读取。');
}
$forcedMonth = $this->normalizeForcedMonth($forcedMonth);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$now = now();
$maps = $this->shortNameMap();
$reader = IOFactory::createReaderForFile($path);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path);
$sheet = $spreadsheet->getSheet(0);
try {
return DB::connection($connection)->transaction(function () use (
$connection,
$sheet,
$maps,
$forcedMonth,
$now,
): array {
DB::connection($connection)->table(self::TABLE)->delete();
$batch = [];
$imported = 0;
$mapped = 0;
$skipped = 0;
foreach ($sheet->getRowIterator(2) as $row) {
$rowNumber = $row->getRowIndex();
$cells = [];
foreach ($row->getCellIterator('A', 'U') as $cell) {
$cells[] = $cell->getFormattedValue();
}
$warehouse = trim((string) ($cells[14] ?? ''));
$createdRaw = trim((string) ($cells[16] ?? ''));
if ($warehouse === '' && $createdRaw === '') {
$skipped++;
continue;
}
$month = $forcedMonth !== '' ? $forcedMonth : $this->monthOf($createdRaw);
if ($month === '') {
$skipped++;
continue;
}
// 代发仓按仓储方匹配;其它仓库按仓库名称做唯一匹配。
$shortName = '';
if ($warehouse !== '') {
$shortName = str_contains($warehouse, '代发仓')
? ($maps['provider'][$warehouse] ?? $maps['warehouse'][$warehouse] ?? '')
: ($maps['warehouse'][$warehouse] ?? '');
}
if ($shortName !== '') {
$mapped++;
}
$batch[] = [
'report_month' => $month,
'row_key' => sha1(substr($month, 0, 7) . '|' . $rowNumber),
'source_no' => $this->text($cells[0] ?? ''),
'document_no' => $this->text($cells[1] ?? ''),
'created_serial' => $this->text($cells[2] ?? ''),
'supplier' => $this->text($cells[3] ?? ''),
'item_no' => $this->text($cells[4] ?? ''),
'barcode' => $this->text($cells[5] ?? ''),
'spec_name' => $this->text($cells[6] ?? ''),
'quantity' => $this->number($cells[7] ?? ''),
'unit_price' => $this->number($cells[8] ?? ''),
'amount' => $this->number($cells[9] ?? ''),
'estimated_unit_price' => $this->number($cells[10] ?? ''),
'estimated_amount' => $this->number($cells[11] ?? ''),
'supplier_barcode' => $this->text($cells[12] ?? ''),
'remark' => $this->text($cells[13] ?? ''),
'warehouse' => $warehouse !== '' ? $warehouse : null,
'warehouse_short_name' => $shortName !== '' ? $shortName : null,
'created_at_raw' => $this->moment($createdRaw),
'express_name' => $this->text($cells[17] ?? ''),
'express_no' => $this->text($cells[18] ?? ''),
'not_sent' => $this->text($cells[19] ?? ''),
'owner_name' => $this->text($cells[20] ?? ''),
'imported_at' => $now,
];
$imported++;
if (count($batch) >= 1000) {
DB::connection($connection)->table(self::TABLE)->insertOrIgnore($batch);
$batch = [];
}
}
if ($batch !== []) {
DB::connection($connection)->table(self::TABLE)->insertOrIgnore($batch);
}
if ($imported === 0) {
throw new RuntimeException('入库明细文件中没有可导入的数据。');
}
return [
'imported' => $imported,
'mapped' => $mapped,
'skipped' => $skipped,
'total' => DB::connection($connection)->table(self::TABLE)->count(),
];
});
} finally {
$spreadsheet->disconnectWorksheets();
}
}
private function normalizeForcedMonth(string $month): string
{
$month = trim($month);
if ($month === '') {
return '';
}
if (preg_match('/^\d{4}-\d{2}$/', $month) === 1) {
return $month . '-01';
}
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $month) === 1) {
return $month;
}
throw new RuntimeException('指定月份格式应为 YYYY-MM。');
}
/** @return array{warehouse:array<string,string>,provider:array<string,string>} */
private function shortNameMap(): array
{
$rows = InventoryWarehouseNameMapping::withoutGlobalScopes()
->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']);
$grouped = [];
foreach ($rows as $row) {
$warehouse = trim((string) $row->warehouse);
if ($warehouse === '') {
continue;
}
$grouped[$warehouse][] = trim((string) $row->warehouse_short_name);
}
$byWarehouse = [];
foreach ($grouped as $warehouse => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byWarehouse[$warehouse] = $unique[0];
}
}
$byProvider = [];
foreach ($rows as $row) {
$provider = trim((string) $row->warehouse_provider);
if ($provider !== '') {
$byProvider[$provider][] = trim((string) $row->warehouse_short_name);
}
}
foreach ($byProvider as $provider => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byProvider[$provider] = $unique[0];
}
}
return ['warehouse' => $byWarehouse, 'provider' => $byProvider];
}
private function monthOf(string $value): string
{
$value = trim($value);
if ($value === '') {
return '';
}
foreach (['Y/m/d H:i:s', 'Y-m-d H:i:s', 'Y/m/d', 'Y-m-d'] as $format) {
$parsed = DateTimeImmutable::createFromFormat($format, $value);
if ($parsed instanceof DateTimeImmutable) {
return $parsed->format('Y-m') . '-01';
}
}
$timestamp = strtotime($value);
return $timestamp === false ? '' : date('Y-m-01', $timestamp);
}
private function moment(string $value): ?string
{
$value = trim($value);
if ($value === '') {
return null;
}
$timestamp = strtotime($value);
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}
private function text(mixed $value): ?string
{
$text = trim((string) $value);
return $text === '' ? null : $text;
}
private function number(mixed $value): ?float
{
$text = str_replace(',', '', trim((string) $value));
if ($text === '' || ! is_numeric($text)) {
return null;
}
return (float) $text;
}
}

View File

@ -2,11 +2,9 @@
namespace App\Console\Commands;
use App\Models\Business\InventoryWarehouseNameMapping;
use Carbon\CarbonImmutable;
use App\Business\InventoryInboundDetailImporter;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Throwable;
/**
* 进销存报表 → 入库明细数据:按原始 Excel 原样导入,仓库简称用仓库名称映射表按「仓库」唯一匹配。
@ -17,194 +15,28 @@ class ImportInventoryInboundDetail extends Command
protected $description = '导入进销存报表的入库明细数据';
public function handle(): int
public function handle(InventoryInboundDetailImporter $importer): int
{
$file = (string) $this->argument('file');
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$table = 'inventory_inbound_detail_rows';
$forcedMonth = trim((string) ($this->option('month') ?? ''));
$now = now();
$maps = $this->shortNameMap();
$this->info('仓库名称映射:仓库名 ' . count($maps['warehouse']) . ' 个、仓储方 ' . count($maps['provider']) . ' 个可唯一匹配');
try {
$result = $importer->import($file, $forcedMonth);
$this->info(sprintf(
'导入完成:%d 行,仓库简称匹配上 %d 行,跳过 %d 行;库中该表共 %d 行',
$result['imported'],
$result['mapped'],
$result['skipped'],
$result['total'],
));
// 原样导入:以本次文件为准整体重建,不做去重、不做加工。
DB::connection($connection)->table($table)->delete();
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);
$this->error('入库明细导入失败:' . $exception->getMessage());
$this->warn('已保留上一版有效数据。');
$reader = IOFactory::createReaderForFile($file);
$reader->setReadDataOnly(true);
$sheet = $reader->load($file)->getSheet(0);
$batch = [];
$imported = 0;
$mapped = 0;
$skipped = 0;
foreach ($sheet->getRowIterator(2) as $row) {
$rowNumber = $row->getRowIndex();
$cells = [];
foreach ($row->getCellIterator('A', 'U') as $cell) {
$cells[] = $cell->getFormattedValue();
}
$warehouse = trim((string) ($cells[14] ?? ''));
$createdRaw = trim((string) ($cells[16] ?? ''));
if ($warehouse === '' && $createdRaw === '') {
$skipped++;
continue;
}
$month = $forcedMonth !== '' ? $forcedMonth : $this->monthOf($createdRaw);
if ($month === '') {
$skipped++;
continue;
}
// 一般用"仓库"匹配仓库简称;含"代发仓"字样的按"仓储方"匹配。
$shortName = '';
if ($warehouse !== '') {
$shortName = str_contains($warehouse, '代发仓')
? ($maps['provider'][$warehouse] ?? $maps['warehouse'][$warehouse] ?? '')
: ($maps['warehouse'][$warehouse] ?? '');
}
if ($shortName !== '') {
$mapped++;
}
$batch[] = [
'report_month' => $month . '-01',
// 唯一键按 Excel 行号生成,保留原表每一行(含重复行)。
'row_key' => sha1($month . '|' . $rowNumber),
'source_no' => $this->text($cells[0] ?? ''),
'document_no' => $this->text($cells[1] ?? ''),
'created_serial' => $this->text($cells[2] ?? ''),
'supplier' => $this->text($cells[3] ?? ''),
'item_no' => $this->text($cells[4] ?? ''),
'barcode' => $this->text($cells[5] ?? ''),
'spec_name' => $this->text($cells[6] ?? ''),
'quantity' => $this->number($cells[7] ?? ''),
'unit_price' => $this->number($cells[8] ?? ''),
'amount' => $this->number($cells[9] ?? ''),
'estimated_unit_price' => $this->number($cells[10] ?? ''),
'estimated_amount' => $this->number($cells[11] ?? ''),
'supplier_barcode' => $this->text($cells[12] ?? ''),
'remark' => $this->text($cells[13] ?? ''),
'warehouse' => $warehouse !== '' ? $warehouse : null,
'warehouse_short_name' => $shortName !== '' ? $shortName : null,
'created_at_raw' => $this->moment($createdRaw),
'express_name' => $this->text($cells[17] ?? ''),
'express_no' => $this->text($cells[18] ?? ''),
'not_sent' => $this->text($cells[19] ?? ''),
'owner_name' => $this->text($cells[20] ?? ''),
'imported_at' => $now,
];
$imported++;
if (count($batch) >= 1000) {
DB::connection($connection)->table($table)->insertOrIgnore($batch);
$this->info('已写入 ' . $imported . ' 行');
$batch = [];
}
return self::FAILURE;
}
if ($batch !== []) {
DB::connection($connection)->table($table)->insertOrIgnore($batch);
}
$this->info(sprintf(
'导入完成:%d 行,仓库简称匹配上 %d 行,跳过 %d 行;库中该表共 %d 行',
$imported,
$mapped,
$skipped,
DB::connection($connection)->table($table)->count(),
));
return self::SUCCESS;
}
/**
* @return array{warehouse:array<string,string>,provider:array<string,string>}
* 仅保留能唯一匹配的键
*/
private function shortNameMap(): array
{
$rows = InventoryWarehouseNameMapping::withoutGlobalScopes()
->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']);
$grouped = [];
foreach ($rows as $row) {
$warehouse = trim((string) $row->warehouse);
if ($warehouse === '') {
continue;
}
$grouped[$warehouse][] = trim((string) $row->warehouse_short_name);
}
$byWarehouse = [];
foreach ($grouped as $warehouse => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byWarehouse[$warehouse] = $unique[0];
}
}
$byProvider = [];
foreach ($rows as $row) {
$provider = trim((string) $row->warehouse_provider);
if ($provider === '') {
continue;
}
$byProvider[$provider][] = trim((string) $row->warehouse_short_name);
}
foreach ($byProvider as $provider => $names) {
$unique = array_values(array_unique($names));
if (count($unique) === 1 && $unique[0] !== '') {
$byProvider[$provider] = $unique[0];
}
}
return ['warehouse' => $byWarehouse, 'provider' => $byProvider];
}
private function monthOf(string $value): string
{
$value = trim($value);
if ($value === '') {
return '';
}
foreach (['Y/m/d H:i:s', 'Y-m-d H:i:s', 'Y/m/d', 'Y-m-d'] as $format) {
$parsed = \DateTimeImmutable::createFromFormat($format, $value);
if ($parsed instanceof \DateTimeImmutable) {
return $parsed->format('Y-m');
}
}
$timestamp = strtotime($value);
return $timestamp === false ? '' : date('Y-m', $timestamp);
}
private function moment(string $value): ?string
{
$value = trim($value);
if ($value === '') {
return null;
}
$timestamp = strtotime($value);
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}
private function text(mixed $value): ?string
{
$text = trim((string) $value);
return $text === '' ? null : $text;
}
private function number(mixed $value): ?float
{
$text = str_replace(',', '', trim((string) $value));
if ($text === '' || ! is_numeric($text)) {
return null;
}
return (float) $text;
}
}

View File

@ -3,6 +3,7 @@
namespace App\Http\Controllers\Business;
use App\Business\BusinessTableImporter;
use App\Business\InventoryInboundDetailImporter;
use App\Business\InventoryWarehouseNameMappingWorkbookImporter;
use App\Business\InventoryWarehouseShortNames;
use App\Business\CourierPayableSummaryFilter;
@ -2791,6 +2792,47 @@ class Pages extends Controller
}, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']);
}
public function importInventoryInboundDetail(
Request $request,
InventoryInboundDetailImporter $importer,
) {
$request->validate([
'file' => ['required', 'file', 'mimes:xlsx,xls', 'max:51200'],
]);
try {
$result = $importer->import((string) $request->file('file')->getRealPath());
} catch (Throwable $exception) {
report($exception);
return $this->inventoryInboundDetailRedirect($request)
->with('error', '入库明细导入失败,请检查 Excel 格式后重新上传。');
}
return $this->inventoryInboundDetailRedirect($request)->with(
'success',
sprintf(
'入库明细导入完成:%s 行,仓库简称匹配 %s 行,跳过 %s 行。',
number_format($result['imported']),
number_format($result['mapped']),
number_format($result['skipped']),
),
);
}
private function inventoryInboundDetailRedirect(Request $request)
{
return redirect()->route('business.pages.show', [
'company_id' => company_id() ?: 1,
'section' => 'product-inventory',
'page' => 'inventory-report',
'tab' => 'inbound-detail',
'detail_month' => substr(trim((string) $request->input('detail_month', '')), 0, 10),
'detail_warehouse' => substr(trim((string) $request->input('detail_warehouse', '')), 0, 191),
'detail_barcode' => substr(trim((string) $request->input('detail_barcode', '')), 0, 191),
]);
}
protected function viewData(
array $section,
?array $page = null,

View File

@ -1032,6 +1032,14 @@
white-space: nowrap;
}
.inventory-inbound-import-form {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
}
.inventory-warehouse-mapping__actions {
display: inline-flex;
gap: 0.4rem;
@ -2343,7 +2351,7 @@
>
<div class="directory-table-notice" role="status">
<span class="material-icons-outlined" aria-hidden="true">cloud_done</span>
<span>已从共享业务镜像读取 {{ $inboundTotal }} 条入库明细,当前页面为只读展示。</span>
<span>已从共享业务镜像读取 {{ $inboundTotal }} 条入库明细;可通过“导入”上传 Excel 整体更新。</span>
</div>
<form method="GET" action="{{ request()->url() }}" class="installation-filter-bar" aria-label="入库明细筛选查询栏">
<label class="installation-filter-field">
@ -2369,8 +2377,30 @@
<button type="submit" class="biz-btn biz-btn-primary">查询</button>
<a href="{{ request()->url() }}#inventory-report-inbound-detail-panel" class="biz-btn biz-btn-ghost">清除</a>
<a href="{{ route('business.product-inventory.inventory-report.inbound-detail.export', ['detail_month' => $inboundMonth, 'detail_warehouse' => $inboundWarehouse ?: null, 'detail_barcode' => $inboundBarcode ?: null]) }}" class="biz-btn">导出</a>
<button type="button" class="biz-btn" data-inventory-inbound-import-trigger>导入</button>
</div>
</form>
<form
id="inventory-inbound-import-form"
method="POST"
enctype="multipart/form-data"
action="{{ route('business.product-inventory.inventory-report.inbound-detail.import') }}"
class="inventory-inbound-import-form"
data-inventory-inbound-import-form
>
@csrf
<input type="hidden" name="detail_month" value="{{ $inboundMonth }}">
<input type="hidden" name="detail_warehouse" value="{{ $inboundWarehouse }}">
<input type="hidden" name="detail_barcode" value="{{ $inboundBarcode }}">
<input
id="inventory-inbound-import-file"
type="file"
name="file"
accept=".xlsx,.xls"
required
data-inventory-inbound-import-file
>
</form>
<div class="directory-table-scroll">
<table class="directory-table" id="inventory-inbound-detail-table" data-finance-table-native>
<thead>
@ -2430,7 +2460,7 @@
<td colspan="22">
<div class="directory-table-empty">
<span class="material-icons-outlined" aria-hidden="true">inbox</span>
<span>尚未导入入库明细数据。</span>
<span>尚未导入入库明细数据,可点击“导入”上传 Excel。</span>
</div>
</td>
</tr>
@ -3171,6 +3201,20 @@
});
});
document.querySelectorAll('[data-inventory-inbound-import-trigger]').forEach((button) => {
const page = button.closest('[data-directory-page]');
const form = page?.querySelector('[data-inventory-inbound-import-form]');
const input = page?.querySelector('[data-inventory-inbound-import-file]');
if (!form || !input) return;
button.addEventListener('click', () => input.click());
input.addEventListener('change', () => {
if (!input.files?.length) return;
button.disabled = true;
button.textContent = '导入中…';
form.requestSubmit();
});
});
document.querySelectorAll('[data-inventory-report-tabs]').forEach((tabs) => {
const report = tabs.closest('[data-directory-page]');
const buttons = [...tabs.querySelectorAll('[data-inventory-report-tab]')];
@ -3198,7 +3242,13 @@
select(buttons[nextIndex].dataset.inventoryReportTab, true);
});
});
select(new URLSearchParams(window.location.search).get('mapping') === '1' ? 'mapping' : 'total');
const params = new URLSearchParams(window.location.search);
const requestedTab = params.get('tab');
const initialTab = requestedTab === 'inbound-detail'
|| window.location.hash === '#inventory-report-inbound-detail-panel'
? 'inbound-detail'
: (params.get('mapping') === '1' ? 'mapping' : 'total');
select(initialTab);
});
document.querySelectorAll('[data-inventory-mapping-dialog]').forEach((dialog) => {

View File

@ -239,6 +239,10 @@ Route::get('workspace/product-inventory/inventory-report/inbound-detail/export',
->middleware('permission:read-business-pages')
->name('business.product-inventory.inventory-report.inbound-detail.export');
Route::post('workspace/product-inventory/inventory-report/inbound-detail/import', 'Business\Pages@importInventoryInboundDetail')
->middleware(['business.page:product-inventory,inventory-report', 'import'])
->name('business.product-inventory.inventory-report.inbound-detail.import');
Route::get('workspace/product-inventory/inventory-report/export', 'Business\Pages@exportInventoryReport')
->middleware('business.page:product-inventory,inventory-report')
->name('business.product-inventory.inventory-report.export');

View File

@ -6,9 +6,13 @@ use App\Models\Auth\Permission;
use App\Models\Business\InventoryWarehouseNameMapping;
use App\Business\InventoryWarehouseShortNames;
use App\Jobs\Common\InventoryReportExport;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Mockery;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Modules\EcommerceFinance\Repositories\CourierFreightReconciliationMirrorRepository;
use Modules\EcommerceFinance\Repositories\NonJingxiRefundMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
@ -88,18 +92,26 @@ class PagesTest extends FeatureTestCase
->assertSee('data-directory-export-all="all-fields"', false)
->assertSee('data-inventory-mapping-template', false)
->assertSee('data-directory-fixed="start"', false)
->assertSee('data-directory-fixed="end"', false);
->assertSee('data-directory-fixed="end"', false)
->assertSee('data-inventory-inbound-import-trigger', false)
->assertSee('data-inventory-inbound-import-form', false)
->assertSee(route('business.product-inventory.inventory-report.inbound-detail.import'), false);
$html = $response->getContent();
$inboundExportPosition = strpos($html, 'inventory-report/inbound-detail/export');
$inboundImportPosition = strpos($html, 'data-inventory-inbound-import-trigger');
$totalPanelStart = strpos($html, 'id="inventory-report-total-panel"');
$mappingPanelStart = strpos($html, 'id="inventory-report-mapping-panel"');
$noticePosition = strpos($html, '已从共享业务镜像读取');
$filterPosition = strpos($html, 'aria-label="进销存报表筛选查询栏"');
$this->assertIsInt($inboundExportPosition);
$this->assertIsInt($inboundImportPosition);
$this->assertIsInt($totalPanelStart);
$this->assertIsInt($mappingPanelStart);
$this->assertIsInt($noticePosition);
$this->assertIsInt($filterPosition);
$this->assertLessThan($inboundImportPosition, $inboundExportPosition);
$this->assertGreaterThan($totalPanelStart, $noticePosition);
$this->assertLessThan($mappingPanelStart, $noticePosition);
$this->assertGreaterThan($totalPanelStart, $filterPosition);
@ -1378,6 +1390,83 @@ class PagesTest extends FeatureTestCase
}
}
public function testInventoryInboundDetailCanBeImportedFromThePage(): void
{
$provider = '测试仓储方-' . uniqid();
$warehouse = '测试仓库-' . uniqid();
InventoryWarehouseNameMapping::query()->create([
'company_id' => 1,
'warehouse_provider' => $provider,
'warehouse' => $warehouse,
'warehouse_short_name' => '测试简称',
]);
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
DB::connection($connection)->table('inventory_inbound_detail_rows')->insert([
'report_month' => '2026-08-01',
'row_key' => sha1('old-row'),
'imported_at' => now(),
]);
$path = tempnam(sys_get_temp_dir(), 'inventory-inbound-');
$xlsxPath = dirname($path) . DIRECTORY_SEPARATOR . basename($path) . '.xlsx';
rename($path, $xlsxPath);
$spreadsheet = new Spreadsheet();
$spreadsheet->getActiveSheet()->fromArray([
[
'来源单号', '单据编号(采购单号)', '创建时间', '供应商', '货号', '条码',
'规格名', '库存变动量', '单价', '金额', '预估单价', '预估金额',
'供应商条码', '备注', '仓库', '仓库简称', '创建时间', '快递名称',
'快递单号', '未发出', '负责人',
],
[
'SRC-1', 'PO-1', '46245', '测试供应商', 'ITEM-1', 'BARCODE-1',
'测试规格', 2, 10, 20, 11, 22, 'SUP-BAR-1', '测试备注',
$warehouse, '测试简称', '2026-09-03 10:00:00', '顺丰', 'SF123',
'否', '测试负责人',
],
], null, 'A1');
(new Xlsx($spreadsheet))->save($xlsxPath);
$spreadsheet->disconnectWorksheets();
$file = new UploadedFile(
$xlsxPath,
'入库明细.xlsx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
null,
true,
);
try {
$response = $this->loginAs()->post(
route('business.product-inventory.inventory-report.inbound-detail.import'),
[
'file' => $file,
'detail_month' => '2026-09-01',
'detail_warehouse' => $warehouse,
'detail_barcode' => 'BARCODE-1',
],
);
} finally {
@unlink($xlsxPath);
}
$response->assertRedirect();
$response->assertSessionHas(
'success',
'入库明细导入完成:1 行,仓库简称匹配 1 行,跳过 0 行。',
);
$rows = DB::connection($connection)->table('inventory_inbound_detail_rows')->get();
$this->assertCount(1, $rows);
$this->assertSame('2026-09-01', substr((string) $rows->first()->report_month, 0, 10));
$this->assertSame($warehouse, $rows->first()->warehouse);
$this->assertSame('测试简称', $rows->first()->warehouse_short_name);
$this->assertSame('BARCODE-1', $rows->first()->barcode);
$this->assertSame('2026-09-03 10:00:00', $rows->first()->created_at_raw);
}
public function testInventoryWarehouseMappingPageUsesTheIndependentLedger(): void
{
$this->loginAs()->get(route('business.pages.show', [