CaiWuXiTong/app/Console/Commands/ImportKukaErpRecipients.php

165 lines
6.3 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use Throwable;
class ImportKukaErpRecipients extends Command
{
protected $signature = 'kuka-posting:import-erp-recipients
{file : 工作簿5.xlsx 路径}
{--company=1 : 公司 ID}
{--sheet=Sheet1 : 工作表名称}';
protected $description = '导入顾家ERP商品导入使用的收货人池';
public function handle(): int
{
try {
$path = (string) $this->argument('file');
if (! is_file($path)) {
throw new RuntimeException('导入文件不存在。');
}
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
if (! Schema::connection($connectionName)->hasTable('kuka_posting_erp_recipient_rows')) {
throw new RuntimeException('ERP收货人池表尚未建立。');
}
$rows = $this->readRows($path, (string) $this->option('sheet'));
if ($rows === []) {
throw new RuntimeException('工作簿中没有可导入的收货人数据。');
}
$companyId = max(1, (int) $this->option('company'));
$now = now();
DB::connection($connectionName)->transaction(function () use ($connectionName, $companyId, $now, $rows): void {
$connection = DB::connection($connectionName);
$connection->table('kuka_posting_erp_recipient_rows')
->where('company_id', $companyId)
->delete();
$connection->table('kuka_posting_erp_recipient_rows')->insert(array_map(
fn (array $row, int $index): array => $row + [
'company_id' => $companyId,
'sort_order' => $index + 1,
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
],
$rows,
array_keys($rows),
));
});
$this->info('已导入 ERP 收货人池:'.count($rows).' 条。');
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
/**
* @return list<array{receiver_name:string,receiver_mobile:string,receiver_state:string,receiver_city:string,receiver_district:string,receiver_address:string,buyer_nick:string,source_row_number:int,row_hash:string}>
*/
private function readRows(string $path, string $sheetName): array
{
$spreadsheet = IOFactory::load($path);
$sheet = $sheetName === ''
? $spreadsheet->getActiveSheet()
: $spreadsheet->getSheetByName($sheetName);
if ($sheet === null) {
throw new RuntimeException('工作簿中没有指定工作表:'.$sheetName);
}
$data = $sheet->toArray(null, false, false, false);
$headers = [
'收货人(必填)',
'收货人手机(必填)',
'收货人的所在省份(必填)',
'收货人的所在城市(必填)',
'收货人的所在区(县)(必填)',
'收货地址(必填)',
'买家昵称(必填)',
];
$headerIndex = null;
$columns = [];
foreach (array_slice($data, 0, 20, true) as $rowIndex => $row) {
$candidate = [];
foreach ($row as $columnIndex => $value) {
$label = trim((string) $value);
if (in_array($label, $headers, true)) {
$candidate[$label] = $columnIndex;
}
}
if (count($candidate) === count($headers)) {
$headerIndex = (int) $rowIndex;
$columns = $candidate;
break;
}
}
if ($headerIndex === null) {
throw new RuntimeException('未找到工作簿5的标准表头。');
}
$rows = [];
foreach (array_slice($data, $headerIndex + 1, null, true) as $rowIndex => $row) {
$values = [];
foreach ($headers as $header) {
$values[$header] = trim((string) ($row[$columns[$header]] ?? ''));
}
if ($values['收货人(必填)'] === 'clientName'
|| $values['收货人手机(必填)'] === 'clientMobile') {
continue;
}
foreach ($headers as $header) {
if ($values[$header] === '') {
throw new RuntimeException('第 '.($rowIndex + 1).' 行存在必填字段为空。');
}
}
$mobile = $this->normalizeMobile($values['收货人手机(必填)']);
if ($mobile === '') {
throw new RuntimeException('第 '.($rowIndex + 1).' 行收货人手机无效。');
}
$normalized = [
'receiver_name' => $values['收货人(必填)'],
'receiver_mobile' => $mobile,
'receiver_state' => $values['收货人的所在省份(必填)'],
'receiver_city' => $values['收货人的所在城市(必填)'],
'receiver_district' => $values['收货人的所在区(县)(必填)'],
'receiver_address' => $values['收货地址(必填)'],
'buyer_nick' => $values['买家昵称(必填)'],
'source_row_number' => (int) $rowIndex + 1,
];
$normalized['row_hash'] = hash('sha256', json_encode(
$normalized,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
));
$rows[] = $normalized;
}
return $rows;
}
private function normalizeMobile(mixed $value): string
{
$mobile = trim((string) $value);
if ($mobile === '') {
return '';
}
if (is_numeric($mobile) && preg_match('/^\d+(?:\.0+)?$/', $mobile) === 1) {
return number_format((float) $mobile, 0, '', '');
}
return preg_replace('/\s+/u', '', $mobile) ?? '';
}
}