CaiWuXiTong/app/Business/CompanyPlan/CompanyPlanWorkbookImporter.php
DoDo 692d590509 feat: 公司盘点页面与未完结店铺关联
新增经营报表 › 公司盘点,支持导入预览、筛选、备注关键词搜索、编辑、导出及未完结店铺关联。

验证:公司盘点与导航相关测试 15 项通过(161 断言),目录表头测试 99 断言通过。
边界:原始 Excel 与本地 SQLite 数据不进入 Git;本次无数据库迁移。
2026-11-09 15:43:43 +08:00

445 lines
15 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Business\CompanyPlan;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Throwable;
class CompanyPlanWorkbookImporter
{
/**
* 类型口径归一:与 CompanyPlanRepository::COMPANY_TYPE_ALIASES 保持一致。
*
* @var array<string,string>
*/
private const COMPANY_TYPE_ALIASES = [
'个体户' => '个体工商户',
];
/**
* 公司状态口径归一:与 CompanyPlanRepository::COMPANY_STATUS_ALIASES 保持一致。
*
* @var array<string,string>
*/
private const COMPANY_STATUS_ALIASES = [
'注销' => '已注销',
];
private const KNOWN_HEADERS = [
'序号' => 'sequence_no',
'公司名称' => 'company_name',
'类型' => 'company_type',
'税务类型' => 'taxpayer_type',
'注册时间' => 'registered_at',
'工商类型' => 'business_registration_type',
'统一社会信用代码' => 'unified_social_credit_code',
'规划' => 'plan',
'公司状态' => 'company_status',
'注销-税务' => 'tax_cancellation',
'注销-工商' => 'business_cancellation',
'注销-银行' => 'bank_cancellation',
'备注' => 'notes',
];
public function __construct(private readonly CompanyPlanRepository $repository) {}
/**
* @return array<string,mixed>
*/
public function preview(UploadedFile $file, int $companyId, int $userId, string $duplicateMode): array
{
$duplicateMode = $duplicateMode === 'skip' ? 'skip' : 'update';
$parsed = $this->parse($file);
$existing = $this->repository->companyNames($companyId);
$newCount = 0;
$updateCount = 0;
$skipCount = 0;
foreach ($parsed['rows'] as $row) {
$exists = isset($existing[$this->repository->normalizeCompanyName($row['company_name'])]);
if (! $exists) {
$newCount++;
} elseif ($duplicateMode === 'skip') {
$skipCount++;
} else {
$updateCount++;
}
}
return [
'company_id' => $companyId,
'user_id' => $userId,
'generated_at' => now()->format('Y-m-d H:i:s'),
'duplicate_mode' => $duplicateMode,
'source_sheet' => $parsed['source_sheet'],
'mapped_headers' => $parsed['mapped_headers'],
'missing_headers' => $parsed['missing_headers'],
'scanned_rows' => $parsed['scanned_rows'],
'valid_rows' => count($parsed['rows']),
'blank_rows' => $parsed['blank_rows'],
'invalid_rows' => $parsed['invalid_rows'],
'invalid_count' => $parsed['invalid_count'],
'new_count' => $newCount,
'update_count' => $updateCount,
'skip_count' => $skipCount,
'rows' => $parsed['rows'],
'sample_rows' => array_slice($parsed['rows'], 0, 10),
];
}
public function storePreview(array $preview): string
{
$token = Str::random(40);
$json = json_encode(
$preview,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR
);
if (! Storage::disk((string) config('company_plan.preview_disk', 'local'))->put(
$this->previewPath($token),
$json
)) {
throw new \RuntimeException('无法保存公司盘点导入预览。');
}
return $token;
}
/**
* @return array<string,mixed>|null
*/
public function previewByToken(string $token, int $companyId, int $userId): ?array
{
if (! preg_match('/^[A-Za-z0-9]{40}$/', $token)) {
return null;
}
$disk = Storage::disk((string) config('company_plan.preview_disk', 'local'));
if (! $disk->exists($this->previewPath($token))) {
return null;
}
try {
$preview = json_decode($disk->get($this->previewPath($token)), true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable) {
$disk->delete($this->previewPath($token));
return null;
}
if (! is_array($preview)
|| (int) ($preview['company_id'] ?? 0) !== $companyId
|| (int) ($preview['user_id'] ?? 0) !== $userId) {
return null;
}
return $preview;
}
/**
* @return array{created:int,updated:int,skipped:int}
*/
public function confirm(string $token, int $companyId, int $userId, string $duplicateMode): array
{
$preview = $this->previewByToken($token, $companyId, $userId);
if ($preview === null) {
throw ValidationException::withMessages([
'import' => '导入预览已失效,请重新选择文件。',
]);
}
$result = $this->repository->importRows(
$companyId,
(array) ($preview['rows'] ?? []),
$duplicateMode === 'skip' ? 'skip' : 'update',
$userId,
);
$this->deletePreview($token);
return $result;
}
public function deletePreview(string $token): void
{
if (preg_match('/^[A-Za-z0-9]{40}$/', $token)) {
Storage::disk((string) config('company_plan.preview_disk', 'local'))
->delete($this->previewPath($token));
}
}
/**
* @return array{
* source_sheet:string,
* mapped_headers:list<string>,
* missing_headers:list<string>,
* scanned_rows:int,
* blank_rows:int,
* invalid_count:int,
* invalid_rows:list<array{row:int,company_name:string,reason:string}>,
* rows:list<array<string,mixed>>
* }
*/
private function parse(UploadedFile $file): array
{
try {
$reader = IOFactory::createReaderForFile($file->getRealPath());
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file->getRealPath());
} catch (Throwable $exception) {
report($exception);
throw ValidationException::withMessages([
'import' => '无法读取 Excel,请确认文件未损坏且格式为 xlsx/xls。',
]);
}
try {
[$worksheet, $headerRowIndex, $headerMap] = $this->resolveWorksheet($spreadsheet->getAllSheets());
} catch (Throwable $exception) {
$spreadsheet->disconnectWorksheets();
throw $exception;
}
$allRows = $worksheet->toArray(null, true, true, false);
$dataRows = array_slice($allRows, $headerRowIndex + 1);
$maxImportRows = max((int) config('company_plan.max_import_rows', 20000), 1);
if (count($dataRows) > $maxImportRows) {
$spreadsheet->disconnectWorksheets();
throw ValidationException::withMessages([
'import' => "单次最多导入 {$maxImportRows} 行,请拆分工作簿后重试。",
]);
}
$fieldsByName = collect(CompanyPlanRepository::FIELDS)->keyBy('name');
$mappedFields = array_values($headerMap);
$missingHeaders = $fieldsByName
->except($mappedFields)
->pluck('label')
->values()
->all();
$rows = [];
$invalidRows = [];
$invalidCount = 0;
$blankRows = 0;
$seenCompanies = [];
foreach ($dataRows as $offset => $rawRow) {
$sourceRow = $headerRowIndex + $offset + 2;
$hasAnyValue = false;
$rowInvalid = false;
$data = [];
foreach ($headerMap as $columnIndex => $fieldName) {
$rawValue = $rawRow[$columnIndex] ?? null;
if ($rawValue !== null && trim((string) $rawValue) !== '') {
$hasAnyValue = true;
}
try {
$data[$fieldName] = $this->normalizeValue($rawValue, $fieldName);
} catch (Throwable $exception) {
$data[$fieldName] = null;
$rowInvalid = true;
$this->appendInvalidRow(
$invalidRows,
$invalidCount,
$sourceRow,
(string) ($rawRow[array_search('company_name', $headerMap, true)] ?? ''),
'第 ' . ($columnIndex + 1) . ' 列“' . ($fieldsByName[$fieldName]['label'] ?? $fieldName) . '”格式不正确。',
);
}
}
if (! $hasAnyValue) {
$blankRows++;
continue;
}
$companyName = trim((string) ($data['company_name'] ?? ''));
if ($rowInvalid) {
continue;
}
if ($companyName === '') {
$this->appendInvalidRow($invalidRows, $invalidCount, $sourceRow, '', '公司名称为空。');
continue;
}
$normalizedCompany = $this->repository->normalizeCompanyName($companyName);
if (isset($seenCompanies[$normalizedCompany])) {
$this->appendInvalidRow(
$invalidRows,
$invalidCount,
$sourceRow,
$companyName,
'文件内公司名称重复,首次出现的第 ' . $seenCompanies[$normalizedCompany] . ' 行优先。',
);
continue;
}
$seenCompanies[$normalizedCompany] = $sourceRow;
$data['company_name'] = $companyName;
$data['_source_row'] = $sourceRow;
$rows[] = $data;
}
usort($invalidRows, static fn (array $left, array $right): int => $left['row'] <=> $right['row']);
$sourceSheet = $worksheet->getTitle();
$spreadsheet->disconnectWorksheets();
return [
'source_sheet' => $sourceSheet,
'mapped_headers' => array_values(array_map(
static fn (string $field): string => (string) ($fieldsByName[$field]['label'] ?? $field),
$mappedFields
)),
'missing_headers' => $missingHeaders,
'scanned_rows' => count($dataRows),
'blank_rows' => $blankRows,
'invalid_count' => $invalidCount,
'invalid_rows' => $invalidRows,
'rows' => $rows,
];
}
/**
* @param list<Worksheet> $worksheets
* @return array{0:Worksheet,1:int,2:array<int,string>}
*/
private function resolveWorksheet(array $worksheets): array
{
foreach ($worksheets as $worksheet) {
if ($worksheet->getTitle() === '主体盘点') {
$rows = $worksheet->toArray(null, true, true, false);
[$headerRowIndex, $headerMap] = $this->findHeader($rows);
if ($headerMap !== []) {
return [$worksheet, $headerRowIndex, $headerMap];
}
}
}
$best = null;
foreach ($worksheets as $worksheet) {
$rows = $worksheet->toArray(null, true, true, false);
[$headerRowIndex, $headerMap] = $this->findHeader($rows);
if ($best === null || count($headerMap) > count($best[2])) {
$best = [$worksheet, $headerRowIndex, $headerMap];
}
}
if ($best === null || ! in_array('company_name', $best[2], true)) {
throw ValidationException::withMessages([
'import' => '未找到“公司名称”等主体盘点表头,请使用下载的导入模板或附件中的“主体盘点”工作表。',
]);
}
return $best;
}
/**
* @param list<array<int,mixed>> $rows
* @return array{0:int,1:array<int,string>}
*/
private function findHeader(array $rows): array
{
$bestIndex = 0;
$bestMap = [];
foreach (array_slice($rows, 0, 20, true) as $rowIndex => $row) {
$map = [];
foreach ($row as $columnIndex => $value) {
$normalized = $this->normalizeHeader($value);
if (isset(self::KNOWN_HEADERS[$normalized])) {
$map[$columnIndex] = self::KNOWN_HEADERS[$normalized];
}
}
if (count($map) > count($bestMap)) {
$bestIndex = $rowIndex;
$bestMap = $map;
}
}
return [$bestIndex, $bestMap];
}
private function normalizeHeader(mixed $value): string
{
$header = str_replace(["\u{FEFF}", "\u{00A0}", '-', '—', '–'], ['', ' ', '-', '-', '-'], trim((string) $value));
return preg_replace('/\s+/u', '', $header) ?? $header;
}
private function normalizeValue(mixed $value, string $field): mixed
{
if ($value === null || trim((string) $value) === '') {
return null;
}
if ($field === 'sequence_no') {
if (! is_numeric($value)) {
throw new \InvalidArgumentException('序号不是数字');
}
return (int) $value;
}
if ($field === 'registered_at') {
return $this->normalizeDate($value);
}
$normalized = trim(str_replace("\u{00A0}", ' ', (string) $value));
if ($field === 'company_type') {
$normalized = self::COMPANY_TYPE_ALIASES[$normalized] ?? $normalized;
}
if ($field === 'company_status') {
$normalized = self::COMPANY_STATUS_ALIASES[$normalized] ?? $normalized;
}
return $normalized;
}
private function normalizeDate(mixed $value): string
{
if ($value instanceof \DateTimeInterface) {
return $value->format('Y-m-d');
}
if (is_numeric($value)) {
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d');
}
return \Illuminate\Support\Carbon::parse((string) $value)->format('Y-m-d');
}
/**
* @param list<array{row:int,company_name:string,reason:string}> $rows
*/
private function appendInvalidRow(array &$rows, int &$count, int $row, string $companyName, string $reason): void
{
$count++;
if (count($rows) < 200) {
$rows[] = [
'row' => $row,
'company_name' => trim($companyName),
'reason' => $reason,
];
}
}
private function previewPath(string $token): string
{
return trim((string) config('company_plan.preview_directory', 'company-plan/previews'), '/')
. '/' . $token . '.json';
}
}