diff --git a/app/Business/JstOrderExportReader.php b/app/Business/JstOrderExportReader.php new file mode 100644 index 000000000..1db58413a --- /dev/null +++ b/app/Business/JstOrderExportReader.php @@ -0,0 +1,297 @@ + 只写一个 A1,靠它判断行数会把整表读成空; + * - 一行订单一个商品明细,单文件常见上万行 × 上百列,解压后几十 MB。 + * + * 所以这里用 ZipArchive 取压缩流 + expat 增量解析,只保留调用方点名的列, + * 内存占用与文件大小无关(导出 20 万行也不会整表进内存)。 + */ +class JstOrderExportReader +{ + private const READ_CHUNK = 262144; + + /** + * 逐行读取导出文件(跳过表头行)。 + * + * @param list $columns 需要取出并作为返回键的表头名,必须与文件第一行完全一致 + * @return Generator> + */ + public function rows(string $path, array $columns): Generator + { + if (! is_file($path)) { + throw new RuntimeException('订单导出文件不存在:' . $path); + } + + $zip = new ZipArchive(); + if ($zip->open($path) !== true) { + throw new RuntimeException('无法打开订单导出文件(不是有效的 xlsx):' . $path); + } + + $stream = $zip->getStream($this->worksheetPath($zip)); + if ($stream === false) { + $zip->close(); + + throw new RuntimeException('订单导出文件里没有可读的工作表。'); + } + + try { + yield from $this->parseSheet($stream, $this->sharedStrings($zip), $columns); + } finally { + fclose($stream); + $zip->close(); + } + } + + /** + * @param resource $stream + * @param list $shared + * @param list $columns + * @return Generator> + */ + private function parseSheet($stream, array $shared, array $columns): Generator + { + $state = [ + 'row' => [], + 'column' => -1, + 'type' => null, + 'value' => '', + 'inValue' => false, + 'rowNumber' => 0, + 'wanted' => [], + 'pending' => [], + ]; + + $parser = xml_parser_create('UTF-8'); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); + + xml_set_element_handler( + $parser, + static function ($parser, string $name, array $attributes) use (&$state): void { + switch ($name) { + case 'row': + $state['row'] = []; + $state['column'] = -1; + break; + + case 'c': + $state['column'] = self::columnIndex($attributes['r'] ?? null, $state['column'] + 1); + $state['type'] = $attributes['t'] ?? null; + $state['value'] = ''; + break; + + case 'v': + case 't': + $state['inValue'] = true; + break; + } + }, + static function ($parser, string $name) use (&$state, $shared, $columns): void { + switch ($name) { + case 'v': + case 't': + $state['inValue'] = false; + break; + + case 'c': + $state['row'][$state['column']] = self::cellValue($state['type'], $state['value'], $shared); + break; + + case 'row': + $state['rowNumber']++; + if ($state['rowNumber'] === 1) { + $state['wanted'] = self::wantedColumns($state['row'], $columns); + + break; + } + + $values = []; + foreach ($state['wanted'] as $index => $column) { + $values[$column] = $state['row'][$index] ?? ''; + } + $state['pending'][] = $values; + break; + } + } + ); + + xml_set_character_data_handler($parser, static function ($parser, string $data) use (&$state): void { + if ($state['inValue']) { + $state['value'] .= $data; + } + }); + + $first = true; + try { + while (! feof($stream)) { + $chunk = fread($stream, self::READ_CHUNK); + if ($chunk === false || $chunk === '') { + break; + } + if ($first) { + // 聚水潭导出的 XML 带 UTF-8 BOM,expat 会当成非法前缀。 + $chunk = preg_replace('/^\xEF\xBB\xBF/', '', $chunk, 1); + $first = false; + } + + if (xml_parse($parser, $chunk, false) === 0) { + throw new RuntimeException('订单导出文件解析失败:' . xml_error_string(xml_get_error_code($parser))); + } + + while ($state['pending'] !== []) { + yield array_shift($state['pending']); + } + } + + if (xml_parse($parser, '', true) === 0) { + throw new RuntimeException('订单导出文件解析失败:' . xml_error_string(xml_get_error_code($parser))); + } + } finally { + xml_parser_free($parser); + } + + while ($state['pending'] !== []) { + yield array_shift($state['pending']); + } + } + + /** + * 表头行 -> [列下标 => 列名],并校验需要的列都在。 + * + * @param array $header + * @param list $columns + * @return array + */ + private static function wantedColumns(array $header, array $columns): array + { + $byName = []; + foreach ($header as $index => $name) { + $name = trim($name); + if ($name !== '' && ! isset($byName[$name])) { + $byName[$name] = $index; + } + } + + $wanted = []; + foreach ($columns as $column) { + if (! isset($byName[$column])) { + throw new RuntimeException('订单导出文件缺少列:' . $column); + } + $wanted[$byName[$column]] = $column; + } + + return $wanted; + } + + /** + * @param list $shared + */ + private static function cellValue(?string $type, string $value, array $shared): string + { + if ($type === 's') { + return $shared[(int) $value] ?? ''; + } + + return trim($value); + } + + /** 单元格引用(如 AV12)-> 0 基列下标。 */ + private static function columnIndex(?string $reference, int $fallback): int + { + if ($reference === null || preg_match('/^([A-Z]+)/i', $reference, $matches) !== 1) { + return $fallback; + } + + $letters = strtoupper($matches[1]); + $index = 0; + for ($i = 0, $length = strlen($letters); $i < $length; $i++) { + $index = $index * 26 + (ord($letters[$i]) - 64); + } + + return $index - 1; + } + + private function worksheetPath(ZipArchive $zip): string + { + $workbook = $zip->getFromName('xl/workbook.xml'); + $relationships = $zip->getFromName('xl/_rels/workbook.xml.rels'); + if (is_string($workbook) && is_string($relationships) + && preg_match('/]*r:id="([^"]+)"/', $workbook, $sheet) === 1 + && preg_match('/Id="' . preg_quote($sheet[1], '/') . '"[^>]*Target="([^"]+)"/', $relationships, $target) === 1) { + $path = ltrim($target[1], '/'); + + return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path; + } + + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = (string) $zip->getNameIndex($i); + if (preg_match('#^xl/worksheets/[^/]+\.xml$#', $name) === 1) { + return $name; + } + } + + return 'xl/worksheets/sheet1.xml'; + } + + /** + * 读取共享字符串表;聚水潭导出通常为空,但标准 xlsx 会用到。 + * + * @return list + */ + private function sharedStrings(ZipArchive $zip): array + { + $xml = $zip->getFromName('xl/sharedStrings.xml'); + if (! is_string($xml) || $xml === '') { + return []; + } + + $out = []; + $index = -1; + $buffer = ''; + $inside = false; + + $parser = xml_parser_create('UTF-8'); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); + xml_set_element_handler( + $parser, + static function ($parser, string $name) use (&$inside, &$buffer, &$index): void { + if ($name === 'si') { + $index++; + $buffer = ''; + } elseif ($name === 't') { + $inside = true; + } + }, + static function ($parser, string $name) use (&$inside, &$buffer, &$out): void { + if ($name === 't') { + $inside = false; + } elseif ($name === 'si') { + $out[] = $buffer; + } + } + ); + xml_set_character_data_handler($parser, static function ($parser, string $data) use (&$inside, &$buffer): void { + if ($inside) { + $buffer .= $data; + } + }); + + try { + xml_parse($parser, preg_replace('/^\xEF\xBB\xBF/', '', $xml, 1), true); + } finally { + xml_parser_free($parser); + } + + return $out; + } +} diff --git a/app/Business/JstOrderLabelImporter.php b/app/Business/JstOrderLabelImporter.php index 7f4f5381d..bd4fc5b05 100644 --- a/app/Business/JstOrderLabelImporter.php +++ b/app/Business/JstOrderLabelImporter.php @@ -7,10 +7,14 @@ use InvalidArgumentException; use RuntimeException; /** - * 聚水潭订单标签明细导入(从共享镜像 ops_jst_orders 拆标签写入 jst_order_labels)。 + * 聚水潭订单标签明细导入(拆标签写入 jst_order_labels)。 * * 一个标签一行:一单有 N 个标签就写 N 行;订单不去重、标签不汇总。 * 无标签的订单保留一行,标签记为「(无标签)」,方便与订单总数核对。 + * + * 两个数据源: + * - 共享镜像 ops_jst_orders(常规,覆盖镜像有数据的区间); + * - 聚水潭「导出订单」Excel(镜像没有的历史区间,例如 2026-03,只能靠财务导出补)。 */ class JstOrderLabelImporter { @@ -20,7 +24,13 @@ class JstOrderLabelImporter private const INSERT_CHUNK = 2000; - public function __construct(private readonly DatabaseManager $databases) {} + /** 聚水潭导出文件里用到的表头。 */ + private const EXPORT_COLUMNS = ['线上订单号', '店铺名称', '下单时间', '标签']; + + public function __construct( + private readonly DatabaseManager $databases, + private readonly ?JstOrderExportReader $exportReader = null, + ) {} /** * @return array{from:string,to:string,orders:int,rows:int,no_label_orders:int,labels:int,seconds:float} @@ -44,13 +54,16 @@ class JstOrderLabelImporter $target = $this->databases->connection(); $startedAt = microtime(true); - if ($replace) { + // 清空区间放到第一次成功读到数据行之后:万一文件打不开或表头不对, + // 不能先把线上已有行删掉又导入失败。 + $clearWindow = function () use ($target, $companyId, $start, $end): void { $target->table('jst_order_labels') ->where('company_id', $companyId) ->where('ordered_at', '>=', $start) ->where('ordered_at', '<', $end) ->delete(); - } + }; + $cleared = ! $replace; $now = now(); $orders = 0; @@ -127,6 +140,172 @@ class JstOrderLabelImporter ]; } + /** + * 从聚水潭「导出订单」Excel 导入。 + * + * 导出文件是一单多行(商品明细),这里按「线上订单号 + 标签」去重后拆行写入; + * 同时兼容「导出订单」直接勾选 4 列导出的极简表头。 + * + * 传 $from/$to 时会顺带按窗口过滤;带 $replace 时必须给窗口, + * 以便在写入前先清掉该区间,避免重复导入翻倍。 + * + * @return array{file:string,company_id:int,from:?string,to:?string,orders:int,rows:int,no_label_orders:int,skipped:int,labels:int,seconds:float} + */ + public function importFromFile( + string $path, + ?string $from = null, + ?string $to = null, + int $companyId = 1, + bool $replace = false, + string $source = 'jst-order-label-file-import', + ): array { + $from = $from === null || trim($from) === '' ? null : $this->normalizeDate(trim($from), '起始日期'); + $to = $to === null || trim($to) === '' ? null : $this->normalizeDate(trim($to), '结束日期'); + if ($from !== null && $to !== null && $from > $to) { + throw new InvalidArgumentException('起始日期不能晚于结束日期。'); + } + if ($replace && ($from === null || $to === null)) { + throw new InvalidArgumentException('按文件导入并使用 --replace 时,必须同时给出 --from 与 --to,才能确定要清空的区间。'); + } + + $start = $from === null ? null : $from . ' 00:00:00'; + $end = $to === null ? null : date('Y-m-d', strtotime($to . ' +1 day')) . ' 00:00:00'; + + $target = $this->databases->connection(); + $startedAt = microtime(true); + + if ($replace) { + $target->table('jst_order_labels') + ->where('company_id', $companyId) + ->where('ordered_at', '>=', $start) + ->where('ordered_at', '<', $end) + ->delete(); + } + + $now = now(); + $orders = 0; + $rows = 0; + $noLabelOrders = 0; + $skipped = 0; + $seen = []; + $orderSeen = []; + $buffer = []; + + $flush = function () use (&$buffer, &$rows, $target): void { + foreach (array_chunk($buffer, self::INSERT_CHUNK) as $chunk) { + $target->table('jst_order_labels')->insert($chunk); + $rows += count($chunk); + } + $buffer = []; + }; + + $reader = $this->exportReader ?? app(JstOrderExportReader::class); + $anyRow = false; + + foreach ($reader->rows($path, self::EXPORT_COLUMNS) as $line) { + $anyRow = true; + if (! $cleared) { + $clearWindow(); + $cleared = true; + } + + $orderNo = trim((string) ($line['线上订单号'] ?? '')); + $orderedAt = $this->normalizeOrderedAt((string) ($line['下单时间'] ?? '')); + if ($orderNo === '' || $orderedAt === null) { + $skipped++; + + continue; + } + if ($start !== null && ($orderedAt < $start || $orderedAt >= $end)) { + $skipped++; + + continue; + } + + if (! isset($orderSeen[$orderNo])) { + $orderSeen[$orderNo] = true; + $orders++; + } + + $shopName = mb_substr(trim((string) ($line['店铺名称'] ?? '')), 0, 191); + $labels = $this->splitLabels((string) ($line['标签'] ?? '')); + $withoutLabel = $labels === []; + if ($labels === []) { + $labels = [self::NO_LABEL]; + } + + foreach ($labels as $label) { + $fingerprint = hash('xxh3', $orderNo . "\0" . $label); + if (isset($seen[$fingerprint])) { + continue; + } + $seen[$fingerprint] = true; + if ($withoutLabel) { + $noLabelOrders++; + } + + $buffer[] = [ + 'company_id' => $companyId, + 'order_no' => mb_substr($orderNo, 0, 100), + 'shop_name' => $shopName, + 'ordered_at' => $orderedAt, + 'label' => $label, + 'created_from' => $source, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + if (count($buffer) >= self::INSERT_CHUNK * 2) { + $flush(); + } + } + + if (! $anyRow) { + throw new RuntimeException('订单导出文件里没有数据行:' . basename($path)); + } + if (! $cleared) { + $clearWindow(); + } + + $flush(); + + $labelQuery = $target->table('jst_order_labels')->where('company_id', $companyId); + if ($start !== null) { + $labelQuery->where('ordered_at', '>=', $start)->where('ordered_at', '<', $end); + } + $labels = $labelQuery->distinct()->count('label'); + + app(JstOrderLabelOptions::class)->forget($companyId); + app(JstOrderLabelOptions::class)->warm($companyId); + + return [ + 'file' => basename($path), + 'company_id' => $companyId, + 'from' => $from, + 'to' => $to, + 'orders' => $orders, + 'rows' => $rows, + 'no_label_orders' => $noLabelOrders, + 'skipped' => $skipped, + 'labels' => (int) $labels, + 'seconds' => round(microtime(true) - $startedAt, 1), + ]; + } + + /** 下单时间归一成 Y-m-d H:i:s;解析不了就返回 null(该行跳过)。 */ + private function normalizeOrderedAt(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); + } + /** @return list */ private function splitLabels(string $labels): array { diff --git a/app/Business/JstOrderLabelOptions.php b/app/Business/JstOrderLabelOptions.php index 57e2a7dcd..9bc516858 100644 --- a/app/Business/JstOrderLabelOptions.php +++ b/app/Business/JstOrderLabelOptions.php @@ -10,6 +10,9 @@ use Illuminate\Support\Facades\Cache; * * 表里有 200 万行以上,distinct 扫描一次要几秒;这里按公司缓存 24 小时, * 导入命令结束时会主动预热,避免每次打开页面都慢。 + * + * 上限只是防呆(选项过多会拖慢页面),要高于实际店铺数:2026-10 导入 4~7 月后 + * 店铺已达 604 个,原来卡在 500 会让一部分店铺选不出来。 */ class JstOrderLabelOptions { @@ -17,7 +20,7 @@ class JstOrderLabelOptions private const TOTAL_TTL_MINUTES = 30; - private const LIMIT = 500; + private const LIMIT = 5000; /** @return list */ public function labels(int $companyId): array diff --git a/app/Console/Commands/ImportJstOrderLabels.php b/app/Console/Commands/ImportJstOrderLabels.php index 6e71a18d6..06e0b7787 100644 --- a/app/Console/Commands/ImportJstOrderLabels.php +++ b/app/Console/Commands/ImportJstOrderLabels.php @@ -11,24 +11,25 @@ class ImportJstOrderLabels extends Command protected $signature = 'jst-order-labels:import {--from= : 起始下单日期 YYYY-MM-DD} {--to= : 结束下单日期 YYYY-MM-DD} + {--file= : 聚水潭「导出订单」Excel 路径;给了它就从文件导入(镜像没有的历史区间用)} {--company=1 : 公司 ID} {--replace : 先清空该区间已有行}'; - protected $description = '把聚水潭订单按标签拆行导入「聚水潭订单标签明细」(账单流水数据页)'; + protected $description = '把聚水潭订单按标签拆行导入「聚水潭订单标签明细」:默认读共享镜像,给 --file 则读聚水潭导出的订单 Excel'; public function handle(JstOrderLabelImporter $importer): int { $from = (string) $this->option('from'); $to = (string) $this->option('to'); + $file = trim((string) $this->option('file')); try { - $result = $importer->import( - $from, - $to, - (int) $this->option('company'), - (bool) $this->option('replace'), - 'jst-order-label-import', - ); + $companyId = (int) $this->option('company'); + $replace = (bool) $this->option('replace'); + + $result = $file === '' + ? $importer->import($from, $to, $companyId, $replace, 'jst-order-label-import') + : $importer->importFromFile($file, $from ?: null, $to ?: null, $companyId, $replace); } catch (Throwable $exception) { $this->error($exception->getMessage()); diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 3959b2a75..c855c6eda 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -1866,7 +1866,8 @@ class Pages extends Controller * * @return list */ - private function filterValues(mixed $raw, int $maxLength, int $limit = 500): array + // 上限与 JstOrderLabelOptions::LIMIT 对齐:下拉里能选到的值,提交时不能被悄悄截断。 + private function filterValues(mixed $raw, int $maxLength, int $limit = 5000): array { $list = is_array($raw) ? $raw : [$raw]; $values = []; diff --git a/tests/Feature/Business/JstOrderLabelsPageTest.php b/tests/Feature/Business/JstOrderLabelsPageTest.php index 5001dcd6e..6f51ffbca 100644 --- a/tests/Feature/Business/JstOrderLabelsPageTest.php +++ b/tests/Feature/Business/JstOrderLabelsPageTest.php @@ -7,6 +7,7 @@ use App\Models\Auth\Permission; use App\Models\Business\JstOrderLabel; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use Tests\Feature\FeatureTestCase; /** @@ -113,4 +114,119 @@ class JstOrderLabelsPageTest extends FeatureTestCase Permission::where('name', 'read-admin-panel')->firstOrFail() ); } + + public function test_import_from_erp_export_file_dedupes_lines_and_labels(): void + { + $this->allowPage(); + + $path = $this->makeExportFile([ + ['内部订单号', '线上订单号', '店铺名称', '下单时间', '标签'], + ['6476896', '3424493003753167', '京东-柯诺苏家具旗舰店', '2026-03-01 01:30:52', '发货后售后,店铺-京东,晚发赔'], + ['6476897', '3424493003753167', '京东-柯诺苏家具旗舰店', '2026-03-01 01:30:52', '发货后售后,店铺-京东,晚发赔'], + ['6476898', '3424493003753167', '京东-柯诺苏家具旗舰店', '2026-03-01 01:30:52', '发货后售后'], + ['6477350', '110197275064171099', '得物-米客米家家居旗舰店', '2026-03-01 08:05:36', ''], + ['9535498', '3290154852795260451', '淘宝-亿家达家居鞋柜电脑桌', '2026-03-11 19:01:30', '历史订单'], + ]); + + try { + $result = app(JstOrderLabelImporter::class)->importFromFile($path, null, null, $this->company->id, false); + } finally { + @unlink($path); + } + + // 同一订单的多条明细行只算一单,重复标签只写一行 + $this->assertSame(3, $result['orders']); + $this->assertSame(5, $result['rows']); + $this->assertSame(1, $result['no_label_orders']); + + $labels = JstOrderLabel::query()->where('company_id', $this->company->id) + ->where('order_no', '3424493003753167')->pluck('label')->sort()->values()->all(); + $this->assertSame(['发货后售后', '店铺-京东', '晚发赔'], $labels); + + $noLabel = JstOrderLabel::query()->where('company_id', $this->company->id) + ->where('order_no', '110197275064171099')->firstOrFail(); + $this->assertSame(JstOrderLabelImporter::NO_LABEL, $noLabel->label); + $this->assertSame('得物-米客米家家居旗舰店', $noLabel->shop_name); + } + + public function test_import_from_file_respects_window_and_replace(): void + { + $this->allowPage(); + app(JstOrderLabelImporter::class)->import('2026-09-01', '2026-09-15', $this->company->id, true); + + $path = $this->makeExportFile([ + ['线上订单号', '店铺名称', '下单时间', '标签'], + ['A-1', '店铺甲', '2026-03-05 10:00:00', '刷单待处理'], + ['A-2', '店铺甲', '2026-03-06 10:00:00', '刷单待处理'], + ]); + + try { + $result = app(JstOrderLabelImporter::class)->importFromFile( + $path, '2026-03-06', '2026-03-31', $this->company->id, true, 'test' + ); + } finally { + @unlink($path); + } + + // 窗口外的 3-05 被跳过;9 月的老数据在窗口外因此不受 --replace 影响 + $this->assertSame(1, $result['orders']); + $this->assertSame(1, $result['skipped']); + $this->assertSame(['A-2'], JstOrderLabel::query()->where('company_id', $this->company->id) + ->where('order_no', 'like', 'A-%')->pluck('order_no')->all()); + // 原有 9 月 5 行 + 新增 A-2 一行 + $this->assertSame(6, JstOrderLabel::query()->where('company_id', $this->company->id)->count()); + } + + /** + * 按聚水潭「导出订单」的真实形态造一个最小 xlsx: + * 字符串走 inlineStr、dimension 只写 A1(尺寸不可信)、一单多行。 + * + * @param list> $rows + */ + private function makeExportFile(array $rows): string + { + $path = tempnam(sys_get_temp_dir(), 'jst-export-') . '.xlsx'; + $sheet = '' + . '' + . ''; + + foreach ($rows as $rowIndex => $values) { + $sheet .= ''; + foreach ($values as $columnIndex => $value) { + $reference = Coordinate::stringFromColumnIndex($columnIndex + 1) . ($rowIndex + 1); + $sheet .= '' + . htmlspecialchars((string) $value, ENT_XML1) . ''; + } + $sheet .= ''; + } + $sheet .= ''; + + $zip = new \ZipArchive(); + $this->assertTrue($zip->open($path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true); + $zip->addFromString('[Content_Types].xml', '' + . '' + . '' + . '' + . '' + . '' + . ''); + $zip->addFromString('_rels/.rels', '' + . '' + . '' + . ''); + $zip->addFromString('xl/workbook.xml', '' + . '' + . ''); + $zip->addFromString('xl/_rels/workbook.xml.rels', '' + . '' + . '' + . ''); + $zip->addFromString('xl/sharedStrings.xml', '' + . ''); + $zip->addFromString('xl/worksheets/sheet1.xml', "\xEF\xBB\xBF" . $sheet); + $zip->close(); + + return $path; + } }