发货同步保留同单号的多次真实出库 (#1551)

This commit is contained in:
limeng 2026-11-29 20:46:09 +08:00
parent 51e805ed37
commit b4ee49e7ef
2 changed files with 155 additions and 50 deletions

View File

@ -127,8 +127,10 @@ class ShippingReplicaSynchronizer
/** @var array<string,bool> 本次已吐出包裹的交易单号 */
private array $emittedSo = [];
/** 快递单号(去@) => [交易单号 => true]:同一单号被不同交易单号共用(合包/拼单)时,按交易单号区分是否已处理 */
/** 快递单号 => 交易单号 => 首包来源键;0 表示已经处理,但无法确认所有包裹对应的出库单。 */
private array $doneTrackSo = [];
/** @var array<int,true> 已确认是同一快递单号下不同出库单的包裹。 */
private array $repeatedOutboundSources = [];
/** @var array<int,true> 本轮按规则排除的包裹 source_id(取消/拆分/合并/线上发货),窗口内旧记录需清掉 */
private array $excludedSourceIds = [];
@ -239,6 +241,7 @@ class ShippingReplicaSynchronizer
$this->emittedTrack = [];
$this->emittedSo = [];
$this->doneTrackSo = [];
$this->repeatedOutboundSources = [];
$this->excludedSourceIds = [];
$this->ioDate = [];
$this->ioLc = [];
@ -390,6 +393,7 @@ class ShippingReplicaSynchronizer
$this->dwsFailedDays = [];
$this->seenSourceIds = [];
$this->expressOrderIds = [];
$this->repeatedOutboundSources = [];
gc_collect_cycles();
}
}
@ -420,7 +424,7 @@ class ShippingReplicaSynchronizer
}
$toDel = [];
foreach ($prefixed as $sourceId => [$tradeNo, $shipDate, $expressNo]) {
if ($expressNo !== '' && isset($clean[$tradeNo][$shipDate][$expressNo])) {
if (! isset($this->repeatedOutboundSources[$sourceId]) && $expressNo !== '' && isset($clean[$tradeNo][$shipDate][$expressNo])) {
$toDel[] = $sourceId;
}
}
@ -557,7 +561,7 @@ class ShippingReplicaSynchronizer
// 订单已取消/已拆分/已合并:实际发货在子单或合并单上,工作平台不出此行。
// 只登记本行自己的单号,不登记订单单号(可能是子单真实单号,需留给出库单兜底)
$this->markDone('', (string) ($r['logistic_id'] ?? ''));
$this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['logistic_id'] ?? ''));
$this->markTrackSo((string) ($r['so_id'] ?? ''), 0, (string) ($r['logistic_id'] ?? ''));
$this->excludeSource($pkgId);
continue;
}
@ -566,29 +570,28 @@ class ShippingReplicaSynchronizer
// 换单:快递明细仍是旧单号,出库单已换成新单号 → 用新单号与对应出库单(工作平台口径)
$r['logistic_id'] = $sw['l_id'];
}
$this->markDone(
$sw !== null ? $sw['io'] : $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), (string) ($r['inner_order_id'] ?? '')),
(string) ($r['logistic_id'] ?? ''),
(string) ($r['jo_lid'] ?? ''),
$sw !== null ? $sw['old'] : ''
);
$this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['logistic_id'] ?? ''), (string) ($r['jo_lid'] ?? ''));
if ($this->excludedByLabel($r['order_labels'] ?? null) || $this->excludedByLabel($r['jo_labels'] ?? null)) {
$so = (string) ($r['so_id'] ?? '');
$oid = (string) ($r['inner_order_id'] ?? '');
$lid = (string) ($r['logistic_id'] ?? '');
$orderLid = (string) ($r['jo_lid'] ?? '');
$io = $sw !== null ? $sw['io'] : $this->ioFor($ioMap, $lid, $oid);
$this->markDone($io, $lid, $orderLid, $sw['old'] ?? '');
$excluded = $this->excludedByLabel($r['order_labels'] ?? null) || $this->excludedByLabel($r['jo_labels'] ?? null);
if ($excluded) {
$this->markTrackSo($so, 0, $lid, $orderLid);
$this->excludeSource($pkgId);
continue; // 线上发货(平台代发/云仓):工作平台不拉,对齐排除(发货明细标签可能滞后,订单标签一并判断)
}
$so = (string) ($r['so_id'] ?? '');
$oid = (string) ($r['inner_order_id'] ?? '');
$io = $sw !== null ? $sw['io'] : $this->ioFor($ioMap, (string) ($r['logistic_id'] ?? ''), $oid);
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, (string) ($r['logistic_id'] ?? ''));
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, $lid);
if (trim((string) ($r['logistic_id'] ?? '')) === '') {
// 发货明细无单号:出库单单号 → 订单单号 → 空(不借运费表里同订单其它包裹的单号)
$ioLid = ($io !== '') ? (string) ($ioMap['ioL'][$io] ?? '') : '';
$joLid = trim((string) ($r['jo_lid'] ?? ''));
$tracking = $ioLid !== '' ? $ioLid : ($joLid !== '' ? $joLid : null);
} else {
$tracking = $this->tracking((string) ($r['logistic_id'] ?? ''), (string) ($r['jo_lid'] ?? ''), $freight, $so);
$tracking = $this->tracking($lid, $orderLid, $freight, $so);
}
$this->markTrackSo($so, $io !== '' ? $pkgId : 0, (string) $tracking, $lid, $orderLid);
// 发货时间 = 出库单 io_date(工作平台口径,样本 400/400 一致),缺失时回落发货明细时间
$shipTime = ($io !== '' ? $this->ts($this->ioDate[$io] ?? null) : null)
?? $this->ts($r['send_time'] ?? null) ?? $this->ts($r['jo_send'] ?? null);
@ -802,20 +805,22 @@ class ShippingReplicaSynchronizer
if ($tracking !== null && isset($this->emittedTrack[ltrim(trim($tracking), '@')])) {
$tracking = null;
}
$this->markDone($this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), $oid), (string) ($r['l_id'] ?? ''));
$this->markTrackSo((string) ($r['so_id'] ?? ''), (string) ($r['l_id'] ?? ''));
if ($this->excludedByLabel($r['labels'] ?? null)) {
$this->excludeSource(self::AUTOSHIP_OFFSET + (int) $oid);
$so = (string) ($r['so_id'] ?? '');
$lid = (string) ($r['l_id'] ?? '');
$io = $this->ioFor($ioMap, $lid, $oid);
$pkgId = self::AUTOSHIP_OFFSET + (int) $oid;
$this->markDone($io, $lid);
$excluded = $this->excludedByLabel($r['labels'] ?? null);
$this->markTrackSo($so, ! $excluded && $io !== '' && $tracking !== null ? $pkgId : 0, $lid);
if ($excluded) {
$this->excludeSource($pkgId);
continue; // 线上发货:对齐排除
}
$so = (string) ($r['so_id'] ?? '');
$io = $this->ioFor($ioMap, (string) ($r['l_id'] ?? ''), $oid);
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, (string) ($r['l_id'] ?? ''));
$items = $this->packageItems($io, $viewItems, $byOid, $bySo, $dws, $oid, $so, $lid);
$shipTime = ($io !== '' ? $this->ts($this->ioDate[$io] ?? null) : null) ?? $this->ts($r['send_date'] ?? null);
$pkg = $this->pkgFromOrder($r, $tracking, $shipTime);
$pkg['platform'] = $this->platformOf($io, $pkg['platform']);
$pkg = $this->withViewAddr($io, $pkg);
$pkgId = self::AUTOSHIP_OFFSET + (int) $oid;
$pkg = $this->withViewCarrier($io, $pkg, $pkgId);
$total += $this->emitPackage($pkgId, $pkg, $items, $skus, $freight, $so, $tracking, $now, true);
}
@ -971,13 +976,14 @@ class ShippingReplicaSynchronizer
}
/** 登记 单号×交易单号 已处理。 */
private function markTrackSo(string $so, string ...$tracks): void
private function markTrackSo(string $so, int $sourceId, string $tracking, string ...$aliases): void
{
$so = trim($so);
foreach ($tracks as $t) {
$trackKey = ltrim(trim($tracking), '@');
foreach ([$tracking, ...$aliases] as $t) {
$t = ltrim(trim($t), '@');
if ($t !== '') {
$this->doneTrackSo[$t][$so] = true;
$this->doneTrackSo[$t][$so] = $sourceId === 0 || $t !== $trackKey ? 0 : ($this->doneTrackSo[$t][$so] ?? $sourceId);
}
}
}
@ -1027,7 +1033,7 @@ class ShippingReplicaSynchronizer
for ($a = $lo; $a <= $hi; $a += $step) {
$page++;
$rows = $this->selectWithReconnect(
"SELECT {$cols} FROM " . self::OUTBOUND . ' WHERE Id >= ? AND Id < ? AND io_date >= ? AND io_date < ?',
"SELECT {$cols} FROM " . self::OUTBOUND . ' WHERE Id >= ? AND Id < ? AND io_date >= ? AND io_date < ? ORDER BY Id',
[$a, $a + $step, $fromS, $toS]
);
$scanned += count($rows);
@ -1050,8 +1056,6 @@ class ShippingReplicaSynchronizer
$skip['done']++;
continue;
}
// 单号已处理过:若是别的交易单号共用此单号(合包/拼单),仍要补吐;交易单号要等视图表头加载后判断
$r['_trk_done'] = $lid !== '' && isset($this->doneTrack[ltrim($lid, '@')]);
$st = (string) ($r['status'] ?? '');
if (stripos($st, 'cancel') !== false || stripos($st, 'delete') !== false) {
$skip['status']++;
@ -1085,16 +1089,22 @@ class ShippingReplicaSynchronizer
$h = $heads[$io] ?? [];
$so = $this->outboundSo($r, $h);
$tracking = trim((string) ($r['l_id'] ?? ''));
if (! empty($r['_trk_done'])) {
$t0 = ltrim($tracking, '@');
if ($so === '' || empty($this->doneTrackSo[$t0]) || isset($this->doneTrackSo[$t0][$so])) {
$skip['done']++;
continue;
}
$trackKey = ltrim($tracking, '@');
// 即时读取同批已处理记录。当前 io_id 已在前面去重;旧包裹来源明确才可补同交易单号的另一次出库。
$previous = $this->doneTrackSo[$trackKey] ?? [];
if (isset($this->doneTrack[$trackKey]) && ($so === '' || $previous === [] || ($previous[$so] ?? null) === 0)) {
$skip['done']++;
continue;
}
$sameTrackAgain = isset($previous[$so]);
$pkgId = self::OUTBOUND_OFFSET + (int) $io;
if ($sameTrackAgain) {
$this->repeatedOutboundSources[$previous[$so]] = true;
$this->repeatedOutboundSources[$pkgId] = true;
}
$pkg = $this->pkgFromOutbound($r, $tracking !== '' ? $tracking : null, $this->ts($r['io_date'] ?? null), $h, $so);
$pkg = $this->withViewAddr($io, $pkg);
$pkg = $this->withViewCarrier($io, $pkg, self::OUTBOUND_OFFSET + (int) $io);
$pkg = $this->withViewCarrier($io, $pkg, $pkgId);
if (trim((string) ($pkg['express_name1'] ?? '')) === self::NO_LOGISTICS) {
if (empty($this->ioWare[$io])) {
$pkg['warehouse_name'] = self::NO_LOGISTICS_WAREHOUSE;
@ -1102,9 +1112,9 @@ class ShippingReplicaSynchronizer
$virtualEmitted++;
}
$this->itemsFromView = true;
$total += $this->emitPackage(self::OUTBOUND_OFFSET + (int) $io, $pkg, $viewItems[$io], $skus, $freight, $so, $tracking !== '' ? $tracking : null, $now, true);
$total += $this->emitPackage($pkgId, $pkg, $viewItems[$io], $skus, $freight, $so, $tracking !== '' ? $tracking : null, $now, true, $sameTrackAgain);
$this->markDone($io, $tracking);
$this->markTrackSo($so, $tracking);
$this->markTrackSo($so, $pkgId, $tracking);
$emitted++;
}
unset($viewItems, $heads, $skus, $freight);
@ -1327,7 +1337,7 @@ class ShippingReplicaSynchronizer
* 输出一个包裹的所有明细行(每件一行;无商品则一行空商品)。
* @return int 组装行数
*/
private function emitPackage(int $pkgId, array $pkg, array $items, array $skus, array $freight, string $so, ?string $tracking, $now, bool $auto = false): int
private function emitPackage(int $pkgId, array $pkg, array $items, array $skus, array $freight, string $so, ?string $tracking, $now, bool $auto = false, bool $sameTrackAgain = false): int
{
$items = array_values(array_filter($items, fn ($it) => ! $this->isPricePatch($it['name'] ?? null)));
$items = $this->dropZeroQtyPlaceholders($items);
@ -1372,6 +1382,11 @@ class ShippingReplicaSynchronizer
// 进而误用同交易单号其它包裹的运费和快递名称。
$f = $freight[$so . '|' . $tk] ?? ($freight[$so . '|'] ?? []);
$hasFreight = isset($f['cost']);
// 聚水潭按「交易单号+单号」返回运费合计。同单号补吐使用本包裹重量,合计只留在首包。
// 已取到上游合计时继续标记运费完整,以免重跑时把旧的重复运费带回来。
if ($sameTrackAgain) {
$f = [];
}
$packageRows = [];
if ($n === 0) {
@ -3028,7 +3043,7 @@ class ShippingReplicaSynchronizer
/**
* 发货时间校正:仓库次日才出库的包裹,同步时出库单还没生成,发货时间先落成发货明细(打单)时间;
* 后续同步若走"保留旧包裹"分支不会改写。这里按快递单号对齐出库单 io_date(=聚水潭发货/出库时间),
* 只把偏早的发货时间往后校正(相差 1 分钟~7 天),同一单号多张出库单时有效单优先、再取最新。
* 只把偏早的发货时间往后校正(相差 1 分钟~7 天)。同一单号有多张有效出库单时须先确认对应包裹。
*/
public function fixShipTimes(string $fromS, string $toS): int
{
@ -3073,7 +3088,7 @@ class ShippingReplicaSynchronizer
if ($withWeight) {
try {
$part = $this->selectWithReconnect(
'SELECT so.l_id, so.io_date, so.status, so.weight, so.f_weight FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
'SELECT so.l_id, so.io_date, so.status, so.weight, so.f_weight, so.io_id FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
$bind,
);
} catch (Throwable $e) {
@ -3085,7 +3100,7 @@ class ShippingReplicaSynchronizer
}
if ($part === null) {
$part = $this->selectWithReconnect(
'SELECT so.l_id, so.io_date, so.status FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
'SELECT so.l_id, so.io_date, so.status, so.io_id FROM ' . self::OUTBOUND . ' so WHERE so.io_date >= ? AND so.io_date < ?',
$bind,
);
}
@ -3095,6 +3110,7 @@ class ShippingReplicaSynchronizer
$cur = $next;
}
$best = [];
$multiple = [];
foreach ($rows as $r) {
$r = (array) $r;
$l = ltrim(trim((string) ($r['l_id'] ?? '')), '@');
@ -3105,11 +3121,17 @@ class ShippingReplicaSynchronizer
$st = strtolower(trim((string) ($r['status'] ?? '')));
$ok = ! in_array($st, ['delete', 'deleted', 'cancelled', 'cancel', 'canceled', '作废'], true);
$rk = ($ok ? '1' : '0') . '|' . $d;
$io = (int) ($r['io_id'] ?? 0);
$hasW = $withWeight && array_key_exists('weight', $r);
$w = $hasW ? (float) ($r['weight'] ?? 0) : 0.0;
$fw = $hasW ? (float) ($r['f_weight'] ?? 0) : 0.0;
$candidate = [$rk, $d, $hasW, $w > 0 ? round($w, 4) : null, $fw > 0 ? round($fw, 4) : null, $io];
if ($ok && $io > 0 && isset($best[$l]) && $best[$l][0][0] === '1' && $best[$l][5] > 0 && $best[$l][5] !== $io) {
$multiple[$l] ??= [$best[$l][5] => $best[$l]];
$multiple[$l][$io] = $candidate;
}
if (! isset($best[$l]) || strcmp($rk, $best[$l][0]) > 0) {
$hasW = $withWeight && array_key_exists('weight', $r);
$w = $hasW ? (float) ($r['weight'] ?? 0) : 0.0;
$fw = $hasW ? (float) ($r['f_weight'] ?? 0) : 0.0;
$best[$l] = [$rk, $d, $hasW, $w > 0 ? round($w, 4) : null, $fw > 0 ? round($fw, 4) : null];
$best[$l] = $candidate;
}
}
unset($rows);
@ -3125,14 +3147,17 @@ class ShippingReplicaSynchronizer
->select(['id', 'source_id', 'express_no', 'ship_time', 'online_weight', 'actual_weight'])
->where('ship_time', '>=', $mirrorFrom)->where('ship_time', '<', $toS)
->whereNotNull('express_no')
->chunkById(20000, function ($chunk) use (&$fixTime, &$first, &$clearIds, $best): void {
->chunkById(20000, function ($chunk) use (&$fixTime, &$first, &$clearIds, $best, $multiple): void {
foreach ($chunk as $row) {
$sid = (int) $row->source_id;
$l = ltrim(trim((string) $row->express_no), '@');
if ($l === '' || ! isset($best[$l])) {
continue;
}
$b = $best[$l];
$b = $this->outboundForMirrorRow($sid, (string) $row->ship_time, $best[$l], $multiple[$l] ?? []);
if ($b === null) {
continue;
}
if (isset($first[$sid])) {
if ($b[2] && ($row->online_weight !== null || $row->actual_weight !== null)) {
$clearIds[] = (int) $row->id;
@ -3153,7 +3178,7 @@ class ShippingReplicaSynchronizer
}
}
}, 'id');
unset($best);
unset($best, $multiple);
$nTime = 0;
foreach ($fixTime as $new => $ids) {
@ -3183,6 +3208,26 @@ class ShippingReplicaSynchronizer
return ['ship_time' => $nTime, 'weight' => $nWeight];
}
private function outboundForMirrorRow(int $sourceId, string $shipTime, array $best, array $multiple): ?array
{
if ($sourceId >= self::OUTBOUND_OFFSET && $sourceId < self::PURCHASE_OUT_OFFSET) {
$io = $sourceId - self::OUTBOUND_OFFSET;
if ($multiple !== []) {
return $multiple[$io] ?? null;
}
return $best[5] === 0 || ($best[5] === $io && $best[0][0] === '1') ? $best : null;
}
if ($multiple === []) {
return $best;
}
// 发货明细和代发订单使用各自的来源键,只有唯一的出库时间能把它们匹配到某张出库单。
$matches = array_filter($multiple, static fn (array $row): bool => $row[1] === $shipTime);
return count($matches) === 1 ? reset($matches) : null;
}
/**
* 清理历史残留的订单占位行:包裹已有实发商品(数量>0)时,删除数量 0、金额 0/空 的订单商品行
* (被替换的原商品、组合装原套装等,聚水潭销售出库单不显示),商品行数(件数 1/N)随之更正。

View File

@ -9,6 +9,7 @@ use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
use Modules\EcommerceFinance\Repositories\ShippingOrderRepository;
use PDOException;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Tests\TestCase;
@ -1145,6 +1146,65 @@ class ShippingReplicaSynchronizerTest extends TestCase
$this->assertEquals(7, $row->settle_weight_kg);
}
#[DataProvider('outboundScanPages')]
public function test_second_outbound_with_the_same_tracking_and_trade_is_emitted_as_its_own_package(bool $differentPages): void
{
// 同一交易单号、同一快递单号分两次出库,工作平台各出一行
$db = DB::connection('business_mirror');
$db->table('jst_oms_shipping')->insert([
'source_id' => 2000000431, 'sku_source_id' => 200000043100, 'express_no' => 'SF-AB',
'trade_no' => 'trade-430', 'ship_time' => '2026-09-02 10:09:44', 'barcode' => 'DG-B', 'freight' => 15.50,
]);
$outbounds = [
['io_id' => '430', 'so_id' => 'trade-430', 'l_id' => 'SF-AB', 'io_date' => '2026-09-02 09:28:48',
'status' => 'Confirmed', 'weight' => 2.5, 'f_weight' => 3],
['io_id' => '431', 'so_id' => 'trade-430', 'l_id' => '@SF-AB', 'io_date' => '2026-09-02 10:09:44',
'status' => 'Confirmed', 'weight' => 4.5, 'f_weight' => 5],
];
$upstream = $this->createMock(UpstreamReadOnlyQuery::class);
$upstream->method('select')->willReturnCallback(function (string $sql, array $bindings) use ($outbounds, $differentPages): array {
if (str_contains($sql, 'MIN(Id) AS lo') && str_contains($sql, 'rpt.jst_salesOutboundInfo')) {
return [['lo' => 1, 'hi' => $differentPages ? 10000 : 2]];
}
if (str_contains($sql, 'WHERE Id >= ?') && str_contains($sql, 'rpt.jst_salesOutboundInfo')) {
return $differentPages ? [$outbounds[(int) $bindings[0] === 1 ? 0 : 1]] : $outbounds;
}
if (str_contains($sql, 'SELECT so.l_id, so.io_date, so.status')) {
return array_values(array_filter($outbounds, static fn (array $row): bool => $row['io_date'] >= $bindings[0]
&& $row['io_date'] < $bindings[1]));
}
if (str_contains($sql, 'SELECT io_id, sku_ids')) {
return [
['io_id' => '430', 'sku_ids' => 'DG-A', 'qty' => 1, 'type' => '0', 'volume' => 100, 'l' => 10, 'w' => 5, 'h' => 2],
['io_id' => '431', 'sku_ids' => 'DG-B', 'qty' => 1, 'type' => '0', 'volume' => 90, 'l' => 9, 'w' => 5, 'h' => 2],
];
}
if (str_contains($sql, 'SUM(freightCost) AS cost')) {
return [['so_id' => 'trade-430', 'expressNo' => 'SF-AB', 'cost' => 15.50, 'w' => 3.25]];
}
return [];
});
$factory = $this->createMock(UpstreamReadOnlyQueryFactory::class);
$factory->method('forSource')->willReturn($upstream);
$result = (new ShippingReplicaSynchronizer($factory))->sync(
Carbon::parse('2026-09-01'), Carbon::parse('2026-09-05'),
);
$this->assertSame(2, $result['outbound']);
$rows = $db->table('jst_oms_shipping')->where('express_no', 'SF-AB')->orderBy('ship_time')->get();
$this->assertSame(['DG-A', 'DG-B'], $rows->pluck('barcode')->all());
$this->assertSame(['2026-09-02 09:28:48', '2026-09-02 10:09:44'], $rows->pluck('ship_time')->all());
$this->assertEquals([2.5, 4.5], $rows->pluck('online_weight')->all());
$this->assertEquals([3, 5], $rows->pluck('actual_weight')->all());
$this->assertEquals(15.50, $rows[0]->freight);
$this->assertNull($rows[1]->freight);
}
public static function outboundScanPages(): array
{
return ['same page' => [false], 'different pages' => [true]];
}
public function test_outbound_mapping_keeps_shared_tracking_orders_distinct_and_ignores_cancelled(): void
{
$upstream = $this->createMock(UpstreamReadOnlyQuery::class);