diff --git a/app/Business/InventoryInboundDetailImporter.php b/app/Business/InventoryInboundDetailImporter.php new file mode 100644 index 00000000..073e8cfc --- /dev/null +++ b/app/Business/InventoryInboundDetailImporter.php @@ -0,0 +1,237 @@ +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,provider:array} */ + 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; + } +} diff --git a/app/Console/Commands/ImportInventoryInboundDetail.php b/app/Console/Commands/ImportInventoryInboundDetail.php index 212aab56..bcf625c9 100644 --- a/app/Console/Commands/ImportInventoryInboundDetail.php +++ b/app/Console/Commands/ImportInventoryInboundDetail.php @@ -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,provider:array} - * 仅保留能唯一匹配的键 - */ - 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; } } diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 1a34abf1..2d1372a4 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -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, diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php index c2c05531..089e98c9 100644 --- a/resources/views/business/pages/partials/directory-table.blade.php +++ b/resources/views/business/pages/partials/directory-table.blade.php @@ -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 @@ >
- 已从共享业务镜像读取 {{ $inboundTotal }} 条入库明细,当前页面为只读展示。 + 已从共享业务镜像读取 {{ $inboundTotal }} 条入库明细;可通过“导入”上传 Excel 整体更新。