207 lines
6.5 KiB
PHP
207 lines
6.5 KiB
PHP
<?php
|
||
|
||
namespace App\Console\Commands;
|
||
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Modules\EcommerceFinance\Repositories\AfterSalesCostRowRepository;
|
||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||
|
||
/**
|
||
* 导入聚水潭「商品利润 → 导出明细数据 → 订单售后费用数据」Excel。
|
||
*
|
||
* 该报表已按商品编码(组合装拆成组件)给出每行和成本,导入后订单售后费用明细页面
|
||
* 在覆盖的店铺/日期范围内直接按这些明细行展示。
|
||
*/
|
||
class ImportAfterSalesCostRows extends Command
|
||
{
|
||
protected $signature = 'order-data:import-after-sales-cost {file : Excel 文件路径} {--chunk=300 : 每批写入行数}';
|
||
|
||
protected $description = '导入聚水潭「订单售后费用数据」Excel 到订单售后费用明细';
|
||
|
||
public function handle(): int
|
||
{
|
||
$path = (string) $this->argument('file');
|
||
|
||
if (! is_file($path)) {
|
||
$this->error('文件不存在:' . $path);
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$headers = (array) config('order_after_sales_cost.headers', []);
|
||
$numberKeys = array_flip((array) config('order_after_sales_cost.number_keys', []));
|
||
|
||
if ($headers === []) {
|
||
$this->error('缺少表头映射:config/order_after_sales_cost.php');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$this->info('读取文件:' . $path);
|
||
|
||
try {
|
||
$reader = IOFactory::createReaderForFile($path);
|
||
$reader->setReadDataOnly(true);
|
||
$sheet = $reader->load($path)->getActiveSheet();
|
||
} catch (\Throwable $exception) {
|
||
$this->error('读取失败:' . $exception->getMessage());
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
$rowIterator = $sheet->getRowIterator();
|
||
$rowIterator->rewind();
|
||
|
||
$rawHeaders = [];
|
||
$first = true;
|
||
$columns = [];
|
||
$chunkSize = max((int) $this->option('chunk'), 50);
|
||
$buffer = [];
|
||
$total = 0;
|
||
$written = 0;
|
||
$skipped = 0;
|
||
$shops = [];
|
||
$minDate = null;
|
||
$maxDate = null;
|
||
$importedAt = now()->toDateTimeString();
|
||
|
||
foreach ($rowIterator as $row) {
|
||
$cells = [];
|
||
foreach ($row->getCellIterator() as $cell) {
|
||
$cells[] = $cell->getValue();
|
||
}
|
||
|
||
if ($first) {
|
||
$first = false;
|
||
$rawHeaders = array_map(static fn ($v) => self::normalizeHeader((string) $v), $cells);
|
||
|
||
foreach ($rawHeaders as $index => $header) {
|
||
if ($header !== '' && isset($headers[$header])) {
|
||
$columns[$index] = $headers[$header];
|
||
}
|
||
}
|
||
|
||
if ($columns === []) {
|
||
$this->error('表头和配置的映射对不上,请检查文件或 config/order_after_sales_cost.php');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
|
||
continue;
|
||
}
|
||
|
||
$total++;
|
||
$payload = [];
|
||
|
||
foreach ($columns as $index => $key) {
|
||
$value = $cells[$index] ?? null;
|
||
|
||
if (is_string($value)) {
|
||
$value = trim($value);
|
||
}
|
||
|
||
if ($value === '' || $value === null) {
|
||
continue;
|
||
}
|
||
|
||
if (isset($numberKeys[$key])) {
|
||
$value = is_numeric($value) ? (float) $value : 0.0;
|
||
} elseif (self::isDateKey($key)) {
|
||
$value = self::dateValue($value);
|
||
}
|
||
|
||
$payload[$key] = $value;
|
||
}
|
||
|
||
$shop = trim((string) ($payload['shop_name'] ?? ''));
|
||
|
||
if ($shop === '' || empty($payload['product_code'])) {
|
||
$skipped++;
|
||
|
||
continue;
|
||
}
|
||
|
||
$buffer[] = AfterSalesCostRowRepository::toRecord($payload, $importedAt);
|
||
$shops[$shop] = true;
|
||
$orderTime = $payload['order_time'] ?? null;
|
||
|
||
if (is_string($orderTime) && $orderTime !== '') {
|
||
$minDate = $minDate === null || $orderTime < $minDate ? $orderTime : $minDate;
|
||
$maxDate = $maxDate === null || $orderTime > $maxDate ? $orderTime : $maxDate;
|
||
}
|
||
|
||
if (count($buffer) >= $chunkSize) {
|
||
$written += $this->flush($buffer);
|
||
$buffer = [];
|
||
$this->output->write("\r写入 " . $written . ' 行');
|
||
}
|
||
}
|
||
|
||
if ($buffer !== []) {
|
||
$written += $this->flush($buffer);
|
||
}
|
||
|
||
$this->newLine(2);
|
||
$this->info(sprintf(
|
||
'完成:读取 %d 行,写入 %d 行,跳过 %d 行;店铺 %d 个;订单时间 %s ~ %s',
|
||
$total,
|
||
$written,
|
||
$skipped,
|
||
count($shops),
|
||
$minDate ?? '-',
|
||
$maxDate ?? '-',
|
||
));
|
||
|
||
return self::SUCCESS;
|
||
}
|
||
|
||
/** @param list<array<string,mixed>> $rows */
|
||
private function flush(array $rows): int
|
||
{
|
||
DB::table('ops_after_sales_cost_rows')->upsert(
|
||
$rows,
|
||
['row_key'],
|
||
[
|
||
'shop_name', 'shop_code', 'online_order_no', 'internal_order_no', 'product_code',
|
||
'order_time', 'product_quantity', 'product_amount', 'product_cost', 'cost_source',
|
||
'combine_type', 'payload', 'imported_at', 'updated_at',
|
||
],
|
||
);
|
||
|
||
return count($rows);
|
||
}
|
||
|
||
private static function normalizeHeader(string $header): string
|
||
{
|
||
$header = str_replace(["\u{3000}", "\u{00A0}"], ' ', $header);
|
||
$header = preg_replace('/\s+/u', ' ', $header) ?? $header;
|
||
|
||
return trim($header);
|
||
}
|
||
|
||
private static function isDateKey(string $key): bool
|
||
{
|
||
return in_array($key, [
|
||
'pay_time', 'order_complete_time', 'send_time', 'order_time', 'registration_time',
|
||
'confirmation_time', 'warehouse_entry_time',
|
||
], true);
|
||
}
|
||
|
||
private static function dateValue(mixed $value): ?string
|
||
{
|
||
if ($value instanceof \DateTimeInterface) {
|
||
return $value->format('Y-m-d H:i:s');
|
||
}
|
||
|
||
if (is_numeric($value) && (float) $value > 20000 && (float) $value < 80000) {
|
||
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d H:i:s');
|
||
}
|
||
|
||
$timestamp = strtotime((string) $value);
|
||
|
||
return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
|
||
}
|
||
}
|