聚水潭订单标签明细:支持按聚水潭导出的订单 Excel 导入,并放开筛选下拉上限
镜像 ops_jst_orders 只覆盖 2026-04-01 之后,缺的历史区间只能靠财务在聚水潭「导出订单」导文件补。所以:- 新增 JstOrderExportReader:ZipArchive+expat 流式解析聚水潭导出 xlsx。这类文件字符串走 inlineStr、dimension 只写 A1、单文件上万行 ×135 列(解压 78MB),常规读法会读成空表或吃满内存;实测 12286 行 3.5 秒、峰值内存 10MB。 - jst-order-labels:import 新增 --file=:按「线上订单号+标签」去重后拆行写入,可配合 --from/--to 过滤窗口;带 --replace 时先成功读到数据行再清区间,避免文件有问题却先删了线上数据。 - 筛选下拉上限 500 -> 5000:导入 4~7 月后店铺已达 604 个,原来下拉里会缺 104 个店铺;提交筛选值的截断上限同步放开。 - 补两个测试:导出文件去重拆行、窗口过滤+replace。
This commit is contained in:
parent
55e1533b40
commit
daa4c939e7
297
app/Business/JstOrderExportReader.php
Normal file
297
app/Business/JstOrderExportReader.php
Normal file
@ -0,0 +1,297 @@
|
||||
<?php
|
||||
|
||||
namespace App\Business;
|
||||
|
||||
use Generator;
|
||||
use RuntimeException;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* 聚水潭「导出订单」Excel(.xlsx)流式读取器。
|
||||
*
|
||||
* 聚水潭导出的文件有几个特点,直接套常规 Excel 读法会踩坑:
|
||||
* - 字符串用 inlineStr 内联存储(sharedStrings 里是空的);
|
||||
* - worksheet 的 <dimension> 只写一个 A1,靠它判断行数会把整表读成空;
|
||||
* - 一行订单一个商品明细,单文件常见上万行 × 上百列,解压后几十 MB。
|
||||
*
|
||||
* 所以这里用 ZipArchive 取压缩流 + expat 增量解析,只保留调用方点名的列,
|
||||
* 内存占用与文件大小无关(导出 20 万行也不会整表进内存)。
|
||||
*/
|
||||
class JstOrderExportReader
|
||||
{
|
||||
private const READ_CHUNK = 262144;
|
||||
|
||||
/**
|
||||
* 逐行读取导出文件(跳过表头行)。
|
||||
*
|
||||
* @param list<string> $columns 需要取出并作为返回键的表头名,必须与文件第一行完全一致
|
||||
* @return Generator<int, array<string, string>>
|
||||
*/
|
||||
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<string> $shared
|
||||
* @param list<string> $columns
|
||||
* @return Generator<int, array<string, string>>
|
||||
*/
|
||||
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<int, string> $header
|
||||
* @param list<string> $columns
|
||||
* @return array<int, string>
|
||||
*/
|
||||
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<string> $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('/<sheet[^>]*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<string>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -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<string> */
|
||||
private function splitLabels(string $labels): array
|
||||
{
|
||||
|
||||
@ -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<string> */
|
||||
public function labels(int $companyId): array
|
||||
|
||||
@ -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());
|
||||
|
||||
|
||||
@ -1866,7 +1866,8 @@ class Pages extends Controller
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
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 = [];
|
||||
|
||||
@ -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<list<string>> $rows
|
||||
*/
|
||||
private function makeExportFile(array $rows): string
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'jst-export-') . '.xlsx';
|
||||
$sheet = '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
. '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
. '<dimension ref="A1"/><sheetData>';
|
||||
|
||||
foreach ($rows as $rowIndex => $values) {
|
||||
$sheet .= '<row r="' . ($rowIndex + 1) . '">';
|
||||
foreach ($values as $columnIndex => $value) {
|
||||
$reference = Coordinate::stringFromColumnIndex($columnIndex + 1) . ($rowIndex + 1);
|
||||
$sheet .= '<c r="' . $reference . '" t="inlineStr"><is><t>'
|
||||
. htmlspecialchars((string) $value, ENT_XML1) . '</t></is></c>';
|
||||
}
|
||||
$sheet .= '</row>';
|
||||
}
|
||||
$sheet .= '</sheetData></worksheet>';
|
||||
|
||||
$zip = new \ZipArchive();
|
||||
$this->assertTrue($zip->open($path, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true);
|
||||
$zip->addFromString('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
. '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
|
||||
. '<Default Extension="xml" ContentType="application/xml"/>'
|
||||
. '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
|
||||
. '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
|
||||
. '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
|
||||
. '</Types>');
|
||||
$zip->addFromString('_rels/.rels', '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'
|
||||
. '</Relationships>');
|
||||
$zip->addFromString('xl/workbook.xml', '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
. '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
|
||||
. 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
. '<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>');
|
||||
$zip->addFromString('xl/_rels/workbook.xml.rels', '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
. '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
. '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'
|
||||
. '</Relationships>');
|
||||
$zip->addFromString('xl/sharedStrings.xml', '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'
|
||||
. '<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="0" uniqueCount="0"></sst>');
|
||||
$zip->addFromString('xl/worksheets/sheet1.xml', "\xEF\xBB\xBF" . $sheet);
|
||||
$zip->close();
|
||||
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user