修复售后退货退款来源遗漏与历史明细校准 #443

Merged
limeng merged 1 commits from fix/limeng-refund-completeness into main 2026-10-21 17:45:37 +08:00
7 changed files with 435 additions and 74 deletions

View File

@ -5877,6 +5877,8 @@ class Pages extends Controller
$columns = [
['label' => '序号/主键ID', 'field' => 'Id', 'identifier' => true],
['label' => '退款日期', 'field' => 'refundDate'],
['label' => '业务来源', 'field' => 'dataSource'],
['label' => '商品明细', 'field' => 'detailStatus'],
['label' => '售后单ID', 'field' => 'as_id', 'identifier' => true],
['label' => '外部售后单号', 'field' => 'outer_as_id', 'identifier' => true],
['label' => '订单ID', 'field' => 'o_id', 'identifier' => true],

View File

@ -325,9 +325,14 @@ return [
'keys' => ['Id'],
'watermark' => 'updateTime',
'indexes' => [
['Id'],
['as_date', 'Id'],
['o_id', 'Id'],
['as_id', 'Id'],
['shop_id', 'outer_as_id(100)'],
['so_id(64)'],
['outer_as_id(64)'],
['as_date', 'Id', 'as_id', 'shop_site(300)'],
],
],
'operations_replica.rpt.jst_returnAndRefundItem' => [
@ -336,11 +341,14 @@ return [
'object' => 'jst_returnAndRefundItem',
'target' => 'ops_jst_return_refund_item',
'keys' => ['Id'],
// The replica can replace historical detail IDs. Append-only sync
// cannot discover those changes; reconcile in bounded weekly runs.
'full_reconcile_hours' => 168,
'indexes' => [
['as_id', 'Id'],
],
],
'operations_replica.rpt.jst_shopInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_shopInfo', 'target' => 'ops_jst_shop_info', 'keys' => ['Id'], 'watermark' => 'updateTime'],
'operations_replica.rpt.jst_shopInfo' => ['source_key' => 'operations_replica', 'schema' => 'rpt', 'object' => 'jst_shopInfo', 'target' => 'ops_jst_shop_info', 'keys' => ['Id'], 'watermark' => 'updateTime', 'indexes' => [['shop_id', 'Id']]],
// 淘系(天猫/淘宝)订单与售后:聚水潭单独存放在 qmcust 这套表里,
// 与 jst_Orders / jst_OrderItem / jst_returnAndRefundInfo 分开。
@ -383,6 +391,8 @@ return [
['as_id'],
['o_id', 'as_id'],
['as_date', 'as_id'],
['so_id(64)'],
['outer_as_id(64)'],
],
],
'operations_replica.rpt.jst_qmcust_refundlist_item' => [

View File

@ -60,7 +60,7 @@
| 订单 | `rpt.jst_Orders`、`rpt.jst_OrderItem` | `ops_jst_orders`、`ops_jst_order_item` |
| 商品与仓库 | `rpt.jst_sku`、`rpt.jst_warehouseInfo`、`rpt.jst_skumap` | `ops_jst_*`(普通商品资料已切换) |
| 推广费用 | `rpt.ads_itemid_sales_cost_ratio_v2_di` | `ops_item_sales_cost_ratio` |
| 退款退货 | `rpt.jst_returnAndRefundInfo`、`rpt.jst_returnAndRefundItem` | `ops_jst_return_refund_*` |
| 退款退货 | `rpt.jst_returnAndRefundInfo`、`rpt.jst_returnAndRefundItem`、`rpt.jst_qmcust_refundlist`、`rpt.jst_qmcust_refundlist_item` | `ops_jst_return_refund_*`、`ops_jst_qmcust_refunds`、`ops_jst_qmcust_refund_items` |
| 聚水潭店铺 | `rpt.jst_shopInfo` | `ops_jst_shop_info` |
| 聚水潭原始账单 | `rpt.jst_originalBillInfo` | `ops_jst_original_bill_info` |
| 店铺维度报表 | `jiansun/dbo.jst_originalBillInfo + dbo.jst_shopInfo + dbo.fys_shopInfo_flow` | `store_report_bill_rows`、`store_report_lifecycle_rows`、`store_report_daily_rows` |
@ -68,6 +68,10 @@
商品价格 `rpt.Bulk_Price_Limit` 继续使用已经上线的类型化同步器,不在通用原表任务中重复同步。
售后(退货退款)页面及其导出共同读取上述两套售后主单、各自商品明细与店铺镜像,按 `as_date` 筛选。原售后资料优先;退款清单按 `as_id`、或非空的 `(shop_id, outer_as_id)` 排除已存在的业务单。无商品明细的主单仍显示,商品数量、明细金额及成本留空;店铺平台无法唯一确认时标为“待确认”,不推断平台。两个来源的订单关联不得混用。订单号筛选按完整内部订单号、线上订单号或平台售后单号精确查询,避免长文本标识的全表扫描;店铺和商品仍支持包含搜索。分页先限制各来源的候选主单及行标识,再加载当前页明细;导出使用同一筛选及稳定游标。
`jst_returnAndRefundItem` 没有更新时间,除按 `Id` 追加外,每 168 小时通过现有调度分批执行可续传全量校准,覆盖历史编号变化及删除;全量完成后才清理上一代残留。人工历史校准前须备份相关镜像、目录及同步状态,并持有生产上游同步互斥锁。退款清单两表继续按 `local_updated` 使用重叠增量,不新建重复镜像。
## JianSun 旧业务库(jiansun)
| 业务范围 | 上游对象 |

View File

@ -17,6 +17,12 @@ class NonJingxiRefundMirrorRepository
public const ITEM_DATASET = 'operations_replica.rpt.jst_returnAndRefundItem';
public const SUPPLEMENT_DATASET = 'operations_replica.rpt.jst_qmcust_refundlist';
public const SUPPLEMENT_ITEM_DATASET = 'operations_replica.rpt.jst_qmcust_refundlist_item';
public const SHOP_DATASET = 'operations_replica.rpt.jst_shopInfo';
private const AUXILIARY_DATASETS = [
'operations_replica.rpt.jst_Orders',
'operations_replica.rpt.jst_OrderItem',
@ -25,14 +31,21 @@ class NonJingxiRefundMirrorRepository
];
private const REQUIRED_QUERY_INDEXES = [
self::INFO_DATASET => [['as_date', 'Id'], ['o_id', 'Id'], ['as_id', 'Id']],
self::INFO_DATASET => [['Id'], ['as_date', 'Id'], ['o_id', 'Id'], ['as_id', 'Id'], ['shop_id', 'outer_as_id'], ['so_id'], ['outer_as_id'], ['as_date', 'Id', 'as_id', 'shop_site']],
self::ITEM_DATASET => [['as_id', 'Id']],
self::SUPPLEMENT_DATASET => [['as_id'], ['as_date', 'as_id'], ['so_id'], ['outer_as_id']],
self::SUPPLEMENT_ITEM_DATASET => [['as_id', 'asi_id']],
self::SHOP_DATASET => [['shop_id', 'Id']],
'operations_replica.rpt.jst_Orders' => [['o_id', 'Id']],
'operations_replica.rpt.jst_OrderItem' => [['o_id', 'Id']],
];
private readonly ConnectionInterface $connection;
private ?array $excludedShopIds = null;
private ?string $supplementDateIndex = null;
public function __construct(
private readonly BusinessMirrorDatasetRegistry $datasets,
private readonly GenericBusinessMirrorRepository $mirror,
@ -45,14 +58,14 @@ class NonJingxiRefundMirrorRepository
$schema = Schema::connection($this->connection->getName());
return $schema->hasTable('business_mirror_table_states')
&& $schema->hasTable($this->dataset(self::INFO_DATASET)->targetTable())
&& $schema->hasTable($this->dataset(self::ITEM_DATASET)->targetTable());
&& collect([self::INFO_DATASET, self::ITEM_DATASET, self::SUPPLEMENT_DATASET, self::SUPPLEMENT_ITEM_DATASET, self::SHOP_DATASET])
->every(fn (string $key): bool => $schema->hasTable($this->dataset($key)->targetTable()));
}
public function ready(): bool
{
return $this->mirror->ready($this->dataset(self::INFO_DATASET))
&& $this->mirror->ready($this->dataset(self::ITEM_DATASET));
return collect([self::INFO_DATASET, self::ITEM_DATASET, self::SUPPLEMENT_DATASET, self::SUPPLEMENT_ITEM_DATASET, self::SHOP_DATASET])
->every(fn (string $key): bool => $this->mirror->ready($this->dataset($key)));
}
public function queryReady(): bool
@ -66,7 +79,13 @@ class NonJingxiRefundMirrorRepository
return false;
}
$indexes = collect($schema->getIndexes($table))
$tableIndexes = collect($schema->getIndexes($table));
if ($datasetKey === self::SUPPLEMENT_DATASET) {
$this->supplementDateIndex = $tableIndexes->first(
static fn (array $index): bool => array_map('strtolower', $index['columns']) === ['as_date', 'as_id']
)['name'] ?? null;
}
$indexes = $tableIndexes
->map(static fn (array $index): array => array_map(
'strtolower',
(array) ($index['columns'] ?? []),
@ -90,6 +109,9 @@ class NonJingxiRefundMirrorRepository
return [
self::INFO_DATASET => $this->mirror->state($this->dataset(self::INFO_DATASET)),
self::ITEM_DATASET => $this->mirror->state($this->dataset(self::ITEM_DATASET)),
self::SUPPLEMENT_DATASET => $this->mirror->state($this->dataset(self::SUPPLEMENT_DATASET)),
self::SUPPLEMENT_ITEM_DATASET => $this->mirror->state($this->dataset(self::SUPPLEMENT_ITEM_DATASET)),
self::SHOP_DATASET => $this->mirror->state($this->dataset(self::SHOP_DATASET)),
];
}
@ -100,7 +122,7 @@ class NonJingxiRefundMirrorRepository
public function syncStatus(?array $states = null, ?CarbonInterface $at = null): array
{
$states ??= $this->states();
if (count(array_filter($states, 'is_array')) !== 2) {
if (count(array_filter($states, 'is_array')) !== 5) {
return ['code' => 'unavailable', 'last_succeeded_at' => null];
}
@ -143,19 +165,10 @@ class NonJingxiRefundMirrorRepository
$page = max($page, 1);
$perPage = min(max($perPage, 1), 100);
$query = $this->baseQuery();
$this->applyFilters($query, $filters);
$total = (clone $query)->count();
$rows = $query
->select($this->selectColumns())
->orderByDesc('r.as_date')
->orderByDesc('r.Id')
->orderByDesc('i.Id')
->forPage($page, $perPage)
->get();
$this->hydratePage($rows);
$total = $this->sourceQuery($filters, false)->count()
+ $this->sourceQuery($filters, true)->count();
$keys = $this->orderedKeys($filters, null, $page * $perPage)->forPage($page, $perPage)->get();
$rows = $this->loadRows($keys);
return ['data' => $rows->all(), 'total' => $total];
}
@ -174,38 +187,24 @@ class NonJingxiRefundMirrorRepository
}
$chunkSize = min(max($chunkSize, 1), 100);
$query = $this->baseQuery();
$this->applyFilters($query, $filters);
$page = 1;
$cursor = null;
do {
$rows = (clone $query)
->select($this->selectColumns())
->orderByDesc('r.as_date')
->orderByDesc('r.Id')
->orderByDesc('i.Id')
->forPage($page, $chunkSize)
->get();
if ($rows->isEmpty()) {
$keys = $this->orderedKeys($filters, $cursor, $chunkSize)->limit($chunkSize)->get();
if ($keys->isEmpty()) {
break;
}
$this->hydratePage($rows);
foreach ($rows as $row) {
foreach ($this->loadRows($keys) as $row) {
yield $row;
}
$page++;
} while ($rows->count() === $chunkSize);
$cursor = $keys->last();
} while ($keys->count() === $chunkSize);
}
/** @return list<string> */
private function selectColumns(): array
{
return [
'i.Id as Id', 'r.as_date as refundDate', 'r.as_id', 'r.outer_as_id',
'r.as_date as refundDate', 'r.as_id', 'r.outer_as_id',
'r.o_id', 'r.so_id', 'r.type', 'r.node', 'r.shop_type', 'r.shop_name',
'r.shop_site as platform', 'r.refund as totalRefundMoney',
'i.outer_oi_id', 'i.shop_sku_id', 'i.i_id', 'i.sku_id', 'i.qty',
@ -216,17 +215,223 @@ class NonJingxiRefundMirrorRepository
];
}
private function baseQuery(): Builder
private function sourceQuery(array $filters, bool $supplement, bool $withItems = true): Builder
{
return $this->connection->table('ops_jst_return_refund_info as r')
->join('ops_jst_return_refund_item as i', 'i.as_id', '=', 'r.as_id')
->where(function (Builder $query): void {
$query->whereNull('r.shop_site')
->orWhere(function (Builder $platform): void {
$platform->where('r.shop_site', 'not like', '%京喜%')
->whereRaw('LOWER(r.shop_site) NOT LIKE ?', ['%jingxi%']);
});
$table = $supplement ? 'ops_jst_qmcust_refunds' : 'ops_jst_return_refund_info';
$query = $this->connection->table($table . ' as r');
if ($supplement && $filters['order_no'] === '' && $this->supplementDateIndex !== null
&& $this->connection->getDriverName() === 'mysql') {
// The legacy text payload makes a full table scan very expensive;
// keep date windows on the verified shared-mirror lookup index.
$query->forceIndex($this->supplementDateIndex);
}
if ($filters['order_no'] !== '') {
$needle = trim($filters['order_no']);
$key = $supplement ? 'as_id' : 'Id';
$matches = $this->connection->table($table)->select($key . ' as matched_id')->where('so_id', $needle)
->union($this->connection->table($table)->select($key . ' as matched_id')->where('outer_as_id', $needle));
if (ctype_digit($needle)) {
$matches->union($this->connection->table($table)->select($key . ' as matched_id')->where('o_id', $needle));
}
// Separate indexed lookups: MariaDB cannot reliably index-merge
// OR predicates across the replica's long text identifier fields.
$query->joinSub($matches, 'matching_refund', 'matching_refund.matched_id', '=', 'r.' . $key);
}
$itemTable = $supplement ? 'ops_jst_qmcust_refund_items' : 'ops_jst_return_refund_item';
if ($withItems) {
$query->leftJoin($itemTable . ' as i', 'i.as_id', '=', 'r.as_id');
}
$platform = 'r.shop_site';
if ($supplement) {
// A shop may have several historical rows. An ambiguous platform is
// left unknown, and must never multiply the refund rows.
$this->excludedShopIds ??= $this->connection->table('ops_jst_shop_info')
->get(['shop_id', 'shop_site'])->groupBy('shop_id')
->filter(function ($rows): bool {
$sites = $rows->pluck('shop_site')->filter()->unique();
$site = (string) $sites->first();
return $sites->count() === 1 && (str_contains($site, '京喜') || str_contains(strtolower($site), 'jingxi'));
})->keys()->map('strval')->all();
if ($this->excludedShopIds !== []) {
$query->where(fn (Builder $q) => $q->whereNull('r.shop_id')->orWhereNotIn('r.shop_id', $this->excludedShopIds));
}
$query->whereNotExists(function (Builder $existing): void {
$existing->selectRaw('1')->from('ops_jst_return_refund_info as existing')
->whereColumn('existing.as_id', 'r.as_id');
})
->whereNotExists(function (Builder $existing): void {
$existing->selectRaw('1')->from('ops_jst_return_refund_info as existing')
->whereNotNull('r.outer_as_id')->where('r.outer_as_id', '!=', '')
->whereNotNull('r.shop_id')->where('r.shop_id', '!=', '')
->whereColumn('existing.shop_id', 'r.shop_id')
->whereColumn('existing.outer_as_id', 'r.outer_as_id');
});
$platform = null;
}
if ($platform !== null) {
$query->where(function (Builder $query) use ($platform): void {
$query->whereNull($platform)->orWhere(function (Builder $query) use ($platform): void {
$query->where($platform, 'not like', '%京喜%')
->whereRaw('LOWER(' . $platform . ') NOT LIKE ?', ['%jingxi%']);
});
});
}
$this->applyFilters($query, $filters);
if ($filters['sku_id'] !== '') {
if ($withItems) {
$this->applySkuFilter($query, $filters['sku_id']);
} else {
$query->whereExists(function (Builder $items) use ($itemTable, $filters): void {
$items->selectRaw('1')->from($itemTable . ' as i')->whereColumn('i.as_id', 'r.as_id');
$this->applySkuFilter($items, $filters['sku_id']);
});
}
}
return $query;
}
private const SORT_COLUMNS = ['refundDate', '_source_rank', '_head_id', '_source_id', '_item_id'];
private function orderedKeys(array $filters, ?object $cursor, int $limit): Builder
{
$branches = [];
foreach ([false, true] as $supplement) {
$rank = $supplement ? 1 : 0;
$headColumn = $supplement ? 'r.as_id' : 'r.Id';
$heads = $this->sourceQuery($filters, $supplement, false)
->select(['r.as_date', 'r.as_id'])->when(! $supplement, fn (Builder $q) => $q->addSelect('r.Id'));
if ($cursor !== null) {
$heads->where(function (Builder $after) use ($cursor, $rank, $headColumn, $supplement, $filters): void {
$after->where('r.as_date', '<', $cursor->refundDate);
if ($rank <= (int) $cursor->_source_rank) {
$after->orWhere(function (Builder $sameDate) use ($cursor, $rank, $headColumn, $supplement, $filters): void {
$sameDate->where('r.as_date', $cursor->refundDate);
if ($rank === (int) $cursor->_source_rank) {
$headValue = $supplement ? $cursor->_source_id : $cursor->_head_id;
$sameDate->where(function (Builder $head) use ($headColumn, $headValue, $cursor, $supplement, $filters): void {
$head->where($headColumn, '<', $headValue)
->orWhere(function (Builder $remaining) use ($headColumn, $headValue, $cursor, $supplement, $filters): void {
$remaining->where($headColumn, $headValue)->whereExists(function (Builder $items) use ($cursor, $supplement, $filters): void {
$items->selectRaw('1')->from(($supplement ? 'ops_jst_qmcust_refund_items' : 'ops_jst_return_refund_item') . ' as i')
->whereColumn('i.as_id', 'r.as_id')
->where($supplement ? 'i.asi_id' : 'i.Id', '<', $cursor->_item_id);
if ($filters['sku_id'] !== '') {
$this->applySkuFilter($items, $filters['sku_id']);
}
});
});
});
}
});
}
});
}
$heads->orderByDesc('r.as_date')->orderByDesc($headColumn)->limit($limit);
// Each eligible header contributes at least one row. The newest N
// headers therefore contain the newest N matching detail rows.
$source = $this->connection->query()->fromSub($heads, 'r')
->leftJoin(($supplement ? 'ops_jst_qmcust_refund_items' : 'ops_jst_return_refund_item') . ' as i', 'i.as_id', '=', 'r.as_id');
if ($filters['sku_id'] !== '') {
$this->applySkuFilter($source, $filters['sku_id']);
}
$source->selectRaw($supplement
? 'r.as_date AS refundDate, 1 AS _source_rank, 0 AS _head_id, COALESCE(i.asi_id, 0) AS _item_id, r.as_id AS _source_id'
: "r.as_date AS refundDate, 0 AS _source_rank, r.Id AS _head_id, COALESCE(i.Id, 0) AS _item_id, '' AS _source_id");
$branch = $this->connection->query()->fromSub($source, 'source_keys');
if ($cursor !== null) {
$branch->where(function (Builder $after) use ($cursor): void {
foreach (self::SORT_COLUMNS as $position => $column) {
$after->orWhere(function (Builder $part) use ($cursor, $position, $column): void {
foreach (array_slice(self::SORT_COLUMNS, 0, $position) as $equal) {
$part->where($equal, '=', $cursor->$equal);
}
$part->where($column, '<', $cursor->$column);
});
}
});
}
foreach (self::SORT_COLUMNS as $column) {
$branch->orderByDesc($column);
}
$branches[] = $this->connection->query()->fromSub($branch->limit($limit), 'bounded_keys');
}
// Bound both branches before the final merge, including cursor exports.
$query = $this->connection->query()->fromSub($branches[0]->unionAll($branches[1]), 'refund_keys');
foreach (self::SORT_COLUMNS as $column) {
$query->orderByDesc($column);
}
return $query;
}
private function loadRows($keys)
{
$loaded = collect();
foreach ([false, true] as $supplement) {
$sourceKeys = $keys->filter(fn (object $key): bool => (bool) $key->_source_rank === $supplement);
if ($sourceKeys->isEmpty()) {
continue;
}
$table = $supplement ? 'ops_jst_qmcust_refunds' : 'ops_jst_return_refund_info';
$itemTable = $supplement ? 'ops_jst_qmcust_refund_items' : 'ops_jst_return_refund_item';
$itemKey = $supplement ? 'i.asi_id' : 'i.Id';
$query = $this->connection->table($table . ' as r')
->leftJoin($itemTable . ' as i', 'i.as_id', '=', 'r.as_id')
->whereIn($supplement ? 'r.as_id' : 'r.Id', $sourceKeys->pluck($supplement ? '_source_id' : '_head_id'))
->where(function (Builder $items) use ($sourceKeys, $itemKey): void {
$items->whereIn($itemKey, $sourceKeys->pluck('_item_id'));
if ($sourceKeys->contains(fn (object $key): bool => (int) $key->_item_id === 0)) {
$items->orWhereNull($itemKey);
}
});
if ($supplement) {
$query->select([
'r.as_date as refundDate', 'r.as_id', 'r.outer_as_id',
'r.o_id', 'r.so_id', 'r.type', 'r.node', 'r.shop_type', 'r.shop_name',
'r.refund as totalRefundMoney', 'i.outer_oi_id', 'i.shop_sku_id', 'i.i_id', 'i.sku_id',
'i.qty', 'i.shop_amount as detailRefundMoney', 'i.type as refundType',
'i.r_qty as refundQty', 'r.buyer_apply_refund as AfSalesMoney',
'r.local_created as createTime', 'r.status', 'r.shop_status', 'r.created', 'r.confirm_date',
'r.shop_id',
])->selectRaw("COALESCE(i.asi_id, r.as_id) AS Id, NULL AS RefundMoneyIncome, '退款清单' AS dataSource, 1 AS _source_rank, 0 AS _head_id, COALESCE(i.asi_id, 0) AS _item_id, r.as_id AS _source_id");
} else {
$query->select($this->selectColumns())
->selectRaw("COALESCE(i.Id, r.Id) AS Id, '售后资料' AS dataSource, 0 AS _source_rank, r.Id AS _head_id, COALESCE(i.Id, 0) AS _item_id, '' AS _source_id");
}
$loaded = $loaded->concat($query->get());
}
$byIdentity = $loaded->keyBy(fn (object $row): string => $this->identity($row));
$rows = $keys->map(fn (object $key) => $byIdentity->get($this->identity($key)))->filter()->values();
$shopIds = $rows->where('_source_rank', 1)->pluck('shop_id')->unique();
$platforms = $shopIds->isEmpty() ? collect() : $this->connection->table('ops_jst_shop_info')
->whereIn('shop_id', $shopIds)->get(['shop_id', 'shop_site'])->groupBy('shop_id');
foreach ($rows as $row) {
if ((int) $row->_source_rank === 1) {
$sites = ($platforms->get($row->shop_id) ?? collect())->pluck('shop_site')->filter()->unique()->values();
$row->platform = $sites->count() === 1 ? $sites->first() : '待确认';
unset($row->shop_id);
}
$row->detailStatus = (int) $row->_item_id === 0 ? '暂无商品明细' : '已关联';
foreach (['totalRefundMoney', 'detailRefundMoney', 'RefundMoneyIncome', 'AfSalesMoney'] as $money) {
if (! is_numeric($row->$money)) {
$row->$money = null;
}
}
foreach (array_slice(self::SORT_COLUMNS, 1) as $column) {
unset($row->$column);
}
}
$this->hydratePage($rows);
return $rows;
}
private function identity(object $row): string
{
return implode('|', [$row->_source_rank, $row->_head_id, $row->_item_id, $row->_source_id]);
}
/** @param array{from:string,to:string,order_no:string,shop_name:string,sku_id:string} $filters */
@ -235,27 +440,19 @@ class NonJingxiRefundMirrorRepository
$query->where('r.as_date', '>=', $filters['from'] . ' 00:00:00')
->where('r.as_date', '<', Carbon::parse($filters['to'])->addDay()->format('Y-m-d 00:00:00'));
if ($filters['order_no'] !== '') {
$needle = $this->contains($filters['order_no']);
$query->where(function (Builder $order) use ($needle): void {
$order->whereRaw("CAST(r.o_id AS CHAR) LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("r.so_id LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("r.outer_as_id LIKE ? ESCAPE '!'", [$needle]);
});
}
if ($filters['shop_name'] !== '') {
$query->whereRaw("r.shop_name LIKE ? ESCAPE '!'", [$this->contains($filters['shop_name'])]);
}
}
if ($filters['sku_id'] !== '') {
$needle = $this->contains($filters['sku_id']);
$query->where(function (Builder $sku) use ($needle): void {
$sku->whereRaw("i.sku_id LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("i.shop_sku_id LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("i.i_id LIKE ? ESCAPE '!'", [$needle]);
});
}
private function applySkuFilter(Builder $query, string $value): void
{
$needle = $this->contains($value);
$query->where(function (Builder $sku) use ($needle): void {
$sku->whereRaw("i.sku_id LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("i.shop_sku_id LIKE ? ESCAPE '!'", [$needle])
->orWhereRaw("i.i_id LIKE ? ESCAPE '!'", [$needle]);
});
}
/** @param \Illuminate\Support\Collection<int,object> $rows */
@ -265,13 +462,14 @@ class NonJingxiRefundMirrorRepository
return;
}
$orderIds = $rows->pluck('o_id')->filter()->unique()->values()->all();
$primaryRows = $rows->where('dataSource', '售后资料');
$orderIds = $primaryRows->pluck('o_id')->filter()->unique()->values()->all();
$skuIds = $rows->pluck('sku_id')->filter()->unique()->values()->all();
$shopNames = $rows->pluck('shop_name')->filter()->unique()->values()->all();
$orderItems = $this->auxiliaryReady(self::AUXILIARY_DATASETS[1])
? $this->connection->table('ops_jst_order_item')
->whereIn('o_id', $orderIds)
->whereIn('outer_oi_id', $rows->pluck('outer_oi_id')->filter()->unique()->all())
->whereIn('outer_oi_id', $primaryRows->pluck('outer_oi_id')->filter()->unique()->all())
->get(['o_id', 'outer_oi_id', 'shop_i_id', 'shop_sku_id', 'i_id', 'sku_id', 'buyer_paid_amount'])
->keyBy(static fn (object $row): string => $row->o_id . '|' . $row->outer_oi_id)
: collect();
@ -291,14 +489,14 @@ class NonJingxiRefundMirrorRepository
: collect();
foreach ($rows as $row) {
$orderItem = $orderItems->get($row->o_id . '|' . $row->outer_oi_id);
$orderItem = $row->dataSource === '售后资料' ? $orderItems->get($row->o_id . '|' . $row->outer_oi_id) : null;
$skuId = $row->sku_id ?: ($orderItem->sku_id ?? null);
$unitCost = isset($skus[$skuId]) ? (float) $skus[$skuId]->cost_price : null;
$refundQuantity = $row->refundQty === null ? null : (float) $row->refundQty;
$row->isZC = str_contains((string) $row->shop_type, '自营') ? '是' : '否';
$row->responsibleDepartment = $shops[$row->shop_name]->responsibleDepartment ?? null;
$row->originPostcode = $orders[$row->o_id]->receiver_zip ?? null;
$row->originPostcode = $row->dataSource === '售后资料' ? ($orders[$row->o_id]->receiver_zip ?? null) : null;
$row->shop_i_id = $orderItem->shop_i_id ?? null;
$row->shop_sku_id = $row->shop_sku_id ?: ($orderItem->shop_sku_id ?? null);
$row->i_id = $row->i_id ?: ($orderItem->i_id ?? null);

View File

@ -2,6 +2,8 @@
$columns = [
['label' => '序号/主键ID', 'field' => 'Id'],
['label' => '退款日期', 'field' => 'refundDate'],
['label' => '业务来源', 'field' => 'dataSource'],
['label' => '商品明细', 'field' => 'detailStatus'],
['label' => '售后单ID', 'field' => 'as_id'],
['label' => '外部售后单号', 'field' => 'outer_as_id'],
['label' => '订单ID', 'field' => 'o_id'],
@ -113,7 +115,7 @@
</div>
<div class="upstream-data-field">
<label for="non-jingxi-refund-order">订单号</label>
<input id="non-jingxi-refund-order" type="search" name="order_no" value="{{ $filters['order_no'] }}" placeholder="订单或售后单号">
<input id="non-jingxi-refund-order" type="search" name="order_no" value="{{ $filters['order_no'] }}" placeholder="完整订单或售后单号(精确查询)">
</div>
<div class="upstream-data-field">
<label for="non-jingxi-refund-shop">店铺名称</label>

View File

@ -96,6 +96,8 @@ class NonJingxiRefundPageTest extends FeatureTestCase
->assertSee('data-sync-state="syncing"', false)
->assertSeeText('业务镜像同步中,当前显示最近成功数据')
->assertSeeText('AS-2002')
->assertSeeText('业务来源')
->assertSeeText('商品明细')
->assertSeeText('SKU-1')
->assertSeeText('99.50')
->assertSeeText('共 26 条记录')

View File

@ -118,6 +118,114 @@ class NonJingxiRefundMirrorRepositoryTest extends TestCase
$this->assertSame('initializing', $this->repository->syncStatus($states)['code']);
}
public function test_supplement_and_header_only_refunds_survive_without_invented_details(): void
{
$db = DB::connection('business_mirror');
$db->table('ops_jst_return_refund_info')->insert($this->refundInfo(1, 101, '2026-07-02 10:00:00', '天猫', '测试店'));
$db->table('ops_jst_qmcust_refunds')->insert([
$this->supplement(201, '2026-07-02 10:00:00', 'SHOP-1'),
$this->supplement(202, '2026-07-03 10:00:00', 'UNKNOWN'),
$this->supplement(203, '2026-08-01 00:00:00', 'SHOP-1'),
$this->supplement(204, '2026-07-04 10:00:00', 'JINGXI'),
]);
$db->table('ops_jst_qmcust_refund_items')->insert([
'asi_id' => 500, 'as_id' => '201', 'sku_id' => 'Q-SKU', 'qty' => 2, 'r_qty' => 1,
'shop_amount' => '12.34', 'outer_oi_id' => 'Q-ITEM', 'type' => '退货退款',
]);
$db->table('ops_jst_shop_info')->insert([
['Id' => 1, 'shop_id' => 'SHOP-1', 'shop_site' => '天猫'],
['Id' => 2, 'shop_id' => 'SHOP-1', 'shop_site' => '天猫'],
['Id' => 3, 'shop_id' => 'JINGXI', 'shop_site' => '京喜'],
]);
$filters = ['from' => '2026-06-01', 'to' => '2026-07-31', 'order_no' => '', 'shop_name' => '', 'sku_id' => ''];
$result = $this->repository->paginate($filters, 1, 25);
$this->assertSame(3, $result['total']);
$this->assertSame(['202', '201', '101'], array_map(fn ($r) => (string) $r->as_id, $result['data']));
$unknown = $result['data'][0];
$this->assertSame('待确认', $unknown->platform);
$this->assertSame('暂无商品明细', $unknown->detailStatus);
$this->assertNull($unknown->sku_id);
$this->assertNull($unknown->detailRefundMoney);
$this->assertNull($unknown->RefundMoneyIncome);
$this->assertSame('退款清单', $result['data'][1]->dataSource);
$this->assertSame('Q-SKU', $result['data'][1]->sku_id);
$this->assertSame('12.34', $result['data'][1]->detailRefundMoney);
$this->assertSame('已关联', $result['data'][1]->detailStatus);
$this->assertSame('暂无商品明细', $result['data'][2]->detailStatus);
$this->assertNull($result['data'][2]->refundCostGoods);
// Cursor export must include both sources at the same timestamp exactly once.
$export = iterator_to_array($this->repository->exportRows($filters, 1));
$this->assertSame(['202', '201', '101'], array_map(fn ($r) => (string) $r->as_id, $export));
$this->assertSame('201', (string) $this->repository->paginate($filters, 2, 1)['data'][0]->as_id);
$filters['order_no'] = 'SO-Q-201';
$this->assertSame(1, $this->repository->paginate($filters, 1, 25)['total']);
$filters['order_no'] = '';
$filters['sku_id'] = 'Q-SKU';
$this->assertSame(1, $this->repository->paginate($filters, 1, 25)['total']);
}
public function test_sources_deduplicate_by_after_sales_id_or_shop_and_external_id(): void
{
$db = DB::connection('business_mirror');
$db->table('ops_jst_return_refund_info')->insert($this->refundInfo(1, 101, '2026-07-02 10:00:00', '天猫', '测试店') + ['shop_id' => 'SHOP-1']);
$sameId = $this->supplement(101, '2026-07-02 10:00:00', 'SHOP-1');
$sameExternal = $this->supplement(202, '2026-07-02 10:00:00', 'SHOP-1');
$sameExternal['outer_as_id'] = 'AS-101';
$differentShop = $sameExternal;
$differentShop['as_id'] = '203';
$differentShop['shop_id'] = 'SHOP-2';
$db->table('ops_jst_qmcust_refunds')->insert([$sameId, $sameExternal, $differentShop]);
$filters = ['from' => '2026-07-01', 'to' => '2026-07-31', 'order_no' => '', 'shop_name' => '', 'sku_id' => ''];
$result = $this->repository->paginate($filters, 1, 25);
$this->assertSame(2, $result['total']);
$this->assertEqualsCanonicalizing(['101', '203'], array_map(fn ($r) => (string) $r->as_id, $result['data']));
}
public function test_export_cursor_crosses_multi_item_headers_and_sources_without_skips(): void
{
$db = DB::connection('business_mirror');
$date = '2026-07-02 10:00:00';
$db->table('ops_jst_return_refund_info')->insert([
$this->refundInfo(1, 101, $date, '天猫', '测试店'),
$this->refundInfo(2, 102, $date, '天猫', '测试店'),
]);
$db->table('ops_jst_return_refund_item')->insert([
$this->refundItem(11, 101, 'MATCH', 'I-11'),
$this->refundItem(12, 102, 'MATCH', 'I-12'),
$this->refundItem(13, 102, 'OTHER', 'I-13'),
$this->refundItem(14, 102, 'MATCH', 'I-14'),
]);
$db->table('ops_jst_qmcust_refunds')->insert([
$this->supplement(201, $date, 'UNKNOWN'), $this->supplement(202, $date, 'UNKNOWN'),
]);
$db->table('ops_jst_qmcust_refund_items')->insert([
['asi_id' => 501, 'as_id' => '202', 'sku_id' => 'MATCH'],
['asi_id' => 502, 'as_id' => '202', 'sku_id' => 'MATCH'],
]);
$filters = ['from' => '2026-07-01', 'to' => '2026-07-31', 'order_no' => '', 'shop_name' => '', 'sku_id' => ''];
$expected = ['202:502', '202:501', '201:201', '102:14', '102:13', '102:12', '101:11'];
$identity = fn ($r) => $r->as_id . ':' . $r->Id;
$this->assertSame($expected, array_map($identity, iterator_to_array($this->repository->exportRows($filters, 1))));
$paged = [];
for ($page = 1; $page <= 4; $page++) {
$paged = array_merge($paged, $this->repository->paginate($filters, $page, 2)['data']);
}
$this->assertSame($expected, array_map($identity, $paged));
$filters['sku_id'] = 'MATCH';
$this->assertSame(['202:502', '202:501', '102:14', '102:12', '101:11'],
array_map($identity, iterator_to_array($this->repository->exportRows($filters, 1))));
}
public function test_supplement_initial_sync_is_required_before_claiming_complete_data(): void
{
DB::connection('business_mirror')->table('business_mirror_table_states')
->where('dataset_key', NonJingxiRefundMirrorRepository::SUPPLEMENT_ITEM_DATASET)
->update(['initial_completed_at' => null, 'status' => 'running']);
$this->assertFalse($this->repository->ready());
$this->assertSame('initializing', $this->repository->syncStatus()['code']);
}
public function test_query_is_blocked_when_a_required_lookup_index_is_missing(): void
{
Schema::connection('business_mirror')->table(
@ -142,6 +250,9 @@ class NonJingxiRefundMirrorRepositoryTest extends TestCase
return [
NonJingxiRefundMirrorRepository::INFO_DATASET => $this->definition('jst_returnAndRefundInfo', 'ops_jst_return_refund_info'),
NonJingxiRefundMirrorRepository::ITEM_DATASET => $this->definition('jst_returnAndRefundItem', 'ops_jst_return_refund_item'),
NonJingxiRefundMirrorRepository::SUPPLEMENT_DATASET => $this->definition('jst_qmcust_refundlist', 'ops_jst_qmcust_refunds'),
NonJingxiRefundMirrorRepository::SUPPLEMENT_ITEM_DATASET => $this->definition('jst_qmcust_refundlist_item', 'ops_jst_qmcust_refund_items'),
NonJingxiRefundMirrorRepository::SHOP_DATASET => $this->definition('jst_shopInfo', 'ops_jst_shop_info'),
'operations_replica.rpt.jst_Orders' => $this->definition('jst_Orders', 'ops_jst_orders'),
'operations_replica.rpt.jst_OrderItem' => $this->definition('jst_OrderItem', 'ops_jst_order_item'),
'operations_replica.rpt.jst_sku' => $this->definition('jst_sku', 'ops_jst_sku'),
@ -172,9 +283,14 @@ class NonJingxiRefundMirrorRepositoryTest extends TestCase
$table->decimal('buyer_apply_refund', 18, 2)->nullable(); $table->dateTime('createTime')->nullable();
$table->string('status')->nullable(); $table->string('shop_status')->nullable(); $table->dateTime('created')->nullable();
$table->dateTime('confirm_date')->nullable();
$table->string('shop_id')->nullable();
$table->index(['Id']);
$table->index(['as_date', 'Id']);
$table->index(['so_id']); $table->index(['outer_as_id']);
$table->index(['as_date', 'Id', 'as_id', 'shop_site']);
$table->index(['o_id', 'Id']);
$table->index(['as_id', 'Id']);
$table->index(['shop_id', 'outer_as_id']);
});
$schema->create('ops_jst_return_refund_item', function (Blueprint $table): void {
$table->integer('Id'); $table->integer('as_id'); $table->string('outer_oi_id')->nullable();
@ -199,6 +315,33 @@ class NonJingxiRefundMirrorRepositoryTest extends TestCase
$schema->create('ops_fys_shop_info', function (Blueprint $table): void {
$table->integer('Id'); $table->string('erpShopName'); $table->string('responsibleDepartment')->nullable();
});
$schema->create('ops_jst_shop_info', function (Blueprint $table): void {
$table->integer('Id'); $table->string('shop_id'); $table->string('shop_site')->nullable();
$table->index(['shop_id', 'Id']);
});
$schema->create('ops_jst_qmcust_refunds', function (Blueprint $table): void {
$table->string('as_id'); $table->dateTime('as_date'); $table->string('outer_as_id')->nullable();
$table->integer('o_id')->nullable(); $table->string('so_id')->nullable(); $table->string('type')->nullable();
$table->string('node')->nullable(); $table->string('shop_type')->nullable(); $table->string('shop_name')->nullable();
$table->string('shop_id')->nullable(); $table->string('refund')->nullable(); $table->string('buyer_apply_refund')->nullable();
$table->string('status')->nullable(); $table->string('shop_status')->nullable(); $table->dateTime('created')->nullable();
$table->dateTime('confirm_date')->nullable(); $table->dateTime('local_created')->nullable();
$table->index(['as_id']); $table->index(['as_date', 'as_id']);
$table->index(['so_id']); $table->index(['outer_as_id']);
});
$schema->create('ops_jst_qmcust_refund_items', function (Blueprint $table): void {
$table->integer('asi_id'); $table->string('as_id'); $table->string('outer_oi_id')->nullable();
$table->string('shop_sku_id')->nullable(); $table->string('i_id')->nullable(); $table->string('sku_id')->nullable();
$table->integer('qty')->nullable(); $table->string('shop_amount')->nullable(); $table->string('type')->nullable();
$table->integer('r_qty')->nullable(); $table->index(['as_id', 'asi_id']);
});
}
private function supplement(int $id, string $date, string $shop): array
{
return ['as_id' => (string) $id, 'as_date' => $date, 'outer_as_id' => 'AS-Q-' . $id,
'o_id' => 9000 + $id, 'so_id' => 'SO-Q-' . $id, 'type' => '仅退款',
'shop_id' => $shop, 'shop_name' => '测试店', 'refund' => '12.34', 'status' => 'Confirmed'];
}
private function markReady(): void